feat(observatory): ship modular AI inference labs

This commit is contained in:
DCCONSTRUCTIONS
2026-09-04 17:59:05 +03:00
parent eff60e490a
commit cada687173
145 changed files with 17651 additions and 1667 deletions
@@ -15,7 +15,9 @@ import {
} from "@nodedc/ui-react";
import { CanonicalVegetationRerunReplay } from "../../components/laboratory/CanonicalVegetationRerunReplay";
import { AICompositionReplay } from "../../components/laboratory/AICompositionReplay";
import { PortableResultReplay } from "../../components/laboratory/PortableResultReplay";
import { AIConfigurationWindow } from "../../components/observatory/AIConfigurationWindow";
import type { ObservationSessionStatus } from "../../core/observation/sessionArchive";
import { createObservationReplayCoordinator } from "../../core/observation/replayCoordinator";
import {
@@ -32,9 +34,14 @@ import {
renameObservatoryLabProjection,
} from "../../core/observatory/catalogMutations";
import { useObservatoryCatalog } from "../../core/observatory/useObservatoryCatalog";
import { useObservatoryLaboratorySetups } from "../../core/observatory/useObservatoryLaboratorySetups";
import { useObservatoryRecordedJobs } from "../../core/observatory/useObservatoryRecordedJobs";
import { recordedProgressLabel } from "../../core/observatory/recordedProgress";
import { useAICompositionJobs } from "../../core/observatory/useAICompositionJobs";
import {
deleteAICompositionRunProjection,
renameAICompositionRunProjection,
type AICompositionRun,
} from "../../core/observatory/aiComposition";
import type { ObservatoryRecordedJob } from "../../core/observatory/recordedJobs";
import type { RecordedProgressView } from "../../core/observatory/recordedProgress";
import type { WorkspaceDefinition } from "../../productModel";
const EMPTY_OBSERVATORY_ITEMS = [] as const;
@@ -53,8 +60,31 @@ type ObservatoryMutationReconciliation =
readonly sessionId: string;
};
type EvidenceSortDirection = "newest" | "oldest";
type ObservatoryEvidenceRow =
| {
readonly kind: "composition";
readonly id: string;
readonly timestamp: string;
readonly run: AICompositionRun;
}
| {
readonly kind: "job";
readonly id: string;
readonly timestamp: string;
readonly job: ObservatoryRecordedJob;
}
| {
readonly kind: "evidence";
readonly id: string;
readonly timestamp: string;
readonly evidence: ObservatoryEvidence;
};
type ObservatoryReplayState =
| { readonly kind: "closed" }
| { readonly kind: "composition"; readonly run: AICompositionRun }
| {
readonly kind: "loading";
readonly binding: ObservatoryRecordedRunBinding;
@@ -114,15 +144,198 @@ function formatDuration(seconds: number): string {
: `${minutes}:${String(remainingSeconds).padStart(2, "0")}`;
}
function compositionEventTimestamp(run: AICompositionRun): string {
if (run.state === "running" || run.jobs.length === 0) return run.createdAtUtc;
return run.jobs.reduce((latest, job) => (
Date.parse(job.updatedAtUtc) > Date.parse(latest) ? job.updatedAtUtc : latest
), run.createdAtUtc);
}
function compositionProducedEvidence(
run: AICompositionRun,
evidence: ObservatoryEvidence,
): boolean {
if (!run.resultIds.includes(evidence.sessionId)) return false;
const publishedAt = Date.parse(evidence.publishedAtUtc);
const compositionCreatedAt = Date.parse(run.createdAtUtc);
return Number.isFinite(publishedAt) && Number.isFinite(compositionCreatedAt)
&& publishedAt >= compositionCreatedAt;
}
function mutationErrorMessage(error: unknown): string {
return error instanceof Error && error.message.trim()
? error.message
: "Не удалось изменить лабораторный результат в Обсерватории.";
}
function evidenceResultSubtitle(evidence: ObservatoryEvidence): string {
const profileName = evidence.lab.calculationProfile?.displayName;
return profileName ? `${evidence.label} · ${profileName}` : evidence.label;
function evidenceConfigurationLabel(
evidence: ObservatoryEvidence,
moduleLabelsBySetup: Readonly<Record<string, string>>,
jobs: readonly ObservatoryRecordedJob[],
): string {
const setupId = evidence.lab.calculationProfile?.setupId
?? jobs.find((job) => job.resultId === evidence.sessionId)?.setupId;
const profileName = setupId
? moduleLabelsBySetup[setupId] ?? evidence.lab.calculationProfile?.displayName
: evidence.lab.calculationProfile?.displayName;
return profileName ?? evidence.label;
}
function aiJobTone(job: ObservatoryRecordedJob): "accent" | "success" | "danger" | "warning" {
if (job.state === "failed" || job.publication.state === "failed") return "danger";
if (job.state === "paused" || job.state === "preemption-pending") return "warning";
if (job.state === "succeeded") return "success";
return "accent";
}
const AI_PROGRESS_PHASE_RANGES = {
"source-transfer": [0, 5],
"source-preparation": [5, 25],
computing: [25, 90],
"result-assembly": [90, 95],
"result-transfer": [95, 99],
} as const;
function aiJobProgressPercent(
job: ObservatoryRecordedJob,
progress: RecordedProgressView | undefined,
): number {
if (job.state === "succeeded") return 100;
if (!progress) return 0;
const [start, end] = AI_PROGRESS_PHASE_RANGES[progress.phase];
if (progress.total === null || progress.total === 0) return start;
const phaseFraction = Math.max(0, Math.min(1, progress.completed / progress.total));
return start + ((end - start) * phaseFraction);
}
function aiJobStage(
job: ObservatoryRecordedJob,
progress: RecordedProgressView | undefined,
): string {
if (job.state === "failed" || job.publication.state === "failed") return "Ошибка";
if (job.state === "accepted" || job.state === "queued" || job.state === "claimed" || !progress) {
return "Инициализация";
}
if (progress.phase === "source-transfer" || progress.phase === "source-preparation") {
return "Передача на сервер";
}
return "Просчёт";
}
function computingStageDetail(
job: ObservatoryRecordedJob,
progress: RecordedProgressView,
recordingDurationSeconds: number,
): string {
if (job.setupId === "ai-range-object-distance-v1") {
if (progress.completed === 0) {
return "Подготавливаем камеру и LiDAR";
}
if (progress.completed === 1) {
return "Собираем видеоряд для модели";
}
if (progress.completed === 2) {
return "RF-DETR обрабатывает запись · измеренная скорость Worker 006: 17–18 FPS";
}
if (progress.completed === 3) return "Сопоставляем рамки с LiDAR · осталось несколько минут";
return "Собираем и проверяем результат";
}
if (job.setupId === "ai-segmentation-ddrnet-v1") {
if (progress.completed === 0) return "Подготавливаем входные данные · обычно 5–10 минут";
if (progress.completed === 1) return "Собираем видеоряд для модели";
if (progress.completed === 2) {
return `DDRNet обрабатывает запись · ориентир ${formatDuration(recordingDurationSeconds)}`;
}
return "Собираем и проверяем результат";
}
if (job.setupId === "ai-segmentation-eomt-v1") {
if (progress.completed === 0) return "Подготавливаем входные данные · обычно 5–10 минут";
if (progress.completed === 1) return "Собираем видеоряд для модели";
if (progress.completed === 2) {
return `EoMT обрабатывает запись · ориентир ${formatDuration(recordingDurationSeconds)}`;
}
return "Собираем и проверяем результат";
}
if (job.setupId === "ai-detection-rf-detr-v1") {
if (progress.completed === 0) return "Подготавливаем входные данные · обычно 5–10 минут";
if (progress.completed === 1) return "Собираем видеоряд для модели";
if (progress.completed === 2) {
return `RF-DETR обрабатывает запись · ориентир ${formatDuration(recordingDurationSeconds)}`;
}
return "Собираем и проверяем результат";
}
return "Обрабатываем запись выбранным модулем";
}
function aiJobStageDetail(
job: ObservatoryRecordedJob,
progress: RecordedProgressView | undefined,
recordingDurationSeconds: number,
): string {
if (job.state === "failed") {
return "Не удалось запустить модель. Конфигурацию можно отправить повторно";
}
if (job.publication.state === "failed") {
return "Результат рассчитан, но не сохранён в Обсерватории";
}
if (job.state === "succeeded") {
if (job.publication.state === "pending") return "Завершаем сохранение результата";
if (job.publication.state === "not-required") return "Публикация результата не требуется";
return "Результат сохранён в Обсерватории";
}
if (!progress) {
return "Готовим конфигурацию и место в очереди";
}
if (progress.phase === "source-transfer") {
if (progress.total !== null && progress.total > 0) {
return `${progress.completed.toLocaleString("ru-RU")} / ${progress.total.toLocaleString("ru-RU")} файлов`;
}
return "Копируем исходную запись на Worker 006";
}
if (progress.phase === "source-preparation") return "Проверяем целостность переданных данных";
if (progress.phase === "computing") {
return computingStageDetail(job, progress, recordingDurationSeconds);
}
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>>,
): number {
if (run.state === "ready") return 100;
if (run.jobs.length === 0) return 0;
return run.jobs.reduce(
(total, job) => total + aiJobProgressPercent(job, progress[job.jobId]),
0,
) / run.jobs.length;
}
function compositionStage(
run: AICompositionRun,
progress: Readonly<Record<string, RecordedProgressView>>,
): string {
if (run.state === "ready") return "Расчёт завершён";
if (run.state === "failed") return "Ошибка расчёта";
const current = run.jobs.find((job) => job.state !== "succeeded") ?? run.jobs[0];
return current ? aiJobStage(current, progress[current.jobId]) : "Инициализация";
}
export function ObservatoryWorkspace({
@@ -132,22 +345,21 @@ export function ObservatoryWorkspace({
}) {
const controller = useObservatoryCatalog();
const [selectedSessionId, setSelectedSessionId] = useState("");
const setupController = useObservatoryLaboratorySetups(selectedSessionId);
const recordedJobsController = useObservatoryRecordedJobs(
selectedSessionId,
setupController.selectedSetupId,
setupController.selectedSetup?.runDefinition?.definitionSha256 ?? "",
);
const [aiConfigurationOpen, setAIConfigurationOpen] = useState(false);
const [evidenceSortDirection, setEvidenceSortDirection] = useState<EvidenceSortDirection>("newest");
const aiJobsController = useAICompositionJobs(selectedSessionId);
const [replay, setReplay] = useState<ObservatoryReplayState>({ kind: "closed" });
const [renameTarget, setRenameTarget] = useState<ObservatoryEvidence | null>(null);
const [compositionRenameTarget, setCompositionRenameTarget] = useState<AICompositionRun | null>(null);
const [renameValue, setRenameValue] = useState("");
const [deleteTarget, setDeleteTarget] = useState<ObservatoryEvidence | null>(null);
const [compositionDeleteTarget, setCompositionDeleteTarget] = useState<AICompositionRun | null>(null);
const [mutationPending, setMutationPending] = useState<"rename" | "delete" | null>(null);
const [mutationError, setMutationError] = useState<string | null>(null);
const [mutationReconciliation, setMutationReconciliation] = useState<
ObservatoryMutationReconciliation | null
>(null);
const overviewRef = useRef<HTMLElement | null>(null);
const overviewRef = useRef<HTMLDivElement | null>(null);
const replayCoordinatorRef = useRef(createObservationReplayCoordinator());
const refreshedPublishedJobRef = useRef<string | null>(null);
const items = controller.catalog?.items ?? EMPTY_OBSERVATORY_ITEMS;
@@ -165,6 +377,7 @@ export function ObservatoryWorkspace({
useEffect(() => {
if (items.some((item) => item.source.id === selectedSessionId)) return;
closeReplay();
setAIConfigurationOpen(false);
setSelectedSessionId(items[0]?.source.id ?? "");
}, [closeReplay, items, selectedSessionId]);
@@ -173,62 +386,54 @@ export function ObservatoryWorkspace({
const selectedSession = items.find(
(item) => item.source.id === selectedSessionId,
) ?? null;
const presentedEvidence = selectedSession?.evidence ?? [];
const presentedCompositionRuns = aiJobsController.runs;
const presentedEvidence = (selectedSession?.evidence ?? []).filter(
(evidence) => !presentedCompositionRuns.some(
(run) => compositionProducedEvidence(run, evidence),
),
);
const options = useMemo(() => items.map(({ source, evidence }) => ({
value: source.id,
label: source.label,
description: `${formatTimestamp(source.startedAtUtc)} · ${formatDuration(source.durationSeconds)} · ${evidence.length} результатов`,
})), [items]);
const setupOptions = useMemo(() => (
setupController.selectableSetups.map((setup) => ({
value: setup.setupId,
label: setup.displayName,
description: setup.description,
}))
), [setupController.selectableSetups]);
const preflightCandidate = setupController.preflight.kind === "ready"
? setupController.preflight.value
: null;
const runPreflight = preflightCandidate
&& preflightCandidate.sourceSessionId === selectedSession?.source.id
&& preflightCandidate.setupId === setupController.selectedSetup?.setupId
&& preflightCandidate.definitionSha256
=== setupController.selectedSetup?.runDefinition?.definitionSha256
? preflightCandidate
: null;
const queueSubmissionAllowed = Boolean(
setupController.selectedSetup?.runDefinition
&& setupController.selectedSetup.compatibility.compatible
&& runPreflight?.outcome === "queueable"
&& runPreflight.submissionAllowed,
const compositionJobIds = useMemo(() => new Set(
presentedCompositionRuns.flatMap((run) => run.jobIds),
), [presentedCompositionRuns]);
const presentedAIJobs = presentLatestAIJobs(aiJobsController.jobs).filter(
(job) => !compositionJobIds.has(job.jobId),
);
const presentedJob = recordedJobsController.activeJob ?? recordedJobsController.latestJob;
const publicationFailed = presentedJob?.publication.state === "failed";
const calculationPending = recordedJobsController.activeJob !== null
|| recordedJobsController.publicationPending
|| recordedJobsController.state === "submitting"
|| recordedJobsController.state === "retrying-publication";
const showCalculate = setupController.selectedSetup !== null
&& !calculationPending && !publicationFailed;
const canSubmitRecordedJob = queueSubmissionAllowed
&& setupController.state === "ready"
&& recordedJobsController.state === "ready"
&& !calculationPending && !publicationFailed;
const queueStatusError = setupController.preflight.kind === "error"
? setupController.preflight.message
: recordedJobsController.error
?? (publicationFailed
? presentedJob?.publication.error ?? "Не удалось опубликовать результат."
: recordedJobsController.computationFailed
? "Не удалось выполнить расчёт. Можно повторить запуск."
: runPreflight?.outcome === "blocked"
? runPreflight.checks.filter((check) => check.outcome === "fail")
.map((check) => check.message).join(" ") || "Запуск профиля недоступен."
: null);
const presentedRows = useMemo<readonly ObservatoryEvidenceRow[]>(() => {
const rows: ObservatoryEvidenceRow[] = [
...presentedCompositionRuns.map((run): ObservatoryEvidenceRow => ({
kind: "composition",
id: run.runId,
timestamp: compositionEventTimestamp(run),
run,
})),
...presentedAIJobs.map((job): ObservatoryEvidenceRow => ({
kind: "job",
id: job.jobId,
timestamp: job.updatedAtUtc,
job,
})),
...presentedEvidence.map((evidence): ObservatoryEvidenceRow => ({
kind: "evidence",
id: evidence.sessionId,
timestamp: evidence.publishedAtUtc,
evidence,
})),
];
const direction = evidenceSortDirection === "newest" ? -1 : 1;
return rows.sort((left, right) => (
direction * (Date.parse(left.timestamp) - Date.parse(right.timestamp))
|| left.id.localeCompare(right.id)
));
}, [evidenceSortDirection, presentedAIJobs, presentedCompositionRuns, presentedEvidence]);
const initialLoading = !controller.catalog
&& ["idle", "loading"].includes(controller.state);
const unavailable = !controller.catalog && controller.state === "error";
const replayEvidenceId = replay.kind === "closed"
const replayEvidenceId = replay.kind === "closed" || replay.kind === "composition"
? null
: replay.binding.evidenceSessionId;
const replayEvidence = replayEvidenceId === null
@@ -238,14 +443,13 @@ export function ObservatoryWorkspace({
) ?? null;
useEffect(() => {
const publishedJob = recordedJobsController.jobs.find(
const publishedJob = aiJobsController.jobs.find(
(job) => job.publication.state === "published" && job.resultId !== null,
);
if (!publishedJob || refreshedPublishedJobRef.current === publishedJob.jobId) return;
refreshedPublishedJobRef.current = publishedJob.jobId;
void controller.refresh();
setupController.refresh();
}, [controller.refresh, recordedJobsController.jobs, setupController.refresh]);
}, [aiJobsController.jobs, controller.refresh]);
useEffect(() => {
if (
@@ -276,8 +480,7 @@ export function ObservatoryWorkspace({
setDeleteTarget(null);
setMutationError(null);
setMutationReconciliation(null);
if (mutationReconciliation.kind === "delete") setupController.refresh();
}, [controller.catalog, mutationPending, mutationReconciliation, setupController.refresh]);
}, [controller.catalog, mutationPending, mutationReconciliation]);
const openReplay = useCallback((binding: ObservatoryRecordedRunBinding) => {
const attempt = replayCoordinatorRef.current.begin();
@@ -307,6 +510,8 @@ export function ObservatoryWorkspace({
const openRename = useCallback((evidence: ObservatoryEvidence) => {
if (!evidence.recordedRun) return;
setCompositionRenameTarget(null);
setCompositionDeleteTarget(null);
setDeleteTarget(null);
setMutationError(null);
setMutationReconciliation(null);
@@ -316,13 +521,52 @@ export function ObservatoryWorkspace({
const openDelete = useCallback((evidence: ObservatoryEvidence) => {
if (!evidence.recordedRun) return;
setCompositionRenameTarget(null);
setCompositionDeleteTarget(null);
setRenameTarget(null);
setMutationError(null);
setMutationReconciliation(null);
setDeleteTarget(evidence);
}, []);
const openCompositionRename = useCallback((run: AICompositionRun) => {
setRenameTarget(null);
setDeleteTarget(null);
setCompositionDeleteTarget(null);
setMutationError(null);
setMutationReconciliation(null);
setRenameValue(run.displayName ?? run.presentation.configurationLabel);
setCompositionRenameTarget(run);
}, []);
const openCompositionDelete = useCallback((run: AICompositionRun) => {
setRenameTarget(null);
setDeleteTarget(null);
setCompositionRenameTarget(null);
setMutationError(null);
setMutationReconciliation(null);
setCompositionDeleteTarget(run);
}, []);
const submitRename = useCallback(async () => {
if (compositionRenameTarget) {
if (mutationPending !== null) return;
setMutationPending("rename");
setMutationError(null);
try {
await renameAICompositionRunProjection(
compositionRenameTarget.runId,
renameValue,
);
setCompositionRenameTarget(null);
aiJobsController.refresh();
} catch (error) {
setMutationError(mutationErrorMessage(error));
} finally {
setMutationPending(null);
}
return;
}
if (!renameTarget?.recordedRun || mutationPending !== null) return;
const requestedDisplayName = renameValue.trim();
const reconciliation: ObservatoryMutationReconciliation = {
@@ -356,9 +600,27 @@ export function ObservatoryWorkspace({
} finally {
setMutationPending(null);
}
}, [controller, mutationPending, renameTarget, renameValue]);
}, [aiJobsController, compositionRenameTarget, controller, mutationPending, renameTarget, renameValue]);
const confirmDelete = useCallback(async () => {
if (compositionDeleteTarget) {
if (mutationPending !== null) return;
setMutationPending("delete");
setMutationError(null);
try {
if (replay.kind === "composition" && replay.run.runId === compositionDeleteTarget.runId) {
flushSync(() => closeReplay());
}
await deleteAICompositionRunProjection(compositionDeleteTarget.runId);
setCompositionDeleteTarget(null);
aiJobsController.refresh();
} catch (error) {
setMutationError(mutationErrorMessage(error));
} finally {
setMutationPending(null);
}
return;
}
if (!deleteTarget?.recordedRun || mutationPending !== null) return;
const reconciliation: ObservatoryMutationReconciliation = {
kind: "delete",
@@ -370,6 +632,7 @@ export function ObservatoryWorkspace({
try {
if (
replay.kind !== "closed"
&& replay.kind !== "composition"
&& replay.binding.evidenceSessionId === deleteTarget.sessionId
) {
flushSync(() => {
@@ -378,7 +641,6 @@ export function ObservatoryWorkspace({
}
await deleteObservatoryLabProjection(deleteTarget.recordedRun);
controller.applyEvidenceDeletion(deleteTarget.sessionId);
setupController.refresh();
setDeleteTarget(null);
setMutationReconciliation(null);
void controller.refresh();
@@ -399,25 +661,16 @@ export function ObservatoryWorkspace({
} finally {
setMutationPending(null);
}
}, [closeReplay, controller, deleteTarget, mutationPending, replay, setupController.refresh]);
}, [aiJobsController, closeReplay, compositionDeleteTarget, controller, deleteTarget, mutationPending, replay]);
return (
<div
ref={overviewRef}
className="observatory-workspace"
data-workspace-id={definition.id}
data-observatory-authority="observation-only"
data-observatory-viewer={replay.kind === "ready" ? "attached" : "detached"}
data-observatory-viewer={replay.kind === "ready" || replay.kind === "composition" ? "attached" : "detached"}
>
<section ref={overviewRef} className="observatory-lead">
<div>
<span className="section-eyebrow">{definition.eyebrow}</span>
<h2>{definition.title}</h2>
<p>
Записанные источники и строго связанные результаты без запуска тяжёлого
визуализатора и без доступа к управлению аппаратом.
</p>
</div>
</section>
<GlassSurface className="observatory-catalog-bar" padding="sm">
<div className="observatory-catalog-bar__copy">
<span className="section-eyebrow">ИСТОЧНИК ДОКАЗАТЕЛЬСТВ</span>
@@ -436,83 +689,23 @@ export function ObservatoryWorkspace({
menuWidth={460}
onChange={selectSession}
/>
<Select
label="Выбрать сетап лаборатории"
value={setupController.selectedSetupId}
options={setupOptions}
disabled={!selectedSessionId || setupOptions.length === 0}
searchable
searchPlaceholder="Поиск по сетапам"
emptyLabel={setupController.state === "error" ? "Каталог профилей недоступен" : "Нет профилей для расчёта"}
minMenuWidth={360}
menuWidth={500}
onChange={setupController.selectSetup}
/>
<Button
size="compact"
variant="secondary"
disabled={
controller.state === "loading"
|| controller.state === "refreshing"
|| setupController.state === "loading"
|| setupController.state === "refreshing"
}
icon={<Icon name="refresh" />}
onClick={() => {
void controller.refresh();
setupController.refresh();
recordedJobsController.refresh();
}}
variant="primary"
disabled={!selectedSession}
onClick={() => setAIConfigurationOpen(true)}
>
Обновить
Сконфигурировать AI-слой
</Button>
<div className="observatory-catalog-bar__run" aria-busy={calculationPending}>
{calculationPending ? (
<>
<ActivityIndicator size="compact" />
<span role="status">
{recordedProgressLabel(presentedJob, recordedJobsController.progress)}
</span>
</>
) : null}
{showCalculate ? (
<Button
size="compact"
variant="primary"
disabled={!canSubmitRecordedJob}
onClick={() => {
void recordedJobsController.submit(
setupController.selectedSetup?.origin === "portable-definition"
&& runPreflight?.definitionSha256
&& runPreflight.checkSha256
? {
definitionSha256: runPreflight.definitionSha256,
checkSha256: runPreflight.checkSha256,
}
: null,
);
}}
>
Рассчитать
</Button>
) : null}
</div>
</div>
</GlassSurface>
{queueStatusError ? (
{aiJobsController.error ? (
<GlassSurface className="observatory-notice" padding="md" tone="soft" role="alert">
<span className="observatory-notice__copy">{queueStatusError}</span>
{publicationFailed ? (
<Button
size="compact"
variant="ghost"
disabled={recordedJobsController.state === "retrying-publication"}
onClick={() => void recordedJobsController.retryPublication()}
>
Повторить публикацию
</Button>
) : null}
<span className="observatory-notice__copy">{aiJobsController.error}</span>
<Button size="compact" variant="ghost" onClick={aiJobsController.refresh}>
Повторить
</Button>
</GlassSurface>
) : null}
@@ -524,13 +717,6 @@ export function ObservatoryWorkspace({
</GlassSurface>
) : null}
{setupController.error ? (
<GlassSurface className="observatory-notice" padding="md" tone="soft" role="alert">
<span className="observatory-notice__copy">{setupController.error}</span>
<Button size="compact" variant="ghost" onClick={setupController.refresh}>Повторить</Button>
</GlassSurface>
) : null}
{controller.catalog
&& (controller.catalog.window.sourceLimitReached
|| controller.catalog.window.laboratoryLimitReached) ? (
@@ -616,23 +802,150 @@ export function ObservatoryWorkspace({
<span className="section-eyebrow">СВЯЗАННЫЕ РЕЗУЛЬТАТЫ</span>
<h3>Лабораторные доказательства</h3>
</div>
<StatusBadge tone={selectedSession.evidence.length > 0 ? "accent" : "neutral"}>
{selectedSession.evidence.length}
</StatusBadge>
<div className="observatory-evidence__ordering">
<StatusBadge tone={presentedRows.length > 0 ? "accent" : "neutral"}>
{presentedRows.length}
</StatusBadge>
<button
type="button"
className="observatory-evidence__sort"
data-direction={evidenceSortDirection}
aria-label={evidenceSortDirection === "newest"
? "Показать сначала старые результаты"
: "Показать сначала новые результаты"}
title={evidenceSortDirection === "newest"
? "Сначала новые"
: "Сначала старые"}
onClick={() => setEvidenceSortDirection((current) => (
current === "newest" ? "oldest" : "newest"
))}
>
<svg viewBox="0 0 18 18" aria-hidden="true">
<path d="M3 5h12M5 9h10M7 13h8" />
</svg>
</button>
</div>
</header>
{selectedSession.evidence.length > 0 ? (
{presentedRows.length > 0 ? (
<ol className="observatory-evidence-list">
{presentedEvidence.map((evidence) => (
{presentedRows.map((row) => {
if (row.kind === "composition") {
const { run } = row;
const failed = run.state === "failed";
const active = run.state === "running";
const progressPercent = compositionProgressPercent(run, aiJobsController.progress);
return (
<li key={run.runId}>
<div className={`observatory-evidence-card${active
? " observatory-evidence-card--progress" : ""}`}
aria-busy={active}>
<span className="observatory-evidence-card__icon" aria-hidden="true">
{failed ? <Icon name="alert" size={16} />
: run.state === "ready" ? <Icon name="clipboard" size={18} />
: <ActivityIndicator size="compact" />}
</span>
<div className="observatory-evidence-card__copy">
<strong>{run.displayName ?? run.presentation.configurationLabel}</strong>
{active ? (
<div className="observatory-evidence-card__progress" aria-hidden="true">
<span style={{ width: `${progressPercent}%` }} />
</div>
) : null}
<small>{run.state === "ready"
? formatTimestamp(row.timestamp)
: `${compositionStage(run, aiJobsController.progress)} · ${formatTimestamp(row.timestamp)}`}</small>
</div>
{active ? (
<StatusBadge tone="accent">{Math.round(progressPercent)}%</StatusBadge>
) : failed ? <StatusBadge tone="danger">Ошибка</StatusBadge> : null}
<div className="observatory-evidence-card__actions">
{run.state === "ready" ? (
<>
<IconButton
label={`Удалить ${run.displayName ?? run.presentation.configurationLabel} из Обсерватории`}
onClick={() => openCompositionDelete(run)}
>
<Icon name="trash" size={16} />
</IconButton>
<IconButton
label={`Переименовать ${run.displayName ?? run.presentation.configurationLabel}`}
onClick={() => openCompositionRename(run)}
>
<Icon name="edit" size={16} />
</IconButton>
<IconButton label={`Открыть визуальный разбор: ${run.configurationLabel}`}
onClick={() => setReplay({ kind: "composition", run })}>
<Icon name="eye" size={16} />
</IconButton>
</>
) : null}
</div>
</div>
</li>
);
}
if (row.kind === "job") {
const { job } = row;
const progress = aiJobsController.progress[job.jobId];
const progressPercent = aiJobProgressPercent(job, progress);
const moduleLabel = aiJobsController.moduleLabelsBySetup[job.setupId] ?? job.setupId;
const failed = job.state === "failed" || job.publication.state === "failed";
const active = !failed && (
job.state !== "succeeded" || job.publication.state === "pending"
);
return (
<li key={job.jobId}>
<div
className={`observatory-evidence-card${active
? " observatory-evidence-card--progress" : ""}`}
aria-busy={active}
>
<span className="observatory-evidence-card__icon" aria-hidden="true">
{failed
? <Icon name="alert" size={16} />
: job.state === "succeeded"
? <Icon name="check" size={16} />
: <ActivityIndicator size="compact" />}
</span>
<div className="observatory-evidence-card__copy">
<strong>{moduleLabel}</strong>
{active ? (
<div className="observatory-evidence-card__progress" aria-hidden="true">
<span style={{ width: `${progressPercent}%` }} />
</div>
) : null}
<small>
{aiJobStage(job, progress)} · {aiJobStageDetail(
job,
progress,
selectedSession.source.durationSeconds,
)}{progress && !failed && job.state !== "succeeded"
? ` · прошло ${formatDuration(progress.elapsedSeconds)}`
: ""} · {formatTimestamp(row.timestamp)}
</small>
</div>
{active ? (
<StatusBadge tone={aiJobTone(job)}>{Math.round(progressPercent)}%</StatusBadge>
) : failed ? <StatusBadge tone="danger">Ошибка</StatusBadge> : null}
</div>
</li>
);
}
const { evidence } = row;
return (
<li key={evidence.sessionId}>
<div className="observatory-evidence-card">
<span className="observatory-evidence-card__icon" aria-hidden="true">
<Icon name="clipboard" size={18} />
</span>
<div className="observatory-evidence-card__copy">
<strong>{evidence.lab.labId}</strong>
<span>{evidenceResultSubtitle(evidence)}</span>
<strong>{evidenceConfigurationLabel(
evidence,
aiJobsController.moduleLabelsBySetup,
aiJobsController.jobs,
)}</strong>
<small>
{evidence.lab.resultKind} · {formatTimestamp(evidence.publishedAtUtc)}
{formatTimestamp(row.timestamp)}
</small>
</div>
<div className="observatory-evidence-card__actions">
@@ -668,7 +981,8 @@ export function ObservatoryWorkspace({
</div>
</div>
</li>
))}
);
})}
</ol>
) : (
<div className="observatory-evidence-empty">
@@ -711,6 +1025,20 @@ export function ObservatoryWorkspace({
<Button size="compact" variant="ghost" onClick={returnToOverview}>Закрыть</Button>
</div>
</GlassSurface>
) : replay.kind === "composition" ? (
<section className="observatory-replay" aria-label="Визуальный разбор конфигурации">
<header className="observatory-replay__header">
<div>
<span className="section-eyebrow">СОХРАНЁННАЯ КОНФИГУРАЦИЯ</span>
<h3>{replay.run.configurationLabel}</h3>
</div>
<Button size="compact" variant="secondary" icon={<Icon name="close" size={14} />}
onClick={returnToOverview}>
Закрыть разбор
</Button>
</header>
<AICompositionReplay run={replay.run} />
</section>
) : replay.kind === "ready" ? (
<section className="observatory-replay" aria-label="Визуальный разбор результата">
<header className="observatory-replay__header">
@@ -718,12 +1046,13 @@ export function ObservatoryWorkspace({
<span className="section-eyebrow">
СОХРАНЁННЫЙ РЕЗУЛЬТАТ / ЗАПИСАННАЯ СЕССИЯ
</span>
<h3>{replayEvidence?.label ?? replay.binding.resultId}</h3>
<p>
{replay.review.kind === "canonical-recorded-rerun"
? "Записанный маршрут синхронизирован по общей временной шкале."
: "Просмотр сохранённых данных результата без повторного расчёта."}
</p>
<h3>{replayEvidence && selectedSession
? evidenceConfigurationLabel(
replayEvidence,
aiJobsController.moduleLabelsBySetup,
aiJobsController.jobs,
)
: replay.binding.resultId}</h3>
</div>
<Button
size="compact"
@@ -740,7 +1069,14 @@ export function ObservatoryWorkspace({
review={replay.review.review}
/>
) : (
<PortableResultReplay review={replay.review} />
<PortableResultReplay review={replay.review}
label={replayEvidence && selectedSession
? evidenceConfigurationLabel(
replayEvidence,
aiJobsController.moduleLabelsBySetup,
aiJobsController.jobs,
)
: replay.binding.resultId} />
)}
</section>
) : null}
@@ -756,7 +1092,7 @@ export function ObservatoryWorkspace({
) : null}
<Window
open={renameTarget !== null}
open={renameTarget !== null || compositionRenameTarget !== null}
title="Переименовать лабораторный результат"
subtitle="Меняется только отображаемое название в Обсерватории"
size="sm"
@@ -765,6 +1101,7 @@ export function ObservatoryWorkspace({
onClose={() => {
if (mutationPending === "rename") return;
setRenameTarget(null);
setCompositionRenameTarget(null);
setMutationError(null);
setMutationReconciliation(null);
}}
@@ -774,6 +1111,7 @@ export function ObservatoryWorkspace({
disabled={mutationPending === "rename"}
onClick={() => {
setRenameTarget(null);
setCompositionRenameTarget(null);
setMutationError(null);
setMutationReconciliation(null);
}}
@@ -808,19 +1146,26 @@ export function ObservatoryWorkspace({
disabled={mutationPending === "rename"}
onChange={(event) => setRenameValue(event.currentTarget.value)}
/>
{mutationError && renameTarget ? (
{mutationError && (renameTarget || compositionRenameTarget) ? (
<p className="observatory-mutation-error" role="alert">{mutationError}</p>
) : null}
</form>
</Window>
<AIConfigurationWindow
open={aiConfigurationOpen && selectedSession !== null}
sourceSessionId={selectedSession?.source.id ?? ""}
sourceLabel={selectedSession?.source.label ?? ""}
onClose={() => setAIConfigurationOpen(false)}
onCalculated={() => aiJobsController.refresh()}
/>
<ConfirmationModal
open={deleteTarget !== null}
open={deleteTarget !== null || compositionDeleteTarget !== null}
title="Удалить результат из Обсерватории?"
description={deleteTarget ? (
description={deleteTarget || compositionDeleteTarget ? (
<div className="observatory-delete-confirmation">
<p>
Будут удалены только каталожная проекция <strong>{deleteTarget.label}</strong>
Будут удалены только каталожная проекция <strong>{deleteTarget?.label ?? compositionDeleteTarget?.displayName ?? compositionDeleteTarget?.presentation.configurationLabel}</strong>
{" "}и её отображаемое название в Обсерватории.
</p>
<p>
@@ -838,6 +1183,7 @@ export function ObservatoryWorkspace({
onClose={() => {
if (mutationPending === "delete") return;
setDeleteTarget(null);
setCompositionDeleteTarget(null);
setMutationError(null);
setMutationReconciliation(null);
}}