"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(session): persist the attempt start so the elapsed clock survives navigation, reload and history
averatec0773d79669eb067d
diff --git a/agent/src/api/sessions_routes.py b/agent/src/api/sessions_routes.pyindex d9f0c22e1..60ed58c26 100644--- a/agent/src/api/sessions_routes.py+++ b/agent/src/api/sessions_routes.py@@ -16,6 +16,7 @@ from fastapi import Depends, FastAPI, HTTPException, Query, Request, statusfrom fastapi.responses import StreamingResponsefrom pydantic import BaseModel, Field+from src.session.events import SSEEventfrom src.session.service import SessionBusyErrorlogger = logging.getLogger(__name__)@@ -803,12 +804,31 @@ def register_sessions_routes(app: FastAPI) -> None:event_id = header_id or last_event_idreplay_active = (replay or "").lower() == "active"replay_all = False+ running_attempt = Noneif replay_active and not event_id and session.last_attempt_id:attempt = svc.store.get_attempt(session_id, session.last_attempt_id)attempt_status = getattr(attempt.status, "value", attempt.status) if attempt else Nonereplay_all = attempt_status == "running"+ if replay_all:+ running_attempt = attemptasync def event_generator():+ # The ring buffer is bounded, so a long attempt's original+ # `attempt.started` may already have rotated out by the time a client+ # joins. Re-announce it from the persisted attempt so the client's+ # elapsed clock starts from the real start, not from now. Clients+ # treat a repeated attempt.started for the same attempt as a no-op.+ if running_attempt is not None and running_attempt.started_at:+ yield SSEEvent(+ event_id=None,+ event_type="attempt.started",+ data={+ "attempt_id": running_attempt.attempt_id,+ "started_at": running_attempt.started_at,+ "replayed": True,+ },+ session_id=session_id,+ ).to_sse()async for event in svc.event_bus.subscribe(session_id,last_event_id=event_id,diff --git a/agent/src/session/events.py b/agent/src/session/events.pyindex ab126c53d..f76b6ebf5 100644--- a/agent/src/session/events.py+++ b/agent/src/session/events.py@@ -64,13 +64,18 @@ class EventBus:max_buffer_size: Maximum number of buffered events per session."""- def __init__(self, max_buffer_size: int = 500) -> None:+ def __init__(self, max_buffer_size: int = 500, heartbeat_interval_s: float = 30.0) -> None:"""Initialize the event bus.Args:max_buffer_size: Maximum number of buffered events per session.+ heartbeat_interval_s: Idle seconds before a subscriber is sent a+ ``heartbeat`` frame. Also bounds how long a subscriber waiting+ on an idle queue takes to notice a cross-thread publish when no+ loop was injected via :meth:`set_loop`."""self.max_buffer_size = max_buffer_size+ self.heartbeat_interval_s = heartbeat_interval_sself._buffers: Dict[str, List[SSEEvent]] = {}self._subscribers: Dict[str, List[asyncio.Queue]] = {}self._listeners: List[Callable[[SSEEvent], None]] = []@@ -253,7 +258,7 @@ class EventBus:while True:try:- event = await asyncio.wait_for(queue.get(), timeout=30.0)+ event = await asyncio.wait_for(queue.get(), timeout=self.heartbeat_interval_s)except asyncio.TimeoutError:yield SSEEvent(event_id=None,diff --git a/agent/src/session/models.py b/agent/src/session/models.pyindex df5e61c3a..7dd051b1c 100644--- a/agent/src/session/models.py+++ b/agent/src/session/models.py@@ -2,6 +2,7 @@from __future__ import annotations+import timeimport uuidfrom dataclasses import dataclass, field, asdictfrom datetime import datetime, timezone@@ -256,6 +257,9 @@ class Attempt:summary: Execution summary.react_trace: ReAct agent trace records.created_at: Creation time in ISO format.+ started_at: Wall-clock time (epoch seconds) execution began, once running.+ Clients that join mid-attempt resume their elapsed clock from it, so+ it must outlive the event ring buffer that first announced it.completed_at: Completion time in ISO format, if available.error: Error message when the attempt fails.metrics: Snapshot of backtest metrics.@@ -270,6 +274,7 @@ class Attempt:summary: Optional[str] = Nonereact_trace: List[Dict[str, Any]] = field(default_factory=list)created_at: str = field(default_factory=_utc_now_iso)+ started_at: Optional[float] = Nonecompleted_at: Optional[str] = Noneerror: Optional[str] = Nonemetrics: Optional[Dict[str, Any]] = None@@ -300,8 +305,9 @@ class Attempt:return cls(**data)def mark_running(self) -> None:- """Mark the attempt as running."""+ """Mark the attempt as running and record when execution began."""self.status = AttemptStatus.RUNNING+ self.started_at = time.time()self.completed_at = Nonedef mark_completed(self, summary: Optional[str] = None) -> None:diff --git a/agent/src/session/service.py b/agent/src/session/service.pyindex 6bf6aede9..a0254d73e 100644--- a/agent/src/session/service.py+++ b/agent/src/session/service.py@@ -343,8 +343,19 @@ class SessionService:started_at = time.perf_counter()try:attempt.mark_running()+ # Wall-clock start (epoch seconds) is the one timing fact clients+ # cannot reconstruct on their own: a client that (re)connects+ # mid-attempt resumes its elapsed timer from it, and history+ # hydration derives the finished attempt's duration from it rather+ # than from the first tool call. It lives on the persisted attempt+ # so it survives the event ring buffer that first announced it.+ wall_started_at = attempt.started_at or time.time()self.store.update_attempt(attempt)- self.event_bus.emit(session.session_id, "attempt.started", {"attempt_id": attempt.attempt_id})+ self.event_bus.emit(+ session.session_id,+ "attempt.started",+ {"attempt_id": attempt.attempt_id, "started_at": wall_started_at},+ )messages = self.store.get_messages(session.session_id)result = await self._run_with_agent(attempt,@@ -375,6 +386,7 @@ class SessionService:if attempt.metrics:reply_metadata["metrics"] = attempt.metricsreply_metadata["elapsed_ms"] = max(0, round((time.perf_counter() - started_at) * 1000))+ reply_metadata["started_at"] = wall_started_atruntime_keys = ("provider","configured_model",@@ -410,6 +422,7 @@ class SessionService:_TERMINAL_EVENTS.get(attempt.status.value, "attempt.failed"),{"attempt_id": attempt.attempt_id, "status": attempt.status.value,"summary": attempt.summary, "error": attempt.error, "run_dir": attempt.run_dir,+ "started_at": wall_started_at, "ended_at": time.time(),**{key: reply_metadata[key] for key in ("elapsed_ms", *runtime_keys) if key in reply_metadata}},)diff --git a/agent/tests/test_session_events_replay_start.py b/agent/tests/test_session_events_replay_start.pynew file mode 100644index 000000000..39ac9551c--- /dev/null+++ b/agent/tests/test_session_events_replay_start.py@@ -0,0 +1,116 @@+"""A client joining a running attempt must learn when it started.++The event ring buffer is bounded, so on a long attempt the original+``attempt.started`` has often rotated out by the time a client (re)connects with+``replay=active``. The route re-announces it from the persisted attempt so the+client's elapsed clock resumes from the real start instead of from "now".+"""++from __future__ import annotations++import json+import threading+from pathlib import Path++import pytest+from fastapi.testclient import TestClient++import api_server+from src.session.events import EventBus+from src.session.models import Attempt+from src.session.service import SessionService+from src.session.store import SessionStore+++class _DummyIndex:+ def index_session(self, session_id: str, title: str) -> None:+ del session_id, title++ def index_message(self, session_id: str, role: str, content: str) -> None:+ del session_id, role, content+++def _service(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> SessionService:+ monkeypatch.setattr("src.session.service.get_shared_index", lambda: _DummyIndex())+ # The TestClient never injects a loop into the bus, so a cross-thread+ # clear() is only noticed when the subscriber's idle wait times out; keep+ # that short so each case finishes in well under a second.+ return SessionService(+ store=SessionStore(tmp_path / "sessions"),+ event_bus=EventBus(heartbeat_interval_s=0.2),+ runs_dir=tmp_path / "runs",+ )+++def _frames(+ client: TestClient, url: str, *, until_closed_by: threading.Timer+) -> list[tuple[str, dict]]:+ """Collect every (event, data) frame until the bus closes the stream.++ ``until_closed_by`` is a timer that clears the session on the bus once the+ subscription exists; the clear sentinel ends the generator so the response+ completes instead of idling on the 30 s heartbeat.+ """+ frames: list[tuple[str, dict]] = []+ event_type = ""+ until_closed_by.start()+ with client.stream("GET", url) as response:+ assert response.status_code == 200+ for line in response.iter_lines():+ if line.startswith("event: "):+ event_type = line[len("event: ") :]+ elif line.startswith("data: "):+ frames.append((event_type, json.loads(line[len("data: ") :])))+ return frames+++def test_active_replay_reannounces_attempt_start_from_the_persisted_attempt(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ service = _service(tmp_path, monkeypatch)+ monkeypatch.setattr(api_server, "_get_session_service", lambda: service)+ session = service.create_session(title="long run")++ # An attempt that has been running long enough for its original+ # attempt.started to have rotated out of the ring buffer: it is persisted as+ # running, but the bus holds no events for the session.+ attempt = Attempt(session_id=session.session_id, prompt="go")+ attempt.mark_running()+ service.store.create_attempt(attempt)+ session.last_attempt_id = attempt.attempt_id+ service.store.update_session(session)+ service.event_bus.clear(session.session_id)+ assert service.event_bus.replay(session.session_id, replay_all=True) == []++ client = TestClient(api_server.app, client=("127.0.0.1", 50000))+ closer = threading.Timer(0.5, lambda: service.event_bus.clear(session.session_id))+ frames = _frames(+ client,+ f"/sessions/{session.session_id}/events?replay=active",+ until_closed_by=closer,+ )++ assert frames, "stream produced no frames"+ event_type, data = frames[0]+ assert event_type == "attempt.started"+ assert data["attempt_id"] == attempt.attempt_id+ assert data["started_at"] == attempt.started_at+ assert data["replayed"] is True+++def test_active_replay_without_a_running_attempt_adds_nothing(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ service = _service(tmp_path, monkeypatch)+ monkeypatch.setattr(api_server, "_get_session_service", lambda: service)+ session = service.create_session(title="idle")++ client = TestClient(api_server.app, client=("127.0.0.1", 50000))+ closer = threading.Timer(0.5, lambda: service.event_bus.clear(session.session_id))+ frames = _frames(+ client,+ f"/sessions/{session.session_id}/events?replay=active",+ until_closed_by=closer,+ )++ assert all(event_type != "attempt.started" for event_type, _ in frames)diff --git a/agent/tests/test_session_service_lifecycle.py b/agent/tests/test_session_service_lifecycle.pyindex 6eb7b550b..83af3b338 100644--- a/agent/tests/test_session_service_lifecycle.py+++ b/agent/tests/test_session_service_lifecycle.py@@ -3,6 +3,7 @@from __future__ import annotationsimport asyncio+import timefrom pathlib import Pathimport pytest@@ -313,3 +314,94 @@ def test_cancel_before_the_agent_loop_exists_releases_the_claim(tmp_path, monkeyassert attempt.status == AttemptStatus.CANCELLEDasyncio.run(scenario())+++# ---------------------------------------------------------------------------+# Start-time provenance+# ---------------------------------------------------------------------------+++def test_attempt_started_event_carries_wall_clock_start(tmp_path, monkeypatch):+ """A client that (re)connects mid-attempt resumes its elapsed clock from+ the real start, so the event must carry it rather than leave the client to+ guess from its own reconnect time."""++ async def scenario() -> None:+ service = _service(tmp_path, monkeypatch)+ session = service.create_session(title="started-at")+ seen: list[tuple[str, dict]] = []+ service.event_bus.emit = lambda sid, event, data: seen.append((event, data)) # type: ignore[assignment]+ _stub_agent(service, monkeypatch, {"status": "success", "content": "ok"})++ before = time.time()+ await service.send_message(session.session_id, "go")+ for _ in range(100):+ await asyncio.sleep(0.01)+ if session.session_id not in service._inflight:+ break+ after = time.time()++ started = [data for event, data in seen if event == "attempt.started"]+ assert len(started) == 1+ stored = service.store.get_session(session.session_id)+ assert started[0]["attempt_id"] == stored.last_attempt_id+ assert isinstance(started[0]["started_at"], float)+ assert before <= started[0]["started_at"] <= after++ asyncio.run(scenario())+++def test_completed_reply_and_terminal_event_carry_attempt_timing(tmp_path, monkeypatch):+ """History hydration needs the attempt's real start: the first tool call is+ only a lower bound (the model thinks before it reaches for a tool, and a+ pure-text turn has no tools), so the reply persists ``started_at`` next to+ ``elapsed_ms`` and the terminal event carries both ends."""++ async def scenario() -> None:+ service = _service(tmp_path, monkeypatch)+ session = service.create_session(title="timing")+ seen: list[tuple[str, dict]] = []+ service.event_bus.emit = lambda sid, event, data: seen.append((event, data)) # type: ignore[assignment]+ _stub_agent(service, monkeypatch, {"status": "success", "content": "ok"})++ before = time.time()+ await service.send_message(session.session_id, "go")+ for _ in range(100):+ await asyncio.sleep(0.01)+ if session.session_id not in service._inflight:+ break+ after = time.time()++ started = next(data for event, data in seen if event == "attempt.started")+ completed = next(data for event, data in seen if event == "attempt.completed")+ reply = service.store.get_messages(session.session_id)[-1]++ assert reply.role == "assistant"+ assert reply.metadata["started_at"] == started["started_at"]+ assert before <= reply.metadata["started_at"] <= after+ assert reply.metadata["elapsed_ms"] >= 0+ assert completed["started_at"] == started["started_at"]+ assert completed["started_at"] <= completed["ended_at"] <= after+ assert completed["elapsed_ms"] == reply.metadata["elapsed_ms"]++ asyncio.run(scenario())+++def test_attempt_records_and_round_trips_its_wall_clock_start():+ """``started_at`` outlives the event ring buffer only if it is persisted+ with the attempt; legacy attempt files without it must still load."""+ attempt = Attempt(session_id="s1", prompt="go")+ assert attempt.started_at is None++ before = time.time()+ attempt.mark_running()+ assert isinstance(attempt.started_at, float)+ assert before <= attempt.started_at <= time.time()++ restored = Attempt.from_dict(attempt.to_dict())+ assert restored.started_at == attempt.started_at+ assert restored.status == AttemptStatus.RUNNING++ legacy = attempt.to_dict()+ del legacy["started_at"]+ assert Attempt.from_dict(legacy).started_at is Nonediff --git a/frontend/src/pages/Agent.tsx b/frontend/src/pages/Agent.tsxindex 42624f8a0..0685429d2 100644--- a/frontend/src/pages/Agent.tsx+++ b/frontend/src/pages/Agent.tsx@@ -534,6 +534,16 @@ export function Agent() {};}const ts = new Date(m.created_at).getTime();+ // The reply is committed when the attempt ends, so created_at is the+ // end. The start comes from the persisted attempt start when present,+ // else is backed out of the attempt's elapsed time; only legacy rows+ // without either fall back to the first tool call.+ const startedAtSec = typeof meta?.started_at === "number" ? meta.started_at : NaN;+ const attemptStartedAt = Number.isFinite(startedAtSec) && startedAtSec > 0+ ? startedAtSec * 1000+ : elapsedMs != null+ ? ts - elapsedMs+ : undefined;const toolTimeline = m.role === "assistant"? buildToolTimelineMessages(m.tool_trail ?? [], {fallbackTimestamp: ts,@@ -544,6 +554,7 @@ export function Agent() {: meta?.status === "cancelled"? "stopped": "done",+ startedAt: attemptStartedAt,endedAt: ts,}): [];@@ -619,6 +630,22 @@ export function Agent() {act().clearStreamingSession(sid);}act().loadHistory(agentMsgs);+ // The live activity is carried across a same-session re-mount so its+ // clock survives, but if the attempt finished while we were away its+ // committed reply is now in history: the durable row above supersedes+ // the live one, which would otherwise sit at "Working" until the safety+ // timeout fired.+ const liveActivity = act().activity;+ if (+ liveActivity+ && msgs.some((message) => (+ message.role === "assistant"+ && message.linked_attempt_id === liveActivity.attemptId+ ))+ ) {+ useAgentStore.setState({ activity: null, toolCalls: [] });+ if (act().status === "streaming") act().setStatus("idle");+ }act().setSessionLoading(false);act().cacheSession(sid, agentMsgs);setRuntimeIdentity(latestRuntimeIdentity ?? {});@@ -684,8 +711,15 @@ export function Agent() {return false;}const current = store.activity;+ // `attempt.started` carries the backend's wall-clock start (epoch+ // seconds). On a replayed stream that is the original start, so the+ // elapsed timer resumes from the truth rather than from reconnect time.+ const startedAtSec = Number(data.started_at);+ const startedAt = Number.isFinite(startedAtSec) && startedAtSec > 0+ ? startedAtSec * 1000+ : undefined;if (!current) {- store.startActivity(attemptId || `pending-${Date.now()}`);+ store.startActivity(attemptId || `pending-${Date.now()}`, startedAt);} else if (attemptId &¤t.attemptId !== attemptId &&@@ -693,7 +727,7 @@ export function Agent() {) {store.setActivityAttemptId(attemptId);} else if (attemptId && current.attemptId !== attemptId) {- store.startActivity(attemptId);+ store.startActivity(attemptId, startedAt);}act().setActivityState(state);return true;@@ -870,14 +904,39 @@ export function Agent() {}const streamedAnswer = act().streamingText + pendingTextRef.current;flushPendingStreamUpdate();+ // No live activity means we never saw this attempt run (connected after+ // the fact); rebuild its timing from the event rather than from now.+ const eventStartedSec = Number(d.started_at);+ const eventElapsedMs = Number(d.elapsed_ms);+ const eventEndedSec = Number(d.ended_at);+ const completedEndedAt = Number.isFinite(eventEndedSec) && eventEndedSec > 0+ ? eventEndedSec * 1000+ : Date.now();+ const completedStartedAt = Number.isFinite(eventStartedSec) && eventStartedSec > 0+ ? eventStartedSec * 1000+ : Number.isFinite(eventElapsedMs) && eventElapsedMs > 0+ ? completedEndedAt - eventElapsedMs+ : undefined;if (!act().activity) {- act().startActivity(attemptId || `completed-${Date.now()}`);+ act().startActivity(attemptId || `completed-${Date.now()}`, completedStartedAt);} else if (attemptId && act().activity?.attemptId !== attemptId) {act().setActivityAttemptId(attemptId);}+ // A client that joined mid-attempt may have started its clock late; the+ // backend's start is authoritative for the durable row.+ const liveStart = act().activity?.startedAt;+ if (+ completedStartedAt !== undefined+ && liveStart !== undefined+ && completedStartedAt < liveStart+ ) {+ useAgentStore.setState((state) => ({+ activity: state.activity ? { ...state.activity, startedAt: completedStartedAt } : null,+ }));+ }const s = act();const completedTools = s.activity?.steps ?? s.toolCalls;- const completedActivity = archiveActivity("done");+ const completedActivity = archiveActivity("done", completedEndedAt);const completedAttemptId = completedActivity?.attemptId || attemptId;useAgentStore.setState((state) => ({messages: state.messages.filter(@@ -1216,7 +1275,18 @@ export function Agent() {genRef.current = gen;setRuntimeIdentity({});const seed = curMsgs.length > 0 ? curMsgs : getCachedSession(urlSessionId);+ // switchSession() drops the live activity so replay can rebuild its+ // steps without duplicating them — but the attempt's start time is not+ // something replay can restore once the ring buffer has rotated past+ // `attempt.started`. Re-seed the still-running activity with its+ // original startedAt so the elapsed clock does not restart at 0s.+ const liveActivity = act().activity;switchSession(urlSessionId, seed);+ if (liveActivity && liveActivity.endedAt === undefined) {+ const store = act();+ store.startActivity(liveActivity.attemptId, liveActivity.startedAt);+ store.setActivityState(liveActivity.state);+ }loadSessionMessages(urlSessionId, gen);setupSSE(urlSessionId);} else if (!urlSessionId && curSid) {diff --git a/frontend/src/pages/__tests__/AgentActivityTimerPersistence.test.tsx b/frontend/src/pages/__tests__/AgentActivityTimerPersistence.test.tsxnew file mode 100644index 000000000..0509bed93--- /dev/null+++ b/frontend/src/pages/__tests__/AgentActivityTimerPersistence.test.tsx@@ -0,0 +1,354 @@+import { act, render, waitFor } from "@testing-library/react";+import { createMemoryRouter, RouterProvider } from "react-router";+import { Agent } from "../Agent";+import { useAgentStore } from "@/stores/agent";++// Regression test for: the "Working · 51s · 12 steps" elapsed clock restarting+// at 0s when the user navigates to another tab (Runtime, Scheduled, …) and+// back while an attempt is still running. The same-session re-hydrate path+// (#229) resets the live activity so SSE replay can rebuild its steps, but the+// attempt's start time is not recoverable from replay once the ring buffer has+// rotated past `attempt.started`, so it must survive the reset. Independently,+// a replayed `attempt.started` now carries the backend's wall-clock start so a+// fresh client resumes the clock from the real start rather than from now.++const apiMock = vi.hoisted(() => ({+ getGoal: vi.fn(),+ getLLMSettings: vi.fn(),+ getRun: vi.fn(),+ getSessionMessages: vi.fn(),+ sseUrl: vi.fn((sid: string) => `/sessions/${sid}/events`),+}));++const sseMock = vi.hoisted(() => ({+ connect: vi.fn(),+ disconnect: vi.fn(),+ onStatusChange: vi.fn(),+}));++vi.mock("@/lib/api", async () => {+ const actual = await vi.importActual<typeof import("@/lib/api")>("@/lib/api");+ return { ...actual, api: apiMock };+});++vi.mock("@/hooks/useSSE", () => ({+ useSSE: () => sseMock,+}));++type Handlers = Record<string, (data: Record<string, unknown>) => void>;++function latestHandlers(): Handlers {+ const call = sseMock.connect.mock.calls.at(-1);+ if (!call) throw new Error("useSSE.connect was never called");+ return call[1] as Handlers;+}++describe("Agent activity elapsed clock survives navigation", () => {+ beforeEach(() => {+ useAgentStore.getState().reset();+ sseMock.connect.mockClear();+ apiMock.getGoal.mockResolvedValue(null);+ apiMock.getSessionMessages.mockResolvedValue([]);+ apiMock.getLLMSettings.mockResolvedValue({+ provider: "deepseek",+ model_name: "deepseek-v4-pro",+ base_url: "https://api.deepseek.com/v1",+ api_key_configured: true,+ api_key_required: true,+ temperature: 0,+ timeout_seconds: 120,+ max_retries: 2,+ reasoning_effort: "low",+ sse_timeout_seconds: 90,+ env_path: "agent/.env",+ providers: [],+ });+ Object.defineProperty(HTMLElement.prototype, "scrollTo", {+ configurable: true,+ value: vi.fn(),+ });+ });++ it("keeps the running attempt's startedAt when leaving the page and coming back", async () => {+ const router = createMemoryRouter(+ [+ { path: "/", element: <Agent /> },+ { path: "/runtime", element: <div>runtime</div> },+ ],+ { initialEntries: ["/?session=session-one"] },+ );+ render(<RouterProvider router={router} />);+ await waitFor(() => expect(apiMock.getSessionMessages).toHaveBeenCalledWith("session-one"));++ // An attempt has been running for a while on this session.+ const originalStart = Date.now() - 51_000;+ act(() => {+ const store = useAgentStore.getState();+ store.startActivity("attempt-1", originalStart);+ store.setActivityState("working");+ store.setStatus("streaming");+ });++ // Navigate to another tab (unmounts Agent, tears down SSE) and back.+ await act(async () => {+ await router.navigate("/runtime");+ });+ await act(async () => {+ await router.navigate("/?session=session-one");+ });++ await waitFor(() => {+ expect(sseMock.connect.mock.calls.length).toBeGreaterThanOrEqual(2);+ });+ const activity = useAgentStore.getState().activity;+ expect(activity).not.toBeNull();+ expect(activity?.attemptId).toBe("attempt-1");+ expect(activity?.startedAt).toBe(originalStart);+ expect(activity?.endedAt).toBeUndefined();++ // The replayed attempt.started for the same attempt must not restart the clock.+ act(() => {+ latestHandlers()["attempt.started"]({ attempt_id: "attempt-1" });+ });+ expect(useAgentStore.getState().activity?.startedAt).toBe(originalStart);+ });++ it("does not resurrect an activity that had already finished", async () => {+ const router = createMemoryRouter(+ [+ { path: "/", element: <Agent /> },+ { path: "/runtime", element: <div>runtime</div> },+ ],+ { initialEntries: ["/?session=session-one"] },+ );+ render(<RouterProvider router={router} />);+ await waitFor(() => expect(apiMock.getSessionMessages).toHaveBeenCalledWith("session-one"));++ act(() => {+ const store = useAgentStore.getState();+ store.startActivity("attempt-done", Date.now() - 5_000);+ store.setActivityState("done", Date.now() - 1_000);+ });++ await act(async () => {+ await router.navigate("/runtime");+ });+ await act(async () => {+ await router.navigate("/?session=session-one");+ });++ await waitFor(() => {+ expect(sseMock.connect.mock.calls.length).toBeGreaterThanOrEqual(2);+ });+ expect(useAgentStore.getState().activity).toBeNull();+ });++ it("starts the clock from the backend's started_at on a fresh attempt.started", async () => {+ const router = createMemoryRouter(+ [{ path: "/", element: <Agent /> }],+ { initialEntries: ["/?session=session-one"] },+ );+ render(<RouterProvider router={router} />);+ await waitFor(() => expect(sseMock.connect).toHaveBeenCalled());++ const startedAtSec = Math.floor(Date.now() / 1000) - 51;+ act(() => {+ latestHandlers()["attempt.started"]({ attempt_id: "attempt-2", started_at: startedAtSec });+ });++ const activity = useAgentStore.getState().activity;+ expect(activity?.attemptId).toBe("attempt-2");+ expect(activity?.startedAt).toBe(startedAtSec * 1000);+ });++ it("falls back to now when attempt.started carries no started_at", async () => {+ const router = createMemoryRouter(+ [{ path: "/", element: <Agent /> }],+ { initialEntries: ["/?session=session-one"] },+ );+ render(<RouterProvider router={router} />);+ await waitFor(() => expect(sseMock.connect).toHaveBeenCalled());++ const before = Date.now();+ act(() => {+ latestHandlers()["attempt.started"]({ attempt_id: "attempt-3" });+ });+ const startedAt = useAgentStore.getState().activity?.startedAt ?? 0;+ expect(startedAt).toBeGreaterThanOrEqual(before);+ expect(startedAt).toBeLessThanOrEqual(Date.now());+ });+});++describe("Agent activity finished while the page was away", () => {+ beforeEach(() => {+ useAgentStore.getState().reset();+ sseMock.connect.mockClear();+ apiMock.getGoal.mockResolvedValue(null);+ apiMock.getRun.mockResolvedValue({});+ apiMock.getLLMSettings.mockResolvedValue({+ provider: "deepseek",+ model_name: "deepseek-v4-pro",+ base_url: "https://api.deepseek.com/v1",+ api_key_configured: true,+ api_key_required: true,+ temperature: 0,+ timeout_seconds: 120,+ max_retries: 2,+ reasoning_effort: "low",+ sse_timeout_seconds: 90,+ env_path: "agent/.env",+ providers: [],+ });+ Object.defineProperty(HTMLElement.prototype, "scrollTo", {+ configurable: true,+ value: vi.fn(),+ });+ });++ it("replaces the carried live activity with the committed row and keeps the real duration", async () => {+ const startedAtMs = Date.UTC(2026, 7, 1, 0, 0, 0);+ const endedAtMs = startedAtMs + 8_000;+ let committed = false;+ apiMock.getSessionMessages.mockImplementation(() => Promise.resolve(+ committed+ ? [+ {+ message_id: "m-prompt",+ session_id: "session-one",+ role: "user" as const,+ content: "read the snapshot",+ created_at: new Date(startedAtMs - 1_000).toISOString(),+ linked_attempt_id: null,+ tool_trail: [],+ metadata: null,+ },+ {+ message_id: "m-reply",+ session_id: "session-one",+ role: "assistant" as const,+ content: "done",+ created_at: new Date(endedAtMs).toISOString(),+ linked_attempt_id: "attempt-1",+ // The only tool ran 5s in, for 80ms: without the attempt start the+ // row would read 80ms instead of 8s.+ tool_trail: [+ { tool: "read_document", status: "ok" as const, elapsed_ms: 80, timestamp: startedAtMs + 5_000 },+ ],+ metadata: { status: "completed", elapsed_ms: 8_000, started_at: startedAtMs / 1000 },+ },+ ]+ : [],+ ));++ const router = createMemoryRouter(+ [+ { path: "/", element: <Agent /> },+ { path: "/runtime", element: <div>runtime</div> },+ ],+ { initialEntries: ["/?session=session-one"] },+ );+ render(<RouterProvider router={router} />);+ await waitFor(() => expect(apiMock.getSessionMessages).toHaveBeenCalledWith("session-one"));++ act(() => {+ const store = useAgentStore.getState();+ store.startActivity("attempt-1", startedAtMs);+ store.setActivityState("working");+ store.setStatus("streaming");+ });++ await act(async () => {+ await router.navigate("/runtime");+ });+ committed = true; // the attempt completed while we were on another tab+ await act(async () => {+ await router.navigate("/?session=session-one");+ });++ await waitFor(() => {+ expect(useAgentStore.getState().activity).toBeNull();+ });+ const state = useAgentStore.getState();+ expect(state.status).toBe("idle");+ const rows = state.messages.filter((m) => m.meta?.activity?.attemptId === "attempt-1");+ expect(rows).toHaveLength(1);+ expect(rows[0].meta?.activity).toMatchObject({+ state: "done",+ startedAt: startedAtMs,+ endedAt: endedAtMs,+ });+ });+});++describe("Agent completion trusts the backend's attempt start", () => {+ beforeEach(() => {+ useAgentStore.getState().reset();+ sseMock.connect.mockClear();+ apiMock.getGoal.mockResolvedValue(null);+ apiMock.getRun.mockResolvedValue({});+ apiMock.getSessionMessages.mockResolvedValue([]);+ apiMock.getLLMSettings.mockResolvedValue({+ provider: "deepseek",+ model_name: "deepseek-v4-pro",+ base_url: "https://api.deepseek.com/v1",+ api_key_configured: true,+ api_key_required: true,+ temperature: 0,+ timeout_seconds: 120,+ max_retries: 2,+ reasoning_effort: "low",+ sse_timeout_seconds: 90,+ env_path: "agent/.env",+ providers: [],+ });+ Object.defineProperty(HTMLElement.prototype, "scrollTo", {+ configurable: true,+ value: vi.fn(),+ });+ });++ it("backdates a late-joined live activity to the backend start when the attempt completes", async () => {+ const router = createMemoryRouter(+ [{ path: "/", element: <Agent /> }],+ { initialEntries: ["/?session=session-one"] },+ );+ render(<RouterProvider router={router} />);+ await waitFor(() => expect(sseMock.connect).toHaveBeenCalled());++ // We joined 47s into a run whose attempt.started had already rotated out+ // of the ring buffer: the first replayed event was a tool call, so the+ // live clock started late.+ const backendStartSec = Math.floor(Date.now() / 1000) - 165;+ const lateJoinMs = (backendStartSec + 47) * 1000;+ act(() => {+ const store = useAgentStore.getState();+ store.startActivity("attempt-late", lateJoinMs);+ store.setActivityState("working");+ store.setStatus("streaming");+ });++ const endedSec = backendStartSec + 165;+ await act(async () => {+ latestHandlers()["attempt.completed"]({+ attempt_id: "attempt-late",+ status: "completed",+ summary: "done",+ started_at: backendStartSec,+ ended_at: endedSec,+ elapsed_ms: 165_000,+ });+ });++ await waitFor(() => {+ expect(useAgentStore.getState().activity).toBeNull();+ });+ const row = useAgentStore.getState().messages.find(+ (m) => m.meta?.activity?.attemptId === "attempt-late",+ );+ expect(row?.meta?.activity).toMatchObject({+ state: "done",+ startedAt: backendStartSec * 1000,+ endedAt: endedSec * 1000,+ });+ });+});diff --git a/frontend/src/pages/__tests__/agentToolTimeline.test.ts b/frontend/src/pages/__tests__/agentToolTimeline.test.tsindex 7b2f6699b..71e90c8b7 100644--- a/frontend/src/pages/__tests__/agentToolTimeline.test.ts+++ b/frontend/src/pages/__tests__/agentToolTimeline.test.ts@@ -81,3 +81,51 @@ describe("buildToolTimelineMessages", () => {});});});++describe("buildToolTimelineMessages attempt start", () => {+ const trail = [+ { tool: "read_document", status: "ok" as const, elapsed_ms: 80, timestamp: 1_785_342_405_000 },+ ];++ it("prefers the attempt's recorded start over the first tool call", () => {+ // The model thought for 5s before its only (80ms) tool call, then answered+ // for another 3s: the durable row must read 8s, not 80ms.+ const [row] = buildToolTimelineMessages(trail, {+ fallbackTimestamp: 1_785_342_408_000,+ attemptId: "attempt-1",+ startedAt: 1_785_342_400_000,+ endedAt: 1_785_342_408_000,+ });+ expect(row.meta?.activity?.startedAt).toBe(1_785_342_400_000);+ expect(row.meta?.activity?.endedAt).toBe(1_785_342_408_000);+ expect(row.timestamp).toBe(1_785_342_400_000);+ });++ it("never places the start after a tool that already ran", () => {+ const [row] = buildToolTimelineMessages(trail, {+ fallbackTimestamp: 1_785_342_408_000,+ attemptId: "attempt-1",+ startedAt: 1_785_342_407_000,+ endedAt: 1_785_342_408_000,+ });+ expect(row.meta?.activity?.startedAt).toBe(1_785_342_405_000);+ });++ it("falls back to the first tool call when no start is recorded", () => {+ const [row] = buildToolTimelineMessages(trail, {+ fallbackTimestamp: 1_785_342_408_000,+ attemptId: "attempt-1",+ endedAt: 1_785_342_408_000,+ });+ expect(row.meta?.activity?.startedAt).toBe(1_785_342_405_000);+ });++ it("uses the fallback timestamp for a tool-less turn without a recorded start", () => {+ const [row] = buildToolTimelineMessages([], {+ fallbackTimestamp: 1_785_342_408_000,+ attemptId: "attempt-1",+ endedAt: 1_785_342_408_000,+ });+ expect(row.meta?.activity?.startedAt).toBe(1_785_342_408_000);+ });+});diff --git a/frontend/src/pages/agentToolTimeline.ts b/frontend/src/pages/agentToolTimeline.tsindex 92ab67913..756ac03d0 100644--- a/frontend/src/pages/agentToolTimeline.ts+++ b/frontend/src/pages/agentToolTimeline.ts@@ -21,6 +21,8 @@ interface ToolTimelineOptions {idPrefix?: string;attemptId?: string;state?: ActivityState;+ /** Attempt wall-clock start (ms). When known it beats the first-tool guess. */+ startedAt?: number;endedAt?: number;activity?: AgentActivity;}@@ -45,9 +47,17 @@ export function buildToolTimelineMessages(: fallbackTimestamp + index),}));- const startedAt = steps.length > 0+ // The first tool call is only a lower bound on when the attempt started: the+ // model thinks before it reaches for a tool, and a pure-text turn has no+ // tools at all. Prefer the attempt's recorded start when the caller has it.+ const inferredStart = steps.length > 0? Math.min(...steps.map((step) => step.timestamp)): fallbackTimestamp;+ const startedAt = (+ typeof options.startedAt === "number" && Number.isFinite(options.startedAt)+ ? Math.min(options.startedAt, inferredStart)+ : inferredStart+ );const inferredEnd = Math.max(fallbackTimestamp,startedAt + steps.reduce((sum, step) => sum + (step.elapsed_ms ?? 0), 0),