feat(workflow-bar): processing-only elapsed timer + optimistic phase paint on resume

Timer now accumulates only while the harness works, pausing while a gate awaits
the reviewer and freezing when finalized (keyed per session, in-memory). Resume
now colours the re-entry phase immediately from the manifest's phase (1..8),
mirroring the F1 paint for new questions.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-07-03 14:13:02 +02:00
co-authored by Claude Opus 4.8
parent e4ada07dab
commit 56ed8b29bd
5 changed files with 91 additions and 49 deletions
@@ -82,6 +82,20 @@ test("Resume from the panel activates the session and closes the panel", async (
await waitFor(() => expect(screen.queryByText("Domanda originale")).not.toBeInTheDocument()); // panel closed
});
test("Resume paints the re-entry phase from the manifest (optimistic, before the first gate)", async () => {
useSessionStore.getState().resetSession();
server.use(
http.post("http://localhost:8787/sessions/:id/resume", () => new HttpResponse(null, { status: 204 })),
http.get("http://localhost:8787/sessions/:id", () =>
HttpResponse.json({ id: "s1", status: "open", phase: 4 })),
);
wrap();
await userEvent.click(await screen.findByText("Attiva uno"));
await screen.findByText("Domanda originale"); // panel open
await userEvent.click(screen.getByRole("button", { name: /resume/i }));
await waitFor(() => expect(useSessionStore.getState().currentPhase).toBe("F4"));
});
test("a failed resume keeps the panel open and does not activate the session", async () => {
server.use(http.post("http://localhost:8787/sessions/:id/resume", () => new HttpResponse(null, { status: 409 })));
wrap();
+19 -10
View File
@@ -15,12 +15,12 @@ import { Button } from "../components/ui/button";
import { Toaster } from "../components/ui/sonner";
import { toast } from "sonner";
import {
closeSession, listSessions, resumeSession,
closeSession, listSessions, resumeSession, getSession,
renameSession, setSessionGroup, archiveSession, unarchiveSession, deleteSession,
} from "../api/sessions";
import type { SessionSummary } from "../api/types";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useEffect, useMemo, useRef, useState } from "react";
import { useMemo, useRef, useState } from "react";
/**
* The page is designed to live INSIDE the Omics Portal chrome (its left sidebar
@@ -55,12 +55,6 @@ export function AppShell() {
const refresh = () => queryClient.invalidateQueries({ queryKey: ["sessions"] });
const activeSession = sessions.find((s) => s.id === activeSessionId) ?? null;
const finalized = activeSession?.status === "finalized";
const [localStart, setLocalStart] = useState<string | null>(null);
useEffect(() => {
if (activeSessionId && !activeSession) setLocalStart((prev) => prev ?? new Date().toISOString());
else if (!activeSessionId) setLocalStart(null);
}, [activeSessionId, activeSession]);
const startedAt = activeSession?.created_at ?? localStart;
function openPanel(id: string) {
const s = sessions.find((x) => x.id === id);
@@ -78,6 +72,17 @@ export function AppShell() {
await resumeSession(id);
setPanelSession(null);
setActiveSessionId(id);
// Optimistic phase paint on resume: colour the re-entry phase immediately,
// before the first gate arrives (mirrors the F1 paint for new questions).
// The manifest's `phase` is the 1-based current phase (1..8).
try {
const m = (await getSession(id)) as { phase?: number };
if (typeof m.phase === "number" && m.phase >= 1 && m.phase <= 8) {
setPhase(`F${m.phase}`);
}
} catch {
/* non-fatal: the first gate will set the phase */
}
} catch {
toast.error("Failed to resume session.");
}
@@ -141,7 +146,11 @@ export function AppShell() {
// waiting on the human; once a widget appears, input is back in the user's court.
const pendingWidget = useSessionStore((s) => s.pendingWidget);
const resetSession = useSessionStore((s) => s.resetSession);
const setPhase = useSessionStore((s) => s.setPhase);
const working = Boolean(activeSessionId) && !pendingWidget;
// Processing time counts only while the harness works, not while a finalized
// session sits idle or a gate awaits the reviewer (pendingWidget).
const running = working && !finalized;
useSessionStream(activeSessionId);
@@ -179,8 +188,8 @@ export function AppShell() {
<div className="mx-auto max-w-3xl">
<WorkflowBar
finalized={finalized}
createdAt={startedAt}
updatedAt={activeSession?.updated_at ?? null}
running={running}
resetKey={activeSessionId}
/>
</div>
</div>
+23 -12
View File
@@ -1,17 +1,28 @@
import { render, screen } from "@testing-library/react";
import { render, screen, act } from "@testing-library/react";
import { ElapsedTimer } from "./ElapsedTimer";
test("renders nothing without a start time", () => {
const { container } = render(<ElapsedTimer startedAt={null} />);
expect(container).toBeEmptyDOMElement();
test("starts at zero", () => {
render(<ElapsedTimer running={false} />);
expect(screen.getByText("0m 0s")).toBeInTheDocument();
});
test("frozen elapsed when stoppedAt is set (2m 5s)", () => {
render(
<ElapsedTimer
startedAt="2026-07-03T10:00:00.000Z"
stoppedAt="2026-07-03T10:02:05.000Z"
/>,
);
expect(screen.getByText("2m 5s")).toBeInTheDocument();
test("accumulates while running, pauses when not, then resumes", () => {
vi.useFakeTimers();
try {
const { rerender } = render(<ElapsedTimer running />);
act(() => vi.advanceTimersByTime(3000));
expect(screen.getByText("0m 3s")).toBeInTheDocument();
// Gate awaiting the reviewer: processing time must NOT advance.
rerender(<ElapsedTimer running={false} />);
act(() => vi.advanceTimersByTime(10000));
expect(screen.getByText("0m 3s")).toBeInTheDocument();
// Reviewer answered, processing resumes.
rerender(<ElapsedTimer running />);
act(() => vi.advanceTimersByTime(2000));
expect(screen.getByText("0m 5s")).toBeInTheDocument();
} finally {
vi.useRealTimers();
}
});
+28 -22
View File
@@ -1,4 +1,4 @@
import { useEffect, useState } from "react";
import { useEffect, useRef, useState } from "react";
function fmt(ms: number): string {
const total = Math.max(0, Math.floor(ms / 1000));
@@ -6,35 +6,41 @@ function fmt(ms: number): string {
}
/**
* Total process time, anchored on the session's created_at (robust to reload and
* resume). Ticks every second while running; freezes at stoppedAt once the session
* is finalized. Renders nothing until a start time is known.
* Processing-time indicator: accumulates ONLY the time the harness/model is
* actively working (`running`), pausing while a gate waits on the reviewer and
* freezing when the session ends. The parent keys this component on the session id,
* so it remounts (and restarts at zero) per session. In-memory: a page reload
* restarts the count.
*/
export function ElapsedTimer({
startedAt,
stoppedAt,
}: {
startedAt: string | null;
stoppedAt?: string | null;
}) {
const [now, setNow] = useState(() => Date.now());
export function ElapsedTimer({ running }: { running: boolean }) {
const [accumMs, setAccumMs] = useState(0);
const runStartRef = useRef<number | null>(null);
const [, tick] = useState(0);
useEffect(() => {
if (!startedAt || stoppedAt) return;
const t = setInterval(() => setNow(Date.now()), 1000);
return () => clearInterval(t);
}, [startedAt, stoppedAt]);
if (!running) return;
runStartRef.current = Date.now();
const t = setInterval(() => tick((n) => n + 1), 1000);
return () => {
// Fold the just-finished run into the accumulator (setState re-renders so the
// frozen total shows), then stop ticking.
if (runStartRef.current != null) {
const started = runStartRef.current;
runStartRef.current = null;
setAccumMs((ms) => ms + (Date.now() - started));
}
clearInterval(t);
};
}, [running]);
if (!startedAt) return null;
const start = new Date(startedAt).getTime();
const end = stoppedAt ? new Date(stoppedAt).getTime() : now;
const live = running && runStartRef.current != null ? Date.now() - runStartRef.current : 0;
return (
<span
className="shrink-0 tabular-nums text-xs text-muted-foreground"
aria-label="Elapsed time"
title="Total elapsed time"
aria-label="Processing time"
title="Processing time (excludes time spent waiting on the reviewer)"
>
{fmt(end - start)}
{fmt(accumMs + live)}
</span>
);
}
+7 -5
View File
@@ -27,12 +27,14 @@ const DOT: Record<DotState, string> = {
export function WorkflowBar({
finalized = false,
createdAt = null,
updatedAt = null,
running = false,
resetKey = null,
}: {
finalized?: boolean;
createdAt?: string | null;
updatedAt?: string | null;
/** The harness/model is actively working (drives the processing timer). */
running?: boolean;
/** Active session id — remounts the timer (resets it) when the session changes. */
resetKey?: string | null;
}) {
const currentPhase = useSessionStore((s) => s.currentPhase);
const phaseError = useSessionStore((s) => s.phaseError);
@@ -96,7 +98,7 @@ export function WorkflowBar({
);
})}
</nav>
<ElapsedTimer startedAt={createdAt} stoppedAt={finalized ? updatedAt : null} />
<ElapsedTimer key={resetKey ?? "none"} running={running} />
</div>
);
}