feat(device-manager): align functional UI with Mission Core interaction patterns
Device Core qualification / qualify (push) Successful in 8m53s

This commit is contained in:
DCCONSTRUCTIONS
2026-09-30 20:53:19 +03:00
parent 7072b86fb8
commit b8d240a0a0
12 changed files with 309 additions and 337 deletions
@@ -122,7 +122,6 @@ test("host hardware monitoring retains the established geometry", async () => {
".infrastructure-host-relations {", ".infrastructure-host-relations {",
"grid-template-columns: repeat(3, minmax(0, 1fr));", "grid-template-columns: repeat(3, minmax(0, 1fr));",
"grid-template-columns: repeat(4, minmax(0, 1fr));", "grid-template-columns: repeat(4, minmax(0, 1fr));",
"background: var(--infrastructure-panel-soft);",
".host-monitoring-series polyline {", ".host-monitoring-series polyline {",
"stroke: var(--nodedc-text-primary);", "stroke: var(--nodedc-text-primary);",
".host-monitoring-hardware-facts {", ".host-monitoring-hardware-facts {",
@@ -134,6 +133,7 @@ test("host hardware monitoring retains the established geometry", async () => {
assert.ok(!infrastructureSource.includes('title="Deployments и endpoints"')); assert.ok(!infrastructureSource.includes('title="Deployments и endpoints"'));
assert.ok(!infrastructureSource.includes("ceiling={100}")); assert.ok(!infrastructureSource.includes("ceiling={100}"));
assert.ok(!infrastructureSource.includes("Канонический ontology catalog")); assert.ok(!infrastructureSource.includes("Канонический ontology catalog"));
assert.ok(!styles.includes("background: var(--infrastructure-panel-soft);"), "Functional panels must not add nested black surfaces");
assert.ok(!styles.includes(".host-telemetry-metric,")); assert.ok(!styles.includes(".host-telemetry-metric,"));
assert.ok(!styles.includes(".host-telemetry-facts")); assert.ok(!styles.includes(".host-telemetry-facts"));
}); });
+62 -56
View File
@@ -4,7 +4,6 @@ import {
ConfirmationModal, ConfirmationModal,
ResourceList as CanonicalResourceList, ResourceList as CanonicalResourceList,
ResourceRow as CanonicalResourceRow, ResourceRow as CanonicalResourceRow,
GlassSurface,
Icon, Icon,
IconButton, IconButton,
Select, Select,
@@ -365,15 +364,15 @@ function CatalogView({ workspace, canManage, onCreatePackage, onCreateVersion, o
return ( return (
<ControlStack> <ControlStack>
<ControlToolbar <ControlToolbar
copy="Adapter packages и model profiles — глобальный versioned каталог. B2 здесь не является отдельным продуктом." copy="Модели устройств и версии адаптеров."
actions={canManage ? <> actions={canManage ? <>
<Button size="compact" onClick={onCreatePackage}>Пакет</Button> <Button size="compact" onClick={onCreatePackage}>Пакет</Button>
<Button size="compact" onClick={onCreateVersion} disabled={!workspace.adapterPackages.length}>Версия</Button> <Button size="compact" onClick={onCreateVersion} disabled={!workspace.adapterPackages.length}>Версия</Button>
<Button size="compact" variant="primary" onClick={onCreateProfile} disabled={!workspace.adapterVersions.length}>Профиль</Button> <Button size="compact" variant="primary" onClick={onCreateProfile} disabled={!workspace.adapterVersions.length}>Профиль</Button>
</> : null} </> : null}
/> />
<ControlSection title="Model profiles" count={workspace.modelProfiles.length}> <ControlSection title="Модели устройств" count={workspace.modelProfiles.length}>
<ResourceGrid empty="В доступном каталоге пока нет model profiles."> <ResourceGrid empty="Модели устройств пока не добавлены.">
{workspace.modelProfiles.map((profile) => ( {workspace.modelProfiles.map((profile) => (
<ResourceCard <ResourceCard
key={profile.modelProfileRef} key={profile.modelProfileRef}
@@ -389,7 +388,7 @@ function CatalogView({ workspace, canManage, onCreatePackage, onCreateVersion, o
))} ))}
</ResourceGrid> </ResourceGrid>
</ControlSection> </ControlSection>
<ControlSection title="Adapter versions" count={workspace.adapterVersions.length}> <ControlSection title="Версии адаптеров" count={workspace.adapterVersions.length}>
<ResourceGrid empty="Версии адаптеров не зарегистрированы."> <ResourceGrid empty="Версии адаптеров не зарегистрированы.">
{workspace.adapterVersions.map((version) => ( {workspace.adapterVersions.map((version) => (
<ResourceCard <ResourceCard
@@ -406,8 +405,8 @@ function CatalogView({ workspace, canManage, onCreatePackage, onCreateVersion, o
))} ))}
</ResourceGrid> </ResourceGrid>
</ControlSection> </ControlSection>
<ControlSection title="Adapter packages" count={workspace.adapterPackages.length}> <ControlSection title="Адаптеры" count={workspace.adapterPackages.length}>
<ResourceGrid empty="Adapter packages не зарегистрированы."> <ResourceGrid empty="Адаптеры пока не добавлены.">
{workspace.adapterPackages.map((adapterPackage) => ( {workspace.adapterPackages.map((adapterPackage) => (
<ResourceCard <ResourceCard
key={adapterPackage.adapterPackageRef} key={adapterPackage.adapterPackageRef}
@@ -438,13 +437,13 @@ function InfrastructureView({ workspace, canManageCatalog, canManageRoutes, onCr
return ( return (
<ControlStack> <ControlStack>
<ControlToolbar <ControlToolbar
copy="Edge — зарегистрированная внешняя роль. Route связывает проект, Edge, profile и логический listener без credentials." copy="Узлы приёма данных и маршруты устройств."
actions={<> actions={<>
{canManageCatalog ? <Button size="compact" onClick={onCreateEdge}>Новый Edge</Button> : null} {canManageCatalog ? <Button size="compact" onClick={onCreateEdge}>Новый узел</Button> : null}
{canManageRoutes ? <Button size="compact" variant="primary" onClick={onCreateRoute} disabled={!workspace.edges.length || !workspace.modelProfiles.length}>Новый маршрут</Button> : null} {canManageRoutes ? <Button size="compact" variant="primary" onClick={onCreateRoute} disabled={!workspace.edges.length || !workspace.modelProfiles.length}>Новый маршрут</Button> : null}
</>} </>}
/> />
<ControlSection title="Routes" count={workspace.routes.length}> <ControlSection title="Маршруты" count={workspace.routes.length}>
<ResourceGrid empty="Маршрутов в проекте пока нет."> <ResourceGrid empty="Маршрутов в проекте пока нет.">
{workspace.routes.map((route) => ( {workspace.routes.map((route) => (
<ResourceCard <ResourceCard
@@ -464,12 +463,12 @@ function InfrastructureView({ workspace, canManageCatalog, canManageRoutes, onCr
))} ))}
</ResourceGrid> </ResourceGrid>
</ControlSection> </ControlSection>
<ControlSection title="Edges" count={workspace.edges.length}> <ControlSection title="Узлы приёма данных" count={workspace.edges.length}>
<ResourceGrid empty="Доступных Edge registrations нет."> <ResourceGrid empty="Узлы пока не добавлены.">
{workspace.edges.map((edge) => ( {workspace.edges.map((edge) => (
<ResourceCard <ResourceCard
key={edge.edgeRef} key={edge.edgeRef}
eyebrow="DEVICE GATEWAY EDGE" eyebrow="Узел приёма данных"
title={edge.displayName} title={edge.displayName}
description={edge.edgeKey} description={edge.edgeKey}
status={edge.lifecycleState} status={edge.lifecycleState}
@@ -650,7 +649,7 @@ function HostTelemetryWorkspace({
<HostTelemetrySeries label="NETWORK TX" value={formatRate(networkRate.sent)} resource={networkRate.sent == null ? "нет данных" : "исходящий трафик"} values={sendHistory} /> <HostTelemetrySeries label="NETWORK TX" value={formatRate(networkRate.sent)} resource={networkRate.sent == null ? "нет данных" : "исходящий трафик"} values={sendHistory} />
</section> </section>
<GlassSurface className="host-monitoring-hardware" padding="lg"> <div className="host-monitoring-hardware">
<InfrastructureSectionHeading <InfrastructureSectionHeading
eyebrow="HARDWARE" eyebrow="HARDWARE"
title={current?.hardware.hostname ?? host.hostKey} title={current?.hardware.hostname ?? host.hostKey}
@@ -681,7 +680,7 @@ function HostTelemetryWorkspace({
))} ))}
{!current?.disks.length ? <div className="infrastructure-empty">Данные о дисках ещё не поступили.</div> : null} {!current?.disks.length ? <div className="infrastructure-empty">Данные о дисках ещё не поступили.</div> : null}
</div> </div>
</GlassSurface> </div>
<section className="infrastructure-section"> <section className="infrastructure-section">
<InfrastructureSectionHeading <InfrastructureSectionHeading
@@ -693,7 +692,7 @@ function HostTelemetryWorkspace({
{networkInterfaces.length ? ( {networkInterfaces.length ? (
<div className="host-monitoring-network-grid"> <div className="host-monitoring-network-grid">
{networkInterfaces.map((item, index) => ( {networkInterfaces.map((item, index) => (
<GlassSurface className="host-monitoring-network-card" padding="md" tone="soft" key={`${item.interface}:${index}`}> <div className="host-monitoring-network-card" key={`${item.interface}:${index}`}>
<header><strong>{item.interface ?? "Интерфейс"}</strong><small>{formatPackets(item.packetsReceived, item.packetsSent)}</small></header> <header><strong>{item.interface ?? "Интерфейс"}</strong><small>{formatPackets(item.packetsReceived, item.packetsSent)}</small></header>
<dl> <dl>
<div><dt>Получено</dt><dd>{formatMetricBytes(item.bytesReceived)}</dd></div> <div><dt>Получено</dt><dd>{formatMetricBytes(item.bytesReceived)}</dd></div>
@@ -701,7 +700,7 @@ function HostTelemetryWorkspace({
<div><dt>Ошибки RX / TX</dt><dd>{formatNullable(item.errorsReceived)} / {formatNullable(item.errorsSent)}</dd></div> <div><dt>Ошибки RX / TX</dt><dd>{formatNullable(item.errorsReceived)} / {formatNullable(item.errorsSent)}</dd></div>
<div><dt>Потери RX / TX</dt><dd>{formatNullable(item.droppedReceived)} / {formatNullable(item.droppedSent)}</dd></div> <div><dt>Потери RX / TX</dt><dd>{formatNullable(item.droppedReceived)} / {formatNullable(item.droppedSent)}</dd></div>
</dl> </dl>
</GlassSurface> </div>
))} ))}
</div> </div>
) : <div className="infrastructure-empty">Сетевые счётчики ещё не поступили.</div>} ) : <div className="infrastructure-empty">Сетевые счётчики ещё не поступили.</div>}
@@ -718,7 +717,7 @@ function HostTelemetryWorkspace({
{runtimeServices.length ? ( {runtimeServices.length ? (
<div className="infrastructure-runtime-grid"> <div className="infrastructure-runtime-grid">
{runtimeServices.map((service, index) => ( {runtimeServices.map((service, index) => (
<GlassSurface className="host-monitoring-runtime-card" padding="md" tone="soft" key={`${service.name}:${index}`}> <div className="host-monitoring-runtime-card" key={`${service.name}:${index}`}>
<header> <header>
<div><span className="infrastructure-eyebrow">SYSTEMD UNIT</span><h3>{service.name ?? "systemd unit"}</h3><code>{service.subState ?? "—"}</code></div> <div><span className="infrastructure-eyebrow">SYSTEMD UNIT</span><h3>{service.name ?? "systemd unit"}</h3><code>{service.subState ?? "—"}</code></div>
<StatusBadge tone={service.activeState === "active" ? "success" : service.activeState === "failed" ? "danger" : "warning"}>{service.activeState ?? "unknown"}</StatusBadge> <StatusBadge tone={service.activeState === "active" ? "success" : service.activeState === "failed" ? "danger" : "warning"}>{service.activeState ?? "unknown"}</StatusBadge>
@@ -729,7 +728,7 @@ function HostTelemetryWorkspace({
<div><dt>Перезапуски</dt><dd>{formatNullable(service.restarts)}</dd></div> <div><dt>Перезапуски</dt><dd>{formatNullable(service.restarts)}</dd></div>
<div><dt>PID</dt><dd>{formatNullable(service.pid)}</dd></div> <div><dt>PID</dt><dd>{formatNullable(service.pid)}</dd></div>
</dl> </dl>
</GlassSurface> </div>
))} ))}
</div> </div>
) : <div className="infrastructure-empty">Состояние сервисов ещё не поступило.</div>} ) : <div className="infrastructure-empty">Состояние сервисов ещё не поступило.</div>}
@@ -964,8 +963,8 @@ function formatPackets(received: number | null | undefined, sent: number | null
function SessionsView({ workspace }: { workspace: ProjectWorkspace }) { function SessionsView({ workspace }: { workspace: ProjectWorkspace }) {
return ( return (
<ControlStack> <ControlStack>
<ControlToolbar copy="Сессии принадлежат Gateway runtime. Device Manager только читает bounded presence/counter projection." /> <ControlToolbar copy="Подключения устройств" />
<ResourceList empty="Gateway sessions пока не наблюдались."> <ResourceList empty="Нет подключений">
{workspace.sessions.map((session) => ( {workspace.sessions.map((session) => (
<ResourceRow <ResourceRow
key={session.sessionRef} key={session.sessionRef}
@@ -989,10 +988,10 @@ function BindingsView({ workspace, canManage, onCreate, onRevoke }: {
return ( return (
<ControlStack> <ControlStack>
<ControlToolbar <ControlToolbar
copy="Binding создаёт только source approval. Active появится лишь после отдельного external proof от целевой системы." copy="Передача данных в приложения"
actions={canManage ? <Button variant="primary" onClick={onCreate} disabled={!workspace.collections.length && !workspace.devices.length}>Новый binding</Button> : null} actions={canManage ? <Button variant="primary" onClick={onCreate} disabled={!workspace.collections.length && !workspace.devices.length}>Новая привязка</Button> : null}
/> />
<ResourceList empty="Data bindings пока не создавались."> <ResourceList empty="Привязок пока нет">
{workspace.bindings.map((binding) => ( {workspace.bindings.map((binding) => (
<ResourceRow <ResourceRow
key={binding.bindingRef} key={binding.bindingRef}
@@ -1049,7 +1048,7 @@ function CommandsView({ workspace, canDispatch, onRefresh, onError }: {
}; };
return ( return (
<ControlStack> <ControlStack>
<GlassSurface className="device-control-command-policy" padding="md" tone="soft"> <div className="device-control-command-policy">
<Icon name={enabled ? "check" : "lock"} /> <Icon name={enabled ? "check" : "lock"} />
<div> <div>
<strong>{enabled ? "Типизированный командный канал активен" : "Command transport выключен"}</strong> <strong>{enabled ? "Типизированный командный канал активен" : "Command transport выключен"}</strong>
@@ -1058,9 +1057,9 @@ function CommandsView({ workspace, canDispatch, onRefresh, onError }: {
: "Ни UI, ни BFF не имеют raw command builder. acknowledged означает подтверждение протокола, verified — отдельное доказательство состояния."}</p> : "Ни UI, ни BFF не имеют raw command builder. acknowledged означает подтверждение протокола, verified — отдельное доказательство состояния."}</p>
</div> </div>
<StatusBadge tone={enabled ? "success" : "warning"}>{workspace.policies.commandTransport}</StatusBadge> <StatusBadge tone={enabled ? "success" : "warning"}>{workspace.policies.commandTransport}</StatusBadge>
</GlassSurface> </div>
{enabled ? ( {enabled ? (
<GlassSurface padding="md" tone="soft"> <div>
<form className="device-control-command-form" onSubmit={submit}> <form className="device-control-command-form" onSubmit={submit}>
<Select <Select
label="B2 трекер" label="B2 трекер"
@@ -1095,7 +1094,7 @@ function CommandsView({ workspace, canDispatch, onRefresh, onError }: {
{submitting ? "Ставим в очередь…" : "Проверить сервис"} {submitting ? "Ставим в очередь…" : "Проверить сервис"}
</Button> </Button>
</form> </form>
</GlassSurface> </div>
) : null} ) : null}
<ResourceList empty="Command intents отсутствуют. Это не означает, что транспорт доступен."> <ResourceList empty="Command intents отсутствуют. Это не означает, что транспорт доступен.">
{workspace.commands.map((command) => ( {workspace.commands.map((command) => (
@@ -1115,8 +1114,8 @@ function CommandsView({ workspace, canDispatch, onRefresh, onError }: {
function AuditView({ workspace }: { workspace: ProjectWorkspace }) { function AuditView({ workspace }: { workspace: ProjectWorkspace }) {
return ( return (
<ControlStack> <ControlStack>
<ControlToolbar copy="Показывается immutable metadata projection. Audit payload намеренно не выдаётся в браузер." /> <ControlToolbar copy="История действий в проекте" />
<ResourceList empty="Audit events для проекта отсутствуют."> <ResourceList empty="Действий пока нет">
{workspace.auditEvents.map((event) => ( {workspace.auditEvents.map((event) => (
<ResourceRow <ResourceRow
key={event.auditEventRef} key={event.auditEventRef}
@@ -1139,17 +1138,17 @@ function AccessView({ workspace, canManage, onCreate }: {
return ( return (
<ControlStack> <ControlStack>
<ControlToolbar <ControlToolbar
copy="Hub задаёт потолок, а Device Project grant — конкретную роль. Direct user grant имеет приоритет над group grants." copy="Доступ к проекту"
actions={canManage ? <Button variant="primary" onClick={onCreate}>Добавить доступ</Button> : null} actions={canManage ? <Button variant="primary" onClick={onCreate}>Добавить доступ</Button> : null}
/> />
<ResourceList empty="Project grants недоступны или ещё не созданы."> <ResourceList empty="Доступ пока не назначен">
{workspace.grants.map((grant) => ( {workspace.grants.map((grant) => (
<ResourceRow <ResourceRow
key={grant.grantRef} key={grant.grantRef}
title={grant.principalRef} title={grant.principalRef}
description={`${grant.principalKind} · ${grant.projectRole}`} description={`${grant.principalKind} · ${grant.projectRole}`}
status={grant.lifecycleState} status={grant.lifecycleState}
trailing={grant.capabilityDeny.length ? `deny: ${grant.capabilityDeny.join(", ")}` : "role capabilities"} trailing={grant.capabilityDeny.length ? `deny: ${grant.capabilityDeny.join(", ")}` : "Права роли"}
/> />
))} ))}
</ResourceList> </ResourceList>
@@ -1170,26 +1169,26 @@ function SettingsView({ workspace, canConfigure, onCreateConfiguration }: {
<PolicyCard label="Command API" value={workspace.policies.commandPlanningApi} /> <PolicyCard label="Command API" value={workspace.policies.commandPlanningApi} />
</div> </div>
<ControlToolbar <ControlToolbar
copy="Configuration revisions immutable. Desired и applied — разные указатели; создание desired не означает применение устройством." copy="Настройки устройств"
actions={canConfigure ? <Button variant="primary" onClick={onCreateConfiguration} disabled={!workspace.devices.length}>Новая desired revision</Button> : null} actions={canConfigure ? <Button variant="primary" onClick={onCreateConfiguration} disabled={!workspace.devices.length}>Новая версия настроек</Button> : null}
/> />
<ResourceList empty="Configuration state пока отсутствует."> <ResourceList empty="Сохранённых настроек пока нет">
{workspace.configurationStates.map((state) => ( {workspace.configurationStates.map((state) => (
<ResourceRow <ResourceRow
key={state.deviceRef} key={state.deviceRef}
title={state.deviceName} title={state.deviceName}
description={`desired: ${shortRef(state.desiredConfigurationRevisionRef)} · applied: ${shortRef(state.appliedConfigurationRevisionRef)}`} description={`Сохранено: ${shortRef(state.desiredConfigurationRevisionRef)} · Применено: ${shortRef(state.appliedConfigurationRevisionRef)}`}
status={state.appliedConfigurationRevisionRef === state.desiredConfigurationRevisionRef ? "applied" : "pending"} status={state.appliedConfigurationRevisionRef === state.desiredConfigurationRevisionRef ? "applied" : "pending"}
trailing={formatDate(state.updatedAt)} trailing={formatDate(state.updatedAt)}
/> />
))} ))}
</ResourceList> </ResourceList>
<ControlSection title="Immutable revisions" count={workspace.configurationRevisions.length}> <ControlSection title="История настроек" count={workspace.configurationRevisions.length}>
<ResourceList empty="Configuration revisions отсутствуют."> <ResourceList empty="Версий пока нет">
{workspace.configurationRevisions.map((revision) => ( {workspace.configurationRevisions.map((revision) => (
<ResourceRow <ResourceRow
key={revision.configurationRevisionRef} key={revision.configurationRevisionRef}
title={`${revision.deviceName} · revision ${revision.revisionNumber}`} title={`${revision.deviceName} · Версия ${revision.revisionNumber}`}
description={revision.changeSummary || revision.modelProfileRef} description={revision.changeSummary || revision.modelProfileRef}
status="immutable" status="immutable"
trailing={shortDigest(revision.configurationDigest)} trailing={shortDigest(revision.configurationDigest)}
@@ -1334,7 +1333,7 @@ function AssetBindingDialog({ workspace, ...props }: DialogBaseProps & { workspa
provenanceRef, provenanceRef,
}); });
}}> }}>
<Select label="Device" value={deviceRef} onChange={setDeviceRef} options={workspace.devices.map((item) => ({ value: item.deviceRef, label: item.displayName, description: item.modelProfileRef }))} /> <Select label="Устройство" value={deviceRef} onChange={setDeviceRef} options={workspace.devices.map((item) => ({ value: item.deviceRef, label: item.displayName, description: item.modelProfileRef }))} />
<Select label="Asset" value={assetRef} onChange={setAssetRef} options={workspace.ontology.assets.map((item) => ({ value: item.assetRef, label: item.displayName, description: item.assetTypeRef }))} /> <Select label="Asset" value={assetRef} onChange={setAssetRef} options={workspace.ontology.assets.map((item) => ({ value: item.assetRef, label: item.displayName, description: item.assetTypeRef }))} />
<KeyField label="Binding key" value={bindingKey} onChange={setBindingKey} /> <KeyField label="Binding key" value={bindingKey} onChange={setBindingKey} />
<Select label="Relation" value={bindingKind} onChange={setBindingKind} options={[ <Select label="Relation" value={bindingKind} onChange={setBindingKind} options={[
@@ -1518,7 +1517,7 @@ function EdgeDialog(props: DialogBaseProps) {
const [edgeKey, setEdgeKey] = useState(""); const [edgeKey, setEdgeKey] = useState("");
const [displayName, setDisplayName] = useState(""); const [displayName, setDisplayName] = useState("");
const [deploymentRef, setDeploymentRef] = useState(""); const [deploymentRef, setDeploymentRef] = useState("");
return <FormWindow {...props} id="edge-form" title="Новый Edge" submit={async () => { return <FormWindow {...props} id="edge-form" title="Новый узел" submit={async () => {
await ensureEdge({ edgeKey, displayName, deploymentRef: deploymentRef || null, lifecycleState: "provisioning" }); await ensureEdge({ edgeKey, displayName, deploymentRef: deploymentRef || null, lifecycleState: "provisioning" });
}}> }}>
<KeyField label="Edge key" value={edgeKey} onChange={setEdgeKey} /> <KeyField label="Edge key" value={edgeKey} onChange={setEdgeKey} />
@@ -1635,7 +1634,7 @@ function ConfigurationDialog({ workspace, ...props }: DialogBaseProps & { worksp
setDeviceRef(workspace.devices[0]?.deviceRef ?? ""); setDeviceRef(workspace.devices[0]?.deviceRef ?? "");
} }
}, [deviceRef, workspace.devices]); }, [deviceRef, workspace.devices]);
return <FormWindow {...props} id="configuration-form" title="Новая desired configuration" disabled={!deviceRef} submit={async () => { return <FormWindow {...props} id="configuration-form" title="Новая конфигурация" disabled={!deviceRef} submit={async () => {
const parsed = JSON.parse(configuration) as Record<string, unknown>; const parsed = JSON.parse(configuration) as Record<string, unknown>;
const created = await createConfigurationRevision({ const created = await createConfigurationRevision({
projectRef: workspace.project.projectRef, projectRef: workspace.project.projectRef,
@@ -1649,10 +1648,10 @@ function ConfigurationDialog({ workspace, ...props }: DialogBaseProps & { worksp
configurationRevisionRef: created.result.configurationRevision.configurationRevisionRef, configurationRevisionRef: created.result.configurationRevision.configurationRevisionRef,
}); });
}}> }}>
<Select label="Device" value={deviceRef} onChange={setDeviceRef} options={workspace.devices.map((item) => ({ value: item.deviceRef, label: item.displayName, description: item.modelProfileRef }))} /> <Select label="Устройство" value={deviceRef} onChange={setDeviceRef} options={workspace.devices.map((item) => ({ value: item.deviceRef, label: item.displayName, description: item.modelProfileRef }))} />
<TextAreaField label="Configuration JSON" value={configuration} onChange={(event) => setConfiguration(event.target.value)} required /> <TextAreaField label="Параметры JSON" value={configuration} onChange={(event) => setConfiguration(event.target.value)} required />
<TextAreaField label="Change summary" value={summary} onChange={(event) => setSummary(event.target.value)} /> <TextAreaField label="Описание изменений" value={summary} onChange={(event) => setSummary(event.target.value)} />
<p className="device-manager-card-copy">Secret-like keys и значения будут отклонены Core. Сохранение desired не выставляет applied.</p> <p className="device-manager-card-copy">После сохранения конфигурация ожидает подтверждения устройства.</p>
</FormWindow>; </FormWindow>;
} }
@@ -1717,9 +1716,13 @@ function ResourceGrid({ children, empty }: { children: ReactNode; empty: string
} }
function ResourceCard({ eyebrow, title, description, status, meta, action = null }: { eyebrow: string; title: string; description: string; status: string; meta: string[]; action?: ReactNode }) { function ResourceCard({ eyebrow, title, description, status, meta, action = null }: { eyebrow: string; title: string; description: string; status: string; meta: string[]; action?: ReactNode }) {
return <SettingsCard eyebrow={eyebrow} title={title} description={description} actions={<><StatusBadge tone={statusTone(status)}>{status}</StatusBadge>{action}</>}> const [expanded, setExpanded] = useState(false);
{meta.length ? <div className="device-manager-capabilities">{meta.map((item) => <StatusBadge key={item}>{item}</StatusBadge>)}</div> : <p className="device-manager-card-copy">Metadata-only projection</p>} return <div className="device-control-disclosure">
</SettingsCard>; <CanonicalResourceRow title={title} description={description} metadata={statusLabel(status)}
status={<StatusBadge variant="indicator" tone={statusTone(status)} aria-label={statusLabel(status)} />} statusPlacement="leading"
actions={<>{action}<IconButton label={`Сведения: ${title}`} aria-expanded={expanded} onClick={() => setExpanded(!expanded)}><Icon name={expanded ? 'chevron-up' : 'chevron-down'} /></IconButton></>} />
{expanded ? <div className="device-control-disclosure__body"><p>{eyebrow}</p>{meta.length ? <ul>{meta.map((item) => <li key={item}>{item}</li>)}</ul> : null}</div> : null}
</div>;
} }
function ResourceList({ children, empty }: { children: ReactNode; empty: string }) { function ResourceList({ children, empty }: { children: ReactNode; empty: string }) {
@@ -1728,21 +1731,24 @@ function ResourceList({ children, empty }: { children: ReactNode; empty: string
} }
function ResourceRow({ title, description, status, trailing }: { title: string; description: string; status: string; trailing: ReactNode }) { function ResourceRow({ title, description, status, trailing }: { title: string; description: string; status: string; trailing: ReactNode }) {
return <GlassSurface className="device-manager-entity device-control-row" padding="md" tone="soft"> return <CanonicalResourceRow title={title} description={description}
<span className="device-manager-entity__icon"><Icon name="circle" /></span> status={<StatusBadge variant="indicator" tone={statusTone(status)} aria-label={status} title={status} />} statusPlacement="leading"
<span className="device-manager-entity__body"><strong>{title}</strong><small>{description}</small></span> metadata={[statusLabel(status), typeof trailing === "string" ? trailing : null].filter(Boolean).join(" · ")}
<span className="device-control-row__status"><StatusBadge tone={statusTone(status)}>{status}</StatusBadge>{typeof trailing === "string" ? <small>{trailing}</small> : trailing}</span> actions={typeof trailing === "string" ? undefined : trailing} />;
</GlassSurface>;
} }
function PolicyCard({ label, value }: { label: string; value: string }) { function PolicyCard({ label, value }: { label: string; value: string }) {
return <GlassSurface padding="md" tone="soft"><small>{label}</small><strong>{value}</strong></GlassSurface>; return <div><small>{label}</small><strong>{value}</strong></div>;
} }
function commaList(value: string) { function commaList(value: string) {
return [...new Set(value.split(",").map((item) => item.trim()).filter(Boolean))].sort(); return [...new Set(value.split(",").map((item) => item.trim()).filter(Boolean))].sort();
} }
function statusLabel(status: string) {
return ({ active: 'Активно', accepted: 'Принято', online: 'На связи', verified: 'Подтверждено', applied: 'Применено', recorded: 'Записано', immutable: 'Сохранено', absent: 'Не обнаружено', failed: 'Ошибка', rejected: 'Отклонено', revoked: 'Отозвано', retired: 'В архиве', connecting: 'Подключение', draft: 'Черновик', provisioning: 'Подготовка', pending: 'Ожидание', pending_external_approval: 'Ожидает подтверждения', unknown: 'Нет данных', unobserved: 'Нет наблюдений', disabled: 'Отключено' } as Record<string, string>)[status] || status;
}
function statusTone(status: string): "neutral" | "success" | "warning" | "danger" { function statusTone(status: string): "neutral" | "success" | "warning" | "danger" {
if (["active", "accepted", "online", "verified", "applied", "recorded", "immutable"].includes(status)) return "success"; if (["active", "accepted", "online", "verified", "applied", "recorded", "immutable"].includes(status)) return "success";
if (["absent", "failed", "rejected", "revoked", "retired"].includes(status)) return "danger"; if (["absent", "failed", "rejected", "revoked", "retired"].includes(status)) return "danger";
+23 -95
View File
@@ -1,10 +1,10 @@
import { useEffect, useMemo, useRef, useState } from "react"; import { useEffect, useMemo, useRef, useState } from "react";
import { import {
Button, Button,
FeatureSettingsWindow,
ConfirmationModal, ConfirmationModal,
ResourceList, ResourceList,
ResourceRow, ResourceRow,
GlassSurface,
Icon, Icon,
IconButton, IconButton,
Select, Select,
@@ -39,52 +39,6 @@ export type DeviceInventoryDetailState = {
editing: boolean; editing: boolean;
}; };
export function DeviceDetailHeaderTools({
device,
detail,
canEdit,
onDetailChange,
}: {
device: DeviceView;
detail: DeviceInventoryDetailState;
canEdit: boolean;
onDetailChange: (detail: DeviceInventoryDetailState | null) => void;
}) {
const catalog = getDeviceProfileCatalog(device.modelProfileRef);
const activeSection = catalog.sections.find((section) => section.id === detail.sectionId)
?? catalog.sections[0];
return (
<div className="device-detail-header-tools">
<Select
className="device-detail-section-select"
label="Раздел устройства"
value={activeSection?.id ?? catalog.sections[0]?.id ?? "passport"}
options={catalog.sections.map((section) => ({
value: section.id,
label: section.label,
}))}
onChange={(sectionId) => onDetailChange({ ...detail, sectionId })}
placement="bottom-end"
minMenuWidth={320}
menuWidth="anchor"
variant="split"
/>
<IconButton
label={detail.editing ? "Завершить редактирование" : "Редактировать устройство"}
disabled={!canEdit}
data-active={detail.editing || undefined}
onClick={() => onDetailChange({
...detail,
editing: !detail.editing,
})}
>
<Icon name="edit" size={17} />
</IconButton>
</div>
);
}
export function DeviceInventoryView({ export function DeviceInventoryView({
workspace, workspace,
canClaim, canClaim,
@@ -155,27 +109,14 @@ export function DeviceInventoryView({
return () => window.clearInterval(timer); return () => window.clearInterval(timer);
}, [detail?.deviceRef, onError, onPoll]); }, [detail?.deviceRef, onError, onPoll]);
if (selectedDevice && detail) {
return (
<DeviceDetailView
device={selectedDevice}
detail={detail}
workspace={workspace}
canConfigure={canConfigure}
canManageProject={canManageProject}
onDetailChange={onDetailChange}
onSaved={onPoll}
onError={onError}
onBack={() => onDetailChange(null)}
/>
);
}
const remoteRows = (b2.data?.items || []).filter(() => !['pending', 'archived', 'active', 'inactive'].includes(statusFilter)) const remoteRows = (b2.data?.items || []).filter(() => !['pending', 'archived', 'active', 'inactive'].includes(statusFilter))
.sort((a, b) => a.name.localeCompare(b.name, 'ru')); .sort((a, b) => a.name.localeCompare(b.name, 'ru'));
const count = workspace.devices.filter((device) => !['suspended', 'retired'].includes(device.lifecycleState)).length + (b2.data?.items.length || 0); const count = workspace.devices.filter((device) => !['suspended', 'retired'].includes(device.lifecycleState)).length + (b2.data?.items.length || 0);
return ( return (
<div className="device-inventory"> <div className="device-inventory">
{selectedDevice && detail ? <DeviceDetailView key={selectedDevice.deviceRef} device={selectedDevice} detail={detail} workspace={workspace}
canConfigure={canConfigure} canManageProject={canManageProject} onDetailChange={onDetailChange} onSaved={onPoll} onError={onError} onBack={() => onDetailChange(null)} /> : null}
<ConfirmationModal open={Boolean(archiveTarget)} title={archiveTarget?.lifecycleState === 'suspended' ? 'Восстановить устройство?' : 'Перенести устройство в архив?'} description={archiveTarget?.displayName} confirmLabel={archiveTarget?.lifecycleState === 'suspended' ? 'Восстановить' : 'В архив'} cancelLabel="Отмена" onClose={() => { if (!archiving) setArchiveTarget(null); }} onConfirm={async () => { <ConfirmationModal open={Boolean(archiveTarget)} title={archiveTarget?.lifecycleState === 'suspended' ? 'Восстановить устройство?' : 'Перенести устройство в архив?'} description={archiveTarget?.displayName} confirmLabel={archiveTarget?.lifecycleState === 'suspended' ? 'Восстановить' : 'В архив'} cancelLabel="Отмена" onClose={() => { if (!archiving) setArchiveTarget(null); }} onConfirm={async () => {
if (!archiveTarget || archiving) return; if (!archiveTarget || archiving) return;
setArchiving(true); setArchiving(true);
@@ -225,10 +166,10 @@ export function DeviceInventoryView({
icon={<Icon name="apps" />} title={device.displayName} metadata={`${profileLabel(workspace, device)} · ${deviceIdentifierDisplayValue(device) || 'IMEI не назначен'}`} icon={<Icon name="apps" />} title={device.displayName} metadata={`${profileLabel(workspace, device)} · ${deviceIdentifierDisplayValue(device) || 'IMEI не назначен'}`}
description={lastSeenAt ? formatDate(lastSeenAt) : undefined} description={lastSeenAt ? formatDate(lastSeenAt) : undefined}
status={<StatusBadge tone={online ? 'success' : 'neutral'}>{device.lifecycleState === 'suspended' ? 'В архиве' : online ? 'Онлайн' : 'Не в сети'}</StatusBadge>} status={<StatusBadge tone={online ? 'success' : 'neutral'}>{device.lifecycleState === 'suspended' ? 'В архиве' : online ? 'Онлайн' : 'Не в сети'}</StatusBadge>}
actions={<><IconButton label={`Открыть ${device.displayName}`} onClick={() => onDetailChange({ deviceRef: device.deviceRef, sectionId: getDeviceProfileCatalog(device.modelProfileRef).sections[0]?.id ?? 'passport', editing: false })}><Icon name="chevron-right" /></IconButton> actions={<><IconButton label={`Настройки ${device.displayName}`} onClick={() => onDetailChange({ deviceRef: device.deviceRef, sectionId: getDeviceProfileCatalog(device.modelProfileRef).sections[0]?.id ?? 'passport', editing: false })}><Icon name="settings" /></IconButton>
{canManageProject && !online ? <Button size="compact" disabled={archiving} onClick={() => setArchiveTarget(device)}>{device.lifecycleState === 'suspended' ? 'Восстановить' : 'В архив'}</Button> : null}</>} /></li>)} {canManageProject && !online ? <Button size="compact" disabled={archiving} onClick={() => setArchiveTarget(device)}>{device.lifecycleState === 'suspended' ? 'Восстановить' : 'В архив'}</Button> : null}</>} /></li>)}
</ResourceList> : null} </ResourceList> : null}
{statusFilter !== 'pending' && !deviceRows.length && !remoteRows.length ? <GlassSurface className="device-manager-empty device-inventory__empty" padding="lg" tone="soft"><Icon name="inbox" size={24} /><h3>{!b2.data && !b2.error ? 'Загрузка устройств…' : b2.error || b2.data?.hosts.some((host) => !host.reachable) ? 'Реестр VPS недоступен' : statusFilter === 'archived' ? 'Архив пуст' : count ? 'Нет устройств с таким состоянием' : 'В проекте пока нет устройств'}</h3></GlassSurface> : null} {statusFilter !== 'pending' && !deviceRows.length && !remoteRows.length ? <div className="device-manager-empty device-inventory__empty"><Icon name="inbox" size={24} /><h3>{!b2.data && !b2.error ? 'Загрузка устройств…' : b2.error || b2.data?.hosts.some((host) => !host.reachable) ? 'Реестр VPS недоступен' : statusFilter === 'archived' ? 'Архив пуст' : count ? 'Нет устройств с таким состоянием' : 'В проекте пока нет устройств'}</h3></div> : null}
{(statusFilter === "pending" || statusFilter === "all" && pendingEnrollments.length > 0) ? ( {(statusFilter === "pending" || statusFilter === "all" && pendingEnrollments.length > 0) ? (
<section className="device-inventory__pending" aria-label="Ожидают подключения"> <section className="device-inventory__pending" aria-label="Ожидают подключения">
@@ -254,9 +195,9 @@ export function DeviceInventoryView({
<p className="device-manager-card-copy">После первого пакета устройство можно принять в реестр. Исходный идентификатор в интерфейсе не раскрывается.</p> <p className="device-manager-card-copy">После первого пакета устройство можно принять в реестр. Исходный идентификатор в интерфейсе не раскрывается.</p>
</SettingsCard> </SettingsCard>
)) : ( )) : (
<GlassSurface className="device-manager-panel-empty device-inventory__pending-empty" padding="md" tone="soft"> <div className="device-manager-panel-empty device-inventory__pending-empty">
Нет ожидающих подключений. Нет ожидающих подключений.
</GlassSurface> </div>
)} )}
</section> </section>
) : null} ) : null}
@@ -407,35 +348,21 @@ function DeviceDetailView({
}; };
return ( return (
<FeatureSettingsWindow open title="Настройки устройства" subtitle={workspace.project.name}
identity={{ title: device.displayName, subtitle: `${catalog.vendor} · ${catalog.model}`, avatarLabel: catalog.vendor.slice(0, 2) }}
sections={catalog.sections.map((section) => ({ id: section.id, label: section.label }))}
activeSection={activeSection.id} onSectionChange={(sectionId) => onDetailChange({ ...detail, sectionId })} onClose={onBack}
headerActions={<><IconButton label="Обновить устройство" disabled={saving} onClick={() => void onSaved().catch(onError)}><Icon name="refresh" /></IconButton>
{(canConfigure || canManageProject) ? <IconButton label={detail.editing ? 'Завершить редактирование' : 'Редактировать устройство'} disabled={saving} onClick={() => onDetailChange({ ...detail, editing: !detail.editing })}><Icon name="edit" /></IconButton> : null}</>}>
<div ref={detailRef} className="device-detail"> <div ref={detailRef} className="device-detail">
<div className="device-detail__header"> <div className="device-detail__connection">
<IconButton label="Вернуться к списку устройств" onClick={onBack}>
<Icon name="chevron-left" size={18} />
</IconButton>
<div className="device-detail__identity">
<small>{catalog.vendor} · {catalog.model}</small>
<h2>{device.displayName}</h2>
<p>{identifierDisplayValue || "Идентификатор не назначен"} · {device.modelProfileRef}</p>
</div>
<StatusBadge tone={session?.lifecycleState === "online" ? "success" : "neutral"}>
{session?.lifecycleState === "online" ? "Онлайн" : session?.lifecycleState || device.lifecycleState}
</StatusBadge>
</div>
<div className="device-detail__legend" aria-label="Режимы доступа">
<AccessBadge access="read-only" />
<AccessBadge access="managed" />
<AccessBadge access="protected" />
</div>
<GlassSurface className="device-detail__connection" padding="md" tone="soft">
<div><span>Состояние связи</span><strong>{session?.lifecycleState || device.session?.state || "Нет сессии"}</strong></div> <div><span>Состояние связи</span><strong>{session?.lifecycleState || device.session?.state || "Нет сессии"}</strong></div>
<div><span>Маршрут</span><strong>{session?.routeName || "Не определён"}</strong></div> <div><span>Маршрут</span><strong>{session?.routeName || "Не определён"}</strong></div>
<div><span>Протокол</span><strong>{session?.protocol || profile?.protocol || "Нет данных"}</strong></div> <div><span>Протокол</span><strong>{session?.protocol || profile?.protocol || "Нет данных"}</strong></div>
<div><span>Последняя активность</span><strong>{formatDate(session?.lastSeenAt || device.session?.lastSeenAt)}</strong></div> <div><span>Последняя активность</span><strong>{formatDate(session?.lastSeenAt || device.session?.lastSeenAt)}</strong></div>
<div><span>Пакеты</span><strong>{session?.frameCount ?? 0}</strong></div> <div><span>Пакеты</span><strong>{session?.frameCount ?? 0}</strong></div>
<div><span>Подключено</span><strong>{formatDate(session?.connectedAt)}</strong></div> <div><span>Подключено</span><strong>{formatDate(session?.connectedAt)}</strong></div>
</GlassSurface> </div>
<div className="device-detail__layout"> <div className="device-detail__layout">
<section className="device-detail-section"> <section className="device-detail-section">
@@ -465,7 +392,7 @@ function DeviceDetailView({
? draftValues[item.path] ? draftValues[item.path]
: readPath(context, item.path); : readPath(context, item.path);
return ( return (
<GlassSurface key={item.key} className="device-detail-field" padding="sm" tone="soft" data-access={access} data-editing={editable || undefined}> <div key={item.key} className="device-detail-field" data-access={access} data-editing={editable || undefined}>
{editable && item.valueKind === "boolean" ? ( {editable && item.valueKind === "boolean" ? (
<Switch <Switch
checked={Boolean(value)} checked={Boolean(value)}
@@ -493,7 +420,7 @@ function DeviceDetailView({
{item.description ? <small>{item.description}</small> : null} {item.description ? <small>{item.description}</small> : null}
</> </>
)} )}
</GlassSurface> </div>
); );
})} })}
</div> </div>
@@ -524,14 +451,15 @@ function DeviceDetailView({
) : null} ) : null}
<div className="device-detail-section__state"> <div className="device-detail-section__state">
<span>Desired</span> <span>Запрошенная конфигурация</span>
<strong>{configurationState?.desiredConfigurationRevisionRef || "Не задано"}</strong> <strong>{configurationState?.desiredConfigurationRevisionRef || "Не задано"}</strong>
<span>Applied</span> <span>Подтверждена устройством</span>
<strong>{configurationState?.appliedConfigurationRevisionRef || "Не подтверждено"}</strong> <strong>{configurationState?.appliedConfigurationRevisionRef || "Не подтверждено"}</strong>
</div> </div>
</section> </section>
</div> </div>
</div> </div>
</FeatureSettingsWindow>
); );
} }
@@ -604,12 +532,12 @@ function AccessNotice({
commandTransport: ProjectWorkspace["policies"]["commandTransport"]; commandTransport: ProjectWorkspace["policies"]["commandTransport"];
}) { }) {
if (access === "read-only") { if (access === "read-only") {
return <GlassSurface className="device-detail-notice" padding="sm" tone="soft"><Icon name="lock" size={15} /><span>Этот блок отражает фактическое состояние устройства и не редактируется.</span></GlassSurface>; return <div className="device-detail-notice"><Icon name="lock" size={15} /><span>Этот блок отражает фактическое состояние устройства и не редактируется.</span></div>;
} }
if (access === "protected") { if (access === "protected") {
return <GlassSurface className="device-detail-notice" padding="sm" tone="soft"><Icon name="shield" size={15} /><span>Операция требует отдельного подтверждения. Обновление прошивки пилотного B2 запрещено.</span></GlassSurface>; return <div className="device-detail-notice"><Icon name="shield" size={15} /><span>Операция требует отдельного подтверждения. Обновление прошивки пилотного B2 запрещено.</span></div>;
} }
return <GlassSurface className="device-detail-notice" padding="sm" tone="soft"><Icon name="settings" size={15} /><span>{commandTransport === "typed-service-ping-v1" ? "Изменение создаёт новую desired-ревизию. Статус Applied появится только после подтверждения устройством." : "Настройка поддерживается моделью, но запись включится только после запуска двустороннего командного канала."}</span></GlassSurface>; return <div className="device-detail-notice"><Icon name="settings" size={15} /><span>{commandTransport === "typed-service-ping-v1" ? "Изменение создаёт новую desired-ревизию. Статус Applied появится только после подтверждения устройством." : "Настройка поддерживается моделью, но запись включится только после запуска двустороннего командного канала."}</span></div>;
} }
function latestSession(workspace: ProjectWorkspace, device: DeviceView): SessionView | null { function latestSession(workspace: ProjectWorkspace, device: DeviceView): SessionView | null {
+13 -31
View File
@@ -9,6 +9,8 @@ import {
Dropdown, Dropdown,
FeatureSettingsWindow, FeatureSettingsWindow,
GlassSurface, GlassSurface,
ResourceList,
ResourceRow,
HeaderNavigation, HeaderNavigation,
HeaderProfile, HeaderProfile,
HeaderWorkspace, HeaderWorkspace,
@@ -61,7 +63,6 @@ import {
type ControlViewId, type ControlViewId,
} from "./DeviceControlViews"; } from "./DeviceControlViews";
import { import {
DeviceDetailHeaderTools,
DeviceInventoryView, DeviceInventoryView,
type DeviceInventoryDetailState, type DeviceInventoryDetailState,
} from "./DeviceInventoryView"; } from "./DeviceInventoryView";
@@ -348,9 +349,6 @@ export function DeviceManagerApp() {
} }
const activeView = visibleNavigationItems.some((item) => item.id === shell.activeView) ? shell.activeView : null; const activeView = visibleNavigationItems.some((item) => item.id === shell.activeView) ? shell.activeView : null;
const selectedInventoryDevice = inventoryDetail
? workspace?.devices.find((device) => device.deviceRef === inventoryDetail.deviceRef) ?? null
: null;
return ( return (
<> <>
<ApplicationShell <ApplicationShell
@@ -493,14 +491,6 @@ export function DeviceManagerApp() {
expanded={shell.contentExpanded} expanded={shell.contentExpanded}
onExpandedChange={shell.setContentExpanded} onExpandedChange={shell.setContentExpanded}
onClose={shell.closeView} onClose={shell.closeView}
headerTools={activeView === "inventory" && selectedInventoryDevice && inventoryDetail ? (
<DeviceDetailHeaderTools
device={selectedInventoryDevice}
detail={inventoryDetail}
canEdit={canConfigure || canManageProject}
onDetailChange={setInventoryDetail}
/>
) : undefined}
utilityActions={[...(activeView === "hosts" && selectedHostRef ? [{ utilityActions={[...(activeView === "hosts" && selectedHostRef ? [{
label: "Вернуться к VPS и хостам", icon: "chevron-left" as const, onClick: () => setSelectedHostRef(null), label: "Вернуться к VPS и хостам", icon: "chevron-left" as const, onClick: () => setSelectedHostRef(null),
}] : []), { }] : []), {
@@ -791,11 +781,9 @@ function EnvironmentBackdrop({
function Metric({ label, value, detail, tone = "neutral" }: { label: string; value: number; detail: string; tone?: "neutral" | "success" | "warning" }) { function Metric({ label, value, detail, tone = "neutral" }: { label: string; value: number; detail: string; tone?: "neutral" | "success" | "warning" }) {
return ( return (
<GlassSurface className="device-manager-metric" padding="md" tone="soft"> <SettingsCard title={label}>
<span>{label}</span> <ResourceRow title={String(value)} metadata={detail} status={<StatusBadge variant="indicator" tone={tone} aria-label={label} />} />
<strong>{value}</strong> </SettingsCard>
<StatusBadge tone={tone}>{detail}</StatusBadge>
</GlassSurface>
); );
} }
@@ -846,7 +834,7 @@ function ProjectView({ selectedHostRef, onSelectHost, view, workspace, canManage
if (view === "collections") return ( if (view === "collections") return (
<div className="device-manager-stack"> <div className="device-manager-stack">
<div className="device-manager-panel-toolbar"> <div className="device-manager-panel-toolbar">
<p>Коллекции группируют устройства для последующих bindings и задач.</p> <p>Группы устройств проекта.</p>
<Button icon={<Icon name="plus" />} disabled={!canManageCollections} onClick={onCreateCollection}>Новая коллекция</Button> <Button icon={<Icon name="plus" />} disabled={!canManageCollections} onClick={onCreateCollection}>Новая коллекция</Button>
</div> </div>
<EntityList <EntityList
@@ -863,9 +851,9 @@ function ProjectView({ selectedHostRef, onSelectHost, view, workspace, canManage
); );
return ( return (
<div className="device-manager-overview-grid"> <div className="device-manager-overview-grid">
<Metric label="Устройства" value={workspace.devices.length} detail="inventory" /> <Metric label="Устройства" value={workspace.devices.length} detail="В реестре" />
<Metric label="Quarantine" value={workspace.discoveries.filter((item) => item.lifecycleState === "quarantine").length} detail="safe projection" /> <Metric label="Ожидают проверки" value={workspace.discoveries.filter((item) => item.lifecycleState === "quarantine").length} detail="Обнаружены" />
<Metric label="Коллекции" value={workspace.collections.length} detail="bindings ready" /> <Metric label="Коллекции" value={workspace.collections.length} detail="Группы устройств" />
<SettingsCard title="Права проекта" description={workspace.project.access.projectRole || "read"}> <SettingsCard title="Права проекта" description={workspace.project.access.projectRole || "read"}>
<div className="device-manager-capabilities"> <div className="device-manager-capabilities">
{workspace.project.access.capabilities.map((capability) => <StatusBadge key={capability}>{capability}</StatusBadge>)} {workspace.project.access.capabilities.map((capability) => <StatusBadge key={capability}>{capability}</StatusBadge>)}
@@ -1253,13 +1241,9 @@ function EnvironmentSettingsDialog({ open, presentation, onClose, onSaved, onErr
function EntityList({ items, empty }: { items: Array<{ id: string; title: string; subtitle: string; status: string; tone: "neutral" | "success" | "warning" }>; empty: string }) { function EntityList({ items, empty }: { items: Array<{ id: string; title: string; subtitle: string; status: string; tone: "neutral" | "success" | "warning" }>; empty: string }) {
if (!items.length) return <div className="device-manager-panel-empty">{empty}</div>; if (!items.length) return <div className="device-manager-panel-empty">{empty}</div>;
return <div className="device-manager-entity-list">{items.map((item) => ( return <ResourceList>{items.map((item) => <li key={item.id}><ResourceRow
<GlassSurface key={item.id} className="device-manager-entity" padding="md" tone="soft"> icon={<Icon name="folder" />} title={item.title} description={item.subtitle}
<span className="device-manager-entity__icon"><Icon name="circle" /></span> status={<StatusBadge tone={item.tone}>{item.status}</StatusBadge>} /></li>)}</ResourceList>;
<span className="device-manager-entity__body"><strong>{item.title}</strong><small>{item.subtitle}</small></span>
<StatusBadge tone={item.tone}>{item.status}</StatusBadge>
</GlassSurface>
))}</div>;
} }
function ProjectDialog({ open, ownerScopes, initialOwnerRef, onClose, onCreated, onError }: { function ProjectDialog({ open, ownerScopes, initialOwnerRef, onClose, onCreated, onError }: {
@@ -1299,7 +1283,7 @@ function ProjectDialog({ open, ownerScopes, initialOwnerRef, onClose, onCreated,
await onCreated(); await onCreated();
} catch (reason) { onError(reason); } finally { setPending(false); } } catch (reason) { onError(reason); } finally { setPending(false); }
}; };
return <Window open={open} title="Новый Device Project" subtitle={ownerScope?.displayName || "Owner scope недоступен"} onClose={onClose} footer={ return <Window open={open} title="Новый проект" subtitle={ownerScope?.displayName || "Компания недоступна"} onClose={onClose} footer={
<WindowFooterActions><Button variant="ghost" onClick={onClose}>Отмена</Button><Button type="submit" form="device-project-form" variant="primary" disabled={pending || !ownerScope}>{pending ? "Создаём…" : "Создать"}</Button></WindowFooterActions> <WindowFooterActions><Button variant="ghost" onClick={onClose}>Отмена</Button><Button type="submit" form="device-project-form" variant="primary" disabled={pending || !ownerScope}>{pending ? "Создаём…" : "Создать"}</Button></WindowFooterActions>
}> }>
<form id="device-project-form" className="device-manager-form" onSubmit={submit}> <form id="device-project-form" className="device-manager-form" onSubmit={submit}>
@@ -1373,7 +1357,6 @@ function ClaimDialog({ enrollment, project, onClose, onClaimed, onError }: {
<form id="device-claim-form" className="device-manager-form" onSubmit={submit}> <form id="device-claim-form" className="device-manager-form" onSubmit={submit}>
<TextField label="Название устройства" value={name} onChange={(event) => setName(event.target.value)} required maxLength={160} /> <TextField label="Название устройства" value={name} onChange={(event) => setName(event.target.value)} required maxLength={160} />
<TextField label="Ключ устройства" value={key} onChange={(event) => setKey(event.target.value.toLowerCase())} required pattern="[a-z][a-z0-9-]{1,62}" /> <TextField label="Ключ устройства" value={key} onChange={(event) => setKey(event.target.value.toLowerCase())} required pattern="[a-z][a-z0-9-]{1,62}" />
<p className="device-manager-card-copy">Claim использует только ссылки на enrollment и discovery. Исходный идентификатор не запрашивается повторно.</p>
</form> </form>
</Window>; </Window>;
} }
@@ -1452,7 +1435,6 @@ function EnrollmentDialog({ open, workspace, onClose, onCreated, onError }: {
<TextField label="Ключ enrollment" value={key} onChange={(event) => setKey(event.target.value.toLowerCase())} required pattern="[a-z][a-z0-9-]{1,62}" /> <TextField label="Ключ enrollment" value={key} onChange={(event) => setKey(event.target.value.toLowerCase())} required pattern="[a-z][a-z0-9-]{1,62}" />
<TextField label="IMEI" value={imei} onChange={(event) => setImei(event.target.value.replace(/\D/g, "").slice(0, 15))} required pattern="[0-9]{15}" inputMode="numeric" autoComplete="off" /> <TextField label="IMEI" value={imei} onChange={(event) => setImei(event.target.value.replace(/\D/g, "").slice(0, 15))} required pattern="[0-9]{15}" inputMode="numeric" autoComplete="off" />
<TextField label="Истекает" type="datetime-local" value={expiresAt} onChange={(event) => setExpiresAt(event.target.value)} description="Опционально. Время будет сохранено в UTC." /> <TextField label="Истекает" type="datetime-local" value={expiresAt} onChange={(event) => setExpiresAt(event.target.value)} description="Опционально. Время будет сохранено в UTC." />
<p className="device-manager-card-copy">IMEI передаётся один раз по HTTPS в Device Control Core. В базе, audit и ответе останутся только HMAC и маска.</p>
</form> </form>
</Window>; </Window>;
} }
+81 -80
View File
@@ -1,12 +1,11 @@
import { useEffect, useRef, useState } from 'react'; import { useEffect, useRef, useState } from 'react';
import { Button, FeatureSettingsWindow, Icon, IconButton, Select, SettingsCard, StatusBadge, TextField, TextAreaField, WindowFooterActions, ConfirmationModal, ResourceList, ResourceRow } from '@nodedc/ui-react'; import { Button, FeatureSettingsWindow, Icon, IconButton, Select, SettingsCard, StatusBadge, TextField, TextAreaField, ConfirmationModal, ResourceList, ResourceRow } from '@nodedc/ui-react';
import { loadProjects } from '../api'; import { loadProjects } from '../api';
import type { InfrastructureHostView, ProjectSummary, ProjectWorkspace } from '../types'; import type { InfrastructureHostView, ProjectSummary, ProjectWorkspace } from '../types';
import { b2Request, type B2Status } from './api'; import { b2Request, type B2Status, type B2Application } from './api';
import './b2.css'; import './b2.css';
type Section = 'connection' | 'contours'; type Section = 'connection' | 'contours';
type Form = 'contour' | 'application' | 'project' | null;
export function B2HostSettings({ host, workspace, onClose, onChanged, onError }: { export function B2HostSettings({ host, workspace, onClose, onChanged, onError }: {
host: InfrastructureHostView; workspace: ProjectWorkspace; onClose: () => void; host: InfrastructureHostView; workspace: ProjectWorkspace; onClose: () => void;
onChanged: () => Promise<void>; onError: (error: unknown) => void; onChanged: () => Promise<void>; onError: (error: unknown) => void;
@@ -15,117 +14,119 @@ export function B2HostSettings({ host, workspace, onClose, onChanged, onError }:
const [section, setSection] = useState<Section>('contours'); const [section, setSection] = useState<Section>('contours');
const [status, setStatus] = useState<B2Status | null>(null); const [status, setStatus] = useState<B2Status | null>(null);
const [pending, setPending] = useState('load'); const [pending, setPending] = useState('load');
const [connection, setConnection] = useState(''); const [connection, setConnection] = useState(''), [importOpen, setImportOpen] = useState(false);
const connectionFile = useRef<HTMLInputElement>(null); const connectionFile = useRef<HTMLInputElement>(null);
const [key, setKey] = useState(''), [name, setName] = useState('');
const [contourId, setContourId] = useState(''), [applicationId, setApplicationId] = useState('');
const [form, setForm] = useState<Form>(null);
const [showHistory, setShowHistory] = useState(false), [showInactive, setShowInactive] = useState(false);
const [targetProject, setTargetProject] = useState(project.projectRef);
const [projects, setProjects] = useState<ProjectSummary[]>([]); const [projects, setProjects] = useState<ProjectSummary[]>([]);
const [issued, setIssued] = useState(''); const [expanded, setExpanded] = useState<string[]>([]), [keyRows, setKeyRows] = useState<string[]>([]);
const [creating, setCreating] = useState(''), [name, setName] = useState('');
const [creationIntent, setCreationIntent] = useState<{ id: string; name: string } | null>(null);
const [history, setHistory] = useState<string[]>([]);
const [issued, setIssued] = useState<{ application: string; value: string } | null>(null);
const [confirm, setConfirm] = useState<{ action: string; fields: Record<string, unknown>; text: string } | null>(null); const [confirm, setConfirm] = useState<{ action: string; fields: Record<string, unknown>; text: string } | null>(null);
const request = <T,>(action: string, data: Record<string, unknown> = {}) => b2Request<T>(project.projectRef, host.hostRef, action, data); const request = <T,>(action: string, data: Record<string, unknown> = {}, requestId?: string) => b2Request<T>(project.projectRef, host.hostRef, action, data, requestId);
const refresh = () => request<B2Status>('status').then(setStatus); const refresh = () => request<B2Status>('status').then(setStatus);
useEffect(() => { useEffect(() => {
let active = true; let active = true;
Promise.all([request<B2Status>('status'), loadProjects()]).then(([value, available]) => { Promise.all([request<B2Status>('status'), loadProjects()]).then(([value, available]) => {
if (!active) return; if (!active) return;
setStatus(value); if (!value.connected) setSection('connection'); setStatus(value); if (!value.connected) { setSection('connection'); setImportOpen(true); }
setProjects(available.filter((item) => item.ownerScope.ownerScopeRef === project.ownerScope.ownerScopeRef)); setProjects(available.filter((item) => item.ownerScope.ownerScopeRef === project.ownerScope.ownerScopeRef));
}).catch((error) => { if (active) onError(error); }).finally(() => { if (active) setPending(''); }); }).catch((error) => { if (active) onError(error); }).finally(() => { if (active) setPending(''); });
return () => { active = false; }; return () => { active = false; };
}, [host.hostRef, project.projectRef]); }, [host.hostRef, project.projectRef]);
async function run(action: string, data: Record<string, unknown> = {}) { async function run(action: string, data: Record<string, unknown> = {}, requestId?: string) {
setPending(action); setPending(action);
try { try {
const result = await request<{ connection?: unknown; id?: string }>(action, data); const result = await request<{ connection?: unknown; id?: string }>(action, data, requestId);
if (result.connection) setIssued(JSON.stringify(result.connection, null, 2)); if (result.connection) setIssued({ application: String(data.name || name || 'Приложение'), value: JSON.stringify(result.connection, null, 2) });
if (action === 'connect') { setConnection(''); setSection('contours'); } if (action === 'connect') { setConnection(''); setImportOpen(false); setSection('contours'); }
if (action === 'contour-create' && result.id) { setContourId(result.id); setApplicationId(''); } setCreating(''); setName(''); setCreationIntent(null);
if (action === 'application-create' && result.id) setApplicationId(result.id);
setForm(null); setName(''); setKey('');
// A successful mutation must not be presented as failed if a subsequent read fails.
try { await refresh(); await onChanged(); } catch (error) { onError(error); } try { await refresh(); await onChanged(); } catch (error) { onError(error); }
return true; return true;
} catch (error) { onError(error); return false; } finally { setPending(''); } } catch (error) { onError(error); await refresh().catch(() => undefined); return false; } finally { setPending(''); }
} }
const contours = status?.contours || [], selected = contours.find((item) => item.id === contourId);
const linkedProject = status?.links?.find((item) => item.contourId === contourId)?.projectRef;
const applications = (status?.applications || []).filter((app) => app.authority !== 'host' && app.key !== 'legacy-mission-core' && app.grants[contourId]);
const application = applications.find((app) => app.id === applicationId);
const inactive = (app: typeof applications[number]) => app.credentials.length > 0 && !app.credentials.some((item) => item.enabled);
const busy = Boolean(pending), canManage = status?.authority === 'host'; const busy = Boolean(pending), canManage = status?.authority === 'host';
const begin = (value: Form) => { setForm(value); setName(''); setKey(''); setTargetProject(project.projectRef); }; const toggle = (items: string[], id: string) => items.includes(id) ? items.filter((value) => value !== id) : [...items, id];
const back = () => {
setIssued(''); setShowHistory(false);
if (form) setForm(null); else if (applicationId) setApplicationId(''); else { setContourId(''); setShowInactive(false); }
};
function downloadIssuedKey() { function downloadIssuedKey() {
const url = URL.createObjectURL(new Blob([issued + '\n'], { type: 'application/json' })); if (!issued) return;
const url = URL.createObjectURL(new Blob([issued.value + '\n'], { type: 'application/json' }));
const link = document.createElement('a'); link.href = url; link.download = 'arnavi-application-key.json'; const link = document.createElement('a'); link.href = url; link.download = 'arnavi-application-key.json';
document.body.append(link); link.click(); link.remove(); window.setTimeout(() => URL.revokeObjectURL(url), 1000); document.body.append(link); link.click(); link.remove(); window.setTimeout(() => URL.revokeObjectURL(url), 1000);
} }
function applicationRow(app: B2Application) {
const legacy = app.key === 'legacy-mission-core';
const open = keyRows.includes(app.id), active = app.credentials.some((item) => item.enabled);
return <li key={app.id} className="b2-disclosure">
<ResourceRow title={app.name} metadata={legacy ? 'Mission Core · совместимое подключение' : active ? 'Ключ выдан' : 'Нет действующего ключа'}
actions={!legacy ? <IconButton label={`Ключи ${app.name}`} aria-expanded={open} aria-controls={`keys-${app.id}`} onClick={() => setKeyRows(toggle(keyRows, app.id))}><Icon name={open ? 'chevron-up' : 'chevron-down'} /></IconButton> : undefined} />
{open && !legacy ? <div id={`keys-${app.id}`} className="b2-disclosure__body">
<ResourceList>{app.credentials.filter((item) => item.enabled || history.includes(app.id)).map((item) => <li key={item.client_id}><ResourceRow
title={<code className="b2-key-id">{item.client_id}</code>} metadata="ID ключа"
status={<StatusBadge>{item.enabled ? 'Действует' : 'Отозван'}</StatusBadge>}
actions={item.enabled && canManage ? <Button size="compact" disabled={busy} onClick={() => setConfirm({ action: 'key-revoke', fields: { clientId: item.client_id }, text: `Отозвать ключ «${app.name}»?` })}>Отозвать</Button> : undefined} /></li>)}</ResourceList>
<div className="b2-actions">
{app.credentials.some((item) => !item.enabled) ? <Button variant="ghost" onClick={() => setHistory(toggle(history, app.id))}>{history.includes(app.id) ? 'Скрыть историю' : 'История ключей'}</Button> : null}
{canManage ? <Button disabled={busy} onClick={() => setConfirm({ action: 'key-issue', fields: { integrationId: app.id, replace: active }, text: active ? `Перевыпустить ключ «${app.name}»? Прежний ключ перестанет работать.` : `Выдать ключ «${app.name}»?` })}>{active ? 'Перевыпустить ключ' : 'Выдать ключ'}</Button> : null}
</div>
</div> : null}
</li>;
}
return <> return <>
<FeatureSettingsWindow open title="Настройки VPS" subtitle={project.ownerScope.displayName} <FeatureSettingsWindow open title="Настройки VPS" subtitle={project.ownerScope.displayName}
identity={{ title: host.displayName, subtitle: status?.endpoint || 'ARNavi VPS', avatarLabel: 'VPS' }} identity={{ title: host.displayName, subtitle: status?.endpoint || 'ARNavi VPS', avatarLabel: 'VPS' }}
sections={[{ id: 'connection', label: 'Подключение', icon: 'network' }, { id: 'contours', label: 'Контуры', icon: 'layers', disabled: !status?.connected }]} sections={[{ id: 'connection', label: 'Сервер', icon: 'network' }, { id: 'contours', label: 'Контуры', icon: 'layers', disabled: !status?.connected }]}
activeSection={section} onSectionChange={(value) => { setSection(value); setForm(null); setIssued(''); }} onClose={onClose} activeSection={section} onSectionChange={setSection} onClose={onClose}
footer={<WindowFooterActions> headerActions={<IconButton label="Обновить состояние VPS" loading={pending === 'refresh'} disabled={busy} onClick={async () => {
{section === 'contours' && (selected || form) ? <IconButton label={form ? 'Отменить создание' : application ? 'К приложениям контура' : 'К списку контуров'} disabled={busy} onClick={back}><Icon name="chevron-left" /></IconButton> : null}
<IconButton label="Обновить состояние VPS" loading={pending === 'refresh'} disabled={busy} onClick={async () => {
setPending('refresh'); try { await refresh(); } catch (error) { onError(error); } finally { setPending(''); } setPending('refresh'); try { await refresh(); } catch (error) { onError(error); } finally { setPending(''); }
}}><Icon name="refresh" /></IconButton> }}><Icon name="refresh" /></IconButton>}>
</WindowFooterActions>}>
<div className="b2-settings" aria-busy={busy}> <div className="b2-settings" aria-busy={busy}>
{issued ? <SettingsCard title={`Ключ · ${issued.application}`} description="Сохраните ключ — повторный просмотр недоступен."><div className="b2-settings">
<TextAreaField label="Ключ подключения приложения" value={issued.value} readOnly rows={4} />
<div className="b2-actions"><Button onClick={downloadIssuedKey}>Скачать файл</Button><Button onClick={() => navigator.clipboard.writeText(issued.value).catch(onError)}>Скопировать</Button><Button onClick={() => setIssued(null)}>Скрыть</Button></div>
</div></SettingsCard> : null}
{section === 'connection' ? <> {section === 'connection' ? <>
<ResourceRow title={host.displayName} description={status?.endpoint} status={<StatusBadge tone={status?.connected ? 'success' : 'neutral'}>{status?.connected ? 'Подключён' : pending === 'load' ? 'Подключение…' : 'Не подключён'}</StatusBadge>} /> <ResourceRow title={host.displayName} description={status?.endpoint} metadata="Подключение Device Core к серверу ARNavi"
<SettingsCard title={status?.connected ? 'Заменить ключ сервера' : 'Подключить сервер'}> status={<StatusBadge tone={status?.connected ? 'success' : 'neutral'}>{status?.connected ? 'Доступен' : pending === 'load' ? 'Проверка…' : 'Не подключён'}</StatusBadge>}
<div className="b2-settings"> actions={<IconButton label="Импортировать ключ доступа Device Core" aria-expanded={importOpen} onClick={() => setImportOpen(!importOpen)}><Icon name="key" /></IconButton>} />
<Button disabled={busy} onClick={() => connectionFile.current?.click()}><Icon name="upload" />Загрузить файл ключа</Button> {importOpen ? <SettingsCard title="Доступ Device Core к VPS" description="Файл доступа выдаёт администратор этого VPS."><div className="b2-settings">
<input ref={connectionFile} type="file" accept=".json,application/json" hidden aria-label="Файл ключа подключения VPS" disabled={busy} onChange={async (event) => { <Button disabled={busy} onClick={() => connectionFile.current?.click()}><Icon name="upload" />Загрузить файл доступа</Button>
<input ref={connectionFile} type="file" accept=".json,application/json" hidden aria-label="Файл доступа к VPS" disabled={busy} onChange={async (event) => {
const file = event.currentTarget.files?.[0]; event.currentTarget.value = ''; if (!file) return; setPending('file'); const file = event.currentTarget.files?.[0]; event.currentTarget.value = ''; if (!file) return; setPending('file');
try { if (file.size > 16384) throw new Error(); const text = await file.text(); JSON.parse(text); setConnection(text); } try { if (file.size > 16384) throw new Error(); const text = await file.text(); JSON.parse(text); setConnection(text); }
catch { onError(new Error('Не удалось прочитать файл ключа VPS.')); } finally { setPending(''); } catch { onError(new Error('Не удалось прочитать файл доступа.')); } finally { setPending(''); }
}} /> }} />
<TextAreaField label="Ключ сервера" value={connection} autoComplete="off" spellCheck={false} onChange={(event) => setConnection(event.target.value)} rows={4} /> <TextAreaField label="Содержимое файла доступа" value={connection} autoComplete="off" spellCheck={false} onChange={(event) => setConnection(event.target.value)} rows={4} />
<Button loading={pending === 'connect'} disabled={busy || !connection.trim()} onClick={() => void run('connect', { connection })}>Подключить</Button> <div className="b2-actions"><Button disabled={busy} onClick={() => { setImportOpen(false); setConnection(''); }}>Отмена</Button><Button loading={pending === 'connect'} disabled={busy || !connection.trim()} onClick={() => void run('connect', { connection })}>{status?.connected ? 'Обновить доступ Device Core' : 'Подключить Device Core'}</Button></div>
</div> </div></SettingsCard> : null}
</SettingsCard>
</> : null} </> : null}
{section === 'contours' ? <> {section === 'contours' ? <ResourceList>{projects.map((item) => {
<div className="b2-path" aria-label="Текущий раздел">{[host.displayName, selected?.name, application?.name].filter(Boolean).join(' / ')}</div> const links = (status?.links || []).filter((link) => link.projectRef === item.projectRef);
{form === 'contour' || form === 'application' ? <SettingsCard title={form === 'contour' ? 'Новый контур' : 'Новое приложение'}> const linked = links.length > 0, open = expanded.includes(item.projectRef);
<div className="b2-settings"> const apps = (status?.applications || []).filter((app) => app.authority !== 'host' && links.some((link) => app.grants[link.contourId]));
{form === 'application' ? <ResourceRow title={selected?.name} metadata="Контур" /> : null} const available = (status?.contours || []).filter((contour) => !status?.links?.some((link) => link.contourId === contour.id));
<TextField label="Название" value={name} maxLength={160} onChange={(e) => setName(e.target.value)} /> return <li key={item.projectRef} className="b2-disclosure">
<TextField label="Код" value={key} placeholder={form === 'contour' ? 'robot2b' : 'delivery-app'} onChange={(e) => setKey(e.target.value.toLowerCase())} /> <ResourceRow title={item.name} metadata={linked ? 'Контур VPS связан с проектом' : 'Проект Device Core'}
<div className="b2-actions"><Button onClick={() => setForm(null)} disabled={busy}>Отмена</Button><Button loading={busy} disabled={busy || !name.trim() || !/^[a-z][a-z0-9-]{0,63}$/.test(key)} onClick={() => void run(form === 'contour' ? 'contour-create' : 'application-create', { key, name, ...(form === 'application' ? { contourId } : {}) })}>Создать</Button></div> actions={<IconButton label={`Контур ${item.name}`} aria-expanded={open} aria-controls={`contour-${item.projectRef}`} onClick={() => setExpanded(toggle(expanded, item.projectRef))}><Icon name={open ? 'chevron-up' : 'chevron-down'} /></IconButton>} />
</div> {open ? <div id={`contour-${item.projectRef}`} className="b2-disclosure__body">
</SettingsCard> : form === 'project' ? <SettingsCard title="Проект Device Core"><div className="b2-settings"> {!linked ? <>
<ResourceRow title={selected?.name} metadata="Контур VPS" /><Select label="Проект" value={targetProject} onChange={setTargetProject} options={projects.map((p) => ({ value: p.projectRef, label: p.name }))} /> {canManage ? <Button disabled={busy} loading={pending === 'project-connect'} onClick={() => void run('project-connect', { targetProjectRef: item.projectRef })}>Подключить проект к VPS</Button> : null}
<div className="b2-actions"><Button disabled={busy} onClick={() => setForm(null)}>Отмена</Button><Button disabled={busy || !targetProject} loading={pending === 'link'} onClick={() => void run('link', { contourId, targetProjectRef: targetProject })}>Связать</Button></div> {available.length ? <Select label="Связать с существующим контуром" value="" options={[{ value: '', label: 'Выбрать контур VPS' }, ...available.map((c) => ({ value: c.id, label: c.name }))]} onChange={(contourId) => { if (contourId) void run('link', { contourId, targetProjectRef: item.projectRef }); }} disabled={busy} /> : null}
</div></SettingsCard> : !selected ? <SettingsCard title="Контуры" actions={canManage ? <IconButton label="Создать контур" disabled={busy} onClick={() => begin('contour')}><Icon name="plus" /></IconButton> : undefined}>
<ResourceList>{contours.map((item) => {
const link = status?.links?.find((value) => value.contourId === item.id), projectName = projects.find((p) => p.projectRef === link?.projectRef)?.name;
return <li key={item.id}><ResourceRow title={item.name} metadata={projectName ? `Проект: ${projectName}` : 'Проект не связан'} actions={<IconButton label={`Открыть контур ${item.name}`} disabled={busy} onClick={() => { setContourId(item.id); setApplicationId(''); }}><Icon name="chevron-right" /></IconButton>} /></li>;
})}</ResourceList>{!contours.length ? <p>{pending === 'load' ? 'Загрузка контуров…' : status ? 'Контуров пока нет' : 'Контуры недоступны'}</p> : null}
</SettingsCard> : !application ? <>
<SettingsCard title={selected.name} actions={<StatusBadge>Контур</StatusBadge>}><ResourceRow title={projects.find((p) => p.projectRef === linkedProject)?.name || 'Не выбран'} metadata="Проект Device Core" actions={!linkedProject ? <Button disabled={busy} onClick={() => begin('project')}>Выбрать проект</Button> : undefined} /></SettingsCard>
<SettingsCard title="Приложения" actions={canManage ? <IconButton label={`Добавить приложение в ${selected.name}`} disabled={busy} onClick={() => begin('application')}><Icon name="plus" /></IconButton> : undefined}>
<ResourceList>{applications.filter((app) => showInactive || !inactive(app)).map((app) => <li key={app.id}><ResourceRow title={app.name} status={<StatusBadge tone={app.credentials.some((c) => c.enabled) ? 'success' : 'neutral'}>{app.credentials.some((c) => c.enabled) ? 'Ключ действует' : 'Нет активного ключа'}</StatusBadge>} actions={<IconButton label={`Ключи ${app.name}`} disabled={busy} onClick={() => { setApplicationId(app.id); setShowHistory(false); }}><Icon name="key" /></IconButton>} /></li>)}</ResourceList>
{!applications.filter((app) => showInactive || !inactive(app)).length ? <p>Нет подключённых приложений</p> : null}
{applications.some(inactive) ? <Button variant="ghost" onClick={() => setShowInactive(!showInactive)}>{showInactive ? 'Скрыть отключённые' : `Отключённые приложения · ${applications.filter(inactive).length}`}</Button> : null}
</SettingsCard>
</> : <> </> : <>
{issued ? <SettingsCard title="Новый ключ" description="Сохраните ключ — повторный просмотр недоступен."><div className="b2-settings"><TextAreaField label="Ключ подключения" value={issued} readOnly rows={4} /><div className="b2-actions"><Button onClick={downloadIssuedKey}>Скачать файл</Button><Button onClick={() => navigator.clipboard.writeText(issued).catch(onError)}>Скопировать</Button><Button onClick={() => setIssued('')}>Скрыть</Button></div></div></SettingsCard> : null} <div className="b2-section-heading"><strong>Приложения и ключи</strong>{canManage ? <IconButton label={`Добавить приложение в ${item.name}`} disabled={busy} onClick={() => { setCreating(item.projectRef); setName(''); setCreationIntent(null); }}><Icon name="plus" /></IconButton> : null}</div>
<SettingsCard title="Ключи приложения" actions={<Button disabled={busy} onClick={() => setConfirm({ action: 'key-issue', fields: { integrationId: application.id, replace: true }, text: `Выдать новый ключ для «${application.name}»? Прежний ключ перестанет работать. Устройства сохранятся.` })}>{application.credentials.some((c) => c.enabled) ? 'Перевыпустить ключ' : 'Выдать ключ'}</Button>}> <ResourceList>{apps.map(applicationRow)}</ResourceList>
<ResourceList>{application.credentials.filter((c) => c.enabled || showHistory).map((credential) => <li key={credential.client_id}><ResourceRow metadata="ID ключа" title={<code className="b2-key-id" title={credential.client_id}>{credential.client_id}</code>} status={<StatusBadge tone={credential.enabled ? 'success' : 'neutral'}>{credential.enabled ? 'Действует' : 'Отозван'}</StatusBadge>} actions={credential.enabled ? <Button size="compact" disabled={busy} onClick={() => setConfirm({ action: 'key-revoke', fields: { clientId: credential.client_id }, text: `Отозвать ключ приложения «${application.name}»?` })}>Отозвать</Button> : undefined} /></li>)}</ResourceList> {!apps.length && creating !== item.projectRef ? <p>Ключи приложений ещё не выданы</p> : null}
{!application.credentials.some((c) => c.enabled) ? <p>Нет активного ключа</p> : null} {creating === item.projectRef ? <div className="b2-settings">
{application.credentials.some((c) => !c.enabled) ? <Button variant="ghost" onClick={() => setShowHistory(!showHistory)}>{showHistory ? 'Скрыть историю' : `История ключей · ${application.credentials.filter((c) => !c.enabled).length}`}</Button> : null} <TextField label="Название приложения" value={name} disabled={busy || Boolean(creationIntent)} maxLength={160} onChange={(event) => setName(event.target.value)} />
</SettingsCard> <div className="b2-actions"><Button disabled={busy} onClick={() => { setCreating(''); setCreationIntent(null); }}>Отмена</Button><Button loading={pending === 'application-connect'} disabled={busy || !name.trim()} onClick={() => {
const intent = creationIntent || { id: crypto.randomUUID().replaceAll('-', ''), name: name.trim() };
setCreationIntent(intent);
void run('application-connect', { name: intent.name, contourId: links[0].contourId }, intent.id);
}}>{creationIntent ? 'Уточнить создание' : 'Создать ключ'}</Button></div>
</div> : null}
</>} </>}
</> : null} </div> : null}
</li>;
})}</ResourceList> : null}
</div> </div>
</FeatureSettingsWindow> </FeatureSettingsWindow>
<ConfirmationModal open={Boolean(confirm)} title="Ключ приложения" description={confirm?.text} confirmLabel="Подтвердить" cancelLabel="Отмена" onClose={() => setConfirm(null)} onConfirm={async () => { if (confirm && await run(confirm.action, confirm.fields)) setConfirm(null); }} /> <ConfirmationModal open={Boolean(confirm)} title="Ключ приложения" description={confirm?.text} confirmLabel="Подтвердить" cancelLabel="Отмена" onClose={() => setConfirm(null)} onConfirm={async () => { if (confirm && await run(confirm.action, confirm.fields)) setConfirm(null); }} />
+2 -2
View File
@@ -20,10 +20,10 @@ const messages: Record<string, string> = {
b2_company_mismatch: 'Выберите проект той же компании.', b2_company_mismatch: 'Выберите проект той же компании.',
device_owner_scope_access_denied: 'Настройки общего VPS доступны администратору компании.', device_owner_scope_access_denied: 'Настройки общего VPS доступны администратору компании.',
}; };
export async function b2Request<T>(projectRef: string, hostRef: string, action: string, fields: Record<string, unknown> = {}): Promise<T> { export async function b2Request<T>(projectRef: string, hostRef: string, action: string, fields: Record<string, unknown> = {}, requestId = crypto.randomUUID().replaceAll('-', '')): Promise<T> {
const response = await fetch('/api/device-manager/b2/infrastructure', { const response = await fetch('/api/device-manager/b2/infrastructure', {
method: 'POST', credentials: 'same-origin', method: 'POST', credentials: 'same-origin',
headers: { 'Content-Type': 'application/json', 'Idempotency-Key': crypto.randomUUID().replaceAll('-', '') }, headers: { 'Content-Type': 'application/json', 'Idempotency-Key': requestId },
body: JSON.stringify({ projectRef, hostRef, action, ...fields }), body: JSON.stringify({ projectRef, hostRef, action, ...fields }),
}); });
const body = await response.json().catch(() => null); const body = await response.json().catch(() => null);
+3
View File
@@ -3,3 +3,6 @@
.b2-path { overflow-wrap: anywhere; } .b2-path { overflow-wrap: anywhere; }
.b2-actions { display: flex; gap: var(--nodedc-space-2); flex-wrap: wrap; justify-content: flex-end; } .b2-actions { display: flex; gap: var(--nodedc-space-2); flex-wrap: wrap; justify-content: flex-end; }
.b2-key-id { font-family: inherit; font-size: var(--nodedc-font-size-sm); overflow-wrap: anywhere; font-weight: 400; } .b2-key-id { font-family: inherit; font-size: var(--nodedc-font-size-sm); overflow-wrap: anywhere; font-weight: 400; }
.b2-disclosure { display: grid; gap: var(--nodedc-space-2); }
.b2-disclosure__body { display: grid; gap: var(--nodedc-space-3); padding: var(--nodedc-space-2) var(--nodedc-space-3) var(--nodedc-space-4); }
.b2-section-heading { display: flex; align-items: center; justify-content: space-between; gap: var(--nodedc-space-3); font-size: var(--nodedc-font-size-sm); }
+9 -59
View File
@@ -5,7 +5,6 @@
.device-control-toolbar { .device-control-toolbar {
align-items: center; align-items: center;
padding: 2px 0 14px; padding: 2px 0 14px;
border-bottom: 1px solid var(--nodedc-glass-outline);
} }
.device-control-toolbar > p { .device-control-toolbar > p {
@@ -42,8 +41,8 @@
.device-control-resource-grid { .device-control-resource-grid {
display: grid; display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr)); gap: var(--nodedc-space-3);
gap: 12px; grid-template-columns: minmax(0, 1fr);
} }
.device-control-row { .device-control-row {
@@ -142,55 +141,9 @@
.infrastructure-assets-block { .infrastructure-assets-block {
min-width: 0; min-width: 0;
border-radius: var(--nodedc-radius-card); border-radius: var(--nodedc-radius-card);
background: var(--infrastructure-panel-soft);
padding: 1rem; padding: 1rem;
} }
.infrastructure-system-workspace .nodedc-status {
min-height: auto;
justify-content: flex-start;
gap: 0.42rem;
border-radius: 0;
background: transparent;
color: var(--nodedc-text-primary);
padding: 0;
font-size: var(--nodedc-font-size-sm);
font-weight: var(--nodedc-font-weight-medium);
}
.infrastructure-system-workspace .nodedc-status::before {
width: 0.42rem;
height: 0.42rem;
flex: 0 0 0.42rem;
border-radius: 50%;
background: var(--nodedc-text-muted);
content: "";
}
.infrastructure-system-workspace .nodedc-status[data-tone="success"],
.infrastructure-system-workspace .nodedc-status[data-tone="warning"],
.infrastructure-system-workspace .nodedc-status[data-tone="danger"],
.infrastructure-system-workspace .nodedc-status[data-tone="accent"] {
background: transparent;
color: var(--nodedc-text-primary);
}
.infrastructure-system-workspace .nodedc-status[data-tone="success"]::before {
background: rgb(var(--nodedc-success-rgb));
}
.infrastructure-system-workspace .nodedc-status[data-tone="warning"]::before {
background: rgb(var(--nodedc-warning-rgb));
}
.infrastructure-system-workspace .nodedc-status[data-tone="danger"]::before {
background: rgb(var(--nodedc-danger-rgb));
}
.infrastructure-system-workspace .nodedc-status[data-tone="accent"]::before {
background: var(--nodedc-text-primary);
}
.infrastructure-eyebrow { .infrastructure-eyebrow {
display: block; display: block;
color: var(--nodedc-text-muted); color: var(--nodedc-text-muted);
@@ -264,7 +217,6 @@
.host-monitoring-series { .host-monitoring-series {
min-width: 0; min-width: 0;
border-radius: var(--nodedc-radius-card); border-radius: var(--nodedc-radius-card);
background: var(--infrastructure-panel-soft);
} }
.infrastructure-count-card { .infrastructure-count-card {
@@ -425,7 +377,6 @@
margin: 0; margin: 0;
padding: 0.72rem; padding: 0.72rem;
border-radius: var(--nodedc-radius-control); border-radius: var(--nodedc-radius-control);
background: var(--infrastructure-panel-soft);
} }
.infrastructure-host-card__facts > div { .infrastructure-host-card__facts > div {
@@ -464,7 +415,6 @@
gap: 0.55rem; gap: 0.55rem;
padding: 0.72rem; padding: 0.72rem;
border-radius: var(--nodedc-radius-control); border-radius: var(--nodedc-radius-control);
background: var(--infrastructure-panel-soft);
} }
.infrastructure-host-relations > section > header { .infrastructure-host-relations > section > header {
@@ -573,7 +523,6 @@
gap: 0.9rem; gap: 0.9rem;
padding: 0.72rem 0.8rem; padding: 0.72rem 0.8rem;
border-radius: var(--nodedc-radius-control); border-radius: var(--nodedc-radius-control);
background: var(--infrastructure-panel-soft);
} }
.infrastructure-registry-row > div, .infrastructure-registry-row > div,
@@ -610,7 +559,6 @@
.infrastructure-empty { .infrastructure-empty {
padding: 0.8rem; padding: 0.8rem;
border-radius: var(--nodedc-radius-control); border-radius: var(--nodedc-radius-control);
background: var(--infrastructure-panel-soft);
color: var(--nodedc-text-muted); color: var(--nodedc-text-muted);
font-size: 0.65rem; font-size: 0.65rem;
line-height: 1.5; line-height: 1.5;
@@ -696,7 +644,6 @@
margin: 0; margin: 0;
gap: 0; gap: 0;
border-radius: var(--nodedc-radius-control); border-radius: var(--nodedc-radius-control);
background: var(--infrastructure-panel-soft);
} }
.host-monitoring-hardware-facts dl > div { .host-monitoring-hardware-facts dl > div {
@@ -1319,7 +1266,6 @@ body {
gap: 0.75rem; gap: 0.75rem;
margin-top: 0.45rem; margin-top: 0.45rem;
padding-top: 1rem; padding-top: 1rem;
border-top: 1px solid var(--nodedc-glass-border);
} }
.device-inventory__section-heading { .device-inventory__section-heading {
@@ -1441,7 +1387,6 @@ body {
align-items: center; align-items: center;
gap: 0.9rem; gap: 0.9rem;
padding-bottom: 1rem; padding-bottom: 1rem;
border-bottom: 1px solid var(--nodedc-glass-border);
} }
.device-detail__identity { .device-detail__identity {
@@ -1604,7 +1549,6 @@ body {
display: flex; display: flex;
justify-content: flex-end; justify-content: flex-end;
gap: 0.55rem; gap: 0.55rem;
border-top: 1px solid var(--nodedc-glass-border);
padding-top: 0.85rem; padding-top: 0.85rem;
} }
@@ -1640,7 +1584,6 @@ body {
display: grid; display: grid;
grid-template-columns: auto minmax(0, 1fr); grid-template-columns: auto minmax(0, 1fr);
gap: 0.35rem 0.7rem; gap: 0.35rem 0.7rem;
border-top: 1px solid var(--nodedc-glass-border);
padding-top: 0.85rem; padding-top: 0.85rem;
color: var(--nodedc-text-secondary); color: var(--nodedc-text-secondary);
font-size: 0.65rem; font-size: 0.65rem;
@@ -1750,3 +1693,10 @@ body {
} }
} }
/* Domain groups use the panel canvas; shared ResourceRow/SettingsCard own surfaces. */
.device-inventory__empty { min-height: 12rem; }
.device-manager-empty h3 { font-size: var(--nodedc-font-size-md); }
.device-control-disclosure__body { padding: var(--nodedc-space-4); color: var(--nodedc-text-secondary); }
.device-control-disclosure__body p { margin-top: 0; }
+40
View File
@@ -0,0 +1,40 @@
# Device Core: UI and UX contract
Device Core remains a separate application with its own companies, projects,
device registry, infrastructure, access rules and management functions. Mission
Core is the reference for interaction and presentation, not its domain model.
The existing home video and media configuration are preserved.
## Components
Consume the pinned NODEDC_DESIGN_GUIDELINE packages. Use ResourceRow for
registries, FeatureSettingsWindow for entity settings, SettingsCard for coherent
forms, and canonical controls and status indicators. Domain wrappers only arrange
these exports; they must not reproduce their visual styles. Avoid nested canvas
surfaces. Keep refresh beside close in the window header. Expand related items
in place instead of replacing the settings page with a back-navigation stack.
## VPS and projects
Existing Device Core projects are the list shown under a VPS. Connecting a
project requests a contour on that VPS using a stable project-derived identity,
then saves the link. Retries reuse that identity. No second project registry is
created. Explicit linking is available for a pre-existing remote contour.
Applications and their keys expand under their project. Creating an application
requires its human-readable name only. Device Core generates its technical ID;
VPS generates the credential. A lost response retains the same creation request
ID in the open form. The status refresh exposes partially completed issuance;
use explicit reissue when a one-time secret was lost. Key IDs are public IDs,
never secrets. Issued means a credential exists, not that the client is online.
Legacy Mission Core access is visible as a compatible connection.
## Acceptance
- Check all five application sections and their empty, populated and error states.
- Verify project switches retain the selected section while clearing entity state.
- Verify project, host, contour and credential isolation with unauthorized actors.
- Verify inline expansion, keyboard focus, Escape, top refresh and narrow layouts.
- Verify the existing home video/media survives releases.
- Full B2 command/settings parity remains a distinct domain integration task;
a UI release or successful deployment must not be recorded as its completion.
+1 -1
View File
@@ -5,7 +5,7 @@
"dependencies": { "dependencies": {
"NODEDC_DESIGN_GUIDELINE": { "NODEDC_DESIGN_GUIDELINE": {
"url": "https://git.dcserve.ru/SILVER/NODEDC_DESIGN_GUIDELINE.git", "url": "https://git.dcserve.ru/SILVER/NODEDC_DESIGN_GUIDELINE.git",
"commit": "1b63366d2e7a911e18a293d30cddb0c95e0ba653" "commit": "77091fda9859f8f00f61e67876816dc7b7d6c4c2"
}, },
"NODEDC_LAUNCHER": { "NODEDC_LAUNCHER": {
"url": "https://git.dcserve.ru/SILVER/NODEDC_LAUNCHER.git", "url": "https://git.dcserve.ru/SILVER/NODEDC_LAUNCHER.git",
@@ -83,7 +83,7 @@ export class B2Infrastructure {
// Host management can affect all projects of the company. A project-only // Host management can affect all projects of the company. A project-only
// grant must not turn into company-wide administration. // grant must not turn into company-wide administration.
if (action !== 'devices') assertActorCanManageOwnerScope(actor, { scopeKind: project.scope_kind, ownerRef: project.owner_ref }); if (action !== 'devices') assertActorCanManageOwnerScope(actor, { scopeKind: project.scope_kind, ownerRef: project.owner_ref });
if (['connect', 'key-issue', 'key-revoke'].includes(action)) { if (['connect', 'key-issue', 'key-revoke', 'application-connect'].includes(action)) {
await findProjectWithCapability(db, actor, projectId, 'credential.manage'); await findProjectWithCapability(db, actor, projectId, 'credential.manage');
} }
const host = (await db.query('select id,host_key,display_name,provider_ref from device_infrastructure_hosts where id=$1 and project_id=$2 and lifecycle_state <> $3 for share', const host = (await db.query('select id,host_key,display_name,provider_ref from device_infrastructure_hosts where id=$1 and project_id=$2 and lifecycle_state <> $3 for share',
@@ -129,12 +129,21 @@ export class B2Infrastructure {
result = { connected: true, endpoint: source.endpoint, authority: source.authority, result = { connected: true, endpoint: source.endpoint, authority: source.authority,
contours: value.contours || value.items, applications: value.applications || [], contours: value.contours || value.items, applications: value.applications || [],
links: links.map((link) => ({ contourId: link.contour_id, projectRef: `project:${link.project_id}` })) }; links: links.map((link) => ({ contourId: link.contour_id, projectRef: `project:${link.project_id}` })) };
} else if (action === 'link') { } else if (action === 'link' || action === 'project-connect') {
fields(input, ['contourId', 'targetProjectRef']); fields(input, action === 'link' ? ['contourId', 'targetProjectRef'] : ['targetProjectRef']);
const targetId = ref(input.targetProjectRef || input.projectRef, 'project'); const targetId = ref(input.targetProjectRef || input.projectRef, 'project');
const target = await findProjectWithCapability(db, actor, targetId, 'infrastructure.manage'); const target = await findProjectWithCapability(db, actor, targetId, 'infrastructure.manage');
if (target.owner_scope_id !== project.owner_scope_id) throw b2Error('b2_company_mismatch', 403); if (target.owner_scope_id !== project.owner_scope_id) throw b2Error('b2_company_mismatch', 403);
const contour = opaque(input.contourId); let contour;
if (action === 'project-connect') {
if (source.authority !== 'host') throw b2Error('b2_host_management_required', 403);
const linked = links.filter((link) => link.project_id === targetId);
if (linked.length > 1) throw b2Error('b2_conflict', 409);
// Stable project identity makes a retry recover the same contour.
contour = linked[0]?.contour_id || (await remote.call('/v2/management/contours', {
key: 'dc-' + targetId, name: target.name,
})).id;
} else contour = opaque(input.contourId);
const permitted = await remote.call('/v2/contours'); const permitted = await remote.call('/v2/contours');
if (!permitted.items.some((item) => item.id === contour)) throw b2Error('b2_access_denied', 403); if (!permitted.items.some((item) => item.id === contour)) throw b2Error('b2_access_denied', 403);
const current = links.find((link) => link.contour_id === contour); const current = links.find((link) => link.contour_id === contour);
@@ -176,6 +185,20 @@ export class B2Infrastructure {
result = await remote.call('/v2/management/applications', { result = await remote.call('/v2/management/applications', {
key: input.key, name: input.name, grants: { [opaque(input.contourId)]: 'manage' }, key: input.key, name: input.name, grants: { [opaque(input.contourId)]: 'manage' },
}); });
} else if (action === 'application-connect') {
fields(input, ['name', 'contourId']);
if (typeof input.name !== 'string' || !input.name.trim() || input.name.length > 160) throw b2Error('b2_name_invalid');
const contour = opaque(input.contourId);
if (!links.some((link) => link.contour_id === contour)) throw b2Error('b2_access_denied', 403);
if (!/^[a-f0-9]{32}$/.test(requestId)) throw b2Error('b2_request_invalid');
const app = await remote.call('/v2/management/applications', {
key: 'app-' + requestId, name: input.name.trim(), grants: { [contour]: 'manage' },
});
// The VPS reserves issuance before returning a one-time secret. If
// the response is lost, status exposes the app for explicit reissue.
result = { id: app.id, connection: await remote.call('/v2/management/credentials', {
integration_id: app.id, replace: false, request_id: requestId,
}) };
} else if (action === 'key-issue') { } else if (action === 'key-issue') {
fields(input, ['integrationId', 'replace']); fields(input, ['integrationId', 'replace']);
if (typeof input.replace !== 'boolean') throw b2Error('b2_replace_invalid'); if (typeof input.replace !== 'boolean') throw b2Error('b2_replace_invalid');
@@ -24,7 +24,7 @@ function repository({ role = 'owner', links = [], otherOwner = ownerId } = {}) {
const db = { release() {}, async query(sql, values) { const db = { release() {}, async query(sql, values) {
if (['begin', 'commit', 'rollback'].includes(sql)) return { rows: [] }; if (['begin', 'commit', 'rollback'].includes(sql)) return { rows: [] };
if (sql.includes('from device_projects')) return { rows: [{ id: values[0], owner_scope_id: values[0] === projectId ? ownerId : otherOwner, if (sql.includes('from device_projects')) return { rows: [{ id: values[0], owner_scope_id: values[0] === projectId ? ownerId : otherOwner,
lifecycle_state: 'active', owner_lifecycle_state: 'active', scope_kind: 'company', owner_ref: 'company:example' }] }; name: 'Test project', lifecycle_state: 'active', owner_lifecycle_state: 'active', scope_kind: 'company', owner_ref: 'company:example' }] };
if (sql.includes('from device_project_grants')) return { rows: [{ id: 'grant', principal_kind: 'user', principal_ref: actor.userRef, if (sql.includes('from device_project_grants')) return { rows: [{ id: 'grant', principal_kind: 'user', principal_ref: actor.userRef,
project_role: role, capability_allow: [], capability_deny: [], lifecycle_state: 'active' }] }; project_role: role, capability_allow: [], capability_deny: [], lifecycle_state: 'active' }] };
if (sql.includes('from device_infrastructure_hosts')) return { rows: [{ id: hostId }] }; if (sql.includes('from device_infrastructure_hosts')) return { rows: [{ id: hostId }] };
@@ -195,3 +195,42 @@ test('unreachable or mismatched host is reported as unavailable, not an empty he
assert.deepEqual(result.items, []); assert.equal(JSON.stringify(result).includes('private-details'), false); assert.deepEqual(result.items, []); assert.equal(JSON.stringify(result).includes('private-details'), false);
} }
}); });
test('project connection generates stable contour identity and links it without user codes', async () => {
const repo = repository(); const calls = []; const contour = 'c'.repeat(32);
const service = new B2Infrastructure({ pool: repo.pool, secrets: { read: async () => pkg }, clientFactory: () => ({ async call(path, body) {
calls.push({ path, body });
return path === '/v2/management/contours' ? { id: contour } : { items: [{ id: contour }] };
} }) });
const result = await service.execute(actor, { action: 'project-connect', projectRef: `project:${projectId}`, hostRef: `host:${hostId}`, targetProjectRef: `project:${projectId}` }, 'a'.repeat(32));
assert.equal(result.linked, true);
assert.equal(calls[0].body.key, 'dc-' + projectId);
assert.equal(calls[0].body.name, 'Test project');
assert.equal(repo.writes.filter((x) => x.sql.includes('device_b2_contour_links')).length, 1);
});
test('connecting an already linked project does not create another contour', async () => {
const contour = 'c'.repeat(32); const repo = repository({ links: [{ contour_id: contour, project_id: projectId }] });
const service = new B2Infrastructure({ pool: repo.pool, secrets: { read: async () => pkg }, clientFactory: () => ({ async call(path) {
assert.equal(path, '/v2/contours'); return { items: [{ id: contour }] };
} }) });
const result = await service.execute(actor, { action: 'project-connect', projectRef: `project:${projectId}`, hostRef: `host:${hostId}` }, 'a'.repeat(32));
assert.equal(result.contourId, contour);
});
test('application creation and issuance use one server-generated request identity', async () => {
const contour = 'c'.repeat(32); const repo = repository({ links: [{ contour_id: contour, project_id: projectId }] });
const calls = []; const requestId = 'd'.repeat(32); const app = 'e'.repeat(32);
const service = new B2Infrastructure({ pool: repo.pool, secrets: { read: async () => pkg }, clientFactory: () => ({ async call(path, body) {
calls.push({ path, body }); return path.endsWith('applications') ? { id: app } : { synthetic: true };
} }) });
const result = await service.execute(actor, { action: 'application-connect', projectRef: `project:${projectId}`, hostRef: `host:${hostId}`, name: 'Partner', contourId: contour }, requestId);
assert.equal(calls[0].body.key, 'app-' + requestId);
assert.equal(calls[1].body.request_id, requestId);
assert.equal(result.id, app);
assert.ok(result.connection);
assert.equal(JSON.stringify(repo.writes).includes('synthetic'), false);
await assert.rejects(service.execute(actor, { action: 'application-connect', projectRef: `project:${projectId}`, hostRef: `host:${hostId}`, name: 'Other', contourId: 'f'.repeat(32) }, requestId), /b2_access_denied/);
assert.equal(calls.length, 2);
});