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 };
}