From 9257383bec15480f3ff90a9878b7a6209e19a58a Mon Sep 17 00:00:00 2001 From: chengyongru Date: Mon, 9 Nov 2026 11:55:22 +0800 Subject: [PATCH] refactor: remove unreachable internal code paths Co-authored-by: chengyongru <61816729+chengyongru@users.noreply.github.com> --- nanobot/channels/discord/runtime.py | 8 +- .../discord/tests/test_discord_channel.py | 2 +- nanobot/channels/msteams/runtime.py | 14 +- nanobot/channels/websocket/runtime.py | 3 - .../websocket/tests/test_websocket_channel.py | 28 ++-- .../tests/test_websocket_envelope_media.py | 2 +- nanobot/channels/weixin/runtime.py | 3 - nanobot/cli/tui_launcher.py | 49 +------ nanobot/llm_usage/store.py | 25 +--- nanobot/session/manager.py | 7 +- tests/cli/test_tui_launcher.py | 121 ------------------ webui/src/components/thread/thread-motion.ts | 8 +- webui/src/lib/nanobot-client.ts | 5 - webui/src/tests/app-layout.test.tsx | 1 - webui/src/tests/nanobot-client.test.ts | 42 +++--- webui/src/tests/thread-motion.test.ts | 18 ++- webui/src/tests/thread-shell.test.tsx | 5 +- webui/src/tests/turn-completion.test.tsx | 2 +- webui/src/tests/useNanobotStream.test.tsx | 1 - webui/src/tests/useReconnectRuns.test.tsx | 26 ++-- webui/src/tests/useSessions.test.tsx | 1 - 21 files changed, 86 insertions(+), 285 deletions(-) diff --git a/nanobot/channels/discord/runtime.py b/nanobot/channels/discord/runtime.py index 05318441a..381f6bad2 100644 --- a/nanobot/channels/discord/runtime.py +++ b/nanobot/channels/discord/runtime.py @@ -497,12 +497,12 @@ class DiscordChannel(BaseChannel): self.logger.exception("client startup failed") finally: self._running = False - await self._reset_runtime_state(close_client=True) + await self._reset_runtime_state() async def stop(self) -> None: """Stop the Discord channel.""" self._running = False - await self._reset_runtime_state(close_client=True) + await self._reset_runtime_state() def _remember_compaction_notice( self, @@ -907,7 +907,7 @@ class DiscordChannel(BaseChannel): await asyncio.gather(*tasks, return_exceptions=True) self._working_emoji_tasks.clear() - async def _reset_runtime_state(self, close_client: bool) -> None: + async def _reset_runtime_state(self) -> None: self._running = False # Drain callbacks before clearing the state they can still create after an await. current = asyncio.current_task() @@ -921,7 +921,7 @@ class DiscordChannel(BaseChannel): self._compaction_notices.clear() self._stream_bufs.clear() self._known_channels.clear() - if close_client and self._client is not None and not self._client.is_closed(): + if self._client is not None and not self._client.is_closed(): try: await self._client.close() except Exception as e: diff --git a/nanobot/channels/discord/tests/test_discord_channel.py b/nanobot/channels/discord/tests/test_discord_channel.py index 0270baed1..0181da101 100644 --- a/nanobot/channels/discord/tests/test_discord_channel.py +++ b/nanobot/channels/discord/tests/test_discord_channel.py @@ -1850,6 +1850,6 @@ async def test_reset_discards_in_flight_compaction_notices() -> None: owner, client = _client_with_channel(target) await client.send_outbound(_compaction_message("Compressing context…", "started")) - await owner._reset_runtime_state(close_client=False) + await owner._reset_runtime_state() assert owner._compaction_notices == {} diff --git a/nanobot/channels/msteams/runtime.py b/nanobot/channels/msteams/runtime.py index e75c9b7c4..bc23213bd 100644 --- a/nanobot/channels/msteams/runtime.py +++ b/nanobot/channels/msteams/runtime.py @@ -142,7 +142,7 @@ class MSTeamsChannel(BaseChannel): self._conversation_refs: dict[str, ConversationRef] = self._load_refs() with self._refs_guard: if self._prune_conversation_refs(): - self._save_refs_locked(prune=True) + self._save_refs_locked() async def start(self) -> None: """Start the Teams webhook listener.""" @@ -286,7 +286,7 @@ class MSTeamsChannel(BaseChannel): resp = await self._http.post(base_url, headers=headers, json=payload) resp.raise_for_status() self.logger.info("Message sent to {}", ref.conversation_id) - self._touch_conversation_ref(str(msg.chat_id), persist=True) + self._touch_conversation_ref(str(msg.chat_id)) except Exception: self.logger.exception("Send failed") raise @@ -736,7 +736,7 @@ class MSTeamsChannel(BaseChannel): if disk_ts > mem_ts: self._conversation_refs[key] = disk_ref - def _touch_conversation_ref(self, chat_id: str, *, persist: bool = False) -> None: + def _touch_conversation_ref(self, chat_id: str) -> None: with self._refs_guard: ref = self._conversation_refs.get(str(chat_id)) if not ref: @@ -747,8 +747,7 @@ class MSTeamsChannel(BaseChannel): if min_interval > 0 and prev > 0 and now - prev < min_interval: return ref.updated_at = now - if persist: - self._save_refs_locked() + self._save_refs_locked() def _write_json_atomically(self, path: Path, data: dict[str, Any]) -> None: payload = json.dumps(data, indent=2) @@ -769,13 +768,12 @@ class MSTeamsChannel(BaseChannel): with suppress(OSError): os.unlink(tmp_path) - def _save_refs_locked(self, *, prune: bool = True) -> None: + def _save_refs_locked(self) -> None: """Persist conversation references (caller must hold _refs_guard).""" try: with self._refs_file_lock(): self._merge_refs_from_disk_locked() - if prune: - self._prune_conversation_refs() + self._prune_conversation_refs() refs_data = { key: { "service_url": ref.service_url, diff --git a/nanobot/channels/websocket/runtime.py b/nanobot/channels/websocket/runtime.py index 92e523c28..9101b38ca 100644 --- a/nanobot/channels/websocket/runtime.py +++ b/nanobot/channels/websocket/runtime.py @@ -374,9 +374,6 @@ class WebSocketChannel(BaseChannel): session_projection=gateway.session_projection, ) self._commands = WebUICommandRouter(self, gateway, outbound=self._outbound) - self._webui_request_tasks = self._commands.request_tasks - self._webui_request_operations = self._commands.request_operations - self._webui_request_locks = self._commands.request_locks def webui_subscribers(self, chat_id: str) -> tuple[ServerConnection, ...]: diff --git a/nanobot/channels/websocket/tests/test_websocket_channel.py b/nanobot/channels/websocket/tests/test_websocket_channel.py index 2ec1c0651..49af5b1fd 100644 --- a/nanobot/channels/websocket/tests/test_websocket_channel.py +++ b/nanobot/channels/websocket/tests/test_websocket_channel.py @@ -421,7 +421,7 @@ async def test_temporary_file_preview_is_owned_restricted_and_not_cached(bus, tm assert (await preview(owner, str(outside)))["error"]["status"] == 403 assert (await preview(owner, str(outside), probe=True))["result"] == {"available": False} assert (await preview(AsyncMock()))["error"]["status"] == 403 - assert not channel._webui_request_operations + assert not channel._commands.request_operations assert {path for path in tmp_path.rglob("*") if path.is_file()} == disk_before assert sessions.list_sessions() == [] @@ -430,7 +430,7 @@ async def test_temporary_file_preview_is_owned_restricted_and_not_cached(bus, tm }) assert (await preview(owner))["error"]["status"] == 404 assert (await preview(owner, metadata=True))["error"]["status"] == 404 - assert not channel._webui_request_operations + assert not channel._commands.request_operations @pytest.mark.asyncio @@ -1220,7 +1220,7 @@ async def test_authenticated_webui_request_returns_correlated_success(bus: Magic "payload": {"provider": "openrouter", "apiKey": "secret"}, }, ) - await asyncio.gather(*tuple(channel._webui_request_tasks.values())) + await asyncio.gather(*tuple(channel._commands.request_tasks.values())) channel.gateway.http.dispatch_webui_mutation.assert_awaited_once_with( conn, @@ -1281,7 +1281,7 @@ async def test_webui_mutations_preserve_request_and_response_order(bus: MagicMoc assert dispatch_order == ["settings.provider.update"] release_first.set() - await asyncio.gather(*tuple(channel._webui_request_tasks.values())) + await asyncio.gather(*tuple(channel._commands.request_tasks.values())) assert dispatch_order == [ "settings.provider.update", @@ -1350,7 +1350,7 @@ async def test_webui_request_survives_disconnect_and_preserves_reconnect_order( await asyncio.sleep(0) assert dispatch_order == ["automation.run"] - pending = tuple(channel._webui_request_tasks.values()) + pending = tuple(channel._commands.request_tasks.values()) release.set() await asyncio.gather(*pending) @@ -1361,7 +1361,7 @@ async def test_webui_request_survives_disconnect_and_preserves_reconnect_order( "request-queued", "request-next", ] - assert first_conn not in channel._webui_request_locks + assert first_conn not in channel._commands.request_locks @pytest.mark.asyncio @@ -1381,9 +1381,9 @@ async def test_webui_request_replays_completed_result_after_reconnect(bus: Magic } await channel._dispatch_envelope(first_conn, "webui-client", envelope) - await asyncio.gather(*tuple(channel._webui_request_tasks.values())) + await asyncio.gather(*tuple(channel._commands.request_tasks.values())) await channel._dispatch_envelope(retry_conn, "webui-client", envelope) - await asyncio.gather(*tuple(channel._webui_request_tasks.values())) + await asyncio.gather(*tuple(channel._commands.request_tasks.values())) channel.gateway.http.dispatch_webui_mutation.assert_awaited_once() assert json.loads(retry_conn.send.await_args.args[0]) == { @@ -1416,7 +1416,7 @@ async def test_webui_request_rejects_request_id_reuse_with_different_payload( "payload": {"id": "job-a"}, }, ) - await asyncio.gather(*tuple(channel._webui_request_tasks.values())) + await asyncio.gather(*tuple(channel._commands.request_tasks.values())) await channel._dispatch_envelope( retry_conn, "webui-client", @@ -1449,7 +1449,7 @@ def test_webui_request_cache_prunes_expired_completed_but_keeps_pending( channel = _ch(bus) now = 1_000.0 monkeypatch.setattr(websocket_module, "time", SimpleNamespace(monotonic=lambda: now)) - operations = cast(dict[str, Any], channel._webui_request_operations) + operations = cast(dict[str, Any], channel._commands.request_operations) operations["pending"] = SimpleNamespace(completed_at=None) operations["expired"] = SimpleNamespace( completed_at=now - websocket_module._WEBUI_REQUEST_CACHE_TTL_S @@ -1472,7 +1472,7 @@ def test_webui_request_cache_prunes_oldest_completed_at_capacity( channel = _ch(bus) now = 1_000.0 monkeypatch.setattr(websocket_module, "time", SimpleNamespace(monotonic=lambda: now)) - operations = cast(dict[str, Any], channel._webui_request_operations) + operations = cast(dict[str, Any], channel._commands.request_operations) operations["pending"] = SimpleNamespace(completed_at=None) for index in range(websocket_module._WEBUI_REQUEST_CACHE_MAX + 1): operations[f"completed-{index}"] = SimpleNamespace( @@ -1507,7 +1507,7 @@ async def test_webui_request_returns_correlated_route_error(bus: MagicMock) -> N "payload": {}, }, ) - await asyncio.gather(*tuple(channel._webui_request_tasks.values())) + await asyncio.gather(*tuple(channel._commands.request_tasks.values())) assert json.loads(conn.send.await_args.args[0]) == { "event": "webui_response", @@ -1570,7 +1570,7 @@ async def test_webui_persists_sidebar_state_larger_than_http_request_line( assert len(json.dumps(envelope).encode()) > 8_192 await channel._dispatch_envelope(conn, "webui-client", envelope) - await asyncio.gather(*tuple(channel._webui_request_tasks.values())) + await asyncio.gather(*tuple(channel._commands.request_tasks.values())) saved = json.loads((tmp_path / "webui" / "sidebar-state.json").read_text(encoding="utf-8")) assert saved["session_order"] == session_order @@ -1624,7 +1624,7 @@ async def test_webui_sidebar_state_update_broadcasts_workbench_to_other_devices( } try: await channel._dispatch_envelope(source, "webui-client", envelope) - await asyncio.gather(*tuple(channel._webui_request_tasks.values())) + await asyncio.gather(*tuple(channel._commands.request_tasks.values())) event = json.loads(other_device.send.await_args.args[0]) assert event["event"] == "sidebar_state_updated" assert event["state"]["archived_keys"] == ["websocket:b"] diff --git a/nanobot/channels/websocket/tests/test_websocket_envelope_media.py b/nanobot/channels/websocket/tests/test_websocket_envelope_media.py index ad80b5e8b..d63b949be 100644 --- a/nanobot/channels/websocket/tests/test_websocket_envelope_media.py +++ b/nanobot/channels/websocket/tests/test_websocket_envelope_media.py @@ -339,7 +339,7 @@ async def test_local_reference_inspection_send_recheck_and_no_staging(tmp_path, assert local["kind"] == "video" assert channel.gateway.uploads.store._entries == {} assert not list(channel.gateway.uploads.store.media_dir.glob("*")) - assert channel._webui_request_operations == {} + assert channel._commands.request_operations == {} for invalid in ("missing.mp4", str(workspace), str(tmp_path / "outside.mp4")): failure = await inspect(invalid) diff --git a/nanobot/channels/weixin/runtime.py b/nanobot/channels/weixin/runtime.py index d3fffc5c3..127f2107d 100644 --- a/nanobot/channels/weixin/runtime.py +++ b/nanobot/channels/weixin/runtime.py @@ -670,13 +670,10 @@ class WeixinChannel(BaseChannel): endpoint: str, params: dict[str, Any] | None = None, auth: bool = True, - extra_headers: dict[str, str] | None = None, ) -> dict[str, Any]: assert self._client is not None url = f"{base_url.rstrip('/')}/{endpoint}" hdrs = self._make_headers(auth=auth) - if extra_headers: - hdrs.update(extra_headers) return await self._request_json( "GET", url, endpoint=endpoint, params=params, headers=hdrs, ) diff --git a/nanobot/cli/tui_launcher.py b/nanobot/cli/tui_launcher.py index 4bddb8bad..cc15e5b2c 100644 --- a/nanobot/cli/tui_launcher.py +++ b/nanobot/cli/tui_launcher.py @@ -6,7 +6,6 @@ import os import platform import shutil import subprocess -import time import urllib.error import urllib.request import zipfile @@ -19,7 +18,6 @@ from nanobot.bun import BunUnavailableError, bun_environment, ensure_bun from nanobot.cli.process_identity import named_executable from nanobot.cli.runtime_config import _model_display from nanobot.cli.webui_support import ( - _gateway_health_ready, _gateway_health_url, _gateway_instance_command, _host_for_local_browser, @@ -64,8 +62,6 @@ _TUI_RELEASE_LIMITS = { } # Keep in sync with TUI_DETACH_EXIT_CODE in tui/src/index.ts. _TUI_DETACH_EXIT_CODE = 90 -_GATEWAY_READY_TIMEOUT_S = 20.0 -_GATEWAY_READY_POLL_S = 0.1 @dataclass(frozen=True) @@ -134,7 +130,6 @@ def launch_tui( config, config_path=config_path, workspace_override=workspace_override, - wait_until_ready=False, ) exit_code = process.wait() if exit_code == _TUI_DETACH_EXIT_CODE: @@ -410,7 +405,6 @@ def _ensure_gateway( *, config_path: Path, workspace_override: str | None, - wait_until_ready: bool = True, ) -> _GatewayHandle: from nanobot.gateway import ( GatewayClientLease, @@ -427,39 +421,6 @@ def _ensure_gateway( lease = GatewayClientLease(runtime, kind="tui") lease.acquire() try: - def ready(status: object) -> bool: - management_ready = getattr(status, "ready", None) - if not isinstance(management_ready, bool): - management_ready = _gateway_health_ready( - config.gateway.host, - config.gateway.port, - ) - return _webui_endpoint_reachable(base_url) and management_ready - - def wait_for_ready(log_path: object) -> _GatewayHandle: - deadline = time.monotonic() + _GATEWAY_READY_TIMEOUT_S - while time.monotonic() < deadline: - current = runtime.status() - if not current.running: - break - if current.port not in {None, config.gateway.port}: - break - if ready(current): - return _GatewayHandle(base_url=base_url, lease=lease) - time.sleep(_GATEWAY_READY_POLL_S) - - current = runtime.status() - if current.running: - raise TuiUnavailableError( - "local gateway process is running but its WebSocket/WebUI listener " - "is unavailable; channel recovery did not restore it. " - "Run `nanobot gateway status` and inspect logs at " - f"{log_path}; if it remains degraded, run `nanobot gateway restart`." - ) - raise TuiUnavailableError( - f"local gateway did not become ready; logs: {log_path}" - ) - status = runtime.status() if status.running: if status.port not in {None, config.gateway.port}: @@ -467,11 +428,7 @@ def _ensure_gateway( "the matching gateway instance is running on a different port; " "restart it or use `nanobot agent --classic`" ) - if not wait_until_ready: - return _GatewayHandle(base_url=base_url, lease=lease) - if ready(status): - return _GatewayHandle(base_url=base_url, lease=lease) - return wait_for_ready(status.log_path) + return _GatewayHandle(base_url=base_url, lease=lease) elif _webui_endpoint_reachable(base_url): raise TuiUnavailableError( "the configured gateway port belongs to a different nanobot instance; " @@ -495,9 +452,7 @@ def _ensure_gateway( "the matching gateway instance is running on a different port; " "restart it or use `nanobot agent --classic`" ) - if not wait_until_ready: - return _GatewayHandle(base_url=base_url, lease=lease) - return wait_for_ready(result.status.log_path) + return _GatewayHandle(base_url=base_url, lease=lease) except BaseException: lease.release(timeout_s=5) raise diff --git a/nanobot/llm_usage/store.py b/nanobot/llm_usage/store.py index 5209db4c2..3151ec1b6 100644 --- a/nanobot/llm_usage/store.py +++ b/nanobot/llm_usage/store.py @@ -339,24 +339,15 @@ class LLMUsageStore: self, *, connection: sqlite3.Connection, - start_ms: int | None, + start_ms: int, end_ms: int, - group_by: tuple[str, ...] = (), - limit: int | None = None, ) -> list[sqlite3.Row]: - selected = f"{', '.join(group_by)}, " if group_by else "" - where = "started_at_ms < ?" - params: list[object] = [end_ms] - if start_ms is not None: - where = "started_at_ms >= ? AND started_at_ms < ?" - params = [start_ms, end_ms] - query = f"SELECT {selected}{_AGGREGATE_SQL} FROM llm_calls WHERE {where}" - if group_by: - query += f" GROUP BY {', '.join(group_by)} ORDER BY total_tokens DESC" - if limit is not None: - query += " LIMIT ?" - params.append(limit) - return list(connection.execute(query, params).fetchall()) + query = ( + f"SELECT provider, model, {_AGGREGATE_SQL} FROM llm_calls " + "WHERE started_at_ms >= ? AND started_at_ms < ? " + "GROUP BY provider, model ORDER BY total_tokens DESC LIMIT ?" + ) + return list(connection.execute(query, (start_ms, end_ms, 50)).fetchall()) def _daily_rows( self, @@ -453,8 +444,6 @@ class LLMUsageStore: connection=connection, start_ms=last_30_start_ms, end_ms=end_ms, - group_by=("provider", "model"), - limit=50, ) providers_30d = [ { diff --git a/nanobot/session/manager.py b/nanobot/session/manager.py index 75099fb6e..2dbe7a761 100644 --- a/nanobot/session/manager.py +++ b/nanobot/session/manager.py @@ -478,14 +478,9 @@ class SessionManager: """Public helper used by HTTP handlers to map an arbitrary key to a stable filename stem.""" return SessionLocation.safe_key(key) - @staticmethod - def _storage_key(key: str) -> str: - """Collision-resistant encoding for internal session storage filenames.""" - return SessionLocation.storage_key(key) - @staticmethod def _decode_storage_key(stem: str) -> str | None: - """Reverse _storage_key(): decode a base64url (no-padding) stem back to the original key.""" + """Decode a base64url (no-padding) stem back to the original key.""" return SessionLocation.decode_storage_key(stem) @staticmethod diff --git a/tests/cli/test_tui_launcher.py b/tests/cli/test_tui_launcher.py index e1f8eeaea..dd1eee412 100644 --- a/tests/cli/test_tui_launcher.py +++ b/tests/cli/test_tui_launcher.py @@ -106,7 +106,6 @@ def test_launcher_passes_the_canonical_model_preset_to_the_tui( monkeypatch.setattr("nanobot.cli.tui_launcher.resolve_tui_command", lambda: ["nanobot-tui"]) def ensure_gateway(*args: object, **kwargs: object) -> SimpleNamespace: assert events == ["spawned"] - assert kwargs["wait_until_ready"] is False return SimpleNamespace( base_url="http://127.0.0.1:8765", lease=FakeLease(), @@ -244,18 +243,6 @@ def test_launcher_keeps_the_tui_alive_while_an_existing_gateway_recovers( "launcher must not probe readiness for a live recovering gateway" ), ) - monkeypatch.setattr( - tui_launcher, - "time", - SimpleNamespace( - monotonic=lambda: pytest.fail( - "launcher must not wait for a live gateway to recover" - ), - sleep=lambda _seconds: pytest.fail( - "launcher must not sleep for gateway recovery" - ), - ), - ) result = launch_tui( config, @@ -768,11 +755,6 @@ def test_gateway_reuses_the_matching_managed_instance( raise AssertionError(f"unowned gateway stopped with timeout {timeout_s}") monkeypatch.setattr("nanobot.gateway.GatewayRuntime", FakeRuntime) - monkeypatch.setattr("nanobot.cli.tui_launcher._webui_endpoint_reachable", lambda _url: True) - monkeypatch.setattr( - "nanobot.cli.tui_launcher._gateway_health_ready", - lambda *_args, **_kwargs: True, - ) gateway = _ensure_gateway( config, @@ -809,22 +791,10 @@ def test_gateway_reuse_returns_a_degraded_live_gateway_without_waiting( "nanobot.cli.tui_launcher._webui_endpoint_reachable", lambda _url: pytest.fail("non-blocking reuse must not probe readiness"), ) - monkeypatch.setattr( - tui_launcher, - "time", - SimpleNamespace( - monotonic=lambda: pytest.fail( - "non-blocking reuse must not enter the readiness wait" - ), - sleep=lambda _seconds: pytest.fail("non-blocking reuse must not sleep"), - ), - ) - gateway = _ensure_gateway( config, config_path=tmp_path / "config.json", workspace_override=None, - wait_until_ready=False, ) assert gateway.base_url == "http://127.0.0.1:8765" @@ -833,93 +803,6 @@ def test_gateway_reuse_returns_a_degraded_live_gateway_without_waiting( gateway.lease.release(wait_for_stop=False) -def test_gateway_reuse_waits_for_a_live_gateway_to_recover_its_webui_listener( - monkeypatch: pytest.MonkeyPatch, - tmp_path: Path, -) -> None: - config = Config() - endpoint_results = iter((False, False, True)) - - class FakeRuntime: - def __init__(self, *, paths: object) -> None: - self.paths = paths - - def status(self) -> SimpleNamespace: - return SimpleNamespace( - running=True, - port=config.gateway.port, - log_path=tmp_path / "gateway.log", - ) - - monkeypatch.setattr("nanobot.gateway.GatewayRuntime", FakeRuntime) - monkeypatch.setattr( - "nanobot.cli.tui_launcher._webui_endpoint_reachable", - lambda _url: next(endpoint_results), - ) - monkeypatch.setattr( - "nanobot.cli.tui_launcher._gateway_health_ready", - lambda *_args, **_kwargs: True, - ) - clock = iter((0.0, 0.0, 0.1)) - sleeps: list[float] = [] - monkeypatch.setattr( - tui_launcher, - "time", - SimpleNamespace(monotonic=lambda: next(clock), sleep=sleeps.append), - ) - - gateway = _ensure_gateway( - config, - config_path=tmp_path / "config.json", - workspace_override=None, - ) - - assert gateway.base_url == "http://127.0.0.1:8765" - assert gateway.lease is not None - assert sleeps == [tui_launcher._GATEWAY_READY_POLL_S] - gateway.lease.release(wait_for_stop=False) - - -def test_gateway_reuse_with_explicit_wait_rejects_a_live_but_unready_gateway( - monkeypatch: pytest.MonkeyPatch, - tmp_path: Path, -) -> None: - config = Config() - - class FakeRuntime: - def __init__(self, *, paths: object) -> None: - self.paths = paths - - def status(self) -> SimpleNamespace: - return SimpleNamespace( - running=True, - port=config.gateway.port, - log_path=tmp_path / "gateway.log", - ) - - monkeypatch.setattr("nanobot.gateway.GatewayRuntime", FakeRuntime) - monkeypatch.setattr( - "nanobot.cli.tui_launcher._webui_endpoint_reachable", - lambda _url: False, - ) - clock = iter((0.0, tui_launcher._GATEWAY_READY_TIMEOUT_S)) - monkeypatch.setattr( - tui_launcher, - "time", - SimpleNamespace( - monotonic=lambda: next(clock), - sleep=lambda _seconds: pytest.fail("expired readiness wait must not sleep"), - ), - ) - - with pytest.raises(TuiUnavailableError, match="process is running.*listener is unavailable"): - _ensure_gateway( - config, - config_path=tmp_path / "config.json", - workspace_override=None, - ) - - def test_gateway_started_for_tui_stops_when_its_last_lease_exits( monkeypatch: pytest.MonkeyPatch, tmp_path: Path, @@ -966,10 +849,6 @@ def test_gateway_started_for_tui_stops_when_its_last_lease_exits( "nanobot.cli.tui_launcher._webui_endpoint_reachable", lambda _url: started, ) - monkeypatch.setattr( - "nanobot.cli.tui_launcher._gateway_health_ready", - lambda *_args, **_kwargs: started, - ) gateway = _ensure_gateway( config, diff --git a/webui/src/components/thread/thread-motion.ts b/webui/src/components/thread/thread-motion.ts index fb8dd3f04..856334d8b 100644 --- a/webui/src/components/thread/thread-motion.ts +++ b/webui/src/components/thread/thread-motion.ts @@ -110,7 +110,6 @@ interface ThreadMotionTurn { interface ThreadMotionSnapshot { mode: ThreadMotionMode; turnId: string | null; - promptId: string | null; promptPositioned: boolean; measurementPending: boolean; } @@ -191,7 +190,6 @@ export class ThreadMotionCoordinator { return { mode: this.mode, turnId: this.turn.id, - promptId: this.turn.promptId, promptPositioned: this.promptPositioned, measurementPending: this.measurementFrameId !== null, }; @@ -315,17 +313,13 @@ export class ThreadMotionCoordinator { return result; } - navigateHistoryTo(top: number): ThreadCameraFollowResult | null { - return this.beginHistoryNavigation(top, null); - } - navigateHistoryToPrompt(promptId: string): ThreadCameraFollowResult | null { const geometry = this.measure(promptId); if (!geometry || geometry.promptTop === null) return null; return this.beginHistoryNavigation(geometry.promptTop, promptId); } - private beginHistoryNavigation(top: number, promptId: string | null): ThreadCameraFollowResult | null { + private beginHistoryNavigation(top: number, promptId: string): ThreadCameraFollowResult | null { if (this.mode !== "navigating-history") this.camera.cancel(); this.transition("navigate-history"); this.historyNavigationPromptId = promptId; diff --git a/webui/src/lib/nanobot-client.ts b/webui/src/lib/nanobot-client.ts index b51d98f98..f853ade3e 100644 --- a/webui/src/lib/nanobot-client.ts +++ b/webui/src/lib/nanobot-client.ts @@ -363,11 +363,6 @@ export class NanobotClient { this.applyRunEffects(this.runs.transition({ kind: "restore-pending", chatId, generation, turnId })); } - /** Last ``goal_status`` ``started_at`` (unix sec) for *chatId*, if the turn is running. */ - getRunStartedAt(chatId: string): number | null { - return this.runs.view(chatId).startedAt; - } - /** Canonical lifecycle turn currently owning the run, retained after completion. */ getRunTurnId(chatId: string): string | null { return this.runs.view(chatId).latestTurnId; diff --git a/webui/src/tests/app-layout.test.tsx b/webui/src/tests/app-layout.test.tsx index b0ddb2347..d7e8e96f5 100644 --- a/webui/src/tests/app-layout.test.tsx +++ b/webui/src/tests/app-layout.test.tsx @@ -295,7 +295,6 @@ vi.mock("@/lib/nanobot-client", async (importOriginal) => { onRunCompletion = () => () => {}; getRunState = () => runState(null); restorePendingRun = vi.fn(); - getRunStartedAt = () => null; getRunTurnId = () => null; getUnsettledRunChatIds = () => []; getRunGeneration = () => 0; diff --git a/webui/src/tests/nanobot-client.test.ts b/webui/src/tests/nanobot-client.test.ts index ef2b8b324..01e9f8a77 100644 --- a/webui/src/tests/nanobot-client.test.ts +++ b/webui/src/tests/nanobot-client.test.ts @@ -199,7 +199,7 @@ describe("NanobotClient", () => { }); expect(client.getRunTurnId("shared-chat")).toBe("turn-a"); - expect(client.getRunStartedAt("shared-chat")).toBe(1_700_000_000); + expect(client.getRunState("shared-chat").startedAt).toBe(1_700_000_000); expect(client.hasUnsettledRun("shared-chat")).toBe(true); }); @@ -630,13 +630,13 @@ describe("NanobotClient", () => { status: "running", started_at: 12_345, }); - expect(client.getRunStartedAt("chat-strip")).toBe(12_345); + expect(client.getRunState("chat-strip").startedAt).toBe(12_345); lastSocket().fakeMessage({ event: "goal_status", chat_id: "chat-strip", status: "idle", }); - expect(client.getRunStartedAt("chat-strip")).toBeNull(); + expect(client.getRunState("chat-strip").startedAt).toBeNull(); }); it("clears the local run strip immediately when a stop is requested", () => { @@ -659,7 +659,7 @@ describe("NanobotClient", () => { client.finishRunLocally("chat-stop"); - expect(client.getRunStartedAt("chat-stop")).toBeNull(); + expect(client.getRunState("chat-stop").startedAt).toBeNull(); expect(client.hasUnsettledRun("chat-stop")).toBe(false); expect(client.isRunCompleted("chat-stop", "turn-stop")).toBe(true); expect(handler).toHaveBeenLastCalledWith("chat-stop", expect.objectContaining({ active: false, startedAt: null })); @@ -687,7 +687,7 @@ describe("NanobotClient", () => { lastSocket().close(); expect(client.status).toBe("reconnecting"); - expect(client.getRunStartedAt("chat-strip")).toBe(12_345); + expect(client.getRunState("chat-strip").startedAt).toBe(12_345); expect(client.getRunTurnId("chat-strip")).toBe("turn-strip"); expect(client.isRunCompleted("chat-strip", "turn-strip")).toBe(false); expect(client.getUnsettledRunChatIds()).toEqual(["chat-strip"]); @@ -695,12 +695,12 @@ describe("NanobotClient", () => { await vi.advanceTimersByTimeAsync(20); expect(FakeSocket.instances.length).toBeGreaterThan(1); lastSocket().fakeOpen(); - expect(client.getRunStartedAt("chat-strip")).toBe(12_345); + expect(client.getRunState("chat-strip").startedAt).toBe(12_345); expect(handler).toHaveBeenCalledTimes(1); lastSocket().fakeMessage({ event: "turn_end", chat_id: "chat-strip", turn_id: "turn-strip", }); - expect(client.getRunStartedAt("chat-strip")).toBeNull(); + expect(client.getRunState("chat-strip").startedAt).toBeNull(); expect(client.getUnsettledRunChatIds()).toEqual([]); expect(client.isRunCompleted("chat-strip", "turn-strip")).toBe(true); expect(client.isRunCompleted("another-chat", "turn-strip")).toBe(false); @@ -728,7 +728,7 @@ describe("NanobotClient", () => { event: "turn_end", chat_id: "chat-strip", }); - expect(client.getRunStartedAt("chat-strip")).toBeNull(); + expect(client.getRunState("chat-strip").startedAt).toBeNull(); expect(handler).toHaveBeenLastCalledWith("chat-strip", expect.objectContaining({ active: false, startedAt: null })); }); @@ -753,7 +753,7 @@ describe("NanobotClient", () => { expect( client.reconcileCanonicalCompletion("chat-race", requestGeneration, ["turn-old"]), ).toBe(false); - expect(client.getRunStartedAt("chat-race")).toBe(12_345); + expect(client.getRunState("chat-race").startedAt).toBe(12_345); }); it("rejects a user-only snapshot for a submitted turn that has not completed", () => { @@ -945,7 +945,7 @@ describe("NanobotClient", () => { reason: "text_too_large", }); - expect(client.getRunStartedAt("chat-rejection-race")).toBe(2_000); + expect(client.getRunState("chat-rejection-race").startedAt).toBe(2_000); expect( client.reconcileCanonicalCompletion("chat-rejection-race", requestGeneration, []), ).toBe(false); @@ -987,7 +987,7 @@ describe("NanobotClient", () => { detail: "message_rejected", }); - expect(client.getRunStartedAt("chat-reject-newer-clock")).toBe(1_000); + expect(client.getRunState("chat-reject-newer-clock").startedAt).toBe(1_000); expect(client.hasUnsettledRun("chat-reject-newer-clock")).toBe(true); }); @@ -1055,7 +1055,7 @@ describe("NanobotClient", () => { chatId: "chat-too-big-race", turnId: "turn-rejected", }]); - expect(client.getRunStartedAt("chat-too-big-race")).toBe(1_000); + expect(client.getRunState("chat-too-big-race").startedAt).toBe(1_000); expect( client.reconcileCanonicalCompletion( "chat-too-big-race", @@ -1259,7 +1259,7 @@ describe("NanobotClient", () => { }; expect(client.canReconcileCanonicalCompletion("chat-authority", requestGeneration, [], snapshot)).toBe(false); expect(client.reconcileCanonicalCompletion("chat-authority", requestGeneration, [], snapshot)).toBe(false); - expect(client.getRunStartedAt("chat-authority")).toBe(123); + expect(client.getRunState("chat-authority").startedAt).toBe(123); expect(client.hasUnsettledRun("chat-authority")).toBe(true); received.mockClear(); lastSocket().fakeMessage({ event: "delta", chat_id: "chat-authority", turn_id: "turn-authority", text: "Still running" }); @@ -1392,7 +1392,7 @@ describe("NanobotClient", () => { }); expect(client.hasUnsettledRun("chat-legacy-idle")).toBe(false); - expect(client.getRunStartedAt("chat-legacy-idle")).toBeNull(); + expect(client.getRunState("chat-legacy-idle").startedAt).toBeNull(); expect(handler).toHaveBeenLastCalledWith(expect.objectContaining({ event: "goal_status", status: "idle", @@ -1656,7 +1656,7 @@ describe("NanobotClient", () => { event: "goal_status", chat_id: "chat-late", turn_id: "turn-late", status: "running", started_at: 123, }); - expect(client.getRunStartedAt("chat-late")).toBe(123); + expect(client.getRunState("chat-late").startedAt).toBe(123); socket.fakeMessage({ event: "turn_end", chat_id: "chat-late", turn_id: "turn-late" }); const message = { event: "message", chat_id: "chat-late", turn_id: "turn-late", kind, text: "Late detail", @@ -1665,7 +1665,7 @@ describe("NanobotClient", () => { expect(handler).toHaveBeenLastCalledWith(message); expect(client.isRunCompleted("chat-late", "turn-late")).toBe(true); - expect(client.getRunStartedAt("chat-late")).toBeNull(); + expect(client.getRunState("chat-late").startedAt).toBeNull(); expect(client.hasUnsettledRun("chat-late")).toBe(false); client.close(); }, @@ -1733,7 +1733,7 @@ describe("NanobotClient", () => { turn_id: "turn-old", }); - expect(client.getRunStartedAt("chat-delayed-idle")).toBe(2_000); + expect(client.getRunState("chat-delayed-idle").startedAt).toBe(2_000); expect(runHandler).not.toHaveBeenCalled(); expect(chatHandler).not.toHaveBeenCalled(); }); @@ -1763,7 +1763,7 @@ describe("NanobotClient", () => { ["turn-complete"], ), ).toBe(true); - expect(client.getRunStartedAt("chat-delayed-run")).toBeNull(); + expect(client.getRunState("chat-delayed-run").startedAt).toBeNull(); }); it("preflights canonical completion without fencing or settling the turn", () => { @@ -1831,7 +1831,7 @@ describe("NanobotClient", () => { ["turn-canonical"], ), ).toBe(true); - expect(client.getRunStartedAt("chat-canonical")).toBeNull(); + expect(client.getRunState("chat-canonical").startedAt).toBeNull(); expect(runHandler).toHaveBeenLastCalledWith("chat-canonical", expect.objectContaining({ active: false, startedAt: null })); const deliveredBeforeLateFrames = chatHandler.mock.calls.length; @@ -1854,7 +1854,7 @@ describe("NanobotClient", () => { }); expect(chatHandler).toHaveBeenCalledTimes(deliveredBeforeLateFrames); - expect(client.getRunStartedAt("chat-canonical")).toBeNull(); + expect(client.getRunState("chat-canonical").startedAt).toBeNull(); const otherChat = vi.fn(); client.onChat("other-chat", otherChat); const taskUpdate = { @@ -1866,7 +1866,7 @@ describe("NanobotClient", () => { expect(chatHandler).toHaveBeenCalledTimes(deliveredBeforeLateFrames + 1); expect(otherChat).not.toHaveBeenCalled(); expect(client.hasUnsettledRun("chat-canonical")).toBe(false); - expect(client.getRunStartedAt("chat-canonical")).toBeNull(); + expect(client.getRunState("chat-canonical").startedAt).toBeNull(); }); it("notifies run status subscribers and replays running chats", () => { diff --git a/webui/src/tests/thread-motion.test.ts b/webui/src/tests/thread-motion.test.ts index ff5c886ea..57fdfcf8d 100644 --- a/webui/src/tests/thread-motion.test.ts +++ b/webui/src/tests/thread-motion.test.ts @@ -533,6 +533,7 @@ describe("ThreadMotionCoordinator", () => { camera, coordinator, advanceFrame, + setGeometry, } = motionHarness(); coordinator.updateTurn({ id: "turn-1", @@ -540,7 +541,8 @@ describe("ThreadMotionCoordinator", () => { hasOutput: true, }); advanceFrame(); - coordinator.navigateHistoryTo(900); + setGeometry({ promptTop: 900 }); + coordinator.navigateHistoryToPrompt("prompt-2"); camera.cancel.mockClear(); coordinator.completeTurn(); @@ -554,13 +556,15 @@ describe("ThreadMotionCoordinator", () => { camera, coordinator, setCameraFollowing, + setGeometry, } = motionHarness(); coordinator.handleUserScrollIntent(false); expect(coordinator.snapshot().mode).toBe("idle"); expect(camera.cancel).not.toHaveBeenCalled(); - coordinator.navigateHistoryTo(900); + setGeometry({ promptTop: 900 }); + coordinator.navigateHistoryToPrompt("prompt-1"); expect(camera.navigateTo).toHaveBeenCalledWith(900); expect(coordinator.snapshot().mode).toBe("navigating-history"); expect(coordinator.observeScroll(false)).toBe("navigation"); @@ -571,7 +575,8 @@ describe("ThreadMotionCoordinator", () => { expect(coordinator.snapshot().mode).toBe("browsing-history"); expect(coordinator.observeScroll(false)).toBe("user"); - coordinator.navigateHistoryTo(700); + setGeometry({ promptTop: 700 }); + coordinator.navigateHistoryToPrompt("prompt-2"); camera.cancel.mockClear(); coordinator.takeUserControl(); expect(camera.cancel).toHaveBeenCalledTimes(1); @@ -581,20 +586,21 @@ describe("ThreadMotionCoordinator", () => { coordinator.takeUserControl(); expect(camera.cancel).not.toHaveBeenCalled(); - coordinator.navigateHistoryTo(600); + setGeometry({ promptTop: 600 }); + coordinator.navigateHistoryToPrompt("prompt-3"); setCameraFollowing(false); expect(coordinator.observeScroll(false)).toBe("navigation"); expect(coordinator.snapshot().mode).toBe("browsing-history"); }); it("settles camera navigation without relying on a scroll event", () => { - const { coordinator } = motionHarness(); + const { coordinator } = motionHarness({ promptTop: 200 }); coordinator.takeUserControl(); coordinator.navigateLatestTo(1_400); coordinator.cameraSettled(); expect(coordinator.snapshot().mode).toBe("follow-latest"); - coordinator.navigateHistoryTo(200); + coordinator.navigateHistoryToPrompt("prompt-1"); coordinator.cameraSettled(); expect(coordinator.snapshot().mode).toBe("navigating-history"); }); diff --git a/webui/src/tests/thread-shell.test.tsx b/webui/src/tests/thread-shell.test.tsx index 454b06fef..e999cbf0f 100644 --- a/webui/src/tests/thread-shell.test.tsx +++ b/webui/src/tests/thread-shell.test.tsx @@ -88,7 +88,6 @@ function makeClient() { }, getRunState: lifecycle.getRunState.bind(lifecycle), restorePendingRun: lifecycle.restorePendingRun.bind(lifecycle), - getRunStartedAt: lifecycle.getRunStartedAt.bind(lifecycle), getRunTurnId: lifecycle.getRunTurnId.bind(lifecycle), isRunCompleted: lifecycle.isRunCompleted.bind(lifecycle), finishRunLocally: vi.fn(lifecycle.finishRunLocally.bind(lifecycle)), @@ -4195,7 +4194,7 @@ describe("ThreadShell", () => { act(() => client._emitSessionUpdate("visibility-complete-a", "thread")); await waitFor(() => expect(screen.getByText("completed while hidden")).toBeInTheDocument()); expect(screen.queryByRole("button", { name: "Stop response" })).not.toBeInTheDocument(); - expect(client.getRunStartedAt("visibility-complete-a")).toBeNull(); + expect(client.getRunState("visibility-complete-a").startedAt).toBeNull(); rerender(view("visibility-complete-b")); await waitFor(() => expect(screen.getByText("other thread")).toBeInTheDocument()); @@ -4302,7 +4301,7 @@ describe("ThreadShell", () => { expect(screen.getByText("saved answer prefix")).toBeInTheDocument(); expect(screen.getByRole("button", { name: "Stop response" })).toBeInTheDocument(); expect(client.reconcileCanonicalCompletion).not.toHaveBeenCalled(); - expect(client.getRunStartedAt(chatId)).toBe(1_700); + expect(client.getRunState(chatId).startedAt).toBe(1_700); const input = screen.getByRole("textbox", { name: "Message input" }); fireEvent.change(input, { target: { value: "queued guidance" } }); diff --git a/webui/src/tests/turn-completion.test.tsx b/webui/src/tests/turn-completion.test.tsx index d09c4697c..20a2bd26b 100644 --- a/webui/src/tests/turn-completion.test.tsx +++ b/webui/src/tests/turn-completion.test.tsx @@ -155,7 +155,7 @@ describe("completed turn event ordering", () => { }); expect(result.current.isStreaming).toBe(false); expect(result.current.runStartedAt).toBeNull(); - expect(client.getRunStartedAt(CHAT_ID)).toBeNull(); + expect(client.getRunState(CHAT_ID).startedAt).toBeNull(); expect(client.hasUnsettledRun(CHAT_ID)).toBe(false); expect(result.current.messages.some((message) => message.content === "additional context")).toBe(true); diff --git a/webui/src/tests/useNanobotStream.test.tsx b/webui/src/tests/useNanobotStream.test.tsx index 8bf5e2fc6..9a5e952ee 100644 --- a/webui/src/tests/useNanobotStream.test.tsx +++ b/webui/src/tests/useNanobotStream.test.tsx @@ -92,7 +92,6 @@ function fakeClient() { getRunState: lifecycle.getRunState.bind(lifecycle), getRunGeneration: lifecycle.getRunGeneration.bind(lifecycle), restorePendingRun: lifecycle.restorePendingRun.bind(lifecycle), - getRunStartedAt: lifecycle.getRunStartedAt.bind(lifecycle), getRunTurnId: lifecycle.getRunTurnId.bind(lifecycle), getGoalState: lifecycle.getGoalState.bind(lifecycle), hasUnsettledRun: lifecycle.hasUnsettledRun.bind(lifecycle), diff --git a/webui/src/tests/useReconnectRuns.test.tsx b/webui/src/tests/useReconnectRuns.test.tsx index aa18ae9d6..eaaaec508 100644 --- a/webui/src/tests/useReconnectRuns.test.tsx +++ b/webui/src/tests/useReconnectRuns.test.tsx @@ -108,7 +108,7 @@ describe("durable run recovery", () => { expect(fetchMock).toHaveBeenCalledTimes(9); expect(peak).toBe(4); expect(client.getUnsettledRunChatIds()).toEqual(["chat-8"]); - expect(client.getRunStartedAt("chat-8")).toBe(456); + expect(client.getRunState("chat-8").startedAt).toBe(456); expect(webuiThreadCache.get("websocket:chat-8")).toBeUndefined(); close(); }); @@ -171,7 +171,7 @@ describe("durable run recovery", () => { expect(fetchMock.mock.calls[1][1].headers["If-None-Match"]).toBe('"active-page"'); await act(async () => { resolveRecovery(response(completedThread())); }); expect(mounted.result.current.messages.at(-1)?.content).toBe("The complete answer"); - expect(client.getRunStartedAt("inactive")).toBeNull(); + expect(client.getRunState("inactive").startedAt).toBeNull(); expect(fetchMock).toHaveBeenCalledTimes(2); mounted.unmount(); close(); @@ -285,7 +285,7 @@ describe("durable run recovery", () => { await act(async () => { reads[0](response(stale)); }); expect(mounted.result.current.messages.at(-1)?.content).toBe("The complete answer"); expect(mounted.result.current.hasPendingToolCalls).toBe(false); - expect(client.getRunStartedAt("inactive")).toBeNull(); + expect(client.getRunState("inactive").startedAt).toBeNull(); mounted.unmount(); close(); }); @@ -309,7 +309,7 @@ describe("durable run recovery", () => { "/api/sessions/websocket%3Ainactive/webui-thread?limit=40&direction=latest&include_model_requests=1&context_graph_encoding=references-v1", expect.objectContaining({ headers: { Authorization: "Bearer renewed-token" } }), ); - expect(client.getRunStartedAt("inactive")).toBeNull(); + expect(client.getRunState("inactive").startedAt).toBeNull(); expect(client.hasUnsettledRun("inactive")).toBe(false); expect(cachedAtCompletion).toEqual([body]); expect(projectThreadEvents(cachedAtCompletion[0].events).at(-1)?.content).toBe("The complete answer"); @@ -335,8 +335,8 @@ describe("durable run recovery", () => { client.onRunStatus(runStatus); await reopen(); expect(fetchMock).toHaveBeenCalledTimes(2); - expect(client.getRunStartedAt("inactive")).toBeNull(); - expect(client.getRunStartedAt("running")).toBe(456); + expect(client.getRunState("inactive").startedAt).toBeNull(); + expect(client.getRunState("running").startedAt).toBe(456); expect(client.getRunTurnId("running")).toBe("turn-running"); expect(client.hasUnsettledRun("running")).toBe(true); expect(runStatus).toHaveBeenCalledTimes(3); @@ -354,7 +354,7 @@ describe("durable run recovery", () => { const { client, running, reopen, close } = setup(); running(); await reopen(); - expect(client.getRunStartedAt("inactive")).toBe(123); + expect(client.getRunState("inactive").startedAt).toBe(123); expect(client.hasUnsettledRun("inactive")).toBe(true); expect(webuiThreadCache.get("websocket:inactive")).toBeUndefined(); close(); @@ -370,7 +370,7 @@ describe("durable run recovery", () => { await reopen(); running("inactive", "turn-new", 456); await act(async () => { resolveRead(response(completedThread())); }); - expect(client.getRunStartedAt("inactive")).toBe(456); + expect(client.getRunState("inactive").startedAt).toBe(456); expect(client.getRunTurnId("inactive")).toBe("turn-new"); expect(client.hasUnsettledRun("inactive")).toBe(true); expect(webuiThreadCache.get("websocket:inactive")).toBeUndefined(); @@ -396,7 +396,7 @@ describe("durable run recovery", () => { const { client, running, reopen, close } = setup(); running(); await reopen(); - expect(client.getRunStartedAt("inactive")).toBeNull(); + expect(client.getRunState("inactive").startedAt).toBeNull(); expect(client.hasUnsettledRun("inactive")).toBe(false); expect(webuiThreadCache.get("websocket:inactive")).toEqual(body); close(); @@ -410,7 +410,7 @@ describe("durable run recovery", () => { const { client, running, reopen, close } = setup(); running(); await reopen(); - expect(client.getRunStartedAt("inactive")).toBe(123); + expect(client.getRunState("inactive").startedAt).toBe(123); expect(client.hasUnsettledRun("inactive")).toBe(true); expect(webuiThreadCache.get("websocket:inactive")).toBeUndefined(); close(); @@ -432,7 +432,7 @@ describe("durable run recovery", () => { body.completed_turn_ids = []; body.active_turn_id = null; await act(async () => { resolveRead(response(body)); }); - expect(client.getRunStartedAt("inactive")).toBe(456); + expect(client.getRunState("inactive").startedAt).toBe(456); expect(client.hasUnsettledRun("inactive")).toBe(true); expect(webuiThreadCache.get("websocket:inactive")).toBeUndefined(); const resumed = vi.fn(); @@ -457,7 +457,7 @@ describe("durable run recovery", () => { await reopen(); act(() => sockets.at(-1)!.close()); await act(async () => { resolveRead(response(completedThread())); }); - expect(client.getRunStartedAt("inactive")).toBe(123); + expect(client.getRunState("inactive").startedAt).toBe(123); expect(client.hasUnsettledRun("inactive")).toBe(true); expect(webuiThreadCache.get("websocket:inactive")).toBeUndefined(); close(); @@ -473,7 +473,7 @@ describe("durable run recovery", () => { await reopen(); hook.unmount(); await act(async () => { resolveRead(response(completedThread())); }); - expect(client.getRunStartedAt("inactive")).toBe(123); + expect(client.getRunState("inactive").startedAt).toBe(123); expect(webuiThreadCache.get("websocket:inactive")).toBeUndefined(); close(); }); diff --git a/webui/src/tests/useSessions.test.tsx b/webui/src/tests/useSessions.test.tsx index 724cf6a01..531ada6bd 100644 --- a/webui/src/tests/useSessions.test.tsx +++ b/webui/src/tests/useSessions.test.tsx @@ -28,7 +28,6 @@ function fakeClient() { onRunCompletion: () => () => {}, onError: () => () => {}, onChat: () => () => {}, - getRunStartedAt: () => null, onSessionUpdate: (handler: (chatId: string, scope?: string) => void) => { sessionUpdateHandlers.add(handler); return () => sessionUpdateHandlers.delete(handler);