refactor(lab): move execution to Worker and manage replay and transfer lifecycles

This commit is contained in:
DCCONSTRUCTIONS
2026-11-10 01:09:39 +03:00
parent cd34b6ce1a
commit fe5900ff3b
101 changed files with 9305 additions and 2256 deletions
@@ -1,5 +1,6 @@
import { EnvironmentSettingsWindow as SharedEnvironmentSettingsWindow } from "@nodedc/ui-react";
import { environmentSurfaceIds, type EnvironmentSettings, type EnvironmentSurfaceId, type UploadedEnvironmentMedia } from "../core/environment/environmentSettings";
import { useLabStorageSettings } from "./storage/LabStorageSettings";
import { roots, workspaces, workspacesForRoot } from "../productModel";
interface Props {
@@ -16,7 +17,8 @@ const surfaces = environmentSurfaceIds.map(id => ({
actions: id === "home" ? workspaces.filter(item => !item.internalOnly) : workspacesForRoot(id),
}));
export function EnvironmentSettingsWindow(props: Props) {
return <SharedEnvironmentSettingsWindow {...props} productName="Mission Core" surfaces={surfaces} initialSurfaceId="fleet"
const storage = useLabStorageSettings(props.open);
return <SharedEnvironmentSettingsWindow {...props} productName="Mission Core" surfaces={surfaces} initialSurfaceId="fleet" additionalSections={[storage]}
onSave={draft => props.onSave({ ...draft, pages: Object.fromEntries(environmentSurfaceIds.map(id => [id, draft.pages[id]])) as EnvironmentSettings["pages"] })}
onUpload={(id, itemId, file) => {
if (!environmentSurfaceIds.includes(id as EnvironmentSurfaceId)) throw new Error("Страница окружения недоступна.");
@@ -6,7 +6,6 @@ import {
useState,
} from "react";
import {
ActivityIndicator,
Button,
Checker,
ControlRow,
@@ -35,7 +34,9 @@ import {
import type { CanonicalLabReplayDescriptor } from "../../core/laboratory/canonicalLabReplay";
import type { ObservationSessionReplayLaunch } from "../../core/observation/sessionArchive";
import { laboratoryResultRerunProfile } from "../../core/observation/viewerProfile";
import { resolveObservationSessionReplay } from "../../core/observation/useObservationSessions";
import { prepareLabReplay, type LabReplayProgress as Progress } from "../../core/laboratory/prepareLabReplay";
import { LabReplayProgress } from "./LabReplayProgress";
import { announceLabStorageChange } from "../../core/storage/localLabStorage";
import type { AIViewerLayer } from "../../core/observatory/aiComposition";
import {
fetchLabViewProfile,
@@ -216,6 +217,7 @@ export function CanonicalResultRerunReplay({
const [viewerStatus, setViewerStatus] = useState<RerunViewportStatus>("idle");
const [launch, setLaunch] = useState<CanonicalReplayLaunch | null>(null);
const [launchError, setLaunchError] = useState<string | null>(null);
const [preparationProgress, setPreparationProgress] = useState<Progress>({ phase: "checking", fraction: null });
const sceneDraftRef = useRef(sceneDraft);
const previousSplitViewRef = useRef(splitView);
const trackedLaunchSha256Ref = useRef<string | null>(null);
@@ -275,15 +277,10 @@ export function CanonicalResultRerunReplay({
setPlayback(null);
setPlaybackController(null);
setViewerStatus("idle");
void resolveObservationSessionReplay(sessionId, {
signal: controller.signal,
maximumWaitMs: 30 * 60 * 1000,
onUpdate: () => undefined,
}).then(async (value) => ({
base: value,
replay: await resolveReplay(resultId, value, { signal: controller.signal }),
})).then((value) => {
if (!controller.signal.aborted) setLaunch(value);
void prepareLabReplay(resultId, sessionId, resolveReplay, {
signal: controller.signal, onProgress: setPreparationProgress,
}).then((value) => {
if (!controller.signal.aborted) { setLaunch(value); announceLabStorageChange(); }
}).catch((caught: unknown) => {
if (!controller.signal.aborted) {
setLaunchError(caught instanceof Error ? caught.message : "Сохранённая запись недоступна.");
@@ -465,7 +462,9 @@ export function CanonicalResultRerunReplay({
emptyMessage="Слои результата недоступны."
deckOverlays={presentationState === "loading" ? (
<div className="canonical-vegetation-rerun-replay__loading">
<ActivityIndicator label="Загружаем синхронизированную запись" />
<LabReplayProgress progress={launch
? { phase: "opening", fraction: playback?.bufferProgress ?? null }
: preparationProgress} />
</div>
) : undefined}
transport={transport}
@@ -0,0 +1,10 @@
import { Description, ProgressBar } from "@nodedc/ui-react";
import { labReplayProgressView, type LabReplayProgress as Progress } from "../../core/laboratory/prepareLabReplay";
export function LabReplayProgress({ progress }: { progress: Progress }) {
const view = labReplayProgressView(progress);
return <div className="lab-replay-progress" aria-busy="true">
<Description role="status" aria-live="polite">{view.text}</Description>
<ProgressBar label={view.label} value={view.value} valueText={view.text} />
</div>;
}
@@ -0,0 +1,29 @@
import { useState } from "react";
import { ConfirmationModal, Icon, IconButton } from "@nodedc/ui-react";
import type { ObservatoryRecordedJob } from "../../core/observatory/recordedJobs";
import { deleteFailedRunProjection } from "../../core/observatory/failedRunHistory";
export function FailedRunActions({ job, onDeleted }: {
job: ObservatoryRecordedJob;
onDeleted: () => void;
}) {
const [open, setOpen] = useState(false);
const [pending, setPending] = useState(false);
const [error, setError] = useState<string | null>(null);
return <>
<IconButton label="Удалить ошибочную попытку" onClick={() => { setError(null); setOpen(true); }}>
<Icon name="trash" size={16} />
</IconButton>
<ConfirmationModal open={open} title="Удалить ошибочную попытку?"
description={<><p>Попытка и её рабочие файлы будут удалены с этого устройства и Worker. Исходная запись сохранится.</p>
{error ? <p role="alert">{error}</p> : null}</>}
confirmLabel="Удалить попытку" pendingLabel="Удаляем…" danger
onClose={() => { if (!pending) setOpen(false); }}
onConfirm={async () => {
setPending(true); setError(null);
try { await deleteFailedRunProjection(job); setOpen(false); onDeleted(); }
catch (cause) { setError(cause instanceof Error ? cause.message : "Не удалось удалить попытку."); }
finally { setPending(false); }
}} />
</>;
}
@@ -0,0 +1,71 @@
import { useEffect, useRef, useState } from "react";
import { ConfirmationModal, Icon, IconButton, ToastStack, type ToastItem } from "@nodedc/ui-react";
import { announceLabStorageChange, pinLabCopy, prepareLocalLabCopy, removeLabCopy,
type LocalLabCopy } from "../../core/storage/localLabStorage";
import { formatLocalLabSize } from "../../core/storage/localLabPresentation";
import type { LabReplayProgress } from "../../core/laboratory/prepareLabReplay";
export type LabCopyProgress = LabReplayProgress;
export function LabCopyActions({ id, sourceId, composition = false, copy, available, storageError, onProgress }: {
id: string; sourceId: string; composition?: boolean; copy?: LocalLabCopy;
available: boolean; storageError: string | null;
onProgress?: (value: LabReplayProgress | null) => void;
}) {
const [busy, setBusy] = useState<"download" | "pin" | "remove" | null>(null);
const [toasts, setToasts] = useState<ToastItem[]>([]);
const [confirm, setConfirm] = useState(false);
const request = useRef<AbortController | null>(null);
const progressCallback = useRef(onProgress);
progressCallback.current = onProgress;
useEffect(() => () => { request.current?.abort(); progressCallback.current?.(null); }, []);
const status = storageError ?? (!available ? "Проверяем локальную копию"
: copy?.local ? `На этом устройстве · ${formatLocalLabSize(copy, true)}`
: "Загрузить запись на это устройство");
async function perform(kind: "download" | "pin" | "remove", action: (signal: AbortSignal) => Promise<unknown>) {
if (request.current) return;
const controller = new AbortController(); request.current = controller;
setBusy(kind); setToasts([]);
try {
await action(controller.signal);
if (!controller.signal.aborted) setConfirm(false);
} catch (reason) {
if (!controller.signal.aborted) setToasts([{ id: "lab-copy-error", tone: "error",
title: "Не удалось изменить локальную копию",
description: reason instanceof Error ? reason.message : "Повторите действие." }]);
} finally {
announceLabStorageChange();
progressCallback.current?.(null);
request.current = null;
if (!controller.signal.aborted) setBusy(null);
}
}
const prepare = (signal: AbortSignal) => prepareLocalLabCopy(id, sourceId, composition,
{ signal, onProgress: (value) => progressCallback.current?.(value) });
const unavailable = !available || !!storageError;
return <>
<IconButton label={status} loading={busy === "download"}
disabled={!!busy || unavailable || !!copy?.local}
onClick={() => void perform("download", prepare)}>
<Icon name={copy?.local ? "database" : "download"} size={16} />
</IconButton>
<IconButton label={copy?.pinned ? "Открепить локальную запись" : "Оставить полную запись на этом устройстве"}
aria-pressed={copy?.pinned ?? false} loading={busy === "pin"} disabled={!!busy || unavailable}
onClick={() => void perform("pin", async (signal) => {
if (!copy?.local && !copy?.pinned) await prepare(signal);
signal.throwIfAborted();
await pinLabCopy(id, !copy?.pinned);
})}>
<Icon name="pin" size={16} />
</IconButton>
{copy?.local ? <IconButton label="Удалить только локальную копию" loading={busy === "remove"}
disabled={!!busy || copy.pinned || unavailable} onClick={() => setConfirm(true)}>
<Icon name="minus" size={16} />
</IconButton> : null}
<ToastStack items={toasts} onDismiss={(key) => setToasts((items) => items.filter((item) => item.id !== key))} />
<ConfirmationModal open={confirm} title="Удалить локальную копию?"
description="Результат и история запуска останутся. Копию можно вернуть кнопкой загрузки или открытием просмотра."
confirmLabel="Удалить копию" cancelLabel="Отмена" onClose={() => { if (!busy) setConfirm(false); }}
onConfirm={() => perform("remove", () => removeLabCopy(id))} />
</>;
}
@@ -0,0 +1,32 @@
import { useEffect, useState } from "react";
import { Button, SettingsCard, TextField, WindowFooterActions } from "@nodedc/ui-react";
import { announceLabStorageChange, saveLabRetention, useLocalLabStorage } from "../../core/storage/localLabStorage";
export function useLabStorageSettings(open: boolean) {
const { data, error: loadError, refresh } = useLocalLabStorage(open);
const [days, setDays] = useState("30");
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [saved, setSaved] = useState(false);
useEffect(() => { if (data) setDays(String(data.retention_days)); }, [data?.retention_days]);
const number = Number(days);
const valid = Number.isInteger(number) && number >= 1 && number <= 365;
const content = <SettingsCard eyebrow="ХРАНИЛИЩЕ" title="Локальные записи лабораторий"
description="Срок хранения готовых записей просмотра после последнего открытия. Закреплённые записи остаются на этом устройстве до снятия булавки.">
<TextField label="Срок временного хранения, дней" type="number" min={1} max={365}
value={days} disabled={busy || !data} onChange={event => { setDays(event.target.value); setSaved(false); }} />
<p>После снятия булавки срок начинается заново. История запусков и результаты на Worker сохраняются.</p>
<p>Правило применяется к учтённым записям просмотра AI Inference. Исходные записи, Gaussian-сцены и разметка сохраняются отдельно.</p>
{loadError || error ? <p role="alert">{error ?? loadError}</p> : saved ? <p role="status">Настройки сохранены.</p> : null}
</SettingsCard>;
const footer = <WindowFooterActions>
<Button variant="secondary" disabled={busy || !data || days === String(data.retention_days)}
onClick={() => { setDays(String(data!.retention_days)); setError(null); }}>Сбросить изменения</Button>
<Button variant="primary" tone="neutral" disabled={busy || !data || !valid || days === String(data.retention_days)}
onClick={() => { setBusy(true); setError(null); void saveLabRetention(number).then(async () => {
await refresh(); setSaved(true); announceLabStorageChange();
}).catch(reason => setError(reason instanceof Error ? reason.message : "Не удалось сохранить срок хранения."))
.finally(() => setBusy(false)); }}>{busy ? "Сохраняем…" : "Сохранить"}</Button>
</WindowFooterActions>;
return { id: "storage", label: "Хранилище", icon: "database" as const, content, footer };
}
@@ -0,0 +1,57 @@
import { resolveObservationSessionReplay } from "../observation/useObservationSessions";
import type { ObservationSessionReplayLaunch } from "../observation/sessionArchive";
import type { CanonicalLabReplayDescriptor } from "./canonicalLabReplay";
export interface LabReplayProgress {
phase: "checking" | "preparing" | "opening";
fraction: number | null;
}
export type LabReplayResolver = (id: string, base: ObservationSessionReplayLaunch,
options: { signal: AbortSignal }) => Promise<CanonicalLabReplayDescriptor>;
/** Shared preparation for the eye, download and offline pin. Never runs inference. */
export async function prepareLabReplay(id: string, sourceId: string, resolve: LabReplayResolver,
{ signal, onProgress, fetcher }: {
signal: AbortSignal;
onProgress?: (progress: LabReplayProgress) => void;
fetcher?: typeof fetch;
}) {
const request = new AbortController();
const abort = () => request.abort();
signal.addEventListener("abort", abort, { once: true });
const timer = globalThis.setTimeout(abort, 30 * 60 * 1000);
const publish = (progress: LabReplayProgress) => {
request.signal.throwIfAborted();
onProgress?.(progress);
};
try {
signal.throwIfAborted();
publish({ phase: "checking", fraction: null });
const base = await resolveObservationSessionReplay(sourceId, {
signal: request.signal, fetcher, maximumWaitMs: 30 * 60 * 1000,
onUpdate: (state) => publish({ phase: "preparing", fraction: state.progress }),
});
publish({ phase: "preparing", fraction: null });
const replay = await resolve(id, base, { signal: request.signal });
request.signal.throwIfAborted();
return { base, replay };
} catch (error) {
if (request.signal.aborted && !signal.aborted) {
throw new Error("Подготовка записи заняла слишком много времени. Повторите загрузку.");
}
throw error;
} finally {
globalThis.clearTimeout(timer);
signal.removeEventListener("abort", abort);
}
}
export function labReplayProgressView(progress: LabReplayProgress) {
const labels = { checking: "Проверка доступности записи", preparing: "Подготовка записи",
opening: "Открытие записи" };
const value = progress.fraction === null || !Number.isFinite(progress.fraction)
? undefined : Math.min(1, Math.max(0, progress.fraction));
return { label: labels[progress.phase], value,
text: value === undefined ? labels[progress.phase]
: `${labels[progress.phase]} · ${Math.round(value * 100)}%` };
}
@@ -170,9 +170,8 @@ function evidenceFromSession(
`LAB-каталог вернул сессию ${session.id} без типизированной связи с источником.`,
);
}
// Historical LABs retain their archive and replay adapters. Observatory is
// the portable-profile product; a familiar LAB label is not admission.
if (session.lab.replayCapability?.kind !== "portable-result-review") return null;
// History follows source identity. Playback admission remains independently
// validated below; an unavailable viewer must never erase a completed run.
const recordedRun = observatoryRecordedRunBinding(session.id, session.lab);
return {
sessionId: session.id,
@@ -303,12 +302,10 @@ async function readCatalogPages(
throw new ObservatoryCatalogContractError("Каталог повторил сессию между страницами.");
}
seenIds.add(item.id);
// Do not accumulate legacy provenance while walking the shared catalog.
if (scope === "source" || item.lab?.replayCapability?.kind === "portable-result-review") {
items.push(item);
} else if (!item.lab) {
if (scope === "laboratory" && !item.lab) {
throw new ObservatoryCatalogContractError("LAB-каталог вернул исходную сессию.");
}
items.push(item);
}
cursor = page.nextCursor;
if (cursor === null) return { items, hasMore: false };
@@ -1,3 +1,4 @@
import type { ObservatoryEvidence } from "./catalog";
import type { ObservatoryRecordedRunBinding } from "./recordedRun";
const SAFE_SESSION_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
@@ -26,7 +27,7 @@ export class ObservatoryCatalogMutationError extends Error {
}
export async function renameObservatoryLabProjection(
binding: ObservatoryRecordedRunBinding,
binding: ObservatoryRecordedRunBinding | Pick<ObservatoryEvidence, "sessionId" | "lab">,
displayName: string,
{
signal,
@@ -78,7 +79,7 @@ export async function renameObservatoryLabProjection(
}
export async function deleteObservatoryLabProjection(
binding: ObservatoryRecordedRunBinding,
binding: ObservatoryRecordedRunBinding | Pick<ObservatoryEvidence, "sessionId" | "lab">,
{
signal,
fetcher = globalThis.fetch,
@@ -113,7 +114,16 @@ export async function deleteObservatoryLabProjection(
}
}
function admittedProjectionId(binding: ObservatoryRecordedRunBinding): string {
function admittedProjectionId(binding: ObservatoryRecordedRunBinding | Pick<ObservatoryEvidence, "sessionId" | "lab">): string {
// Catalog ownership is independent of whether this client supports replay.
// The server verifies the typed LAB projection against its source rows.
if ("lab" in binding) {
if (!SAFE_SESSION_ID.test(binding.sessionId) || !binding.lab.labId
|| !binding.lab.resultId || binding.lab.sourceSessionId === binding.sessionId) {
throw new ObservatoryCatalogMutationError("Выбранный результат не допущен к изменению каталога AI Inference.");
}
return binding.sessionId;
}
const sessionId = binding.evidenceSessionId;
const admittedViewer = (
binding.kind === "canonical-recorded-rerun"
@@ -0,0 +1,24 @@
import type { ObservatoryRecordedJob, ObservatoryRecordedJobFetch } from "./recordedJobs";
export function failedRunDetail(job: Pick<ObservatoryRecordedJob, "terminalMessage">): string {
const message = job.terminalMessage ?? "";
if (/source-member|source transport|Content-Length|camera-source/i.test(message)) {
return "Не удалось подготовить исходную запись";
}
if (/assemble|export|presentation/i.test(message)) return "Не удалось собрать запись результата";
if (/Docker Engine|container.*start|start.*container/i.test(message)) return "Не удалось запустить вычислительный контейнер";
if (/exit 143|exit=143|cancel|interrupted/i.test(message)) return "Расчёт прерван до получения результата";
if (/prepare/i.test(message)) return "Ошибка подготовки расчёта";
return "Расчёт завершился ошибкой; готового результата нет";
}
export async function deleteFailedRunProjection(
job: Pick<ObservatoryRecordedJob, "jobId" | "state" | "resultId">,
fetcher: ObservatoryRecordedJobFetch = globalThis.fetch,
): Promise<void> {
if (!/^observatory-run-[a-f0-9]{32}$/.test(job.jobId) || job.state !== "failed" || job.resultId !== null) {
throw new Error("Удалить можно только ошибочную попытку без результата.");
}
const response = await fetcher(`/api/v1/observatory/ai-runs/${encodeURIComponent(job.jobId)}`, { method: "DELETE" });
if (response.status !== 204) throw new Error("Не удалось удалить попытку из истории. Обновите список и повторите.");
}
@@ -1,132 +0,0 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
fetchObservatoryPortableLaboratorySetups,
preflightObservatoryLaboratorySetup,
selectableObservatorySetups,
type ObservatoryLaboratoryRunPreflight,
type ObservatoryLaboratorySetupCatalog,
} from "./laboratorySetups";
type SetupCatalogState = "idle" | "loading" | "ready" | "refreshing" | "error";
export type SetupPreflightState =
| { readonly kind: "idle" }
| { readonly kind: "checking" }
| { readonly kind: "ready"; readonly value: ObservatoryLaboratoryRunPreflight }
| { readonly kind: "error"; readonly message: string };
export function useObservatoryLaboratorySetups(sourceSessionId: string) {
const [catalog, setCatalog] = useState<ObservatoryLaboratorySetupCatalog | null>(null);
const [state, setState] = useState<SetupCatalogState>("idle");
const [error, setError] = useState<string | null>(null);
const [selectedSetupId, setSelectedSetupId] = useState("");
const [revision, setRevision] = useState(0);
const [preflight, setPreflight] = useState<SetupPreflightState>({ kind: "idle" });
const requestSequence = useRef(0);
const preflightRequest = useRef<AbortController | null>(null);
const activeCatalog = catalog?.sourceSessionId === sourceSessionId ? catalog : null;
const selectableSetups = useMemo(() => selectableObservatorySetups(activeCatalog), [activeCatalog]);
const selectedSetup = selectableSetups.find((setup) => setup.setupId === selectedSetupId) ?? null;
const selectedDefinitionSha256 = selectedSetup?.runDefinition?.definitionSha256 ?? null;
useEffect(() => {
preflightRequest.current?.abort();
preflightRequest.current = null;
if (!sourceSessionId) {
setCatalog(null);
setState("idle");
setError(null);
setSelectedSetupId("");
setPreflight({ kind: "idle" });
return;
}
const sequence = ++requestSequence.current;
const request = new AbortController();
setState((current) => activeCatalog && current !== "idle" ? "refreshing" : "loading");
setError(null);
setPreflight({ kind: "idle" });
// Archived definitions belong to evidence, not to the calculation selector.
void fetchObservatoryPortableLaboratorySetups(sourceSessionId, { signal: request.signal })
.then((next) => {
if (request.signal.aborted || requestSequence.current !== sequence) return;
setCatalog(next);
const selectable = selectableObservatorySetups(next);
setSelectedSetupId((current) => (
selectable.some((setup) => setup.setupId === current)
? current
: selectable[0]?.setupId ?? ""
));
setState("ready");
})
.catch((caught: unknown) => {
if (request.signal.aborted || requestSequence.current !== sequence) return;
setState("error");
setError(caught instanceof Error && caught.message.trim()
? caught.message
: "Каталог профилей недоступен.");
});
return () => request.abort();
}, [revision, sourceSessionId]);
useEffect(() => () => preflightRequest.current?.abort(), []);
useEffect(() => {
preflightRequest.current?.abort();
preflightRequest.current = null;
setPreflight((current) => current.kind === "idle" ? current : { kind: "idle" });
}, [selectedSetupId, sourceSessionId, selectedDefinitionSha256]);
const selectSetup = useCallback((setupId: string) => {
preflightRequest.current?.abort();
preflightRequest.current = null;
setSelectedSetupId(setupId);
setPreflight({ kind: "idle" });
}, []);
const refresh = useCallback(() => setRevision((value) => value + 1), []);
const check = useCallback(async () => {
if (!sourceSessionId || !selectedSetup || preflight.kind === "checking") return;
preflightRequest.current?.abort();
const request = new AbortController();
preflightRequest.current = request;
setPreflight({ kind: "checking" });
try {
const value = await preflightObservatoryLaboratorySetup(
sourceSessionId,
selectedSetup,
{ signal: request.signal },
);
if (request.signal.aborted || preflightRequest.current !== request) return;
setPreflight({ kind: "ready", value });
} catch (caught) {
if (request.signal.aborted || preflightRequest.current !== request) return;
setPreflight({
kind: "error",
message: caught instanceof Error && caught.message.trim()
? caught.message
: "Не удалось проверить возможность запуска.",
});
} finally {
if (preflightRequest.current === request) preflightRequest.current = null;
}
}, [preflight.kind, selectedSetup, sourceSessionId]);
useEffect(() => {
if (state !== "ready" || !selectedSetup || preflight.kind !== "idle") return;
void check();
}, [check, preflight.kind, selectedSetup, state]);
return {
catalog: activeCatalog,
selectableSetups,
state,
error,
selectedSetupId: selectedSetup?.setupId ?? "",
selectedSetup,
selectSetup,
refresh,
preflight,
check,
};
}
@@ -1,207 +0,0 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { fetchRecordedProgress, type RecordedProgressView } from "./recordedProgress";
import {
fetchObservatoryRecordedJobs,
retryObservatoryRecordedJobPublication,
submitObservatoryRecordedJob,
type ObservatoryRecordedJob,
} from "./recordedJobs";
type RecordedJobsState =
| "idle"
| "loading"
| "ready"
| "refreshing"
| "submitting"
| "retrying-publication"
| "error";
interface JobSnapshot {
readonly selectionKey: string;
readonly jobs: readonly ObservatoryRecordedJob[];
readonly state: RecordedJobsState;
readonly error: string | null;
readonly progress?: RecordedProgressView | null;
}
const EMPTY_JOBS = [] as const;
const OPEN_STATES = new Set([
"accepted", "queued", "claimed", "running", "paused", "preemption-pending",
"reconciliation-required",
]);
const POLL_INTERVAL_MS = 1_500;
export function useObservatoryRecordedJobs(
sourceSessionId: string,
setupId: string,
definitionSha256: string,
) {
const selectionKey = JSON.stringify([sourceSessionId, setupId, definitionSha256]);
const [snapshot, setSnapshot] = useState<JobSnapshot>({
selectionKey: "", jobs: EMPTY_JOBS, state: "idle", error: null,
});
const [revision, setRevision] = useState(0);
const requestRef = useRef<AbortController | null>(null);
const requestSequence = useRef(0);
const idempotencyKeys = useRef(new Map<string, string>());
const observedJobId = useRef<string | null>(null);
const hasSelection = Boolean(sourceSessionId && setupId && definitionSha256);
// A source/profile change must not display even one render of the previous queue.
const current = snapshot.selectionKey === selectionKey ? snapshot : null;
const jobs = current?.jobs ?? EMPTY_JOBS;
const state = current?.state ?? (hasSelection ? "loading" : "idle");
const error = current?.error ?? null;
useEffect(() => {
requestRef.current?.abort();
requestRef.current = null;
if (!hasSelection) {
setSnapshot({ selectionKey, jobs: EMPTY_JOBS, state: "idle", error: null });
return;
}
const sequence = ++requestSequence.current;
const request = new AbortController();
requestRef.current = request;
setSnapshot({
selectionKey, jobs,
state: jobs.length > 0 ? "refreshing" : "loading", error: null,
progress: current?.progress ?? null,
});
void fetchObservatoryRecordedJobs(sourceSessionId, setupId, {
definitionSha256, signal: request.signal,
}).then(async (next) => {
if (request.signal.aborted || requestSequence.current !== sequence) return;
const pending = next.find((job) => OPEN_STATES.has(job.state));
const progress = pending
? await fetchRecordedProgress(pending, { signal: request.signal }).catch(() => null)
: null;
if (request.signal.aborted || requestSequence.current !== sequence) return;
if (pending) observedJobId.current = pending.jobId;
setSnapshot({ selectionKey, jobs: next, state: "ready", error: null, progress });
}).catch((caught: unknown) => {
if (request.signal.aborted || requestSequence.current !== sequence) return;
setSnapshot({
selectionKey, jobs, state: "error",
error: caught instanceof Error && caught.message.trim()
? caught.message
: "Очередь расчётов недоступна.",
});
}).finally(() => {
if (requestRef.current === request) requestRef.current = null;
});
return () => request.abort();
}, [revision, selectionKey]);
useEffect(() => () => requestRef.current?.abort(), []);
const latestJob = jobs[0] ?? null;
const activeJob = jobs.find((job) => OPEN_STATES.has(job.state)) ?? null;
const publicationPending = jobs.some((job) => job.publication.state === "pending");
// Do not promote historical terminal logs to a new operator action's error.
const computationFailed = latestJob?.state === "failed"
&& latestJob.jobId === observedJobId.current;
useEffect(() => {
if ((state !== "ready" && state !== "error") || (!activeJob && !publicationPending)) return;
const timer = globalThis.setTimeout(
() => setRevision((value) => value + 1),
POLL_INTERVAL_MS,
);
return () => globalThis.clearTimeout(timer);
}, [activeJob, publicationPending, revision, state]);
useEffect(() => {
if (!latestJob || activeJob) return;
idempotencyKeys.current.delete(selectionKey);
}, [activeJob, latestJob, selectionKey]);
const refresh = useCallback(() => setRevision((value) => value + 1), []);
const submit = useCallback(async (
portableBinding: {
readonly definitionSha256: string;
readonly checkSha256: string;
} | null = null,
): Promise<ObservatoryRecordedJob | null> => {
if (!hasSelection || state !== "ready"
|| portableBinding?.definitionSha256 !== definitionSha256
|| publicationPending || latestJob?.publication.state === "failed") return null;
if (activeJob) return activeJob;
requestRef.current?.abort();
const request = new AbortController();
requestRef.current = request;
const key = idempotencyKeys.current.get(selectionKey) ?? createIdempotencyKey();
idempotencyKeys.current.set(selectionKey, key);
setSnapshot({ selectionKey, jobs, state: "submitting", error: null });
try {
const job = await submitObservatoryRecordedJob(
sourceSessionId, setupId, key, portableBinding, { signal: request.signal },
);
if (request.signal.aborted || requestRef.current !== request) return null;
observedJobId.current = job.jobId;
setSnapshot({
selectionKey, jobs: [job, ...jobs.filter((candidate) => candidate.jobId !== job.jobId)],
state: "ready", error: null,
});
return job;
} catch (caught) {
if (request.signal.aborted || requestRef.current !== request) return null;
setSnapshot({
selectionKey, jobs, state: "error",
error: caught instanceof Error && caught.message.trim()
? caught.message
: "Не удалось поставить расчёт в очередь.",
});
return null;
} finally {
if (requestRef.current === request) requestRef.current = null;
}
}, [activeJob, definitionSha256, hasSelection, jobs, latestJob,
publicationPending, selectionKey, setupId, sourceSessionId, state]);
const retryPublication = useCallback(async (): Promise<ObservatoryRecordedJob | null> => {
if (!latestJob || latestJob.publication.state !== "failed"
|| state === "retrying-publication") return null;
requestRef.current?.abort();
const request = new AbortController();
requestRef.current = request;
setSnapshot({ selectionKey, jobs, state: "retrying-publication", error: null });
try {
const job = await retryObservatoryRecordedJobPublication(latestJob.jobId, {
signal: request.signal,
});
if (request.signal.aborted || requestRef.current !== request) return null;
setSnapshot({
selectionKey, jobs: [job, ...jobs.filter((candidate) => candidate.jobId !== job.jobId)],
state: "ready", error: null,
});
return job;
} catch (caught) {
if (request.signal.aborted || requestRef.current !== request) return null;
setSnapshot({
selectionKey, jobs, state: "error",
error: caught instanceof Error && caught.message.trim()
? caught.message
: "Не удалось повторить публикацию результата.",
});
return null;
} finally {
if (requestRef.current === request) requestRef.current = null;
}
}, [jobs, latestJob, selectionKey, state]);
return {
jobs, latestJob, activeJob, publicationPending, computationFailed,
progress: current?.progress ?? null,
state, error, refresh, submit, retryPublication,
};
}
function createIdempotencyKey(): string {
const entropy = typeof globalThis.crypto?.randomUUID === "function"
? globalThis.crypto.randomUUID()
: `${Date.now().toString(36)}-${Math.random().toString(16).slice(2)}`;
return `observatory-ui:${entropy}`;
}
export type ObservatoryRecordedJobsController = ReturnType<typeof useObservatoryRecordedJobs>;
@@ -0,0 +1,11 @@
import type { LocalLabCopy } from "./localLabStorage";
export function formatLocalLabSize(copy: LocalLabCopy | undefined, available: boolean) {
if (!available) return "размер уточняется";
if (!copy?.local) return "0 Б на устройстве";
const units = ["Б", "КБ", "МБ", "ГБ"];
let value = copy.bytes;
let unit = 0;
while (value >= 1000 && unit < units.length - 1) { value /= 1000; unit += 1; }
return `${new Intl.NumberFormat("ru-RU", { maximumFractionDigits: 1 }).format(value)} ${units[unit]}`;
}
@@ -0,0 +1,73 @@
import { useCallback, useEffect, useState } from "react";
import { prepareLabReplay, type LabReplayProgress } from "../laboratory/prepareLabReplay";
import { resolveAICompositionReplay, resolveCanonicalLabReplay } from "../laboratory/canonicalLabReplay";
export interface LocalLabCopy {
local: boolean;
pinned: boolean;
bytes: number;
last_used: number;
}
export interface LocalLabStorage {
retention_days: number;
entries: Readonly<Record<string, LocalLabCopy>>;
}
const endpoint = "/api/v1/storage/laboratory";
async function request(path = "", method = "GET", body?: unknown): Promise<LocalLabStorage> {
const response = await fetch(`${endpoint}${path}`, {
method, credentials: "same-origin", cache: "no-store",
headers: { "Content-Type": "application/json" },
...(body === undefined ? {} : { body: JSON.stringify(body) }),
});
const value = await response.json();
if (!response.ok) throw new Error(value.detail ?? "Хранилище недоступно.");
if (!Number.isInteger(value.retention_days) || value.retention_days < 1
|| value.retention_days > 365 || !value.entries || typeof value.entries !== "object"
|| Array.isArray(value.entries)) throw new Error("Некорректные настройки хранения.");
for (const copy of Object.values(value.entries) as LocalLabCopy[]) {
if (typeof copy.local !== "boolean" || typeof copy.pinned !== "boolean"
|| !Number.isSafeInteger(copy.bytes) || copy.bytes < 0
|| !Number.isFinite(copy.last_used)) throw new Error("Некорректное состояние локальной копии.");
}
return value;
}
export const saveLabRetention = (days: number) => request("/policy", "PUT", { retention_days: days });
export const pinLabCopy = (id: string, pinned: boolean) => request(`/copies/${encodeURIComponent(id)}/pin`, "PUT", { pinned });
export const removeLabCopy = (id: string) => request(`/copies/${encodeURIComponent(id)}`, "DELETE");
export async function prepareLocalLabCopy(id: string, sourceId: string, composition: boolean,
options: { signal: AbortSignal; onProgress?: (value: LabReplayProgress) => void }) {
return prepareLabReplay(id, sourceId, (resultId, base, request) => composition
? resolveAICompositionReplay(resultId, base, request)
: resolveCanonicalLabReplay(resultId, base, { ...request,
sourceKind: id.startsWith("m49-tgs") ? "portable-tgs"
: /^ai-layer-(rf-detr|object-distance)-/.test(id) ? "portable-objects" : "portable-semantic" }),
options);
}
export function useLocalLabStorage(enabled = true) {
const [data, setData] = useState<LocalLabStorage | null>(null);
const [error, setError] = useState<string | null>(null);
const refresh = useCallback(async () => {
try { setData(await request()); setError(null); }
catch (reason) { setError(reason instanceof Error ? reason.message : "Хранилище недоступно."); }
}, []);
useEffect(() => {
if (!enabled) return;
void refresh();
const update = () => void refresh();
window.addEventListener("focus", update);
window.addEventListener("lab-local-storage-changed", update);
const interval = window.setInterval(update, 15000);
return () => {
window.clearInterval(interval);
window.removeEventListener("focus", update);
window.removeEventListener("lab-local-storage-changed", update);
};
}, [enabled, refresh]);
return { data, error, refresh };
}
export function announceLabStorageChange() {
window.dispatchEvent(new Event("lab-local-storage-changed"));
}
@@ -507,3 +507,24 @@
border: 1px solid rgb(var(--nodedc-accent-rgb));
background: transparent;
}
/* The LAB stage and list share measured preparation feedback. Controls are canonical. */
.lab-replay-progress {
--nodedc-progress-height: calc(var(--nodedc-space-2) * 0.7);
--nodedc-description-font-size: calc(var(--nodedc-font-size-sm) * 0.85);
display: grid;
gap: var(--nodedc-space-3, 0.75rem);
width: min(24rem, 100%);
min-width: 0;
}
.observatory-evidence-card > .lab-replay-progress {
width: min(16rem, 22vw);
}
@container observatory-session (max-width: 48rem) {
.observatory-evidence-card > .lab-replay-progress {
grid-column: 2 / -1;
grid-row: 2;
width: 100%;
}
}
@@ -17,6 +17,12 @@ import {
import { CanonicalVegetationRerunReplay } from "../../components/laboratory/CanonicalVegetationRerunReplay";
import { AICompositionReplay } from "../../components/laboratory/AICompositionReplay";
import { PortableResultReplay } from "../../components/laboratory/PortableResultReplay";
import { useLocalLabStorage } from "../../core/storage/localLabStorage";
import { FailedRunActions } from "../../components/observatory/FailedRunActions";
import { failedRunDetail } from "../../core/observatory/failedRunHistory";
import { LabCopyActions, type LabCopyProgress as CopyProgress } from "../../components/observatory/LabCopyActions";
import { LabReplayProgress } from "../../components/laboratory/LabReplayProgress";
import { formatLocalLabSize } from "../../core/storage/localLabPresentation";
import { AIConfigurationWindow } from "../../components/observatory/AIConfigurationWindow";
import type { ObservationSessionStatus } from "../../core/observation/sessionArchive";
import { createObservationReplayCoordinator } from "../../core/observation/replayCoordinator";
@@ -273,7 +279,7 @@ function aiJobStageDetail(
recordingDurationSeconds: number,
): string {
if (job.state === "failed") {
return "Не удалось запустить модель. Конфигурацию можно отправить повторно";
return failedRunDetail(job);
}
if (job.publication.state === "failed") {
return "Результат рассчитан, но не сохранён в AI Inference";
@@ -299,23 +305,6 @@ function aiJobStageDetail(
return "Собираем, передаём и сохраняем результат";
}
function presentAIJob(job: ObservatoryRecordedJob): boolean {
if (job.state === "failed") return true;
if (job.publication.state === "pending" || job.publication.state === "failed") return true;
return job.state !== "succeeded";
}
function presentLatestAIJobs(
jobs: readonly ObservatoryRecordedJob[],
): readonly ObservatoryRecordedJob[] {
const seenSetups = new Set<string>();
return jobs.filter((job) => {
if (seenSetups.has(job.setupId)) return false;
seenSetups.add(job.setupId);
return presentAIJob(job);
});
}
function compositionProgressPercent(
run: AICompositionRun,
progress: Readonly<Record<string, RecordedProgressView>>,
@@ -344,6 +333,7 @@ export function ObservatoryWorkspace({
definition: WorkspaceDefinition;
}) {
const controller = useObservatoryCatalog();
const localStorage = useLocalLabStorage();
const [selectedSessionId, setSelectedSessionId] = useState("");
const [aiConfigurationOpen, setAIConfigurationOpen] = useState(false);
const [evidenceSortDirection, setEvidenceSortDirection] = useState<EvidenceSortDirection>("newest");
@@ -360,6 +350,9 @@ export function ObservatoryWorkspace({
ObservatoryMutationReconciliation | null
>(null);
const overviewRef = useRef<HTMLDivElement | null>(null);
const [copyProgress, setCopyProgress] = useState<Record<string, CopyProgress | null>>({});
const updateCopyProgress = (id: string, value: CopyProgress | null) =>
setCopyProgress((current) => ({ ...current, [id]: value }));
const replayCoordinatorRef = useRef(createObservationReplayCoordinator());
const refreshedPublishedJobRef = useRef<string | null>(null);
const items = controller.catalog?.items ?? EMPTY_OBSERVATORY_ITEMS;
@@ -400,8 +393,9 @@ export function ObservatoryWorkspace({
const compositionJobIds = useMemo(() => new Set(
presentedCompositionRuns.flatMap((run) => run.jobIds),
), [presentedCompositionRuns]);
const presentedAIJobs = presentLatestAIJobs(aiJobsController.jobs).filter(
(job) => !compositionJobIds.has(job.jobId),
const presentedAIJobs = aiJobsController.jobs.filter(
(job) => !compositionJobIds.has(job.jobId)
&& !presentedEvidence.some((evidence) => evidence.lab.resultId === job.resultId),
);
const presentedRows = useMemo<readonly ObservatoryEvidenceRow[]>(() => {
const rows: ObservatoryEvidenceRow[] = [
@@ -509,7 +503,6 @@ export function ObservatoryWorkspace({
}, [closeReplay]);
const openRename = useCallback((evidence: ObservatoryEvidence) => {
if (!evidence.recordedRun) return;
setCompositionRenameTarget(null);
setCompositionDeleteTarget(null);
setDeleteTarget(null);
@@ -520,7 +513,6 @@ export function ObservatoryWorkspace({
}, []);
const openDelete = useCallback((evidence: ObservatoryEvidence) => {
if (!evidence.recordedRun) return;
setCompositionRenameTarget(null);
setCompositionDeleteTarget(null);
setRenameTarget(null);
@@ -567,7 +559,7 @@ export function ObservatoryWorkspace({
}
return;
}
if (!renameTarget?.recordedRun || mutationPending !== null) return;
if (!renameTarget || mutationPending !== null) return;
const requestedDisplayName = renameValue.trim();
const reconciliation: ObservatoryMutationReconciliation = {
kind: "rename",
@@ -579,7 +571,7 @@ export function ObservatoryWorkspace({
setMutationReconciliation(reconciliation);
try {
const result = await renameObservatoryLabProjection(
renameTarget.recordedRun,
renameTarget,
renameValue,
);
controller.applyEvidenceRename(result.sessionId, result.displayName);
@@ -621,7 +613,7 @@ export function ObservatoryWorkspace({
}
return;
}
if (!deleteTarget?.recordedRun || mutationPending !== null) return;
if (!deleteTarget || mutationPending !== null) return;
const reconciliation: ObservatoryMutationReconciliation = {
kind: "delete",
sessionId: deleteTarget.sessionId,
@@ -639,7 +631,7 @@ export function ObservatoryWorkspace({
closeReplay();
});
}
await deleteObservatoryLabProjection(deleteTarget.recordedRun);
await deleteObservatoryLabProjection(deleteTarget);
controller.applyEvidenceDeletion(deleteTarget.sessionId);
setDeleteTarget(null);
setMutationReconciliation(null);
@@ -800,7 +792,7 @@ export function ObservatoryWorkspace({
<header>
<div>
<span className="section-eyebrow">СВЯЗАННЫЕ РЕЗУЛЬТАТЫ</span>
<h3>Лабораторные доказательства</h3>
<h3>История запусков</h3>
</div>
<div className="observatory-evidence__ordering">
<StatusBadge tone={presentedRows.length > 0 ? "accent" : "neutral"}>
@@ -852,15 +844,21 @@ export function ObservatoryWorkspace({
</div>
) : null}
<small>{run.state === "ready"
? formatTimestamp(row.timestamp)
? `${formatTimestamp(row.timestamp)} / ${formatLocalLabSize(localStorage.data?.entries[run.runId], !!localStorage.data && !localStorage.error)}`
: `${compositionStage(run, aiJobsController.progress)} · ${formatTimestamp(row.timestamp)}`}</small>
</div>
{active ? (
<StatusBadge tone="accent">{Math.round(progressPercent)}%</StatusBadge>
) : failed ? <StatusBadge tone="danger">Ошибка</StatusBadge> : null}
{copyProgress[run.runId] ? <LabReplayProgress progress={copyProgress[run.runId]!} /> : null}
<div className="observatory-evidence-card__actions">
{run.state === "ready" ? (
<>
<LabCopyActions id={run.runId} sourceId={run.sourceSessionId} composition
onProgress={(value) => updateCopyProgress(run.runId, value)}
copy={localStorage.data?.entries[run.runId]} available={!!localStorage.data}
storageError={localStorage.error} />
<IconButton
label={`Удалить ${run.displayName ?? run.presentation.configurationLabel} из AI Inference`}
onClick={() => openCompositionDelete(run)}
@@ -927,6 +925,9 @@ export function ObservatoryWorkspace({
{active ? (
<StatusBadge tone={aiJobTone(job)}>{Math.round(progressPercent)}%</StatusBadge>
) : failed ? <StatusBadge tone="danger">Ошибка</StatusBadge> : null}
{job.state === "failed" && job.resultId === null ? (
<FailedRunActions job={job} onDeleted={aiJobsController.refresh} />
) : null}
</div>
</li>
);
@@ -946,11 +947,19 @@ export function ObservatoryWorkspace({
)}</strong>
<small>
{formatTimestamp(row.timestamp)}
{evidence.recordedRun?.kind === "portable-result-review"
? ` / ${formatLocalLabSize(localStorage.data?.entries[evidence.lab.resultId], !!localStorage.data && !localStorage.error)}` : ""}
{!evidence.recordedRun ? " · Просмотр этого формата пока недоступен" : ""}
</small>
</div>
{copyProgress[evidence.lab.resultId] ? <LabReplayProgress progress={copyProgress[evidence.lab.resultId]!} /> : null}
<div className="observatory-evidence-card__actions">
{evidence.recordedRun ? (
<>
<>
{evidence.recordedRun?.kind === "portable-result-review" ? <LabCopyActions
id={evidence.lab.resultId} sourceId={evidence.lab.sourceSessionId}
onProgress={(value) => updateCopyProgress(evidence.lab.resultId, value)}
copy={localStorage.data?.entries[evidence.lab.resultId]} available={!!localStorage.data}
storageError={localStorage.error} /> : null}
<IconButton
label={`Удалить ${evidence.lab.labId} из AI Inference`}
onClick={() => openDelete(evidence)}
@@ -963,7 +972,7 @@ export function ObservatoryWorkspace({
>
<Icon name="edit" size={16} />
</IconButton>
<IconButton
{evidence.recordedRun ? <IconButton
label={`Открыть визуальный разбор: ${evidence.lab.labId}`}
disabled={
replay.kind === "loading"
@@ -975,9 +984,8 @@ export function ObservatoryWorkspace({
&& replay.binding.evidenceSessionId === evidence.sessionId
? <ActivityIndicator size="compact" />
: <Icon name="eye" size={16} />}
</IconButton>
</IconButton> : null}
</>
) : null}
</div>
</div>
</li>
@@ -1161,23 +1169,23 @@ export function ObservatoryWorkspace({
<ConfirmationModal
open={deleteTarget !== null || compositionDeleteTarget !== null}
title="Удалить результат из AI Inference?"
title="Удалить LAB безвозвратно?"
description={deleteTarget || compositionDeleteTarget ? (
<div className="observatory-delete-confirmation">
<p>
Будут удалены только каталожная проекция <strong>{deleteTarget?.label ?? compositionDeleteTarget?.displayName ?? compositionDeleteTarget?.presentation.configurationLabel}</strong>
{" "}и её отображаемое название в AI Inference.
Будут удалены LAB <strong>{deleteTarget?.label ?? compositionDeleteTarget?.displayName ?? compositionDeleteTarget?.presentation.configurationLabel}</strong>
{" "}и её данные на этом устройстве и на Worker, включая закреплённую локальную копию.
</p>
<p>
Исходная сессия, запечатанный лабораторный результат и файлы доказательств
останутся неизменными.
Исходная запись и данные, используемые другими LAB, сохранятся.
Отменить удаление нельзя.
</p>
{mutationError ? (
<p className="observatory-mutation-error" role="alert">{mutationError}</p>
) : null}
</div>
) : null}
confirmLabel="Удалить из AI Inference"
confirmLabel="Удалить LAB"
pendingLabel="Удаляем…"
danger
onClose={() => {
@@ -0,0 +1,21 @@
import assert from "node:assert/strict";
import { before, after, test } from "node:test";
import { createServer } from "./support/vite-server.mjs";
let server, api;
before(async () => { server = await createServer({ appType: "custom", logLevel: "silent", server: { middlewareMode: true } }); api = await server.ssrLoadModule("/src/core/observatory/failedRunHistory.ts"); });
after(async () => { await server?.close(); });
test("failed history distinguishes source, container and result assembly failures without exposing logs", () => {
assert.equal(api.failedRunDetail({ terminalMessage: "step camera-source exited with code 1" }), "Не удалось подготовить исходную запись");
assert.equal(api.failedRunDetail({ terminalMessage: "step assemble exited with code 1" }), "Не удалось собрать запись результата");
assert.equal(api.failedRunDetail({ terminalMessage: "Docker Engine returned 500" }), "Не удалось запустить вычислительный контейнер");
});
test("history removal rejects active and successful work before request", async () => {
const job = { jobId: `observatory-run-${"a".repeat(32)}`, state: "failed", resultId: null };
let calls=0;
const fetcher = async () => { calls++; return new Response(null,{status:204}); };
await assert.rejects(api.deleteFailedRunProjection({...job,state:"running"},fetcher));
await assert.rejects(api.deleteFailedRunProjection({...job,resultId:"result"},fetcher));
assert.equal(calls,0);
await api.deleteFailedRunProjection(job,fetcher);
assert.equal(calls,1);
});
@@ -0,0 +1,55 @@
import assert from "node:assert/strict";
import { after, before, test } from "node:test";
import { createServer } from "./support/vite-server.mjs";
let server, prepareLabReplay, labReplayProgressView, formatLocalLabSize;
before(async () => {
server = await createServer({ appType: "custom", logLevel: "silent", server: { middlewareMode: true } });
({ prepareLabReplay, labReplayProgressView } = await server.ssrLoadModule("/src/core/laboratory/prepareLabReplay.ts"));
({ formatLocalLabSize } = await server.ssrLoadModule("/src/core/storage/localLabPresentation.ts"));
});
after(async () => server?.close());
function baseResponse() {
const url = "/api/v1/observation-sessions/session-1/recording.rrd";
return Response.json({ schema_version: "missioncore.observation-session-replay/v2", launch: {
kind: "rerun-recording", session_id: "session-1", source_url: url,
viewer_source_url: `${url}?generation=${"a".repeat(64)}`, media_type: "application/vnd.rerun.rrd",
timeline: "session_time", timeline_start_seconds: 0, timeline_end_seconds: 10,
seekable: true, byte_length: 100, sha256: "a".repeat(64),
playback: { speed: 1, loop: false }, media_sources: [],
} });
}
test("copy preparation binds the selected source then builds one replay without inference", async () => {
const stages = [], calls = [];
const value = await prepareLabReplay("result-1", "session-1", async (id, base, options) => {
calls.push(id); assert.equal(base.sessionId, "session-1"); assert.equal(options.signal.aborted, false);
return { byteLength: 245 };
}, { signal: new AbortController().signal, onProgress: p => stages.push(p),
fetcher: async url => { calls.push(url); return baseResponse(); } });
assert.deepEqual(calls, ["/api/v1/observation-sessions/session-1/replay", "result-1"]);
assert.deepEqual(stages, [{ phase: "checking", fraction: null }, { phase: "preparing", fraction: null }]);
assert.equal(value.replay.byteLength, 245);
});
test("source failure does not start assembly or publish a success stage", async () => {
let assembled = false;
await assert.rejects(prepareLabReplay("result", "session-1", async () => { assembled = true; }, {
signal: new AbortController().signal, fetcher: async () => Response.json({detail:"offline"}, {status:503}),
}));
assert.equal(assembled, false);
});
test("closing preparation aborts its request and suppresses stale completion", async () => {
const owner = new AbortController(); let requestSignal;
await assert.rejects(prepareLabReplay("result", "session-1", async (_, __, options) => {
requestSignal = options.signal; owner.abort(); return { byteLength: 1 };
}, { signal: owner.signal, fetcher: async () => baseResponse() }), { name: "AbortError" });
assert.equal(requestSignal.aborted, true);
});
test("unknown progress stays indeterminate; measured opening progress has a percentage", () => {
assert.equal(labReplayProgressView({ phase: "preparing", fraction: null }).value, undefined);
assert.equal(labReplayProgressView({ phase: "opening", fraction: .47 }).text, "Открытие записи · 47%");
assert.equal(labReplayProgressView({ phase: "opening", fraction: NaN }).value, undefined);
});
test("removed copy shows zero even when old metadata retains a size; unknown is distinct", () => {
assert.equal(formatLocalLabSize({local:false, bytes:425918766}, true), "0 Б на устройстве");
assert.equal(formatLocalLabSize(undefined, false), "размер уточняется");
assert.equal(formatLocalLabSize({local:true, bytes:425918766}, true), "425,9 МБ");
});
@@ -222,7 +222,7 @@ test("Observatory exposes bounded-window uncertainty without inventing a broken
);
});
test("historical canonical replay stays out of Observatory without modifying its archive record", () => {
test("historical canonical replay remains in source history without modifying its archive record", () => {
const canonicalResultId = `lab-v1-vegetation-shadow-${"8".repeat(64)}`;
const canonical = evidence(
canonicalResultId,
@@ -252,12 +252,12 @@ test("historical canonical replay stays out of Observatory without modifying its
[canonical],
);
assert.deepEqual(catalog.items[0].evidence, []);
assert.equal(catalog.window.laboratoryCount, 0);
assert.equal(catalog.items[0].evidence[0].recordedRun.kind, "canonical-recorded-rerun");
assert.equal(catalog.window.laboratoryCount, 1);
assert.deepEqual(canonical, before);
});
test("only admitted portable evidence is visible regardless of LAB label, age or installed version", () => {
test("history retains unsupported formats while playback admission remains explicit", () => {
const legacy = evidence("legacy", "source", "2026-09-03T13:00:00Z");
legacy.lab.labId = "LAB M4.9T5";
legacy.lab.replayCapability = null;
@@ -267,9 +267,9 @@ test("only admitted portable evidence is visible regardless of LAB label, age or
const catalog = buildObservatoryCatalog(
[source("source", "2026-07-19T10:00:00Z")], [legacy, historical, current],
);
assert.deepEqual(catalog.items[0].evidence.map((item) => item.sessionId), ["new-portable", "old-portable"]);
assert.equal(catalog.window.laboratoryCount, 2);
assert.equal(findObservatoryEvidence(catalog, "legacy"), null);
assert.deepEqual(catalog.items[0].evidence.map((item) => item.sessionId), ["legacy", "new-portable", "old-portable"]);
assert.equal(catalog.window.laboratoryCount, 3);
assert.equal(findObservatoryEvidence(catalog, "legacy").recordedRun, null);
});
test("a malformed portable binding errors instead of silently disappearing as legacy", () => {
@@ -325,7 +325,8 @@ test("500 sources and later-page results are searchable metadata, with no archiv
} });
assert.equal(calls.length, 7);
assert.equal(catalog.items.length, 500);
assert.equal(catalog.window.laboratoryCount, 1);
assert.equal(catalog.window.laboratoryCount, 102);
assert.equal(catalog.items.find(item => item.source.id === "source-0").evidence.length, 101);
assert.equal(catalog.window.sourceLimitReached, false);
assert.equal(catalog.window.laboratoryLimitReached, false);
assert.equal(catalog.items.find((item) => item.source.id === "source-499").evidence[0].sessionId, "portable-after-legacy");
@@ -121,3 +121,14 @@ test("Observatory mutations reject response drift and preserve API detail", asyn
&& error.message === "Проекция не принадлежит AI Inference.",
);
});
test("legacy LAB projection can be removed without a replay capability", async () => {
let called = false;
await deleteObservatoryLabProjection({ sessionId: "lab-old", lab: {
labId: "LAB E21", sourceSessionId: "source", resultId: "archived-result", replayCapability: null,
} }, { fetcher: async (url) => {
assert.equal(url, "/api/v1/observatory/lab-projections/lab-old"); called = true;
return new Response(null, { status: 204 });
} });
assert.equal(called, true);
});
@@ -1,96 +0,0 @@
import assert from "node:assert/strict";
import React from "react";
import { after, before, test } from "node:test";
import { createServer } from "./support/vite-server.mjs";
let server;
let useObservatoryRecordedJobs;
let useObservatoryLaboratorySetups;
before(async () => {
server = await createServer({
appType: "custom", logLevel: "silent", server: { middlewareMode: true },
});
({ useObservatoryRecordedJobs } = await server.ssrLoadModule("/src/core/observatory/useObservatoryRecordedJobs.ts"));
({ useObservatoryLaboratorySetups } = await server.ssrLoadModule("/src/core/observatory/useObservatoryLaboratorySetups.ts"));
});
after(async () => { await server?.close(); });
// Deliberately inspect the render BEFORE effects/cleanup: stale state must already be hidden.
function renderBeforeEffects(hook, args, stateSlots) {
const internals = React.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;
const previous = internals.H;
let stateIndex = 0;
internals.H = {
useState: (initial) => [
stateIndex < stateSlots.length ? stateSlots[stateIndex++]
: typeof initial === "function" ? initial() : initial,
() => {},
],
useRef: (value) => ({ current: value }),
useMemo: (factory) => factory(),
useCallback: (fn) => fn,
useEffect: () => {},
};
try { return hook(...args); } finally { internals.H = previous; }
}
test("queue data and errors cannot survive a source/setup/version change for one render", () => {
const original = ["source-a", "profile-a", "a".repeat(64)];
const activeJob = { state: "running", publication: { state: "not-required" } };
const snapshot = {
selectionKey: JSON.stringify(original), jobs: [activeJob], state: "ready", error: "old error",
};
assert.equal(renderBeforeEffects(useObservatoryRecordedJobs, original, [snapshot]).activeJob, activeJob);
for (const next of [
["source-b", original[1], original[2]],
[original[0], "profile-b", original[2]],
[original[0], original[1], "b".repeat(64)],
["", "", ""],
]) {
const view = renderBeforeEffects(useObservatoryRecordedJobs, next, [snapshot]);
assert.deepEqual(view.jobs, []);
assert.equal(view.activeJob, null);
assert.equal(view.latestJob, null);
assert.equal(view.error, null);
assert.notEqual(view.state, "ready");
}
});
test("published, incompatible and previous-source profiles have no effective selection", () => {
const profile = {
setupId: "profile-a", origin: "portable-definition",
compatibility: { compatible: true },
runDefinition: { definitionSha256: "a".repeat(64) },
preflight: { outcome: "ready" },
};
function render(sourceId, setups) {
return renderBeforeEffects(useObservatoryLaboratorySetups, [sourceId], [
{ sourceSessionId: "source-a", setups }, "ready", null, "profile-a", 0, { kind: "idle" },
]);
}
assert.equal(render("source-a", [profile]).selectedSetupId, "profile-a");
for (const view of [
render("source-b", [profile]),
render("source-a", [{ ...profile, preflight: { outcome: "existing" } }]),
render("source-a", [{ ...profile, compatibility: { compatible: false } }]),
render("source-a", []),
]) {
assert.equal(view.selectedSetupId, "");
assert.equal(view.selectedSetup, null);
assert.deepEqual(view.selectableSetups, []);
}
});
test("historical failures are not presented as errors of a new operator action", () => {
const selection = ["source-a", "profile-a", "a".repeat(64)];
const snapshot = {
selectionKey: JSON.stringify(selection),
jobs: [{ jobId: "old-run", state: "failed", publication: { state: "not-required" } }],
state: "ready", error: null,
};
const view = renderBeforeEffects(useObservatoryRecordedJobs, selection, [snapshot]);
assert.equal(view.computationFailed, false);
assert.equal(view.error, null);
assert.equal(view.activeJob, null);
});
@@ -101,7 +101,7 @@ test("Observatory mounts the one shared canonical replay only after explicit adm
assert.doesNotMatch(workspace, /evidenceConfigurationLabel\([^)]*,\s*selectedSession\.source\.label/);
assert.match(
workspace,
/evidence\.recordedRun \? \([\s\S]*name="trash"[\s\S]*name="edit"[\s\S]*Открыть визуальный разбор:[\s\S]*name="eye"/,
/name="trash"[\s\S]*name="edit"[\s\S]*evidence\.recordedRun \? <IconButton[\s\S]*Открыть визуальный разбор:[\s\S]*name="eye"/,
);
assert.doesNotMatch(workspace, /observatory-evidence-card[^>]*tone="soft"/);
assert.match(workspace, /Открыть визуальный разбор/);
@@ -200,8 +200,8 @@ test("Observatory rename and delete use admitted projection mutations and canoni
assert.match(workspace, /<Window[\s\S]*title="Переименовать лабораторный результат"/);
assert.match(workspace, /<TextField[\s\S]*label="Название"[\s\S]*maxLength=\{160\}/);
assert.match(workspace, /<WindowFooterActions>[\s\S]*Сохранить/);
assert.match(workspace, /<ConfirmationModal[\s\S]*title="Удалить результат из AI Inference\?"/);
assert.match(workspace, /Исходная сессия, запечатанный лабораторный результат и файлы доказательств/);
assert.match(workspace, /<ConfirmationModal[\s\S]*title="Удалить LAB безвозвратно\?"/);
assert.match(workspace, /Исходная запись и данные, используемые другими LAB, сохранятся/);
assert.match(workspace, /renameAICompositionRunProjection/);
assert.match(workspace, /deleteAICompositionRunProjection/);
assert.match(workspace, /openCompositionRename\(run\)/);
@@ -219,7 +219,7 @@ test("Observatory rename and delete use admitted projection mutations and canoni
const deleteFlowEnd = workspace.indexOf("}, [aiJobsController, closeReplay", deleteFlowStart);
assert.ok(deleteFlowStart >= 0 && deleteFlowEnd > deleteFlowStart);
const wholeDeleteFlow = workspace.slice(deleteFlowStart, deleteFlowEnd);
const evidenceFlowStart = wholeDeleteFlow.indexOf("if (!deleteTarget?.recordedRun");
const evidenceFlowStart = wholeDeleteFlow.indexOf("if (!deleteTarget ||");
assert.ok(evidenceFlowStart >= 0);
const deleteFlow = wholeDeleteFlow.slice(evidenceFlowStart);
const teardown = deleteFlow.indexOf("closeReplay();");
@@ -296,7 +296,7 @@ test("Observatory configures independent AI modules and shows queued evidence pr
assert.match(workspace, /computing: \[25, 90\]/);
assert.match(workspace, /Подготавливаем камеру и LiDAR/);
assert.match(workspace, /прошло.*formatDuration\(progress\.elapsedSeconds\)/s);
assert.match(workspace, /Не удалось запустить модель/);
assert.match(workspace, /return failedRunDetail\(job\)/);
assert.doesNotMatch(workspace, /job\.terminalMessage|job\.publication\.error/);
assert.doesNotMatch(workspace, /function aiModuleLabel\(/);
assert.match(workspace, /aiJobsController\.moduleLabelsBySetup\[job\.setupId\] \?\? job\.setupId/);
@@ -334,11 +334,9 @@ test("Observatory configures independent AI modules and shows queued evidence pr
/accumulationSeconds: showLocalSlam \? sceneDraft\.accumulationSeconds : 0/,
);
assert.match(workspace, /<AICompositionReplay run=\{replay\.run\} \/>/);
assert.match(workspace, /function presentAIJob\(job: ObservatoryRecordedJob\)/);
assert.match(workspace, /if \(job\.state === "failed"\) return true/);
assert.match(workspace, /return job\.state !== "succeeded"/);
assert.match(workspace, /function presentLatestAIJobs/);
assert.match(workspace, /seenSetups\.has\(job\.setupId\)/);
assert.doesNotMatch(workspace, /presentLatestAIJobs|seenSetups/);
assert.match(workspace, /evidence.lab.resultId === job.resultId/);
assert.match(workspace, /История запусков/);
assert.match(configWindow, /fetchAICompositionJobs\(sourceSessionId, request\.signal\)/);
assert.match(
configWindow,