refactor(lab): move execution to Worker and manage replay and transfer lifecycles
This commit is contained in:
@@ -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,
|
||||
|
||||
Reference in New Issue
Block a user