From 5537bdabd3ae3ba4a0a61a0c214d7aca64b37056 Mon Sep 17 00:00:00 2001 From: chengyongru <61816729+chengyongru@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:22:51 +0800 Subject: [PATCH] refactor(webui): separate gateway mutations and UI state (#6727) --- .../websocket/tests/test_websocket_channel.py | 29 +- .../tests/test_websocket_http_routes.py | 242 ++-- nanobot/webui/automation_routes.py | 462 +++++++ nanobot/webui/cli_apps_api.py | 9 +- nanobot/webui/gateway_services.py | 15 +- nanobot/webui/http_utils.py | 8 + nanobot/webui/inbound_commands.py | 217 ++-- nanobot/webui/mcp_presets_api.py | 186 +-- nanobot/webui/mutation.py | 21 + nanobot/webui/nanobot_features_api.py | 4 +- nanobot/webui/outbound_delivery.py | 11 +- nanobot/webui/request_settings.py | 15 +- nanobot/webui/settings_contracts.py | 37 +- nanobot/webui/settings_model_oauth.py | 273 ++++ nanobot/webui/settings_models.py | 349 ++--- nanobot/webui/settings_routes.py | 461 +++---- nanobot/webui/settings_system.py | 12 +- nanobot/webui/transcript.py | 726 ++--------- nanobot/webui/transcript_replay.py | 402 ++++++ nanobot/webui/transcript_trace.py | 209 +++ nanobot/webui/ws_http.py | 1143 ++++------------- tests/webui/test_background.py | 28 +- tests/webui/test_gateway_terminal.py | 7 +- tests/webui/test_record_pages.py | 56 +- tests/webui/test_remote_instances.py | 1 + tests/webui/test_settings_edit_admission.py | 13 +- tests/webui/test_settings_models.py | 53 + tests/webui/test_settings_routes.py | 207 ++- tests/webui/test_subagent_persistence.py | 2 +- tests/webui/test_subagent_tasks.py | 7 +- tests/webui/test_update_plans.py | 86 +- tests/webui/test_ws_http_oauth.py | 12 +- webui/src/App.tsx | 461 +------ webui/src/components/ChatList.tsx | 64 +- webui/src/components/FileActions.tsx | 4 +- webui/src/components/ImageLightbox.tsx | 3 + webui/src/components/PreviewPane.tsx | 7 +- webui/src/components/StarPrompt.tsx | 5 +- .../components/pairing/PairingCodePopup.tsx | 3 + .../remote/RemoteConnectionsPage.tsx | 3 +- .../thread/ComposerUsagePopover.tsx | 6 +- .../src/components/thread/PromptNavigator.tsx | 3 +- .../src/components/thread/ThreadComposer.tsx | 143 +-- .../src/components/thread/ThreadMessages.tsx | 45 +- webui/src/components/thread/ThreadShell.tsx | 138 +- .../src/components/thread/ThreadViewport.tsx | 56 +- .../thread/activity/FileEditRow.tsx | 2 +- .../components/thread/history-row-identity.ts | 45 + webui/src/components/ui/alert-dialog.tsx | 36 +- webui/src/components/ui/dialog.tsx | 4 +- webui/src/components/ui/dropdown-menu.tsx | 33 +- webui/src/components/ui/popover.tsx | 5 +- webui/src/components/ui/select.tsx | 4 +- webui/src/components/ui/sheet.tsx | 4 +- .../src/components/ui/tooltip-primitives.tsx | 32 +- webui/src/globals.css | 2 +- webui/src/hooks/useComposerVoiceInput.ts | 128 ++ webui/src/hooks/useFilePreviewResize.ts | 116 ++ webui/src/hooks/useLocalGateway.ts | 205 +++ webui/src/hooks/useNanobotStream.ts | 259 ++-- webui/src/hooks/useSidebarGroupMotion.ts | 70 + webui/src/hooks/useStreamBatch.ts | 101 ++ webui/src/lib/dom-overlays.ts | 43 + webui/src/lib/nanobot-client.ts | 40 +- webui/src/shell-route.ts | 210 +++ webui/src/tests/app-layout.test.tsx | 22 + webui/src/tests/nanobot-client.test.ts | 15 +- webui/src/tests/prompt-navigator.test.tsx | 24 + .../tests/temporary-chat-navigation.test.tsx | 50 +- webui/src/tests/thread-viewport.test.tsx | 14 +- 70 files changed, 4058 insertions(+), 3650 deletions(-) create mode 100644 nanobot/webui/automation_routes.py create mode 100644 nanobot/webui/mutation.py create mode 100644 nanobot/webui/settings_model_oauth.py create mode 100644 nanobot/webui/transcript_replay.py create mode 100644 nanobot/webui/transcript_trace.py create mode 100644 webui/src/components/thread/history-row-identity.ts create mode 100644 webui/src/hooks/useComposerVoiceInput.ts create mode 100644 webui/src/hooks/useFilePreviewResize.ts create mode 100644 webui/src/hooks/useLocalGateway.ts create mode 100644 webui/src/hooks/useSidebarGroupMotion.ts create mode 100644 webui/src/hooks/useStreamBatch.ts create mode 100644 webui/src/lib/dom-overlays.ts create mode 100644 webui/src/shell-route.ts diff --git a/nanobot/channels/websocket/tests/test_websocket_channel.py b/nanobot/channels/websocket/tests/test_websocket_channel.py index e779fedd3..19e43440b 100644 --- a/nanobot/channels/websocket/tests/test_websocket_channel.py +++ b/nanobot/channels/websocket/tests/test_websocket_channel.py @@ -59,12 +59,6 @@ from nanobot.session.manager import Session, SessionManager from nanobot.session.model_selection import SESSION_MODEL_PRESET_METADATA_KEY from nanobot.session.session_handles import session_handle_for_name from nanobot.webui.gateway_services import GatewayServices, build_gateway_services -from nanobot.webui.http_utils import ( - http_error as _http_error, -) -from nanobot.webui.http_utils import ( - http_json_response as _http_json_response, -) from nanobot.webui.http_utils import ( issue_route_secret_matches as _issue_route_secret_matches, ) @@ -83,6 +77,7 @@ from nanobot.webui.metadata import ( WEBUI_SYSTEM_COMMAND_TURN_PREFIX, WEBUI_TURN_METADATA_KEY, ) +from nanobot.webui.mutation import MutationResult from nanobot.webui.settings_api import settings_payload, update_provider_settings from .ws_test_client import http_get as _http_get @@ -1259,10 +1254,9 @@ async def test_authenticated_webui_request_returns_correlated_success(bus: Magic conn = AsyncMock() channel._webui_connections.add(conn) channel.gateway.http.dispatch_webui_mutation = AsyncMock( - return_value=_http_json_response({"saved": True}) + return_value=MutationResult.success({"saved": True}) ) - await channel._dispatch_envelope( conn, "webui-client", @@ -1301,12 +1295,12 @@ async def test_webui_mutations_preserve_request_and_response_order(bus: MagicMoc _connection: object, action: str, _payload: dict[str, object], - ) -> Any: + ) -> MutationResult: dispatch_order.append(action) if action == "settings.provider.update": first_started.set() await release_first.wait() - return _http_json_response({"action": action}) + return MutationResult.success({"action": action}) channel.gateway.http.dispatch_webui_mutation = dispatch await channel._dispatch_envelope( @@ -1360,12 +1354,12 @@ async def test_webui_request_survives_disconnect_and_preserves_reconnect_order( release = asyncio.Event() dispatch_order: list[str] = [] - async def mutate(_connection: object, action: str, _payload: dict[str, Any]) -> Any: + async def mutate(_connection: object, action: str, _payload: dict[str, Any]) -> MutationResult: dispatch_order.append(action) if action == "automation.run": started.set() await release.wait() - return _http_json_response({"action": action}) + return MutationResult.success({"action": action}) channel.gateway.http.dispatch_webui_mutation = AsyncMock(side_effect=mutate) envelope = { @@ -1424,7 +1418,7 @@ async def test_webui_request_replays_completed_result_after_reconnect(bus: Magic retry_conn = AsyncMock() channel._webui_connections.update({first_conn, retry_conn}) channel.gateway.http.dispatch_webui_mutation = AsyncMock( - return_value=_http_json_response({"installed": True}) + return_value=MutationResult.success({"installed": True}) ) envelope = { "type": "webui_request", @@ -1456,7 +1450,7 @@ async def test_webui_request_rejects_request_id_reuse_with_different_payload( retry_conn = AsyncMock() channel._webui_connections.update({first_conn, retry_conn}) channel.gateway.http.dispatch_webui_mutation = AsyncMock( - return_value=_http_json_response({"ran": True}) + return_value=MutationResult.success({"ran": True}) ) await channel._dispatch_envelope( @@ -1546,9 +1540,6 @@ async def test_webui_request_returns_correlated_route_error(bus: MagicMock) -> N channel = _ch(bus) conn = AsyncMock() channel._webui_connections.add(conn) - channel.gateway.http.dispatch_webui_mutation = AsyncMock( - return_value=_http_error(400, "invalid settings payload") - ) await channel._dispatch_envelope( conn, @@ -1556,7 +1547,7 @@ async def test_webui_request_returns_correlated_route_error(bus: MagicMock) -> N { "type": "webui_request", "request_id": "request-2", - "action": "settings.agent.update", + "action": "session.delete", "payload": {}, }, ) @@ -1566,7 +1557,7 @@ async def test_webui_request_returns_correlated_route_error(bus: MagicMock) -> N "event": "webui_response", "request_id": "request-2", "ok": False, - "error": {"status": 400, "message": "invalid settings payload"}, + "error": {"status": 400, "message": "missing session key"}, } diff --git a/nanobot/channels/websocket/tests/test_websocket_http_routes.py b/nanobot/channels/websocket/tests/test_websocket_http_routes.py index a6e9cd13e..8148c6f1c 100644 --- a/nanobot/channels/websocket/tests/test_websocket_http_routes.py +++ b/nanobot/channels/websocket/tests/test_websocket_http_routes.py @@ -25,6 +25,8 @@ from nanobot.session.manager import Session, SessionManager from nanobot.session.session_handles import SessionHandleResolver from nanobot.triggers.local_store import LocalTriggerStore from nanobot.webui.gateway_services import GatewayServices, build_gateway_services +from nanobot.webui.mutation import MutationResult +from nanobot.webui.settings_contracts import MutationParams from .ws_test_client import InProcessHttpChannel from .ws_test_client import http_get as _http_get @@ -724,10 +726,10 @@ async def test_webui_skill_management_routes( headers=headers, ) assert update_response.status_code == 200 - assert update_response.json()["last_action"]["enabled"] is False + assert update_response.result["last_action"]["enabled"] is False custom = next( item - for item in update_response.json()["skills"] + for item in update_response.result["skills"] if item["name"] == "custom-skill" ) assert custom["enabled"] is False @@ -739,10 +741,10 @@ async def test_webui_skill_management_routes( headers=headers, ) assert delete_response.status_code == 200 - assert delete_response.json()["last_action"]["deleted"] is True + assert delete_response.result["last_action"]["deleted"] is True assert all( item["name"] != "custom-skill" - for item in delete_response.json()["skills"] + for item in delete_response.result["skills"] ) finally: await channel.stop() @@ -863,7 +865,7 @@ async def test_webui_skills_marketplace_routes_search_and_install( headers=headers, ) assert install_response.status_code == 200 - body = install_response.json() + body = install_response.result assert body["last_action"] == { "installed": True, "already_installed": False, @@ -917,8 +919,8 @@ async def test_webui_skill_source_identity_reaches_public_reads_and_mutations( "source": "vercel-labs/agent-browser", "skill": "agent-browser", }, headers=headers) assert same.status_code == 200 - assert same.json()["last_action"]["already_installed"] is True - assert any(skill["name"] == "agent-browser" for skill in same.json()["skills"]) + assert same.result["last_action"]["already_installed"] is True + assert any(skill["name"] == "agent-browser" for skill in same.result["skills"]) assert (directory / "SKILL.md").read_text(encoding="utf-8") == content finally: await channel.stop() @@ -975,7 +977,7 @@ async def test_webui_skill_install_rejects_overlapping_requests( ) assert overlapping.status_code == 409 - assert "already in progress" in overlapping.text + assert "already in progress" in overlapping.message assert install_mock.await_count == 1 finish.set() @@ -1009,7 +1011,7 @@ async def test_webui_skill_delete_remains_local_only( ) assert response.status_code == 403 - assert "remote skill deletion is disabled" in response.text + assert "remote skill deletion is disabled" in response.message delete.assert_not_called() @@ -1056,7 +1058,7 @@ async def test_webui_skill_install_honors_remote_install_opt_in( ) assert response.status_code == 200 - assert response.json()["last_action"]["name"] == "react-testing" + assert response.result["last_action"]["name"] == "react-testing" @pytest.mark.asyncio @@ -1099,11 +1101,11 @@ async def test_cli_apps_routes_require_token_and_return_payload( ) monkeypatch.setattr( "nanobot.webui.settings_routes.cli_apps_action", - lambda action, query, *, config_path=None: { + lambda action, params, *, config_path=None: { "apps": [], "installed_count": 1, "catalog_updated_at": "2026-04-18", - "last_action": {"ok": True, "message": f"{action}:{query['name'][0]}"}, + "last_action": {"ok": True, "message": f"{action}:{params.values['name']}"}, }, ) channel = _ch(bus, session_manager=_seed_session(tmp_path), port=29912) @@ -1128,7 +1130,7 @@ async def test_cli_apps_routes_require_token_and_return_payload( {"name": "gimp"}, ) assert installed.status_code == 200 - assert installed.json()["last_action"]["message"] == "install:gimp" + assert installed.result["last_action"]["message"] == "install:gimp" finally: await channel.stop() await server_task @@ -1167,7 +1169,7 @@ async def test_nanobot_feature_routes_require_token_and_enable( {"name": "matrix"}, ) assert enabled.status_code == 200 - body = enabled.json() + body = enabled.result assert body["last_action"]["message"] == "Enabled channel 'matrix'" assert body["restart_required_sections"] == ["runtime"] @@ -1177,7 +1179,7 @@ async def test_nanobot_feature_routes_require_token_and_enable( {"name": "websocket"}, ) assert disabled_websocket.status_code == 400 - assert "cannot be disabled from WebUI" in disabled_websocket.text + assert "cannot be disabled from WebUI" in disabled_websocket.message assert "websocket" not in json.loads(config_path.read_text(encoding="utf-8"))["channels"] disabled = await _webui_mutate( @@ -1186,7 +1188,7 @@ async def test_nanobot_feature_routes_require_token_and_enable( {"name": "matrix"}, ) assert disabled.status_code == 200 - body = disabled.json() + body = disabled.result assert body["last_action"]["message"] == "Disabled channel 'matrix'" assert body["restart_required_sections"] == ["runtime"] assert json.loads(config_path.read_text(encoding="utf-8"))["channels"]["matrix"][ @@ -1311,7 +1313,7 @@ async def test_pairing_routes_require_token_and_approve_or_deny( {"code": "ABCD-EFGH"}, ) assert approved_response.status_code == 200 - body = approved_response.json() + body = approved_response.result assert body["last_action"]["action"] == "approve" assert body["last_action"]["sender_id"] == "ou_123" assert approved == ["ABCD-EFGH"] @@ -1322,7 +1324,7 @@ async def test_pairing_routes_require_token_and_approve_or_deny( {"code": "ABCD-EFGH"}, ) assert denied_action.status_code == 200 - assert denied_action.json()["last_action"]["action"] == "deny" + assert denied_action.result["last_action"]["action"] == "deny" assert denied == ["ABCD-EFGH"] missing_code = await _webui_mutate( @@ -1330,7 +1332,7 @@ async def test_pairing_routes_require_token_and_approve_or_deny( "settings.pairing.approve", ) assert missing_code.status_code == 400 - assert "Missing pairing code" in missing_code.text + assert "Missing pairing code" in missing_code.message @pytest.mark.asyncio @@ -1379,7 +1381,7 @@ async def test_nanobot_feature_remote_install_requires_opt_in( ) assert blocked.status_code == 403 - assert "remote WebUI is disabled" in blocked.text + assert "remote WebUI is disabled" in blocked.message assert install_calls == [] config_path.write_text( @@ -1463,7 +1465,7 @@ async def test_nanobot_feature_channel_action_can_apply_without_restart( ) assert response.status_code == 200 - body = response.json() + body = response.result assert calls == [("enable", "matrix", None)] assert body["requires_restart"] is False assert body["restart_required_sections"] == [] @@ -1502,13 +1504,13 @@ async def test_nanobot_feature_install_only_tracks_pending_restart_without_start def feature_action( action: str, - query: dict[str, list[str]], + params: MutationParams, *, allow_install: bool, config_path: Path, ) -> dict[str, Any]: assert action == "enable" - assert query == {"name": ["whatsapp"], "install_only": ["true"]} + assert params.values == {"name": "whatsapp", "install_only": True} assert allow_install is True return {**features_payload(), "requires_restart": installed_now} @@ -1539,7 +1541,7 @@ async def test_nanobot_feature_install_only_tracks_pending_restart_without_start assert response.status_code == 200 assert runtime_calls == [] - features = response.json()["features"] + features = response.result["features"] assert features[0]["enabled"] is False assert [feature["restart_pending"] for feature in features] == [installed_now, False] @@ -1588,7 +1590,7 @@ async def test_channel_connect_runtime_import_error_is_not_reported_as_unsupport ) assert response.status_code == 500 - assert "failed to start fake connection" in response.text + assert "failed to start fake connection" in response.message @pytest.mark.asyncio @@ -1616,7 +1618,7 @@ async def test_whatsapp_connect_reports_libmagic_failure( ) assert response.status_code == 400 - assert "WhatsApp could not load libmagic" in response.text + assert "WhatsApp could not load libmagic" in response.message @pytest.mark.asyncio @@ -1705,7 +1707,7 @@ async def test_feishu_connect_routes_write_config_and_hot_reload( ) assert started.status_code == 200 - start_body = started.json() + start_body = started.result assert start_body["status"] == "pending" assert start_body["instance_id"] == "default" assert start_body["qr_url"].startswith("https://accounts.feishu.cn/") @@ -1717,7 +1719,7 @@ async def test_feishu_connect_routes_write_config_and_hot_reload( ) assert polled.status_code == 200 - body = polled.json() + body = polled.result assert body["status"] == "succeeded" assert body["instance_id"] == "default" assert "app_secret" not in body @@ -1893,10 +1895,10 @@ async def test_channel_configure_route_saves_discord_config_and_hot_reloads( ) assert response.status_code == 200 - body = response.json() + body = response.result assert body["saved"] is True assert body["name"] == "discord" - assert "discord-token" not in response.text + assert "discord-token" not in json.dumps(body) assert calls == [("enable", "discord", "default")] assert body["nanobot_features"]["requires_restart"] is False data = json.loads(config_path.read_text(encoding="utf-8")) @@ -1948,7 +1950,7 @@ async def test_channel_configure_route_preserves_existing_channel_values( ) assert response.status_code == 200 - body = response.json() + body = response.result assert body["saved_keys"] == ["channels.discord.allowChannels"] discord = next( feature @@ -2307,37 +2309,37 @@ async def test_mcp_presets_routes_require_token_and_return_payload( "installed_count": 0, }, ) - preset_queries: list[tuple[str, dict[str, list[str]]]] = [] - custom_queries: list[tuple[str, dict[str, list[str]]]] = [] + preset_calls: list[tuple[str, dict[str, Any]]] = [] + custom_calls: list[tuple[str, dict[str, Any]]] = [] def _mcp_preset_action( action: str, - query: dict[str, list[str]], + params: MutationParams, *, config_path: Path | None = None, ) -> dict[str, Any]: - preset_queries.append((action, query)) + preset_calls.append((action, params.values)) return { "presets": [], "installed_count": 1, "requires_restart": action != "test", - "last_action": {"ok": True, "message": f"{action}:{query['name'][0]}"}, + "last_action": {"ok": True, "message": f"{action}:{params.values['name']}"}, } def _custom_action( action: str, - query: dict[str, list[str]], + params: MutationParams, *, config_path: Path | None = None, ) -> dict[str, Any]: - custom_queries.append((action, query)) + custom_calls.append((action, params.values)) return { "presets": [], "installed_count": 1, "requires_restart": True, "last_action": { "ok": True, - "message": f"{action}:{query.get('name', ['config'])[0]}", + "message": f"{action}:{params.values.get('name', 'config')}", }, } @@ -2380,9 +2382,9 @@ async def test_mcp_presets_routes_require_token_and_return_payload( {"name": "browserbase", "browserbase_api_key": "bb_live_secret"}, ) assert enabled.status_code == 200 - assert preset_queries[-1][1]["browserbase_api_key"] == ["bb_live_secret"] - body = enabled.json() - assert "bb_live_secret" not in enabled.text + assert preset_calls[-1][1]["browserbase_api_key"] == "bb_live_secret" + body = enabled.result + assert "bb_live_secret" not in json.dumps(body) assert body["last_action"]["message"] == "enable:browserbase MCP config reloaded." assert body["hot_reload"]["ok"] is True assert body["restart_required_sections"] == [] @@ -2393,7 +2395,7 @@ async def test_mcp_presets_routes_require_token_and_return_payload( {"name": "browserbase"}, ) assert disabled.status_code == 200 - assert preset_queries[-1][0] == "disable" + assert preset_calls[-1][0] == "disable" custom = await _webui_mutate( channel, @@ -2401,8 +2403,8 @@ async def test_mcp_presets_routes_require_token_and_return_payload( {"name": "docs", "command": "npx"}, ) assert custom.status_code == 200 - assert custom_queries[-1][1]["command"] == ["npx"] - assert custom.json()["last_action"]["message"] == "custom:docs MCP config reloaded." + assert custom_calls[-1][1]["command"] == "npx" + assert custom.result["last_action"]["message"] == "custom:docs MCP config reloaded." imported = await _webui_mutate( channel, @@ -2410,7 +2412,7 @@ async def test_mcp_presets_routes_require_token_and_return_payload( {"config": "{}"}, ) assert imported.status_code == 200 - assert imported.json()["last_action"]["message"] == "import:config MCP config reloaded." + assert imported.result["last_action"]["message"] == "import:config MCP config reloaded." tools = await _webui_mutate( channel, @@ -2418,7 +2420,8 @@ async def test_mcp_presets_routes_require_token_and_return_payload( {"name": "docs", "enabled_tools": []}, ) assert tools.status_code == 200 - assert tools.json()["last_action"]["message"] == "tools:docs MCP config reloaded." + assert custom_calls[-1] == ("tools", {"name": "docs", "enabled_tools": []}) + assert tools.result["last_action"]["message"] == "tools:docs MCP config reloaded." finally: await channel.stop() await server_task @@ -2517,7 +2520,7 @@ async def test_webui_sidebar_state_routes_are_config_dir_scoped( {"state": payload}, ) assert updated.status_code == 200 - body = updated.json() + body = updated.result assert body["pinned_keys"] == ["websocket:sidebar"] assert body["archived_keys"] == ["websocket:old"] assert await sm.state.archived_keys() == ["websocket:old"] @@ -2561,7 +2564,7 @@ async def test_session_delete_removes_canonical_and_display_history(history, {"key": "websocket:doomed"}, ) assert resp.status_code == 200 - assert resp.json()["deleted"] is True + assert resp.result["deleted"] is True assert sm.read_session_snapshot(session_key) is None assert history.read(session_key) == [] finally: @@ -2595,7 +2598,7 @@ async def test_session_delete_removes_display_without_model_messages(history, ) assert response.status_code == 200 - assert response.json()["deleted"] is True + assert response.result["deleted"] is True assert sm.read_session_snapshot(key) is None assert history.read(key) == [] finally: @@ -2643,7 +2646,7 @@ async def test_session_delete_removes_unpersisted_new_chat( response = await _webui_mutate(channel, "session.delete", {"key": key}) assert response.status_code == 200 - assert response.json()["deleted"] is True + assert response.result["deleted"] is True assert channel.gateway.workspaces.scope_for_session_key(key).project_path == tmp_path.resolve() @@ -2690,7 +2693,7 @@ async def test_webui_automation_edit_keeps_pending_run(bus, tmp_path, monkeypatc }, ) assert response.status_code == 200 - row = next(item for item in response.json()["jobs"] if item["id"] == job.id) + row = next(item for item in response.result["jobs"] if item["id"] == job.id) assert row["name"] == "Updated report" assert row["payload"]["message"] == "Include the latest figures" assert row["state"]["next_run_at_ms"] == due_at @@ -2928,7 +2931,7 @@ async def test_webui_automations_route_lists_all_jobs_and_allows_user_actions( }, ) assert updated.status_code == 200 - by_id = {job["id"]: job for job in updated.json()["jobs"]} + by_id = {job["id"]: job for job in updated.result["jobs"]} assert by_id[user_job.id]["name"] == "Daily quiz" assert by_id[user_job.id]["payload"]["message"] == "Ask the daily quiz" assert by_id[user_job.id]["schedule"]["kind"] == "cron" @@ -2996,7 +2999,7 @@ async def test_webui_automations_route_lists_all_jobs_and_allows_user_actions( {"id": user_job.id}, ) assert disabled.status_code == 200 - by_id = {job["id"]: job for job in disabled.json()["jobs"]} + by_id = {job["id"]: job for job in disabled.result["jobs"]} assert by_id[user_job.id]["enabled"] is False disabled_run = await _webui_mutate( @@ -3012,7 +3015,7 @@ async def test_webui_automations_route_lists_all_jobs_and_allows_user_actions( {"id": incomplete_job.id}, ) assert unbound_run.status_code == 409 - assert "no linked chat" in unbound_run.text + assert "no linked chat" in unbound_run.message unbound_enable = await _webui_mutate( channel, @@ -3020,7 +3023,7 @@ async def test_webui_automations_route_lists_all_jobs_and_allows_user_actions( {"id": incomplete_job.id}, ) assert unbound_enable.status_code == 409 - assert "no linked chat" in unbound_enable.text + assert "no linked chat" in unbound_enable.message protected_delete = await _webui_mutate( channel, @@ -3047,7 +3050,7 @@ async def test_webui_automations_route_lists_all_jobs_and_allows_user_actions( {"id": user_job.id}, ) assert enabled.status_code == 200 - by_id = {job["id"]: job for job in enabled.json()["jobs"]} + by_id = {job["id"]: job for job in enabled.result["jobs"]} assert by_id[user_job.id]["enabled"] is True deleted = await _webui_mutate( @@ -3056,8 +3059,8 @@ async def test_webui_automations_route_lists_all_jobs_and_allows_user_actions( {"id": user_job.id}, ) assert deleted.status_code == 200 - assert user_job.id not in {job["id"] for job in deleted.json()["jobs"]} - assert "heartbeat" in {job["id"] for job in deleted.json()["jobs"]} + assert user_job.id not in {job["id"] for job in deleted.result["jobs"]} + assert "heartbeat" in {job["id"] for job in deleted.result["jobs"]} finally: await channel.stop() await server_task @@ -3116,7 +3119,7 @@ async def test_webui_automations_route_manages_local_triggers( {"id": trigger.id}, ) assert run.status_code == 409 - assert "CLI message" in run.text + assert "CLI message" in run.message renamed = await _webui_mutate( channel, @@ -3174,7 +3177,7 @@ async def test_session_delete_blocks_when_bound_automation_exists( ) assert resp.status_code == 200 - body = resp.json() + body = resp.result assert body["deleted"] is False assert body["blocked_by_automations"] is True assert [job["name"] for job in body["automations"]] == ["Daily check"] @@ -3213,7 +3216,7 @@ async def test_session_delete_blocks_and_cascades_local_triggers( {"key": "websocket:doomed"}, ) assert blocked.status_code == 200 - assert blocked.json()["blocked_by_automations"] is True + assert blocked.result["blocked_by_automations"] is True assert trigger_store.get(trigger.id) is not None deleted = await _webui_mutate( @@ -3222,7 +3225,7 @@ async def test_session_delete_blocks_and_cascades_local_triggers( {"key": "websocket:doomed", "delete_automations": True}, ) assert deleted.status_code == 200 - assert deleted.json()["deleted"] is True + assert deleted.result["deleted"] is True assert trigger_store.get(trigger.id) is None finally: await channel.stop() @@ -3262,7 +3265,7 @@ async def test_session_delete_can_cascade_bound_automations( ) assert resp.status_code == 200 - assert resp.json()["deleted"] is True + assert resp.result["deleted"] is True assert sm.read_session_snapshot(session_key) is None assert cron.list_bound_cron_jobs_for_session("websocket:doomed") == [] assert cron.list_jobs(include_disabled=True) == [] @@ -3302,7 +3305,7 @@ async def test_session_delete_blocks_origin_automation_when_unified_enabled( ) assert resp.status_code == 200 - body = resp.json() + body = resp.result assert body["deleted"] is False assert body["blocked_by_automations"] is True assert [job["name"] for job in body["automations"]] == ["Chat daily check"] @@ -3331,7 +3334,7 @@ async def test_session_delete_action_accepts_websocket_keys( {"key": "websocket:encoded-key"}, ) assert deleted.status_code == 200 - assert deleted.json()["deleted"] is True + assert deleted.result["deleted"] is True assert sm.read_session_snapshot(session_key) is None finally: await channel.stop() @@ -3830,26 +3833,19 @@ async def _webui_mutate( *, headers: dict[str, str] | None = None, connection: _FakeConn = _LOCAL, -) -> httpx.Response: +) -> MutationResult: request_headers = {"Host": "127.0.0.1:8765", **(headers or {})} mutation_connection = _FakeConn(connection.remote_address) mutation_connection.request = _FakeReq(request_headers) - response = await channel.gateway.http.dispatch_webui_mutation( + return await channel.gateway.http.dispatch_webui_mutation( mutation_connection, action, payload or {}, ) - request = httpx.Request("GET", "http://127.0.0.1/webui-mutation") - return httpx.Response( - response.status_code, - headers=list(response.headers.raw_items()), - content=response.body, - request=request, - ) @pytest.mark.asyncio -async def test_recovery_mutation_uses_authenticated_websocket_action(bus: MagicMock) -> None: +async def test_recovery_mutation_dispatches_continue_action(bus: MagicMock) -> None: recovery_action = AsyncMock(return_value={ "status": "resuming", "recovery_id": "recovery-1", @@ -3863,7 +3859,7 @@ async def test_recovery_mutation_uses_authenticated_websocket_action(bus: MagicM ) assert response.status_code == 200 - assert response.json()["status"] == "resuming" + assert response.result["status"] == "resuming" recovery_action.assert_awaited_once_with( "continue", {"chat_id": "chat-1", "recovery_id": "recovery-1"}, @@ -3950,31 +3946,31 @@ def _trusted_proxy_config( } -def test_trusted_proxy_requires_non_empty_assertion(bus: MagicMock) -> None: +async def test_trusted_proxy_requires_non_empty_assertion(bus: MagicMock) -> None: channel = _ch(bus, **_trusted_proxy_config()) for assertion in (None, "", " "): headers = {"Cf-Access-Jwt-Assertion": assertion} if assertion is not None else {} - resp = channel.gateway.http._handle_bootstrap(_LOCAL, _FakeReq(headers)) + resp = await channel.gateway.http._handle_bootstrap(_LOCAL, _FakeReq(headers)) assert resp.status_code == 403 -def test_trusted_proxy_rejects_untrusted_peer_spoof(bus: MagicMock) -> None: +async def test_trusted_proxy_rejects_untrusted_peer_spoof(bus: MagicMock) -> None: channel = _ch(bus, **_trusted_proxy_config()) - resp = channel.gateway.http._handle_bootstrap( + resp = await channel.gateway.http._handle_bootstrap( _REMOTE, _FakeReq({"Cf-Access-Jwt-Assertion": "spoofed"}), ) assert resp.status_code == 403 -def test_trusted_proxy_bootstrap_has_no_tokens( +async def test_trusted_proxy_bootstrap_has_no_tokens( bus: MagicMock, ) -> None: assertion = "opaque-upstream-assertion" channel = _ch(bus, **_trusted_proxy_config()) log = MagicMock() channel.gateway.http._log = log - resp = channel.gateway.http._handle_bootstrap( + resp = await channel.gateway.http._handle_bootstrap( _LOCAL, _FakeReq( { @@ -4024,9 +4020,9 @@ def test_trusted_proxy_authorizes_websocket_without_token(bus: MagicMock) -> Non assert _LOCAL in channel._webui_connections -def test_forwarding_headers_alone_never_authorize_bootstrap(bus: MagicMock) -> None: +async def test_forwarding_headers_alone_never_authorize_bootstrap(bus: MagicMock) -> None: channel = _ch(bus) - resp = channel.gateway.http._handle_bootstrap( + resp = await channel.gateway.http._handle_bootstrap( _REMOTE, _FakeReq( { @@ -4040,13 +4036,13 @@ def test_forwarding_headers_alone_never_authorize_bootstrap(bus: MagicMock) -> N assert resp.status_code == 403 -def test_trusted_proxy_bypasses_bootstrap_secret_and_tokens(bus: MagicMock) -> None: +async def test_trusted_proxy_bypasses_bootstrap_secret_and_tokens(bus: MagicMock) -> None: channel = _ch( bus, tokenIssueSecret="route-secret", **_trusted_proxy_config(), ) - resp = channel.gateway.http._handle_bootstrap( + resp = await channel.gateway.http._handle_bootstrap( _LOCAL, _FakeReq({"Cf-Access-Jwt-Assertion": "present"}), ) @@ -4130,17 +4126,17 @@ def test_wildcard_ipv6_without_auth_raises(bus: MagicMock) -> None: _ch(bus, host="::") -def test_wildcard_ipv6_with_secret_is_valid(bus: MagicMock) -> None: +async def test_wildcard_ipv6_with_secret_is_valid(bus: MagicMock) -> None: channel = _ch(bus, host="::", tokenIssueSecret="s3cret") - resp = channel.gateway.http._handle_bootstrap( + resp = await channel.gateway.http._handle_bootstrap( _REMOTE, _FakeReq({"X-Nanobot-Auth": "s3cret"}) ) assert resp.status_code == 200 -def test_bootstrap_accepts_static_token_as_secret(bus: MagicMock) -> None: +async def test_bootstrap_accepts_static_token_as_secret(bus: MagicMock) -> None: channel = _ch(bus, host="0.0.0.0", token="static-tok") - resp = channel.gateway.http._handle_bootstrap( + resp = await channel.gateway.http._handle_bootstrap( _REMOTE, _FakeReq({"Authorization": "Bearer static-tok"}) ) assert resp.status_code == 200 @@ -4150,9 +4146,9 @@ def test_bootstrap_accepts_static_token_as_secret(bus: MagicMock) -> None: assert body["api_token"] != body["token"] -def test_bootstrap_ws_url_uses_forwarded_https_host(bus: MagicMock) -> None: +async def test_bootstrap_ws_url_uses_forwarded_https_host(bus: MagicMock) -> None: channel = _ch(bus, host="127.0.0.1", port=29931, tokenIssueSecret="s3cret") - resp = channel.gateway.http._handle_bootstrap( + resp = await channel.gateway.http._handle_bootstrap( _LOCAL, _FakeReq( { @@ -4167,7 +4163,7 @@ def test_bootstrap_ws_url_uses_forwarded_https_host(bus: MagicMock) -> None: assert body["ws_url"] == "wss://nanobot.example/" -def test_bootstrap_ws_url_uses_configured_public_url(bus: MagicMock) -> None: +async def test_bootstrap_ws_url_uses_configured_public_url(bus: MagicMock) -> None: channel = _ch( bus, host="127.0.0.1", @@ -4175,7 +4171,7 @@ def test_bootstrap_ws_url_uses_configured_public_url(bus: MagicMock) -> None: tokenIssueSecret="s3cret", publicWsUrl="wss://claw.wasapi.xyz/", ) - resp = channel.gateway.http._handle_bootstrap( + resp = await channel.gateway.http._handle_bootstrap( _LOCAL, _FakeReq( { @@ -4201,24 +4197,24 @@ def test_public_ws_url_must_match_configured_path() -> None: ) -def test_bootstrap_without_auth_rejects_remote_requests(bus: MagicMock) -> None: +async def test_bootstrap_without_auth_rejects_remote_requests(bus: MagicMock) -> None: channel = _ch(bus, host="127.0.0.1") - resp = channel.gateway.http._handle_bootstrap(_REMOTE, _NO_HEADERS) + resp = await channel.gateway.http._handle_bootstrap(_REMOTE, _NO_HEADERS) assert resp.status_code == 403 -def test_bootstrap_without_auth_rejects_reverse_proxy_remote_headers(bus: MagicMock) -> None: +async def test_bootstrap_without_auth_rejects_reverse_proxy_remote_headers(bus: MagicMock) -> None: channel = _ch(bus, host="127.0.0.1") - resp = channel.gateway.http._handle_bootstrap( + resp = await channel.gateway.http._handle_bootstrap( _LOCAL, _FakeReq({"Host": "nanobot.example", "X-Forwarded-For": "203.0.113.42"}), ) assert resp.status_code == 403 -def test_localhost_without_auth_is_valid(bus: MagicMock) -> None: +async def test_localhost_without_auth_is_valid(bus: MagicMock) -> None: channel = _ch(bus, host="127.0.0.1") - resp = channel.gateway.http._handle_bootstrap(_LOCAL, _LOCAL_BROWSER_REQ) + resp = await channel.gateway.http._handle_bootstrap(_LOCAL, _LOCAL_BROWSER_REQ) assert resp.status_code == 200 body = json.loads(resp.body) assert body["token"].startswith("nbwt_") @@ -4232,9 +4228,9 @@ def test_localhost_without_auth_is_valid(bus: MagicMock) -> None: ) -def test_authenticated_bootstrap_returns_distinct_api_token(bus: MagicMock) -> None: +async def test_authenticated_bootstrap_returns_distinct_api_token(bus: MagicMock) -> None: channel = _ch(bus, host="127.0.0.1", tokenIssueSecret="s3cret") - resp = channel.gateway.http._handle_bootstrap( + resp = await channel.gateway.http._handle_bootstrap( _LOCAL, _FakeReq({"Authorization": "Bearer s3cret"}) ) assert resp.status_code == 200 @@ -4250,31 +4246,31 @@ def test_authenticated_bootstrap_returns_distinct_api_token(bus: MagicMock) -> N ) -def test_bootstrap_prefers_runtime_model_name(bus: MagicMock, monkeypatch: pytest.MonkeyPatch) -> None: +async def test_bootstrap_prefers_runtime_model_name(bus: MagicMock, monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr( "nanobot.webui.ws_http._default_model_name_from_config", lambda _config_path=None: "from-disk", ) channel = _ch(bus, host="127.0.0.1", runtime_model_name=lambda: " live/model ") - resp = channel.gateway.http._handle_bootstrap(_LOCAL, _LOCAL_BROWSER_REQ) + resp = await channel.gateway.http._handle_bootstrap(_LOCAL, _LOCAL_BROWSER_REQ) assert resp.status_code == 200 body = json.loads(resp.body) assert body["model_name"] == "live/model" -def test_bootstrap_falls_back_when_runtime_returns_empty(bus: MagicMock, monkeypatch: pytest.MonkeyPatch) -> None: +async def test_bootstrap_falls_back_when_runtime_returns_empty(bus: MagicMock, monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr( "nanobot.webui.ws_http._default_model_name_from_config", lambda _config_path=None: "from-disk", ) channel = _ch(bus, host="127.0.0.1", runtime_model_name=lambda: " ") - resp = channel.gateway.http._handle_bootstrap(_LOCAL, _LOCAL_BROWSER_REQ) + resp = await channel.gateway.http._handle_bootstrap(_LOCAL, _LOCAL_BROWSER_REQ) assert resp.status_code == 200 body = json.loads(resp.body) assert body["model_name"] == "from-disk" -def test_bootstrap_falls_back_when_runtime_raises(bus: MagicMock, monkeypatch: pytest.MonkeyPatch) -> None: +async def test_bootstrap_falls_back_when_runtime_raises(bus: MagicMock, monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr( "nanobot.webui.ws_http._default_model_name_from_config", lambda _config_path=None: "from-disk", @@ -4284,23 +4280,23 @@ def test_bootstrap_falls_back_when_runtime_raises(bus: MagicMock, monkeypatch: p raise RuntimeError("resolver failed") channel = _ch(bus, host="127.0.0.1", runtime_model_name=boom) - resp = channel.gateway.http._handle_bootstrap(_LOCAL, _LOCAL_BROWSER_REQ) + resp = await channel.gateway.http._handle_bootstrap(_LOCAL, _LOCAL_BROWSER_REQ) assert resp.status_code == 200 body = json.loads(resp.body) assert body["model_name"] == "from-disk" -def test_bootstrap_rejects_wrong_secret(bus: MagicMock) -> None: +async def test_bootstrap_rejects_wrong_secret(bus: MagicMock) -> None: channel = _ch(bus, host="0.0.0.0", tokenIssueSecret="correct") - resp = channel.gateway.http._handle_bootstrap( + resp = await channel.gateway.http._handle_bootstrap( _REMOTE, _FakeReq({"Authorization": "Bearer wrong"}) ) assert resp.status_code == 401 -def test_bootstrap_accepts_remote_with_valid_secret(bus: MagicMock) -> None: +async def test_bootstrap_accepts_remote_with_valid_secret(bus: MagicMock) -> None: channel = _ch(bus, host="0.0.0.0", tokenIssueSecret="s3cret") - resp = channel.gateway.http._handle_bootstrap( + resp = await channel.gateway.http._handle_bootstrap( _REMOTE, _FakeReq({"Authorization": "Bearer s3cret"}) ) assert resp.status_code == 200 @@ -4308,17 +4304,17 @@ def test_bootstrap_accepts_remote_with_valid_secret(bus: MagicMock) -> None: assert body["token"].startswith("nbwt_") -def test_bootstrap_accepts_x_nanobot_auth_header(bus: MagicMock) -> None: +async def test_bootstrap_accepts_x_nanobot_auth_header(bus: MagicMock) -> None: channel = _ch(bus, host="0.0.0.0", tokenIssueSecret="s3cret") - resp = channel.gateway.http._handle_bootstrap( + resp = await channel.gateway.http._handle_bootstrap( _REMOTE, _FakeReq({"X-Nanobot-Auth": "s3cret"}) ) assert resp.status_code == 200 -def test_bootstrap_secret_also_enforced_on_localhost(bus: MagicMock) -> None: +async def test_bootstrap_secret_also_enforced_on_localhost(bus: MagicMock) -> None: channel = _ch(bus, host="0.0.0.0", tokenIssueSecret="s3cret") - resp = channel.gateway.http._handle_bootstrap(_LOCAL, _NO_HEADERS) + resp = await channel.gateway.http._handle_bootstrap(_LOCAL, _NO_HEADERS) assert resp.status_code == 401 @@ -4339,9 +4335,9 @@ async def test_star_prompt_requires_authenticated_mutation_and_persists_dismissa assert raw.status_code in {401, 405} first = await _webui_mutate(channel, "star_prompt.claim", {}) assert first.status_code == 200 - assert first.json() == {"show": True} + assert first.result == {"show": True} second = await _webui_mutate(channel, "star_prompt.claim", {}) - assert second.json() == {"show": False} + assert second.result == {"show": False} dismissed = await _webui_mutate(channel, "star_prompt.dismiss", {}) assert dismissed.status_code == 200 assert StarPromptState.model_validate_json(state_path.read_text()).dismissed_forever @@ -4387,7 +4383,7 @@ async def test_project_selection_remembers_resolved_path_without_changing_access scope = channel.gateway.workspaces.default_scope() response = await _webui_mutate(channel, "workspace.resolve_project", {"path": str(project)}, connection=connection) assert response.status_code == 200 - assert response.json() == {"name": "project", "path": str(project)} + assert response.result == {"name": "project", "path": str(project)} assert channel.gateway.workspaces.default_scope() == scope payload = channel.gateway.workspaces.payload(can_change_project=True) assert payload["recent_projects"] == [{"name": "project", "path": str(project)}] @@ -4406,14 +4402,14 @@ async def test_project_favorites_mutation_persists_without_selecting_project( channel = _ch(bus, workspace_path=tmp_path) response = await _webui_mutate(channel, "workspace.favorite", {"path": str(project), "pinned": True}, connection=connection) assert response.status_code == 200 - assert response.json() == {"favorite_projects": [{"name": "pinned", "path": str(project)}]} + assert response.result == {"favorite_projects": [{"name": "pinned", "path": str(project)}]} payload = channel.gateway.workspaces.payload(can_change_project=True) - assert payload["favorite_projects"] == response.json()["favorite_projects"] + assert payload["favorite_projects"] == response.result["favorite_projects"] assert payload["recent_projects"] == [] assert payload["default_scope"]["project_path"] == str(tmp_path) response = await _webui_mutate(channel, "workspace.favorite", {"path": str(project), "pinned": False}, connection=connection) assert response.status_code == 200 - assert response.json() == {"favorite_projects": []} + assert response.result == {"favorite_projects": []} @pytest.mark.asyncio diff --git a/nanobot/webui/automation_routes.py b/nanobot/webui/automation_routes.py new file mode 100644 index 000000000..dbe5b908a --- /dev/null +++ b/nanobot/webui/automation_routes.py @@ -0,0 +1,462 @@ +from __future__ import annotations + +import asyncio +import time +from collections.abc import Callable +from datetime import datetime +from typing import TYPE_CHECKING, Any, cast +from zoneinfo import ZoneInfo, ZoneInfoNotFoundError + +from croniter import croniter +from loguru import logger +from websockets.http11 import Request as WsRequest +from websockets.http11 import Response + +from nanobot.cron.binding import CronBindingError, binding_revision +from nanobot.cron.session_turns import is_bound_cron_job +from nanobot.cron.types import CronJob, CronSchedule +from nanobot.triggers.local_types import LocalTrigger +from nanobot.webui.automation_chats import AutomationChat, automation_chats +from nanobot.webui.automation_results import cron_run_response, trigger_run_response +from nanobot.webui.http_utils import http_error as _http_error +from nanobot.webui.http_utils import http_json_response as _http_json_response +from nanobot.webui.http_utils import parse_query as _parse_query +from nanobot.webui.http_utils import query_first as _query_first +from nanobot.webui.mutation import MutationResult +from nanobot.webui.session_automations import ( + all_automations_payload, + session_automation_jobs, + session_automations_payload, +) +from nanobot.webui.settings_contracts import MutationParams +from nanobot.webui.settings_contracts import query_first as _mutation_text + +if TYPE_CHECKING: + from nanobot.cron.service import CronService + from nanobot.session.manager import SessionManager + from nanobot.triggers.local_store import LocalTriggerStore + from nanobot.webui.workspaces import WebUIWorkspaceController + + +class WebUIAutomationRoutes: + """Own automation reads, WebSocket writes, and session-deletion integration.""" + + def __init__( + self, + *, + session_manager: SessionManager | None, + workspaces: WebUIWorkspaceController, + cron_service: CronService | None, + local_trigger_store: LocalTriggerStore | None, + cron_pending_job_ids: Callable[[str], set[str]] | None, + local_trigger_pending_ids: Callable[[str], set[str]] | None, + channel_runtime_status: Callable[[], dict[str, Any]] | None, + log: Any = logger, + ) -> None: + self.session_manager = session_manager + self.workspaces = workspaces + self.cron_service = cron_service + self.local_trigger_store = local_trigger_store + self.cron_pending_job_ids = cron_pending_job_ids + self.local_trigger_pending_ids = local_trigger_pending_ids + self.channel_runtime_status = channel_runtime_status + self._log = log + + async def dispatch_read( + self, request: WsRequest, path: str, authorize: Callable[[WsRequest], bool], + ) -> Response | None: + if path not in {"/api/webui/automations", "/api/webui/automations/result", "/api/webui/automations/chats"}: + return None + if not authorize(request): + return _http_error(401, "Unauthorized") + if path == "/api/webui/automations/result": + return await self._handle_webui_automation_result(request) + if path == "/api/webui/automations/chats": + return await self._handle_webui_automation_chats(request) + return _http_json_response(self._automations_payload()) + + def session_payload(self, key: str) -> dict[str, Any]: + return session_automations_payload( + self.cron_service, + key, + local_trigger_store=self.local_trigger_store, + session_manager=self.session_manager, + pending_job_ids=self._pending_automation_ids_for_session(key), + ) + + def session_jobs(self, key: str) -> list[CronJob | LocalTrigger]: + return session_automation_jobs(self.cron_service, key, local_trigger_store=self.local_trigger_store) + + async def remove_session_jobs(self, jobs: list[CronJob | LocalTrigger]) -> None: + for job in jobs: + if isinstance(job, LocalTrigger): + if self.local_trigger_store is not None: + await asyncio.to_thread(self.local_trigger_store.delete, job.id) + elif self.cron_service is not None: + self.cron_service.remove_job(job.id) + + def _pending_cron_job_ids_for_all(self) -> set[str]: + if self.cron_service is None or self.cron_pending_job_ids is None: + return set() + pending: set[str] = set() + for job in self.cron_service.list_jobs(include_disabled=True): + session_key = job.payload.session_key + if not session_key and job.payload.origin_channel and job.payload.origin_chat_id: + session_key = f"{job.payload.origin_channel}:{job.payload.origin_chat_id}" + if session_key: + pending.update(self.cron_pending_job_ids(session_key)) + return pending + + def _pending_local_trigger_ids_for_all(self) -> set[str]: + if self.local_trigger_store is None or self.local_trigger_pending_ids is None: + return set() + pending: set[str] = set() + for trigger in self.local_trigger_store.list_triggers(include_disabled=True): + session_key = trigger.session_key + if not session_key and trigger.channel and trigger.chat_id: + session_key = f"{trigger.channel}:{trigger.chat_id}" + if session_key: + pending.update(self.local_trigger_pending_ids(session_key)) + return pending + + def _pending_automation_ids_for_session(self, session_key: str) -> set[str]: + pending: set[str] = set() + if self.cron_pending_job_ids is not None: + pending.update(self.cron_pending_job_ids(session_key)) + if self.local_trigger_pending_ids is not None: + pending.update(self.local_trigger_pending_ids(session_key)) + return pending + + def _automations_payload(self) -> dict[str, Any]: + pending_job_ids = self._pending_cron_job_ids_for_all() + pending_job_ids.update(self._pending_local_trigger_ids_for_all()) + return all_automations_payload( + self.cron_service, + local_trigger_store=self.local_trigger_store, + session_manager=self.session_manager, + pending_job_ids=pending_job_ids, + ) + + async def _automation_chats(self, job: CronJob) -> list[AutomationChat]: + if self.session_manager is None: + return [] + return await automation_chats( + job, self.session_manager, self.workspaces, + self.channel_runtime_status() if self.channel_runtime_status else {}, + ) + + async def _handle_webui_automation_chats(self, request: WsRequest) -> Response: + job_id = _query_first(_parse_query(request.path), "id") or "" + job = self.cron_service.get_job(job_id) if self.cron_service else None + if job is None or not is_bound_cron_job(job): + return _http_error(404, "automation has no movable chat") + chats = await self._automation_chats(job) + current = next((chat for chat in chats + if chat.binding.session_key == job.payload.session_key), None) + return _http_json_response({ + "revision": binding_revision(job), + "current": current.public_payload() if current else None, + "chats": [chat.public_payload() for chat in chats], + }) + + async def _handle_webui_automation_result(self, request: WsRequest) -> Response: + query = _parse_query(request.path) + job_id = (_query_first(query, "id") or "").strip() + try: + run_at_ms = int(_query_first(query, "run_at_ms") or "") + except ValueError: + return _http_error(400, "invalid run timestamp") + if not job_id or run_at_ms < 0: + return _http_error(400, "invalid automation run") + kind = _query_first(query, "kind") or "cron" + try: + if kind == "local_trigger": + trigger = self.local_trigger_store.get(job_id) if self.local_trigger_store else None + if trigger is None or self.local_trigger_store is None: + return _http_error(404, "automation not found") + deliveries = [item for item in trigger.run_history if item.run_at_ms == run_at_ms] + if len(deliveries) != 1: + return _http_error(404, "run not found") + response = await asyncio.to_thread( + trigger_run_response, self.local_trigger_store.runs_dir, trigger, deliveries[0], + ) + elif kind == "cron": + job = self.cron_service.get_job(job_id) if self.cron_service else None + if job is None or self.cron_service is None: + return _http_error(404, "automation not found") + if job.payload.kind == "system_event": + return _http_error(403, "system automation is protected") + runs = [item for item in job.state.run_history if item.run_at_ms == run_at_ms] + if len(runs) != 1: + return _http_error(404, "run not found") + response = await asyncio.to_thread( + cron_run_response, self.cron_service.store_path.parent / "runs", job, runs[0], + ) + else: + return _http_error(400, "invalid automation kind") + except OSError: + self._log.exception("Could not read automation run result") + return _http_error(500, "Could not read run result") + return _http_json_response({"response": response}) + + async def mutate( + self, + params: MutationParams, + action: str, + ) -> MutationResult: + if self.cron_service is None and self.local_trigger_store is None: + return MutationResult.failure(503, "automation service unavailable") + + job_id = (_mutation_text(params, "id") or _mutation_text(params, "job_id") or "").strip() + if not job_id: + return MutationResult.failure(400, "missing automation id") + trigger = self.local_trigger_store.get(job_id) if self.local_trigger_store else None + if trigger is not None: + return self._handle_local_trigger_action(params, action, trigger) + + if self.cron_service is None: + return MutationResult.failure(404, "automation not found") + job = self.cron_service.get_job(job_id) + if job is None: + return MutationResult.failure(404, "automation not found") + if job.payload.kind == "system_event": + return MutationResult.failure(403, "system automation is protected") + if action in {"enable", "run"} and not is_bound_cron_job(job): + return MutationResult.failure(409, "automation has no linked chat") + + if action == "enable": + if self.cron_service.enable_job(job_id, enabled=True) is None: + return MutationResult.failure(404, "automation not found") + elif action == "disable": + if self.cron_service.enable_job(job_id, enabled=False) is None: + return MutationResult.failure(404, "automation not found") + elif action == "delete": + result = self.cron_service.remove_job(job_id) + if result == "not_found": + return MutationResult.failure(404, "automation not found") + if result == "protected": + return MutationResult.failure(403, "system automation is protected") + elif action == "run": + if not job.enabled: + return MutationResult.failure(409, "automation is disabled") + task = asyncio.create_task(self.cron_service.run_job(job_id, force=False)) + task.add_done_callback(self._log_automation_run_result) + elif action == "change-chat": + values = _automation_values(params.values) + if (not isinstance(values, dict) + or set(values) != {"target_id", "revision", "message"} + or not all(isinstance(v, str) for v in values.values())): + return MutationResult.failure(400, "invalid automation chat payload") + if job.id in self._pending_cron_job_ids_for_all(): + return MutationResult.failure(409, "automation_chat_busy") + target = next((chat for chat in await self._automation_chats(job) + if chat.id == values["target_id"]), None) + if target is None or not target.available: + return MutationResult.failure(409, "automation_chat_unavailable") + if target.binding.session_key == job.payload.session_key: + return MutationResult.failure(400, "choose a different chat") + try: + self.cron_service.change_binding( + job_id, revision=values["revision"], binding=target.binding, + message=values["message"], + ) + except CronBindingError as exc: + return MutationResult.failure(409, f"automation_chat_{exc.reason}") + except OSError: + logger.exception("WebUI automation chat save failed") + return MutationResult.failure(500, "could not save the chat; try again") + elif action == "update": + values = _automation_values(params.values) + if values is None: + return MutationResult.failure(400, "invalid automation update payload") + parsed = _parse_automation_update(values, current_job=job) + if isinstance(parsed, str): + return MutationResult.failure(400, parsed) + try: + result = self.cron_service.update_job(job_id, **parsed) + except ValueError as exc: + return MutationResult.failure(400, str(exc)) + if result == "not_found": + return MutationResult.failure(404, "automation not found") + if result == "protected": + return MutationResult.failure(403, "system automation is protected") + else: + return MutationResult.failure(404, "unknown automation action") + + return MutationResult.success(self._automations_payload()) + + def _handle_local_trigger_action( + self, + params: MutationParams, + action: str, + trigger: LocalTrigger, + ) -> MutationResult: + if self.local_trigger_store is None: + return MutationResult.failure(503, "trigger service unavailable") + if action == "enable": + if self.local_trigger_store.enable(trigger.id, enabled=True) is None: + return MutationResult.failure(404, "automation not found") + elif action == "disable": + if self.local_trigger_store.enable(trigger.id, enabled=False) is None: + return MutationResult.failure(404, "automation not found") + elif action == "delete": + if not self.local_trigger_store.delete(trigger.id): + return MutationResult.failure(404, "automation not found") + elif action == "run": + return MutationResult.failure(409, "local trigger requires a CLI message") + elif action == "update": + values = _automation_values(params.values) + if values is None: + return MutationResult.failure(400, "invalid automation update payload") + parsed = _parse_local_trigger_update(values) + if isinstance(parsed, str): + return MutationResult.failure(400, parsed) + if parsed: + if self.local_trigger_store.update(trigger.id, **parsed) is None: + return MutationResult.failure(404, "automation not found") + else: + return MutationResult.failure(404, "unknown automation action") + + return MutationResult.success(self._automations_payload()) + + @staticmethod + def _log_automation_run_result(task: asyncio.Task[bool]) -> None: + try: + ran = task.result() + except Exception: + logger.exception("WebUI automation run-now task failed") + return + if not ran: + logger.warning("WebUI automation run-now task did not execute") + + +def _automation_values(payload: dict[str, Any]) -> dict[str, Any] | None: + if "values" not in payload: + return {} + values = payload.get("values") + return cast(dict[str, Any], values) if isinstance(values, dict) else None + + +def _parse_automation_update( + values: dict[str, Any], + *, + current_job: CronJob | None = None, +) -> dict[str, Any] | str: + update: dict[str, Any] = {} + if "name" in values: + raw_name = values.get("name") + if not isinstance(raw_name, str): + return "name must be a string" + name = raw_name.strip() + if not name: + return "name cannot be empty" + update["name"] = name + if "message" in values: + raw_message = values.get("message") + if not isinstance(raw_message, str): + return "message must be a string" + message = raw_message.strip() + if not message: + return "message cannot be empty" + update["message"] = message + if "schedule" in values: + raw_schedule = values.get("schedule") + if not isinstance(raw_schedule, dict): + return "schedule must be an object" + parsed_schedule = _parse_automation_schedule(cast(dict[str, Any], raw_schedule)) + if isinstance(parsed_schedule, str): + return parsed_schedule + if current_job is not None and _schedule_matches_job(parsed_schedule, current_job): + return update + schedule_error = _validate_automation_schedule(parsed_schedule) + if schedule_error: + return schedule_error + update["schedule"] = parsed_schedule + update["delete_after_run"] = parsed_schedule.kind == "at" + return update + + +def _parse_local_trigger_update(values: dict[str, Any]) -> dict[str, Any] | str: + update: dict[str, Any] = {} + if "name" in values: + raw_name = values.get("name") + if not isinstance(raw_name, str): + return "name must be a string" + name = raw_name.strip() + if not name: + return "name cannot be empty" + update["name"] = name + forbidden = [key for key in ("message", "schedule") if key in values] + if forbidden: + return "local trigger updates only support name" + return update + + +def _parse_automation_schedule(values: dict[str, Any]) -> CronSchedule | str: + raw_kind = values.get("kind") + if not isinstance(raw_kind, str): + return "schedule kind must be a string" + kind = raw_kind.strip() + if kind == "every": + every_ms = _positive_int(values.get("every_ms")) + if every_ms is None: + return "every schedule requires positive every_ms" + return CronSchedule(kind="every", every_ms=every_ms) + if kind == "cron": + raw_expr = values.get("expr") + if not isinstance(raw_expr, str): + return "cron schedule requires expr" + expr = raw_expr.strip() + if not expr: + return "cron schedule requires expr" + raw_tz = values.get("tz") + if raw_tz is not None and not isinstance(raw_tz, str): + return "cron schedule timezone must be a string" + tz = raw_tz.strip() if isinstance(raw_tz, str) else "" + return CronSchedule(kind="cron", expr=expr, tz=tz or None) + if kind == "at": + at_ms = _positive_int(values.get("at_ms")) + if at_ms is None: + return "one-time schedule requires positive at_ms" + return CronSchedule(kind="at", at_ms=at_ms) + return "unknown schedule kind" + + +def _schedule_matches_job(schedule: CronSchedule, job: CronJob) -> bool: + current = job.schedule + if schedule.kind != current.kind: + return False + if schedule.kind == "at": + return schedule.at_ms == current.at_ms + if schedule.kind == "every": + return schedule.every_ms == current.every_ms + if schedule.kind == "cron": + return (schedule.expr or "") == (current.expr or "") and ( + schedule.tz or None + ) == (current.tz or None) + return False + + +def _validate_automation_schedule(schedule: CronSchedule) -> str | None: + if schedule.kind == "at": + if not schedule.at_ms or schedule.at_ms <= int(time.time() * 1000): + return "one-time schedule must be in the future" + return None + if schedule.kind != "cron": + return None + + try: + tz = ZoneInfo(schedule.tz) if schedule.tz else datetime.now().astimezone().tzinfo + except (ZoneInfoNotFoundError, ValueError): + return "cron schedule timezone is invalid" + try: + croniter(cast(str, schedule.expr), datetime.now(tz=tz)).get_next(datetime) + except ValueError: + return "cron schedule is invalid" + return None + + +def _positive_int(value: Any) -> int | None: + if isinstance(value, bool) or not isinstance(value, int): + return None + return value if value > 0 else None diff --git a/nanobot/webui/cli_apps_api.py b/nanobot/webui/cli_apps_api.py index ee2897d04..a6d3b55b2 100644 --- a/nanobot/webui/cli_apps_api.py +++ b/nanobot/webui/cli_apps_api.py @@ -9,8 +9,8 @@ from typing import Any, cast from nanobot.apps.cli import CliAppError, CliAppManager, CliAppsRuntimeConfig from nanobot.config.loader import load_config - -QueryParams = dict[str, list[str]] +from nanobot.webui.settings_contracts import QueryParams +from nanobot.webui.settings_contracts import query_first as _query_first _CLI_APP_NAME_RE = re.compile(r"^[a-z0-9][a-z0-9_-]{0,63}$", re.IGNORECASE) _CLI_APP_ATTACHMENT_KEYS = ( @@ -84,11 +84,6 @@ def normalize_cli_app_mentions(raw: Any) -> list[dict[str, str]]: return out -def _query_first(query: QueryParams, key: str) -> str | None: - values = query.get(key) - return values[0] if values else None - - def _manager(config_path: Path | None = None) -> CliAppManager: config = load_config(config_path) if config_path is not None else load_config() cli_cfg = config.tools.cli_apps diff --git a/nanobot/webui/gateway_services.py b/nanobot/webui/gateway_services.py index f779478c5..7f9816180 100644 --- a/nanobot/webui/gateway_services.py +++ b/nanobot/webui/gateway_services.py @@ -11,6 +11,7 @@ from nanobot.channels.websocket.attachment_http import AttachmentHTTP from nanobot.channels.websocket.attachment_store import AttachmentStore from nanobot.config.loader import get_config_path from nanobot.config.paths import get_media_dir +from nanobot.webui.automation_routes import WebUIAutomationRoutes from nanobot.webui.gateway_endpoint import WebUIGatewayEndpoint from nanobot.webui.gateway_tokens import GatewayTokenStore from nanobot.webui.ingress_policy import DEFAULT_WEBUI_INGRESS_POLICY, WebUIIngressPolicy @@ -136,10 +137,16 @@ def build_gateway_services( settings=settings, skills_workspace_path=workspace_path, disabled_skills=disabled_skills, - cron_service=cron_service, - local_trigger_store=local_trigger_store, - cron_pending_job_ids=cron_pending_job_ids, - local_trigger_pending_ids=local_trigger_pending_ids, + automation_routes=WebUIAutomationRoutes( + session_manager=session_manager, + workspaces=workspaces, + cron_service=cron_service, + local_trigger_store=local_trigger_store, + cron_pending_job_ids=cron_pending_job_ids, + local_trigger_pending_ids=local_trigger_pending_ids, + channel_runtime_status=channel_runtime_status, + log=logger, + ), channel_feature_action=channel_feature_action, channel_runtime_status=channel_runtime_status, mcp_runtime_status=mcp_runtime_status, diff --git a/nanobot/webui/http_utils.py b/nanobot/webui/http_utils.py index f21786293..f69a79f5e 100644 --- a/nanobot/webui/http_utils.py +++ b/nanobot/webui/http_utils.py @@ -86,6 +86,14 @@ def host_for_url(host: str, port: int) -> str: return f"{host}:{port}" +def etag_matches(value: str, etag: str) -> bool: + target = etag.strip().removeprefix("W/") + return any( + candidate.strip().removeprefix("W/") in {"*", target} + for candidate in value.split(",") + ) + + def accepts_gzip(value: str) -> bool: wildcard_quality: float | None = None for item in value.split(","): diff --git a/nanobot/webui/inbound_commands.py b/nanobot/webui/inbound_commands.py index 1dd170b58..7bfb39107 100644 --- a/nanobot/webui/inbound_commands.py +++ b/nanobot/webui/inbound_commands.py @@ -22,7 +22,7 @@ from nanobot.channels.websocket.attachment_policy import validate_attachment_bat from nanobot.channels.websocket.attachment_store import AttachmentUploadError from nanobot.command.application import builtin_command_starts_agent_turn from nanobot.command.builtin import USER_SHELL_COMMAND -from nanobot.providers.model_options import ModelOptions +from nanobot.providers.model_options import ModelOptions, ModelOptionsPayload from nanobot.runtime_admission import RuntimeMaintenanceError from nanobot.runtime_context import ( RUNTIME_CONTEXT_INPUT_META, @@ -167,7 +167,6 @@ class WebUICommandRouter: self.request_operations: dict[str, WebUIRequestOperation] = {} self.request_locks: dict[ServerConnection, asyncio.Lock] = {} self._background_lock = asyncio.Lock() - self._background_references: set[tuple[str, str]] = set() self._accepted_messages: dict[tuple[str, str], float] = {} self._message_locks: dict[tuple[str, str], tuple[asyncio.Lock, int]] = {} @@ -560,6 +559,71 @@ class WebUICommandRouter: else: self._message_locks[key] = (lock, users - 1) + def _parse_inbound_attachments( + self, + raw_media: Any, + ) -> tuple[list[str], list[str], list[str | None], list[tuple[bool, int]]]: + if not isinstance(raw_media, list): + raise AttachmentUploadError("malformed") + attachments = cast(list[Any], raw_media) + if len(attachments) > self._uploads.store.limits.max_count + 1: + raise AttachmentUploadError("Too many attachments") + references: list[str] = [] + local_paths: list[str] = [] + media_names: list[str | None] = [] + attachment_order: list[tuple[bool, int]] = [] + for item in attachments: + if not isinstance(item, dict): + raise AttachmentUploadError("malformed") + attachment = cast(dict[str, Any], item) + reference = attachment.get("reference") + path = attachment.get("path") + if "data_url" in attachment or (reference is None) == (path is None): + raise AttachmentUploadError("Expected an upload reference or local path") + if path is not None: + if not isinstance(path, str) or not path or len(path) > 4096: + raise AttachmentUploadError("Invalid local attachment path") + attachment_order.append((True, len(local_paths))) + local_paths.append(path) + else: + if not isinstance(reference, str) or len(reference) > 64: + raise AttachmentUploadError("Invalid upload reference") + attachment_order.append((False, len(references))) + references.append(reference) + name = attachment.get("name") + media_names.append((safe_filename(name) or None) if isinstance(name, str) else None) + return references, local_paths, media_names, attachment_order + + @staticmethod + def _model_options_for_message( + envelope: dict[str, Any], content: str, *, trusted_webui: bool, is_user_shell: bool, + ) -> ModelOptionsPayload | None: + if "model_options" not in envelope: + return None + if not trusted_webui: + raise ValueError("model_options requires a trusted WebUI message") + if is_user_shell or not builtin_command_starts_agent_turn(content): + return None + return ModelOptions.parse(envelope["model_options"]).to_dict() + + @staticmethod + def _message_context_blocks( + envelope: dict[str, Any], session_mentions: list[SessionMention], *, is_user_shell: bool, + ) -> list[RuntimeContextBlock]: + blocks: list[RuntimeContextBlock] = [] + if not is_user_shell and envelope.get("intent") == "create_automation": + blocks.append(RuntimeContextBlock( + source="webui_automation_creation", + content=render_template("agent/automation_creation.md", strip=True), + )) + quote = webui_quote_runtime_context({WEBUI_QUOTE_METADATA: envelope.get("quoted_context")}) + if quote is not None: + blocks.append(quote) + session_context = session_mentions_runtime_context(session_mentions) + if session_context is not None: + blocks.append(session_context) + return blocks + async def _dispatch_message_once( self, connection: ServerConnection, @@ -634,37 +698,11 @@ class WebUICommandRouter: raw_media = envelope.get("media", []) media_paths: list[str] = [] - media_names: list[str | None] = [] - references: list[str] = [] - local_paths: list[str] = [] - attachment_order: list[tuple[bool, int]] = [] upload_owner = self._uploads.owner(connection) if raw_media else "" try: - if not isinstance(raw_media, list): - raise AttachmentUploadError("malformed") - attachments = cast(list[Any], raw_media) - if len(attachments) > self._uploads.store.limits.max_count + 1: - raise AttachmentUploadError("Too many attachments") - for item in attachments: - if not isinstance(item, dict): - raise AttachmentUploadError("malformed") - attachment = cast(dict[str, Any], item) - reference = attachment.get("reference") - path = attachment.get("path") - if "data_url" in attachment or (reference is None) == (path is None): - raise AttachmentUploadError("Expected an upload reference or local path") - if path is not None: - if not isinstance(path, str) or not path or len(path) > 4096: - raise AttachmentUploadError("Invalid local attachment path") - attachment_order.append((True, len(local_paths))) - local_paths.append(path) - else: - if not isinstance(reference, str) or len(reference) > 64: - raise AttachmentUploadError("Invalid upload reference") - attachment_order.append((False, len(references))) - references.append(reference) - name = attachment.get("name") - media_names.append((safe_filename(name) or None) if isinstance(name, str) else None) + references, local_paths, media_names, attachment_order = ( + self._parse_inbound_attachments(raw_media) + ) except AttachmentUploadError as exc: await self._transport.webui_send_event( connection, "error", detail="attachment_rejected", reason=str(exc), @@ -700,6 +738,7 @@ class WebUICommandRouter: if scope is None: return + # Re-check after awaiting scope resolution in case allowlist access was revoked mid-flight. if not self._transport.is_allowed(client_id): await self._transport.webui_send_event( connection, @@ -734,31 +773,32 @@ class WebUICommandRouter: ) if is_user_shell: metadata[INBOUND_META_USER_SHELL] = True - if "model_options" in envelope: - if not trusted_webui: - await self._transport.webui_send_event( - connection, "error", detail="model_options requires a trusted WebUI message", - **rejection_fields, - ) - return - if not is_user_shell and builtin_command_starts_agent_turn(content): - try: - options = ModelOptions.parse(envelope["model_options"]) - except ValueError as exc: - await self._transport.webui_send_event( - connection, "error", detail=str(exc), **rejection_fields, - ) - return - metadata[INBOUND_META_MODEL_OPTIONS] = options.to_dict() + try: + options = self._model_options_for_message( + envelope, content, trusted_webui=trusted_webui, is_user_shell=is_user_shell, + ) + except ValueError as exc: + await self._transport.webui_send_event( + connection, "error", detail=str(exc), **rejection_fields, + ) + return + if options is not None: + metadata[INBOUND_META_MODEL_OPTIONS] = options dispatch_content = ( f"{USER_SHELL_COMMAND} {content[1:].lstrip()}" if is_user_shell else content ) cli_apps = normalize_cli_app_mentions(envelope.get("cli_apps")) if cli_apps: metadata["cli_apps"] = cli_apps - mcp_presets = normalize_mcp_preset_mentions( - envelope.get("mcp_presets"), - config_path=self.gateway.settings.config.path, + raw_mcp_presets = envelope.get("mcp_presets") + mcp_presets = ( + await asyncio.to_thread( + normalize_mcp_preset_mentions, + raw_mcp_presets, + config_path=self.gateway.settings.config.path, + ) + if raw_mcp_presets + else [] ) if mcp_presets: metadata["mcp_presets"] = mcp_presets @@ -781,8 +821,6 @@ class WebUICommandRouter: ) for path in local_paths ] - if any((upload_owner, ref) in self._background_references for ref in references): - raise AttachmentUploadError("Attachment is being used for a background") uploaded = self._uploads.store.inspect(references, owner=upload_owner) if references else [] validate_attachment_batch( [item["mime"] for item in local] + [item.mime for item in uploaded], @@ -854,20 +892,9 @@ class WebUICommandRouter: session_mentions=session_mentions or None, ) if trusted_webui: - context_blocks: list[RuntimeContextBlock] = [] - if not is_user_shell and envelope.get("intent") == "create_automation": - context_blocks.append(RuntimeContextBlock( - source="webui_automation_creation", - content=render_template("agent/automation_creation.md", strip=True), - )) - quote = webui_quote_runtime_context( - {WEBUI_QUOTE_METADATA: envelope.get("quoted_context")} + context_blocks = self._message_context_blocks( + envelope, session_mentions, is_user_shell=is_user_shell, ) - if quote is not None: - context_blocks.append(quote) - session_context = session_mentions_runtime_context(session_mentions) - if session_context is not None: - context_blocks.append(session_context) if context_blocks: metadata[RUNTIME_CONTEXT_INPUT_META] = context_blocks await self._transport.webui_dispatch_message( @@ -1042,11 +1069,17 @@ class WebUICommandRouter: if policy is None: raise TemporaryChatError("temporary_chat_unavailable") if metadata_only: - result = file_reference_payload(path, scope=policy.workspace_scope) + result = await asyncio.to_thread( + file_reference_payload, path, scope=policy.workspace_scope, + ) elif probe: - result = file_preview_availability_payload(path, scope=policy.workspace_scope) + result = await asyncio.to_thread( + file_preview_availability_payload, path, scope=policy.workspace_scope, + ) else: - result = file_preview_payload(path, scope=policy.workspace_scope) + result = await asyncio.to_thread( + file_preview_payload, path, scope=policy.workspace_scope, + ) except TemporaryChatError as exc: await self.send_webui_response( connection, request_id, status=404, message=exc.detail, @@ -1217,17 +1250,18 @@ class WebUICommandRouter: owner = self._uploads.owner(connection) try: entry = self._uploads.store.inspect([reference], owner=owner)[0] - # Snapshot a bounded staged file before yielding so disconnect cleanup - # never unlinks an open source handle on Windows. - with entry.path.open("rb") as source: - data = source.read(MAX_BYTES + 1) - key = (owner, reference) - self._background_references.add(key) - try: - await asyncio.to_thread(save_background, directory, data, entry.mime) - finally: - self._background_references.discard(key) - self._uploads.store.discard([reference], owner=owner) + # Claim before yielding so disconnect cleanup cannot unlink the worker's source. + self._uploads.store.commit([reference], owner=owner) + + def persist_staged_background() -> None: + try: + with entry.path.open("rb") as source: + data = source.read(MAX_BYTES + 1) + save_background(directory, data, entry.mime) + finally: + entry.path.unlink(missing_ok=True) + + await asyncio.to_thread(persist_staged_background) except (AttachmentUploadError, ValueError) as exc: return WebUIRequestResult(status=400, message=str(exc)) return WebUIRequestResult(result={"ok": True}) @@ -1246,26 +1280,11 @@ class WebUICommandRouter: action, payload, ) - status = response.status_code - body = bytes(response.body).decode("utf-8", errors="replace").strip() - if 200 <= status < 300: - try: - result = json.loads(body) - except json.JSONDecodeError: - return WebUIRequestResult( - status=502, - message="WebUI mutation returned an invalid response", - ) - if action == "sidebar.update" and isinstance(result, dict): - await self.broadcast_webui_event( - "sidebar_state_updated", - state=result, - ) - return WebUIRequestResult(result=result) - return WebUIRequestResult( - status=status, - message=body or response.reason_phrase, - ) + if 200 <= response.status_code < 300: + if action == "sidebar.update": + await self.broadcast_webui_event("sidebar_state_updated", state=response.result) + return WebUIRequestResult(result=response.result) + return WebUIRequestResult(status=response.status_code, message=response.message) except asyncio.CancelledError: raise except Exception: diff --git a/nanobot/webui/mcp_presets_api.py b/nanobot/webui/mcp_presets_api.py index 7729703f8..b57233398 100644 --- a/nanobot/webui/mcp_presets_api.py +++ b/nanobot/webui/mcp_presets_api.py @@ -13,6 +13,8 @@ from datetime import datetime, timezone from pathlib import Path from typing import TYPE_CHECKING, Any, Literal, Mapping, cast +from loguru import logger + from nanobot.agent.plugins import ( AgentPlugin, discover_agent_plugins, @@ -25,14 +27,15 @@ from nanobot.agent.tools.mcp_oauth import ( from nanobot.agent.tools.registry import ToolRegistry from nanobot.apps.cli import CliAppManager from nanobot.apps.protocol import app_manifest, compact_dict +from nanobot.config.errors import ConfigLoadError from nanobot.config.loader import load_config, resolve_config_env_vars, save_config from nanobot.config.network import NetworkConfig from nanobot.config.paths import get_runtime_subdir from nanobot.config.schema import MCPServerConfig from nanobot.utils.helpers import ensure_dir from nanobot.webui.mcp_presets import MCP_PRESETS, McpPreset, McpPresetField - -QueryParams = dict[str, list[str]] +from nanobot.webui.settings_contracts import QueryParams, parameter_value +from nanobot.webui.settings_contracts import query_first as _query_first if TYPE_CHECKING: from nanobot.webui.settings_services import WebUISettingsConfig @@ -80,11 +83,6 @@ def _favicon_url(domain: str) -> str: -def _query_first(query: QueryParams, key: str) -> str | None: - values = query.get(key) - return values[0] if values else None - - def _query_value(query: QueryParams, key: str) -> str | None: raw = _query_first(query, key) if raw is None: @@ -115,8 +113,10 @@ def _known_preset_names() -> set[str]: def _known_mcp_names(config_path: Path | None = None) -> set[str]: names = _known_preset_names() - with suppress(Exception): + try: names.update(load_config(config_path).tools.mcp_servers) + except ConfigLoadError: + logger.debug("Could not load configured MCP server names; using built-in presets") return names @@ -754,13 +754,17 @@ async def mcp_presets_test_action( preset = _preset_by_name_optional(name) display_name = _display_name_for(name, preset) - try: - config = resolve_config_env_vars( + def _load_resolved_config(): + return resolve_config_env_vars( load_config(config_path) if config_path is not None else load_config(), config_path=config_path, ) + + try: + config = await asyncio.to_thread(_load_resolved_config) except ValueError as exc: - return mcp_presets_payload( + return await asyncio.to_thread( + mcp_presets_payload, last_action={ "ok": False, "message": _scrub_test_error(str(exc)), @@ -776,9 +780,16 @@ async def mcp_presets_test_action( if cfg is None: raise McpPresetError(f"{display_name} is not enabled", status=404) - status = _status_for(preset, cfg) if preset is not None else ( - "missing_dependency" if cfg.command and not _command_available(cfg.command) else "configured" - ) + def _preflight_status() -> tuple[str, bool]: + cmd_ok = True if not cfg.command else _command_available(cfg.command) + resolved = ( + _status_for(preset, cfg) + if preset is not None + else ("missing_dependency" if not cmd_ok else "configured") + ) + return resolved, cmd_ok + + status, cmd_available = await asyncio.to_thread(_preflight_status) if status == "missing_credentials": last_action: dict[str, Any] = { "ok": False, @@ -788,9 +799,11 @@ async def mcp_presets_test_action( "tool_names": [], "checked_at": _checked_at(), } - return mcp_presets_payload(last_action=last_action, config_path=config_path) + return await asyncio.to_thread( + mcp_presets_payload, last_action=last_action, config_path=config_path, + ) - if cfg.command and not _command_available(cfg.command): + if cfg.command and not cmd_available: last_action = { "ok": False, "message": f"{display_name} requires '{cfg.command}' on PATH.", @@ -799,7 +812,9 @@ async def mcp_presets_test_action( "tool_names": [], "checked_at": _checked_at(), } - return mcp_presets_payload(last_action=last_action, config_path=config_path) + return await asyncio.to_thread( + mcp_presets_payload, last_action=last_action, config_path=config_path, + ) registry = ToolRegistry() stacks: dict[str, Any] = {} @@ -861,15 +876,20 @@ async def mcp_presets_test_action( tool_names = last_action.get("tool_names", []) preview = {name: tool_names} if tool_names else None - return mcp_presets_payload( + return await asyncio.to_thread( + mcp_presets_payload, last_action=last_action, tool_preview=preview, config_path=config_path, ) -def _parse_json_value(raw: str | None, *, fallback: Any) -> Any: - if raw is None or not raw.strip(): +def _parse_json_value(raw: Any, *, fallback: Any) -> Any: + if raw is None: + return fallback + if not isinstance(raw, str): + return raw + if not raw.strip(): return fallback try: return json.loads(raw) @@ -877,10 +897,8 @@ def _parse_json_value(raw: str | None, *, fallback: Any) -> Any: raise McpPresetError(f"invalid JSON: {exc.msg}") from exc -def _parse_string_list(raw: str | None) -> list[str]: - if raw is None or not raw.strip(): - return [] - parsed = _parse_json_value(raw, fallback=None) +def _parse_string_list(raw: Any) -> list[str]: + parsed = _parse_json_value(raw, fallback=[]) if isinstance(parsed, list): items = cast(list[object], parsed) if all(isinstance(item, str) for item in items): @@ -890,7 +908,7 @@ def _parse_string_list(raw: str | None) -> list[str]: raise McpPresetError("expected a JSON string array") -def _parse_string_map(raw: str | None) -> dict[str, str]: +def _parse_string_map(raw: Any) -> dict[str, str]: parsed = _parse_json_value(raw, fallback={}) if not isinstance(parsed, dict): raise McpPresetError("expected a JSON object") @@ -903,8 +921,8 @@ def _parse_string_map(raw: str | None) -> dict[str, str]: return out -def _parse_enabled_tools(raw: str | None) -> list[str]: - if raw is None or not raw.strip(): +def _parse_enabled_tools(raw: Any) -> list[str]: + if raw is None or (isinstance(raw, str) and not raw.strip()): return ["*"] values = _parse_string_list(raw) if "*" in values: @@ -966,22 +984,48 @@ def _validated_server_name(name: str) -> str: return name.strip().lower() +def _build_mcp_server_config( + *, + transport_raw: str | None, + command: str, + url: str, + auth_raw: Any, + args: list[str], + env: dict[str, str], + cwd: str, + headers: dict[str, str], + use_proxy: bool, + tool_timeout: int, + enabled_tools: list[str], + stdio_error: str, + remote_error: str, +) -> MCPServerConfig: + transport = _normalize_transport(transport_raw, command=command, url=url) + if transport == "stdio" and not command: + raise McpPresetError(stdio_error) + if transport in {"sse", "streamableHttp"} and not url: + raise McpPresetError(remote_error) + auth = _normalize_auth(auth_raw, transport=transport, url=url, headers=headers) + return MCPServerConfig( + type=transport, + auth=auth, + command=command if transport == "stdio" else "", + args=args, + env=env, + cwd=cwd if transport == "stdio" else "", + url=url if transport in {"sse", "streamableHttp"} else "", + headers=headers, + use_proxy=use_proxy, + tool_timeout=tool_timeout, + enabled_tools=enabled_tools, + ) + + def _custom_server_from_query(query: QueryParams) -> tuple[str, MCPServerConfig]: name = _validated_server_name((_query_first(query, "name") or "").strip()) command = (_query_first(query, "command") or "").strip() url = (_query_first(query, "url") or "").strip() - transport = _normalize_transport(_query_first(query, "transport"), command=command, url=url) - if transport == "stdio" and not command: - raise McpPresetError("stdio MCP servers require a command") - if transport in {"sse", "streamableHttp"} and not url: - raise McpPresetError("remote MCP servers require a URL") - headers = _parse_string_map(_query_first(query, "headers")) - auth = _normalize_auth( - _query_first(query, "auth"), - transport=transport, - url=url, - headers=headers, - ) + headers = _parse_string_map(parameter_value(query, "headers")) raw_timeout = (_query_first(query, "tool_timeout") or "").strip() tool_timeout = _DEFAULT_CUSTOM_TIMEOUT if raw_timeout: @@ -989,18 +1033,20 @@ def _custom_server_from_query(query: QueryParams) -> tuple[str, MCPServerConfig] tool_timeout = max(5, min(int(raw_timeout), 600)) except ValueError as exc: raise McpPresetError("tool_timeout must be an integer") from exc - cfg = MCPServerConfig( - type=transport, - auth=auth, - command=command if transport == "stdio" else "", - args=_parse_string_list(_query_first(query, "args")), - env=_parse_string_map(_query_first(query, "env")), - cwd=(_query_first(query, "cwd") or "").strip() if transport == "stdio" else "", - url=url if transport in {"sse", "streamableHttp"} else "", + cfg = _build_mcp_server_config( + transport_raw=_query_first(query, "transport"), + command=command, + url=url, + auth_raw=_query_first(query, "auth"), + args=_parse_string_list(parameter_value(query, "args")), + env=_parse_string_map(parameter_value(query, "env")), + cwd=(_query_first(query, "cwd") or "").strip(), headers=headers, use_proxy=_proxy_enabled(query), tool_timeout=tool_timeout, - enabled_tools=_parse_enabled_tools(_query_first(query, "enabled_tools")), + enabled_tools=_parse_enabled_tools(parameter_value(query, "enabled_tools")), + stdio_error="stdio MCP servers require a command", + remote_error="remote MCP servers require a URL", ) return name, cfg @@ -1013,11 +1059,6 @@ def _mcp_server_config(name: str, raw: Any) -> tuple[str, MCPServerConfig]: command = str(server.get("command") or "").strip() url = str(server.get("url") or "").strip() transport_value = str(server.get("type", server.get("transport", "")) or "") - transport = _normalize_transport(transport_value, command=command, url=url) - if transport == "stdio" and not command: - raise McpPresetError(f"MCP server '{server_name}' stdio transport requires a command") - if transport in {"sse", "streamableHttp"} and not url: - raise McpPresetError(f"MCP server '{server_name}' remote transport requires a URL") args_value: object = server.get("args") or [] env_value: object = server.get("env") or {} headers_value: object = server.get("headers") or {} @@ -1047,34 +1088,31 @@ def _mcp_server_config(name: str, raw: Any) -> tuple[str, MCPServerConfig]: use_proxy = server.get("useProxy", server.get("use_proxy", False)) if not isinstance(use_proxy, bool): raise McpPresetError(f"MCP server '{server_name}' useProxy must be a boolean") - auth = _normalize_auth( - server.get("auth"), - transport=transport, - url=url, - headers=typed_headers, - ) if not isinstance(enabled_tools_value, list): enabled_tools_value = ["*"] else: enabled_tools = cast(list[object], enabled_tools_value) if not all(isinstance(item, str) for item in enabled_tools): enabled_tools_value = ["*"] - return server_name, MCPServerConfig( - type=transport, - auth=auth, - command=command if transport == "stdio" else "", + cfg = _build_mcp_server_config( + transport_raw=transport_value, + command=command, + url=url, + auth_raw=server.get("auth"), args=cast(list[str], args), env=cast(dict[str, str], env), - cwd=cwd if transport == "stdio" else "", - url=url if transport in {"sse", "streamableHttp"} else "", + cwd=cwd, headers=typed_headers, use_proxy=use_proxy, tool_timeout=timeout_int, enabled_tools=cast(list[str], enabled_tools_value), + stdio_error=f"MCP server '{server_name}' stdio transport requires a command", + remote_error=f"MCP server '{server_name}' remote transport requires a URL", ) + return server_name, cfg -def _import_mcp_servers(raw_json: str | None) -> dict[str, MCPServerConfig]: +def _import_mcp_servers(raw_json: Any) -> dict[str, MCPServerConfig]: parsed = _parse_json_value(raw_json, fallback=None) if not isinstance(parsed, Mapping): raise McpPresetError("MCP config must be a JSON object") @@ -1125,7 +1163,7 @@ def custom_mcp_action( return payload if action in {"import", "import-cursor"}: - servers = _import_mcp_servers(_query_first(query, "config")) + servers = _import_mcp_servers(parameter_value(query, "config")) for cfg in servers.values(): _validate_proxy(cfg, config.network) delete_credentials = [ @@ -1152,7 +1190,7 @@ def custom_mcp_action( cfg = config.tools.mcp_servers.get(name) if cfg is None: raise McpPresetError("unknown MCP server", status=404) - cfg.enabled_tools = _parse_enabled_tools(_query_first(query, "enabled_tools")) + cfg.enabled_tools = _parse_enabled_tools(parameter_value(query, "enabled_tools")) config.tools.mcp_servers[name] = cfg save_config(config, config_path) payload = mcp_presets_payload( @@ -1311,15 +1349,18 @@ async def mcp_presets_settings_action( """Run a WebUI MCP preset action and hot-reload the agent when config changes.""" config_path = config.path if config is not None else None if action is None: - return mcp_presets_payload( + return await asyncio.to_thread( + mcp_presets_payload, runtime_status=mcp_runtime_status() if mcp_runtime_status is not None else None, config_path=config_path, ) name = (_query_first(query, "name") or "").strip() if name.startswith("plugin-"): - plugin_config = load_config(config_path) if config_path is not None else load_config() + plugin_config = await asyncio.to_thread( + load_config if config_path is None else (lambda: load_config(config_path)) + ) plugin_name = name.removeprefix("plugin-") - plugins = discover_agent_plugins(plugin_config.workspace_path) + plugins = await asyncio.to_thread(discover_agent_plugins, plugin_config.workspace_path) plugin = next((item for item in plugins if item.name == plugin_name), None) if name not in plugin_config.tools.mcp_servers and plugin is not None: if action not in {"enable", "disable"}: @@ -1331,7 +1372,8 @@ async def mcp_presets_settings_action( action == "enable", ) verb = "enabled" if action == "enable" else "disabled" - payload = mcp_presets_payload( + payload = await asyncio.to_thread( + mcp_presets_payload, last_action={"ok": True, "message": f"{plugin.display_name} {verb}."}, config_path=config_path, ) diff --git a/nanobot/webui/mutation.py b/nanobot/webui/mutation.py new file mode 100644 index 000000000..34f372a43 --- /dev/null +++ b/nanobot/webui/mutation.py @@ -0,0 +1,21 @@ +"""Result of an authenticated WebUI mutation, before WebSocket encoding.""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any + + +@dataclass(frozen=True, slots=True) +class MutationResult: + status_code: int + result: dict[str, Any] | None = None + message: str | None = None + + @classmethod + def success(cls, result: dict[str, Any], *, status: int = 200) -> MutationResult: + return cls(status_code=status, result=result) + + @classmethod + def failure(cls, status: int, message: str | None) -> MutationResult: + return cls(status_code=status, message=message) diff --git a/nanobot/webui/nanobot_features_api.py b/nanobot/webui/nanobot_features_api.py index 7fecd525f..906c3bf68 100644 --- a/nanobot/webui/nanobot_features_api.py +++ b/nanobot/webui/nanobot_features_api.py @@ -11,9 +11,7 @@ from nanobot.optional_features import ( install_optional_feature_support, optional_features_payload, ) -from nanobot.webui.http_utils import query_first - -QueryParams = dict[str, list[str]] +from nanobot.webui.settings_contracts import QueryParams, query_first def nanobot_features_payload(*, config_path: Path | None = None) -> dict[str, Any]: diff --git a/nanobot/webui/outbound_delivery.py b/nanobot/webui/outbound_delivery.py index 07416ecd9..4aeae6aa9 100644 --- a/nanobot/webui/outbound_delivery.py +++ b/nanobot/webui/outbound_delivery.py @@ -438,12 +438,17 @@ class WebUIOutboundDelivery: chat_id, persisted=persisted, metadata=metadata, phase=phase, ) + async def _rewrite_markdown_images(self, text: str) -> str: + if "![" not in text: + return self._media.rewrite_local_markdown_images(text) + return await asyncio.to_thread(self._media.rewrite_local_markdown_images, text) + async def _message_payload(self, msg: OutboundMessage, progress: ProgressEvent | None) -> dict[str, Any]: text = msg.content user_shell = msg.metadata.get(INBOUND_META_USER_SHELL) is True payload: MessageWirePayload = { "event": "message", "chat_id": msg.chat_id, - "text": text if user_shell else self._media.rewrite_local_markdown_images(text), + "text": text if user_shell else await self._rewrite_markdown_images(text), } if user_shell: payload["render_as"] = "text" @@ -454,7 +459,7 @@ class WebUIOutboundDelivery: payload["media"] = msg.media urls: list[dict[str, str]] = [] for entry in msg.media: - signed = self._media.sign_or_stage_media_path(Path(entry)) + signed = await asyncio.to_thread(self._media.sign_or_stage_media_path, Path(entry)) if signed is not None: urls.append(signed) if urls: @@ -555,7 +560,7 @@ class WebUIOutboundDelivery: if delta: buffered.chunks.append(delta) full_text = "".join(buffered.chunks) - rewritten = self._media.rewrite_local_markdown_images(full_text) + rewritten = await self._rewrite_markdown_images(full_text) completed_text = rewritten if delta or rewritten != full_text: payload["text"] = rewritten diff --git a/nanobot/webui/request_settings.py b/nanobot/webui/request_settings.py index 4c46f9f2e..9db59ba46 100644 --- a/nanobot/webui/request_settings.py +++ b/nanobot/webui/request_settings.py @@ -5,7 +5,7 @@ import re from typing import Any, cast from nanobot.config.schema import ProviderConfig -from nanobot.webui.settings_contracts import QueryParams, WebUISettingsError, query_first_alias +from nanobot.webui.settings_contracts import QueryParams, WebUISettingsError, parameter_value _REDACTED_PROVIDER_SECRET = "••••••••" _PROVIDER_STRUCTURED_FIELDS = ("extra_headers", "extra_body", "extra_query") @@ -45,13 +45,14 @@ def parse_request_object( snake: str, camel: str, ) -> dict[str, Any] | None: - raw = (query_first_alias(query, snake, camel) or "").strip() - if not raw: + value = parameter_value(query, snake if snake in query else camel) + if value is None or (isinstance(value, str) and not value.strip()): return None - try: - value: object = json.loads(raw) - except json.JSONDecodeError as exc: - raise WebUISettingsError(f"{snake} must be a JSON object") from exc + if isinstance(value, str): + try: + value = json.loads(value) + except json.JSONDecodeError as exc: + raise WebUISettingsError(f"{snake} must be a JSON object") from exc if not isinstance(value, dict): raise WebUISettingsError(f"{snake} must be a JSON object") return cast(dict[str, Any], value) or None diff --git a/nanobot/webui/settings_contracts.py b/nanobot/webui/settings_contracts.py index b53fe05b6..93eccb650 100644 --- a/nanobot/webui/settings_contracts.py +++ b/nanobot/webui/settings_contracts.py @@ -1,9 +1,23 @@ from __future__ import annotations +import json from dataclasses import dataclass from typing import Any -QueryParams = dict[str, list[str]] +HttpQuery = dict[str, list[str]] + + +@dataclass(frozen=True, slots=True) +class MutationParams: + """Original JSON fields, distinct from multi-valued HTTP query strings.""" + + values: dict[str, Any] + + def __contains__(self, key: str) -> bool: + return key in self.values + + +QueryParams = HttpQuery | MutationParams @dataclass(frozen=True) @@ -59,11 +73,30 @@ class WebUISettingsError(ValueError): self.status = status -def query_first(query: QueryParams, key: str) -> str | None: +def parameter_value(query: QueryParams, key: str) -> Any: + if isinstance(query, MutationParams): + return query.values.get(key) values = query.get(key) return values[0] if values else None +def parameter_json(query: QueryParams, key: str, default: Any = None) -> Any: + value = parameter_value(query, key) + if value is None or value == "": + return default + return json.loads(value) if isinstance(value, str) else value + + +def query_first(query: QueryParams, key: str) -> str | None: + value = parameter_value(query, key) + if value is None: + # An explicit null has historically meant a blank scalar. + return "" if isinstance(query, MutationParams) and key in query else None + if isinstance(value, bool): + return "true" if value else "false" + return str(value) if isinstance(value, (str, int, float)) else None + + def query_first_alias(query: QueryParams, snake: str, camel: str) -> str | None: value = query_first(query, snake) return query_first(query, camel) if value is None else value diff --git a/nanobot/webui/settings_model_oauth.py b/nanobot/webui/settings_model_oauth.py new file mode 100644 index 000000000..97a15c221 --- /dev/null +++ b/nanobot/webui/settings_model_oauth.py @@ -0,0 +1,273 @@ +"""WebUI OAuth provider adapters; the service registry still owns live flows.""" + +# oauth-cli-kit does not publish type stubs. +# pyright: reportMissingTypeStubs=false + +from __future__ import annotations + +import secrets +import time +from contextlib import contextmanager, suppress +from dataclasses import dataclass +from pathlib import Path +from typing import TYPE_CHECKING, Any, Callable, Generator, Literal, Protocol + +from loguru import logger + +from nanobot.config.loader import resolve_config_env_vars +from nanobot.providers.oauth_guidance import OAUTH_CLI_KIT_MISSING_MESSAGE +from nanobot.webui.settings_contracts import WebUISettingsError + +if TYPE_CHECKING: + from nanobot.config.schema import Config + from nanobot.providers.registry import ProviderSpec + from nanobot.webui.settings_services import ( + WebUIOAuthFlow, + WebUIOAuthFlowRegistry, + WebUIOAuthToken, + ) + +_WEBUI_OAUTH_TIMEOUT_S = 600 + + +if TYPE_CHECKING: + class _StartableOAuthFlow(WebUIOAuthFlow, Protocol): + @property + def authorization_url(self) -> str: ... + + @property + def remaining_seconds(self) -> int: ... + + def start(self) -> object: ... + + +@dataclass(frozen=True) +class _PendingLogin: + flow: _StartableOAuthFlow + user_code: Callable[[], str] | None = None + + +@dataclass(frozen=True) +class _LoginContext: + config: Config + config_path: Path | None + remote_browser: Callable[[], bool] + oauth_flows: WebUIOAuthFlowRegistry + + def proxy(self, provider: Literal["openai_codex", "xai_grok"]) -> str | None: + try: + resolved = resolve_config_env_vars(self.config, config_path=self.config_path) + return resolved.network.resolve_proxy(getattr(resolved.providers, provider).use_proxy) + except ValueError as exc: + raise WebUISettingsError(str(exc), status=400) from exc + + +def _complete(flow: WebUIOAuthFlow, response: str | None) -> WebUIOAuthToken | None: + return flow.complete(response) + + +@dataclass(frozen=True) +class OAuthProviderAdapter: + completion_input: Literal["callback_url", "device_code", "authorization_code"] + load_status: Callable[[], Callable[[], WebUIOAuthToken | None]] + create_login: Callable[[_LoginContext], _PendingLogin] + prepare_logout: Callable[[], Callable[[], object]] + login_failure: Callable[[Exception], str] + complete: Callable[[WebUIOAuthFlow, str | None], WebUIOAuthToken | None] = _complete + supports_proxy: bool = False + allow_refresh_token: bool = False + disclose_login_error: bool = True + + def start_login( + self, provider: str, config: Config, config_path: Path | None, + remote_browser: Callable[[], bool], oauth_flows: WebUIOAuthFlowRegistry, + ) -> dict[str, Any]: + login = self.create_login(_LoginContext(config, config_path, remote_browser, oauth_flows)) + flow = login.flow + flow_id = secrets.token_urlsafe(24) + # Register before network I/O so cancellation also owns in-flight starts. + try: + oauth_flows.register(provider, flow_id, flow) + flow.start() + except Exception as exc: + oauth_flows.remove(provider, flow_id, flow) + raise WebUISettingsError(self.login_failure(exc), status=502) from ( + exc if self.disclose_login_error else None + ) + result = { + "status": "authorization_required", + "provider": provider, + "flow_id": flow_id, + "authorization_url": flow.authorization_url, + "expires_in": flow.remaining_seconds, + "completion_input": self.completion_input, + } + if login.user_code is not None: + result["user_code"] = login.user_code() + return result + + def logout(self, provider: str, oauth_flows: WebUIOAuthFlowRegistry) -> None: + revoke = self.prepare_logout() + oauth_flows.clear(provider) + revoke() + + +@contextmanager +def _oauth_cli_kit_import() -> Generator[None]: + try: + yield + except ImportError: + raise WebUISettingsError(OAUTH_CLI_KIT_MISSING_MESSAGE, status=500) from None + + +def _codex_status_loader() -> Callable[[], WebUIOAuthToken | None]: + from oauth_cli_kit.providers import OPENAI_CODEX_PROVIDER + from oauth_cli_kit.storage import FileTokenStorage + + return lambda: FileTokenStorage(token_filename=OPENAI_CODEX_PROVIDER.token_filename).load() + + +def _copilot_status_loader() -> Callable[[], WebUIOAuthToken | None]: + from nanobot.providers.github_copilot_provider import get_github_copilot_login_status + + return get_github_copilot_login_status + + +def _xai_status_loader() -> Callable[[], WebUIOAuthToken | None]: + from nanobot.providers.xai_oauth import get_xai_oauth_login_status + + return get_xai_oauth_login_status + + +def _codex_login(context: _LoginContext) -> _PendingLogin: + with _oauth_cli_kit_import(): + from nanobot.providers.openai_codex_oauth import OpenAICodexOAuthLoginFlow + + return _PendingLogin(OpenAICodexOAuthLoginFlow( + proxy=context.proxy("openai_codex"), + timeout_s=_WEBUI_OAUTH_TIMEOUT_S, + open_browser=not context.remote_browser(), + )) + + +def _copilot_login(context: _LoginContext) -> _PendingLogin: + with _oauth_cli_kit_import(): + from nanobot.providers.github_copilot_oauth import GitHubCopilotOAuthFlow + + # Replace even an existing sign-in: its token might have been revoked. + context.oauth_flows.clear("github_copilot") + flow = GitHubCopilotOAuthFlow() + return _PendingLogin(flow, lambda: flow.user_code) + + +def _xai_login_failure(exc: Exception) -> str: + return f"xAI OAuth login failed: {exc}" + + +def _xai_login(context: _LoginContext) -> _PendingLogin: + from nanobot.providers.xai_oauth import create_xai_oauth_login + + proxy = context.proxy("xai_grok") + try: + return _PendingLogin(create_xai_oauth_login(proxy=proxy, timeout_s=_WEBUI_OAUTH_TIMEOUT_S)) + except Exception as exc: + raise WebUISettingsError(_xai_login_failure(exc), status=502) from exc + + +def _complete_codex(flow: WebUIOAuthFlow, response: str | None) -> WebUIOAuthToken | None: + from nanobot.providers.openai_codex_oauth import OpenAICodexOAuthInputError + + try: + return flow.complete(response) + except OpenAICodexOAuthInputError as exc: + raise WebUISettingsError(str(exc), status=400) from exc + + +def _remove_token_files(token_path: Path) -> None: + for path in (token_path, token_path.with_suffix(".lock")): + with suppress(FileNotFoundError): + path.unlink() + + +def _codex_logout() -> Callable[[], None]: + with _oauth_cli_kit_import(): + from oauth_cli_kit.providers import OPENAI_CODEX_PROVIDER + from oauth_cli_kit.storage import FileTokenStorage + + return lambda: _remove_token_files(FileTokenStorage( + token_filename=OPENAI_CODEX_PROVIDER.token_filename, + ).get_token_path()) + + +def _copilot_logout() -> Callable[[], None]: + with _oauth_cli_kit_import(): + from nanobot.providers.github_copilot_provider import get_storage + + return lambda: _remove_token_files(get_storage().get_token_path()) + + +def _xai_logout() -> Callable[[], bool]: + from nanobot.providers.xai_oauth import logout_xai_oauth + + return logout_xai_oauth + + +_OAUTH_ADAPTERS = { + "openai_codex": OAuthProviderAdapter( + completion_input="callback_url", + load_status=_codex_status_loader, + create_login=_codex_login, + prepare_logout=_codex_logout, + login_failure=lambda exc: f"OpenAI Codex OAuth login failed: {exc}", + complete=_complete_codex, + supports_proxy=True, + allow_refresh_token=True, + ), + "github_copilot": OAuthProviderAdapter( + completion_input="device_code", + load_status=_copilot_status_loader, + create_login=_copilot_login, + prepare_logout=_copilot_logout, + login_failure=lambda _: "GitHub sign-in failed. Start again.", + disclose_login_error=False, + ), + "xai_grok": OAuthProviderAdapter( + completion_input="authorization_code", + load_status=_xai_status_loader, + create_login=_xai_login, + prepare_logout=_xai_logout, + login_failure=_xai_login_failure, + supports_proxy=True, + allow_refresh_token=True, + ), +} + + +def oauth_provider_adapter(spec: ProviderSpec) -> OAuthProviderAdapter | None: + return _OAUTH_ADAPTERS.get(spec.name) if spec.is_oauth else None + + +def oauth_provider_status(spec: ProviderSpec | None) -> dict[str, Any]: + unconfigured = {"configured": False, "account": None, "expires_at": None, "login_supported": False} + if spec is None or (adapter := oauth_provider_adapter(spec)) is None: + return unconfigured + try: + loader = adapter.load_status() + except Exception as exc: + logger.debug("{} OAuth backend unavailable: {}", spec.name, exc) + return unconfigured + token = None + try: + token = loader() + except Exception as exc: + logger.debug("could not load OAuth token status for {}: {}", spec.name, exc) + expires_at = getattr(token, "expires", None) if token else None + now_ms = int(time.time() * 1000) + valid_expiry = bool(expires_at and expires_at > now_ms) + has_refresh = bool(adapter.allow_refresh_token and getattr(token, "refresh", None)) + return { + "configured": bool(token and token.access and (has_refresh or valid_expiry)), + "account": getattr(token, "account_id", None) if token else None, + "expires_at": expires_at, + "login_supported": True, + } diff --git a/nanobot/webui/settings_models.py b/nanobot/webui/settings_models.py index 1288e2ab4..0221e5d43 100644 --- a/nanobot/webui/settings_models.py +++ b/nanobot/webui/settings_models.py @@ -5,9 +5,6 @@ updates, model discovery, and OAuth workflows. It deliberately has no dependency on the WebSocket transport. """ -# oauth-cli-kit does not publish type stubs. -# pyright: reportMissingTypeStubs=false - from __future__ import annotations import asyncio @@ -15,9 +12,7 @@ import json import math import os import re -import secrets import time -from contextlib import suppress from dataclasses import dataclass from datetime import date, datetime, timezone from pathlib import Path @@ -39,7 +34,6 @@ from nanobot.providers.model_options import ( CodexFastMode, codex_supports_ultrafast, ) -from nanobot.providers.oauth_guidance import OAUTH_CLI_KIT_MISSING_MESSAGE from nanobot.providers.oauth_model_catalog import ( get_oauth_model_catalog, invalidate_oauth_model_catalog, @@ -61,11 +55,20 @@ from nanobot.webui.settings_contracts import ( SettingsRequest, SettingsRouteResult, WebUISettingsError, + parameter_json, + parameter_value, parse_bool, query_first, query_first_alias, query_has_alias, ) +from nanobot.webui.settings_model_oauth import ( + OAuthProviderAdapter, + oauth_provider_adapter, +) +from nanobot.webui.settings_model_oauth import ( + oauth_provider_status as oauth_provider_status, +) if TYPE_CHECKING: from nanobot.webui.settings_services import ( @@ -129,8 +132,6 @@ class ProviderModelRowPayload(ProviderModelMetadataPayload): description: NotRequired[str] -_OAUTH_PROXY_PROVIDERS = {"openai_codex", "xai_grok"} -_WEBUI_OAUTH_TIMEOUT_S = 600 _MODEL_CONFIGURATION_SLUG_RE = re.compile(r"[^a-z0-9_-]+") _ENV_REF_RE = re.compile(r"\$\{([A-Za-z_][A-Za-z0-9_]*)\}") _PROVIDER_STRUCTURED_FIELDS = ("extra_headers", "extra_body", "extra_query") @@ -170,7 +171,7 @@ def _provider_config_updates( updates[snake] = request_settings.parse_request_object(query, snake, camel) if query_has_alias(query, "api", "api"): try: - updates["api"] = json.loads(query_first(query, "api") or "null") + updates["api"] = parameter_json(query, "api") except ValueError as exc: raise WebUISettingsError("api must declare supportedApis and a preferredApi from that list") from exc return updates @@ -211,86 +212,6 @@ def provider_requires_api_base(spec: Any) -> bool: return bool(spec.backend == "openai_compat" and spec.is_direct and not spec.default_api_base) -def oauth_provider_status(spec: Any) -> dict[str, Any]: - if not getattr(spec, "is_oauth", False): - return {"configured": False, "account": None, "expires_at": None, "login_supported": False} - - if spec.name == "openai_codex": - try: - from oauth_cli_kit.providers import OPENAI_CODEX_PROVIDER - from oauth_cli_kit.storage import FileTokenStorage - except Exception: - return { - "configured": False, - "account": None, - "expires_at": None, - "login_supported": False, - } - token = None - with suppress(Exception): - token = FileTokenStorage(token_filename=OPENAI_CODEX_PROVIDER.token_filename).load() - expires_at = getattr(token, "expires", None) if token else None - now_ms = int(time.time() * 1000) - return { - "configured": bool( - token - and token.access - and (getattr(token, "refresh", None) or (expires_at and expires_at > now_ms)) - ), - "account": getattr(token, "account_id", None) if token else None, - "expires_at": expires_at, - "login_supported": True, - } - - if spec.name == "github_copilot": - try: - from nanobot.providers.github_copilot_provider import get_github_copilot_login_status - except Exception: - return { - "configured": False, - "account": None, - "expires_at": None, - "login_supported": False, - } - token = None - with suppress(Exception): - token = get_github_copilot_login_status() - return { - "configured": bool(token and token.access and token.expires > int(time.time() * 1000)), - "account": getattr(token, "account_id", None) if token else None, - "expires_at": getattr(token, "expires", None) if token else None, - "login_supported": True, - } - - if spec.name == "xai_grok": - try: - from nanobot.providers.xai_oauth import get_xai_oauth_login_status - except Exception: - return { - "configured": False, - "account": None, - "expires_at": None, - "login_supported": False, - } - token = None - with suppress(Exception): - token = get_xai_oauth_login_status() - expires_at = getattr(token, "expires", None) if token else None - now_ms = int(time.time() * 1000) - return { - "configured": bool( - token - and token.access - and (getattr(token, "refresh", None) or (expires_at and expires_at > now_ms)) - ), - "account": getattr(token, "account_id", None) if token else None, - "expires_at": expires_at, - "login_supported": True, - } - - return {"configured": False, "account": None, "expires_at": None, "login_supported": False} - - def provider_configured_for_settings( spec: Any, provider_config: Any, @@ -353,7 +274,8 @@ def _provider_advanced_field_names(spec: ProviderSpec) -> list[str]: fields.append("extra_body") if spec.backend in {"openai_compat", "anthropic"}: fields.extend(("extra_query", "use_proxy")) - if spec.name in _OAUTH_PROXY_PROVIDERS and "use_proxy" not in fields: + adapter = oauth_provider_adapter(spec) + if adapter is not None and adapter.supports_proxy and "use_proxy" not in fields: fields.append("use_proxy") if spec.backend == "bedrock": fields.extend(("region", "profile")) @@ -1323,7 +1245,7 @@ def update_agent_model_settings( defaults.context_window_tokens = context_window_tokens changed = True if "api" in query: - api = _parse_preset_api(config, defaults.model, defaults.provider, query_first(query, "api")) + api = _parse_preset_api(config, defaults.model, defaults.provider, query) if defaults.api != api: defaults.api = api changed = True @@ -1333,12 +1255,10 @@ def update_agent_model_settings( def _parse_preset_api( - config: Config, model: str, provider: str, raw: str | None, + config: Config, model: str, provider: str, query: QueryParams, ) -> ModelAPIConfig | None: - if not raw: - return None try: - value: object = json.loads(raw) + value: object = parameter_json(query, "api") api = ModelAPIConfig.model_validate(value) if value is not None else None except ValueError: raise WebUISettingsError( @@ -1419,7 +1339,7 @@ def create_model_configuration( supports_images=parse_bool( query_first_alias(query, "supports_images", "supportsImages") or "true", "supports_images", ), - api=_parse_preset_api(config, model, provider, query_first(query, "api")), + api=_parse_preset_api(config, model, provider, query), ) config.model_presets[name] = _preset_with_request_updates(config, candidate, query) if activate_as_primary: @@ -1518,7 +1438,7 @@ def update_model_configuration( preset.supports_images = supports_images changed = True if "api" in query: - api = _parse_preset_api(config, preset.model, preset.provider, query_first(query, "api")) + api = _parse_preset_api(config, preset.model, preset.provider, query) if preset.api != api: preset.api = api changed = True @@ -1538,31 +1458,44 @@ def update_model_configuration( return changed +@dataclass(frozen=True) +class _ModelCallOrderRequest: + order: tuple[str, ...] + + @classmethod + def from_query(cls, query: QueryParams) -> _ModelCallOrderRequest: + key = "order" + if parameter_value(query, key) is None and query_first(query, key) is None: + key = "presetNames" + raw = parameter_value(query, key) + if raw is None and query_first(query, key) is None: + raise WebUISettingsError("model call order is required") + if raw is None or raw == "": + # Explicit null and empty text were both blank on the scalar wire. + raise WebUISettingsError("model call order must be a JSON array") + try: + order: object = parameter_json(query, key) + except json.JSONDecodeError: + raise WebUISettingsError("model call order must be a JSON array") from None + error = "model call order must contain at least one preset" + if not isinstance(order, list) or not order: + raise WebUISettingsError(error) + names: list[str] = [] + for name in cast(list[object], order): + if not isinstance(name, str) or not (clean := name.strip()): + raise WebUISettingsError(error) + names.append(clean) + return cls(tuple(names)) + + def update_model_call_order( config: Config, query: QueryParams, *, oauth_status: OAuthStatusReader, ) -> bool: - raw_order = query_first_alias(query, "order", "presetNames") - if raw_order is None: - raise WebUISettingsError("model call order is required") - try: - order: object = json.loads(raw_order) - except json.JSONDecodeError: - raise WebUISettingsError("model call order must be a JSON array") from None - if ( - not isinstance(order, list) - or not order - or any( - not isinstance(name, str) or not name.strip() - for name in cast(list[object], order) - ) - ): - raise WebUISettingsError("model call order must contain at least one preset") - - normalized_order = [cast(str, name).strip() for name in cast(list[object], order)] - return _set_model_call_order(config, normalized_order, oauth_status=oauth_status) + request = _ModelCallOrderRequest.from_query(query) + return _set_model_call_order(config, list(request.order), oauth_status=oauth_status) def append_model_call_order(config: Config, name: str, *, oauth_status: OAuthStatusReader) -> None: @@ -1747,7 +1680,8 @@ def update_provider_settings( except ValueError as exc: raise WebUISettingsError(str(exc)) from None if spec.is_oauth: - if spec.name not in _OAUTH_PROXY_PROVIDERS: + adapter = oauth_provider_adapter(spec) + if adapter is None or not adapter.supports_proxy: raise WebUISettingsError("unknown provider") unsupported = set(updates) - {"use_proxy", "extra_body"} if unsupported: @@ -1805,6 +1739,21 @@ def update_provider_settings( return changed, restart_required +def _requested_oauth_provider( + query: QueryParams, operation: str, +) -> tuple[ProviderSpec, OAuthProviderAdapter]: + provider_name = (query_first(query, "provider") or "").strip() + if not provider_name and operation != "completion": + raise WebUISettingsError("provider is required") + spec = find_by_name(provider_name) + if spec is None or not spec.is_oauth: + if operation != "completion": + raise WebUISettingsError("unknown OAuth provider") + elif (adapter := oauth_provider_adapter(spec)) is not None: + return spec, adapter + raise WebUISettingsError(f"OAuth {operation} is not supported for this provider") + + def login_oauth_provider( config: Config, query: QueryParams, @@ -1812,115 +1761,13 @@ def login_oauth_provider( oauth_flows: WebUIOAuthFlowRegistry, config_path: Path | None, ) -> dict[str, Any]: - provider_name = (query_first(query, "provider") or "").strip() - if not provider_name: - raise WebUISettingsError("provider is required") - spec = find_by_name(provider_name) - if spec is None or not spec.is_oauth: - raise WebUISettingsError("unknown OAuth provider") + spec, adapter = _requested_oauth_provider(query, "login") - if spec.name == "openai_codex": - try: - from nanobot.providers.openai_codex_oauth import OpenAICodexOAuthLoginFlow - except ImportError: - raise WebUISettingsError(OAUTH_CLI_KIT_MISSING_MESSAGE, status=500) from None + def remote_browser() -> bool: + value = query_first(query, "remote_browser") + return parse_bool(value, "remote_browser") if value is not None else False - try: - resolved_config = resolve_config_env_vars(config, config_path=config_path) - proxy = resolved_config.network.resolve_proxy(resolved_config.providers.openai_codex.use_proxy) - except ValueError as exc: - raise WebUISettingsError(str(exc), status=400) from exc - remote_browser_value = query_first(query, "remote_browser") - remote_browser = ( - parse_bool(remote_browser_value, "remote_browser") - if remote_browser_value is not None - else False - ) - flow = OpenAICodexOAuthLoginFlow( - proxy=proxy, - timeout_s=_WEBUI_OAUTH_TIMEOUT_S, - open_browser=not remote_browser, - ) - flow_id = secrets.token_urlsafe(24) - try: - oauth_flows.register(spec.name, flow_id, flow) - flow.start() - except Exception as exc: - oauth_flows.remove(spec.name, flow_id, flow) - raise WebUISettingsError( - f"OpenAI Codex OAuth login failed: {exc}", - status=502, - ) from exc - return { - "status": "authorization_required", - "provider": spec.name, - "flow_id": flow_id, - "authorization_url": flow.authorization_url, - "expires_in": flow.remaining_seconds, - "completion_input": "callback_url", - } - - if spec.name == "github_copilot": - try: - from nanobot.providers.github_copilot_oauth import GitHubCopilotOAuthFlow - except ImportError: - raise WebUISettingsError(OAUTH_CLI_KIT_MISSING_MESSAGE, status=500) from None - - # An existing token can be revoked. Expose the device prompt immediately - # instead of waiting for approval inside a blocking CLI login request. - oauth_flows.clear(spec.name) - copilot_flow = GitHubCopilotOAuthFlow() - flow_id = secrets.token_urlsafe(24) - # Own the flow before network I/O, so logout/replacement also cancels a - # login that is still waiting for GitHub to return its device prompt. - try: - oauth_flows.register(spec.name, flow_id, copilot_flow) - copilot_flow.start() - except Exception: - oauth_flows.remove(spec.name, flow_id, copilot_flow) - raise WebUISettingsError("GitHub sign-in failed. Start again.", status=502) from None - return { - "status": "authorization_required", - "provider": spec.name, - "flow_id": flow_id, - "authorization_url": copilot_flow.authorization_url, - "user_code": copilot_flow.user_code, - "expires_in": copilot_flow.remaining_seconds, - "completion_input": "device_code", - } - - if spec.name == "xai_grok": - from nanobot.providers.xai_oauth import create_xai_oauth_login - - try: - resolved_config = resolve_config_env_vars(config, config_path=config_path) - proxy = resolved_config.network.resolve_proxy(resolved_config.providers.xai_grok.use_proxy) - except ValueError as exc: - raise WebUISettingsError(str(exc), status=400) from exc - try: - flow = create_xai_oauth_login( - proxy=proxy, - timeout_s=_WEBUI_OAUTH_TIMEOUT_S, - ) - except Exception as exc: - raise WebUISettingsError(f"xAI OAuth login failed: {exc}", status=502) from exc - flow_id = secrets.token_urlsafe(24) - try: - oauth_flows.register(spec.name, flow_id, flow) - flow.start() - except Exception as exc: - oauth_flows.remove(spec.name, flow_id, flow) - raise WebUISettingsError(f"xAI OAuth login failed: {exc}", status=502) from exc - return { - "status": "authorization_required", - "provider": spec.name, - "flow_id": flow_id, - "authorization_url": flow.authorization_url, - "expires_in": flow.remaining_seconds, - "completion_input": "authorization_code", - } - - raise WebUISettingsError("OAuth login is not supported for this provider") + return adapter.start_login(spec.name, config, config_path, remote_browser, oauth_flows) def complete_oauth_provider( @@ -1931,11 +1778,8 @@ def complete_oauth_provider( config_path: Path | None, settings_payload: SettingsPayloadBuilder, ) -> dict[str, Any]: - provider_name = (query_first(query, "provider") or "").strip() + spec, adapter = _requested_oauth_provider(query, "completion") flow_id = (query_first(query, "flow_id") or "").strip() - spec = find_by_name(provider_name) - if spec is None or spec.name not in {"openai_codex", "xai_grok", "github_copilot"}: - raise WebUISettingsError("OAuth completion is not supported for this provider") if not flow_id: raise WebUISettingsError("flow_id is required") @@ -1949,15 +1793,7 @@ def complete_oauth_provider( return {"status": "cancelled", "provider": spec.name, "flow_id": flow_id} try: - if spec.name == "openai_codex": - from nanobot.providers.openai_codex_oauth import OpenAICodexOAuthInputError - - try: - token = flow.complete(authorization_response) - except OpenAICodexOAuthInputError as exc: - raise WebUISettingsError(str(exc), status=400) from exc - else: - token = flow.complete(authorization_response) + token = adapter.complete(flow, authorization_response) except WebUISettingsError: raise except Exception as exc: @@ -1986,43 +1822,8 @@ def logout_oauth_provider( config_path: Path | None, settings_payload: SettingsPayloadBuilder, ) -> dict[str, Any]: - provider_name = (query_first(query, "provider") or "").strip() - if not provider_name: - raise WebUISettingsError("provider is required") - spec = find_by_name(provider_name) - if spec is None or not spec.is_oauth: - raise WebUISettingsError("unknown OAuth provider") - - if spec.name == "openai_codex": - try: - from oauth_cli_kit.providers import OPENAI_CODEX_PROVIDER - from oauth_cli_kit.storage import FileTokenStorage - except ImportError: - raise WebUISettingsError(OAUTH_CLI_KIT_MISSING_MESSAGE, status=500) from None - oauth_flows.clear(spec.name) - token_path = FileTokenStorage( - token_filename=OPENAI_CODEX_PROVIDER.token_filename - ).get_token_path() - elif spec.name == "github_copilot": - try: - from nanobot.providers.github_copilot_provider import get_storage - except ImportError: - raise WebUISettingsError(OAUTH_CLI_KIT_MISSING_MESSAGE, status=500) from None - oauth_flows.clear(spec.name) - token_path = get_storage().get_token_path() - elif spec.name == "xai_grok": - from nanobot.providers.xai_oauth import logout_xai_oauth - - oauth_flows.clear(spec.name) - logout_xai_oauth() - invalidate_oauth_model_catalog(spec.name) - return settings_payload(config_path=config_path) - else: - raise WebUISettingsError("OAuth logout is not supported for this provider") - - for path in (token_path, token_path.with_suffix(".lock")): - with suppress(FileNotFoundError): - path.unlink() + spec, adapter = _requested_oauth_provider(query, "logout") + adapter.logout(spec.name, oauth_flows) invalidate_oauth_model_catalog(spec.name) return settings_payload(config_path=config_path) diff --git a/nanobot/webui/settings_routes.py b/nanobot/webui/settings_routes.py index 96b8d4d6f..a649791d6 100644 --- a/nanobot/webui/settings_routes.py +++ b/nanobot/webui/settings_routes.py @@ -2,8 +2,9 @@ from __future__ import annotations import asyncio import html -import json +import re from collections.abc import Awaitable, Callable, Mapping +from dataclasses import dataclass from functools import partial from typing import Any, cast @@ -21,7 +22,11 @@ from nanobot.webui import settings_contracts as contracts from nanobot.webui import settings_models as model_domain from nanobot.webui import settings_system as system_domain from nanobot.webui.cli_apps_api import cli_apps_action, cli_apps_payload -from nanobot.webui.http_utils import http_json_response +from nanobot.webui.http_utils import ( + case_insensitive_header, + etag_matches, + http_json_response, +) from nanobot.webui.http_utils import http_response as _http_response from nanobot.webui.http_utils import is_local_browser_request as _is_local_browser_request from nanobot.webui.mcp_oauth_api import McpOAuthManager @@ -29,6 +34,7 @@ from nanobot.webui.mcp_presets_api import ( ensure_mcp_oauth_server, mcp_presets_settings_action, ) +from nanobot.webui.mutation import MutationResult from nanobot.webui.nanobot_features_api import ( nanobot_feature_instance_target, nanobot_features_action, @@ -58,7 +64,8 @@ from nanobot.webui.settings_api import ( update_web_search_settings, ) from nanobot.webui.settings_contracts import ( - QueryParams, + HttpQuery, + MutationParams, SettingsRequest, SettingsRouteResult, ) @@ -66,8 +73,6 @@ from nanobot.webui.settings_runtime import runtime_config_payload from nanobot.webui.settings_services import WebUISettingsServices from nanobot.webui.version_check import check_for_update -_WEBUI_MUTATION_PAYLOAD_ATTR = "_nanobot_webui_mutation_payload" -_WEBUI_MUTATION_REQUEST_ATTR = "_nanobot_webui_mutation_request" _CHANNEL_CONNECT_ACTIONS = frozenset({"start", "poll", "cancel"}) _MCP_OAUTH_CALLBACK_URL_MAX_BYTES = 8 * 1024 _MCP_RELOAD_TIMEOUT_SECONDS = 15.0 @@ -90,141 +95,80 @@ def _channel_connect_route(path: str) -> tuple[str, str] | None: return (channel_name, parts[2]) if channel_name else None -_MCP_PRESET_ACTIONS_BY_PATH = { - "/api/settings/mcp-presets/enable": "enable", - "/api/settings/mcp-presets/disable": "disable", - "/api/settings/mcp-presets/remove": "remove", - "/api/settings/mcp-presets/test": "test", - "/api/settings/mcp-presets/reconnect": "reconnect", - "/api/settings/mcp-presets/proxy": "proxy", - "/api/settings/mcp-presets/custom": "custom", - "/api/settings/mcp-presets/import": "import", - "/api/settings/mcp-presets/import-cursor": "import-cursor", - "/api/settings/mcp-presets/tools": "tools", -} +@dataclass(frozen=True, slots=True) +class _SettingsRoute: + domain: str + action: str + mutation: str | None = None -_MODEL_ROUTES = { - "/api/settings/update": "agent-update", - "/api/settings/model-configurations/create": "model-create", - "/api/settings/model-configurations/update": "model-update", - "/api/settings/model-configurations/delete": "model-delete", - "/api/settings/model-configurations/migrate": "models-migrate", - "/api/settings/model-call-order/update": "call-order-update", - "/api/settings/provider/update": "provider-update", - "/api/settings/provider/create": "provider-create", - "/api/settings/provider-models": "provider-models", - "/api/settings/model-api": "model-api", - "/api/settings/provider/oauth-login": "oauth-login", - "/api/settings/provider/oauth-login/complete": "oauth-complete", - "/api/settings/provider/oauth-logout": "oauth-logout", -} -_CAPABILITY_ROUTES = { - "/api/settings/web-search/update": "web-search-update", - "/api/settings/image-generation/update": "image-update", - "/api/settings/transcription/update": "transcription-update", - "/api/settings/network-safety/update": "network-update", +_SETTINGS_ROUTES = { + "/api/settings/update": _SettingsRoute("models", "agent-update", "settings.agent.update"), + "/api/settings/model-configurations/create": _SettingsRoute("models", "model-create", "settings.model_configuration.create"), + "/api/settings/model-configurations/update": _SettingsRoute("models", "model-update", "settings.model_configuration.update"), + "/api/settings/model-configurations/delete": _SettingsRoute("models", "model-delete", "settings.model_configuration.delete"), + "/api/settings/model-configurations/migrate": _SettingsRoute("models", "models-migrate", "settings.model_configuration.migrate"), + "/api/settings/model-call-order/update": _SettingsRoute("models", "call-order-update", "settings.model_call_order.update"), + "/api/settings/provider/update": _SettingsRoute("models", "provider-update", "settings.provider.update"), + "/api/settings/provider/create": _SettingsRoute("models", "provider-create", "settings.provider.create"), + "/api/settings/provider-models": _SettingsRoute("models", "provider-models"), + "/api/settings/model-api": _SettingsRoute("models", "model-api"), + "/api/settings/provider/oauth-login": _SettingsRoute("models", "oauth-login", "settings.provider.oauth_login"), + "/api/settings/provider/oauth-login/complete": _SettingsRoute("models", "oauth-complete", "settings.provider.oauth_complete"), + "/api/settings/provider/oauth-logout": _SettingsRoute("models", "oauth-logout", "settings.provider.oauth_logout"), + "/api/settings/web-search/update": _SettingsRoute("capabilities", "web-search-update", "settings.web_search.update"), + "/api/settings/image-generation/update": _SettingsRoute("capabilities", "image-update", "settings.image_generation.update"), + "/api/settings/transcription/update": _SettingsRoute("capabilities", "transcription-update", "settings.transcription.update"), + "/api/settings/network-safety/update": _SettingsRoute("capabilities", "network-update", "settings.network_safety.update"), + "/api/settings/sandbox/check": _SettingsRoute("system", "sandbox-check", "settings.sandbox.check"), + "/api/settings/runtime-config/update": _SettingsRoute("system", "runtime-config-update", "settings.runtime_config.update"), + "/api/settings/cli-apps": _SettingsRoute("system", "cli-list"), + "/api/settings/cli-apps/install": _SettingsRoute("system", "cli-install", "settings.cli_app.install"), + "/api/settings/cli-apps/update": _SettingsRoute("system", "cli-update", "settings.cli_app.update"), + "/api/settings/cli-apps/uninstall": _SettingsRoute("system", "cli-uninstall", "settings.cli_app.uninstall"), + "/api/settings/cli-apps/test": _SettingsRoute("system", "cli-test", "settings.cli_app.test"), + "/api/settings/nanobot-features": _SettingsRoute("system", "features-list"), + "/api/settings/nanobot-features/enable": _SettingsRoute("system", "features-enable", "settings.feature.enable"), + "/api/settings/nanobot-features/disable": _SettingsRoute("system", "features-disable", "settings.feature.disable"), + "/api/settings/channels/validate": _SettingsRoute("system", "channel-validate", "settings.channel.validate"), + "/api/settings/channels/configure": _SettingsRoute("system", "channel-configure", "settings.channel.configure"), + "/api/settings/pairing": _SettingsRoute("system", "pairing-list"), + "/api/settings/pairing/approve": _SettingsRoute("system", "pairing-approve", "settings.pairing.approve"), + "/api/settings/pairing/deny": _SettingsRoute("system", "pairing-deny", "settings.pairing.deny"), + "/api/settings/mcp-presets": _SettingsRoute("system", "mcp-list"), + "/api/settings/version-check": _SettingsRoute("system", "version-check"), + "/api/settings/nanobot-update/channel": _SettingsRoute("system", "update-channel", "settings.nanobot.update.channel"), + "/api/settings/nanobot-update/plan": _SettingsRoute("system", "update-plan-read"), + "/api/settings/nanobot-update/plan/create": _SettingsRoute("system", "update-plan-create", "settings.nanobot.update.plan"), + "/api/settings/nanobot-update/job": _SettingsRoute("system", "update-job-read"), + "/api/settings/nanobot-update/job/prepare": _SettingsRoute("system", "update-job-prepare", "settings.nanobot.update.prepare"), + "/api/settings/nanobot-update/job/settle": _SettingsRoute("system", "update-job-settle", "settings.nanobot.update.settle"), + "/api/settings/nanobot-update/job/execute": _SettingsRoute("system", "update-job-execute", "settings.nanobot.update.execute"), + "/api/settings/nanobot-update/job/retry": _SettingsRoute("system", "update-job-retry", "settings.nanobot.update.retry"), + "/api/settings/mcp-presets/enable": _SettingsRoute("system", "mcp-enable", "settings.mcp.enable"), + "/api/settings/mcp-presets/disable": _SettingsRoute("system", "mcp-disable", "settings.mcp.disable"), + "/api/settings/mcp-presets/remove": _SettingsRoute("system", "mcp-remove", "settings.mcp.remove"), + "/api/settings/mcp-presets/test": _SettingsRoute("system", "mcp-test", "settings.mcp.test"), + "/api/settings/mcp-presets/reconnect": _SettingsRoute("system", "mcp-reconnect", "settings.mcp.reconnect"), + "/api/settings/mcp-presets/proxy": _SettingsRoute("system", "mcp-proxy", "settings.mcp.proxy"), + "/api/settings/mcp-presets/custom": _SettingsRoute("system", "mcp-custom", "settings.mcp.custom"), + "/api/settings/mcp-presets/import": _SettingsRoute("system", "mcp-import", "settings.mcp.import"), + "/api/settings/mcp-presets/import-cursor": _SettingsRoute("system", "mcp-import-cursor", "settings.mcp.import_cursor"), + "/api/settings/mcp-presets/tools": _SettingsRoute("system", "mcp-tools", "settings.mcp.tools"), + "/api/settings/mcp-oauth/start": _SettingsRoute("oauth", "start", "settings.mcp.oauth_start"), + "/api/settings/mcp-oauth/complete": _SettingsRoute("oauth", "complete", "settings.mcp.oauth_complete"), + "/api/settings/mcp-oauth/cancel": _SettingsRoute("oauth", "cancel", "settings.mcp.oauth_cancel"), } - -_SYSTEM_ROUTES = { - "/api/settings/sandbox/check": "sandbox-check", - "/api/settings/runtime-config/update": "runtime-config-update", - "/api/settings/cli-apps": "cli-list", - "/api/settings/cli-apps/install": "cli-install", - "/api/settings/cli-apps/update": "cli-update", - "/api/settings/cli-apps/uninstall": "cli-uninstall", - "/api/settings/cli-apps/test": "cli-test", - "/api/settings/nanobot-features": "features-list", - "/api/settings/nanobot-features/enable": "features-enable", - "/api/settings/nanobot-features/disable": "features-disable", - "/api/settings/channels/validate": "channel-validate", - "/api/settings/channels/configure": "channel-configure", - "/api/settings/pairing": "pairing-list", - "/api/settings/pairing/approve": "pairing-approve", - "/api/settings/pairing/deny": "pairing-deny", - "/api/settings/mcp-presets": "mcp-list", - "/api/settings/version-check": "version-check", - "/api/settings/nanobot-update/channel": "update-channel", - "/api/settings/nanobot-update/plan": "update-plan-read", - "/api/settings/nanobot-update/plan/create": "update-plan-create", - "/api/settings/nanobot-update/job": "update-job-read", - "/api/settings/nanobot-update/job/prepare": "update-job-prepare", - "/api/settings/nanobot-update/job/settle": "update-job-settle", - "/api/settings/nanobot-update/job/execute": "update-job-execute", - "/api/settings/nanobot-update/job/retry": "update-job-retry", - **{ - path: f"mcp-{action}" - for path, action in _MCP_PRESET_ACTIONS_BY_PATH.items() - }, -} - -_SETTINGS_MUTATION_PATHS = frozenset({ - "/api/settings/sandbox/check", - "/api/settings/nanobot-update/channel", - "/api/settings/nanobot-update/plan/create", - "/api/settings/nanobot-update/job/prepare", - "/api/settings/nanobot-update/job/settle", - "/api/settings/nanobot-update/job/execute", - "/api/settings/nanobot-update/job/retry", - "/api/settings/runtime-config/update", - "/api/settings/update", - "/api/settings/model-configurations/create", - "/api/settings/model-configurations/update", - "/api/settings/model-configurations/delete", - "/api/settings/model-configurations/migrate", - "/api/settings/model-call-order/update", - "/api/settings/provider/update", - "/api/settings/provider/create", - "/api/settings/provider/oauth-login", - "/api/settings/provider/oauth-login/complete", - "/api/settings/provider/oauth-logout", - "/api/settings/web-search/update", - "/api/settings/image-generation/update", - "/api/settings/transcription/update", - "/api/settings/network-safety/update", - "/api/settings/cli-apps/install", - "/api/settings/cli-apps/update", - "/api/settings/cli-apps/uninstall", - "/api/settings/cli-apps/test", - "/api/settings/nanobot-features/enable", - "/api/settings/nanobot-features/disable", - "/api/settings/channels/validate", - "/api/settings/channels/configure", - "/api/settings/pairing/approve", - "/api/settings/pairing/deny", - "/api/settings/mcp-oauth/start", - "/api/settings/mcp-oauth/complete", - "/api/settings/mcp-oauth/cancel", - *_MCP_PRESET_ACTIONS_BY_PATH, +_SETTINGS_WS_ROUTES = {route.mutation: route for route in _SETTINGS_ROUTES.values() if route.mutation} +_CHANNEL_CONNECT_WS = {f"settings.channel.connect.{action}": action for action in _CHANNEL_CONNECT_ACTIONS} +_CHANNEL_NAME_RE = re.compile(r"[A-Za-z0-9_-]{1,64}") +_LOCAL_BROWSER_ACTIONS = frozenset({ + "runtime-config-update", "features-enable", "channel-configure", "channel-connect", + "update-channel", "version-check", "update-plan-create", "update-plan-read", + "update-job-prepare", "update-job-settle", "update-job-execute", "update-job-retry", }) -def _mutation_payload(request: WsRequest) -> dict[str, Any] | None: - payload = getattr(request, _WEBUI_MUTATION_PAYLOAD_ATTR, None) - if not isinstance(payload, dict): - return None - return cast(dict[str, Any], payload) - - -def _query_value(value: Any) -> str: - if isinstance(value, bool): - return "true" if value else "false" - if value is None: - return "" - if isinstance(value, (dict, list)): - return json.dumps(value, ensure_ascii=False, separators=(",", ":")) - return str(value) - - -def _payload_query(payload: dict[str, Any]) -> QueryParams: - return { - key: [_query_value(value)] - for key, value in payload.items() - if key - and key not in {"authorization_response", "channel", "values"} - } - - class WebUISettingsRouter: """Authenticate and dispatch settings requests to transport-neutral domains.""" @@ -235,7 +179,7 @@ class WebUISettingsRouter: bus: MessageBus, logger: Any, check_api_token: Callable[[WsRequest], bool], - parse_query: Callable[[str], QueryParams], + parse_query: Callable[[str], HttpQuery], json_response: Callable[[dict[str, Any]], Response], error_response: Callable[[int, str | None], Response], runtime_surface: str, @@ -245,7 +189,7 @@ class WebUISettingsRouter: mcp_runtime_status: Callable[[], Mapping[str, str]] | None = None, mcp_reload: Callable[[], Awaitable[dict[str, Any]]] | None = None, image_generation_reload: Callable[[], Awaitable[dict[str, Any]]] | None = None, - mcp_oauth_redirect_uri: Callable[[WsRequest], str] | None = None, + mcp_oauth_redirect_uri: Callable[[Any], str] | None = None, ) -> None: self.settings = settings self.bus = bus @@ -272,6 +216,9 @@ class WebUISettingsRouter: logger, ) self._system = system_domain.SystemSettingsHandler(settings, logger, bus.admission) + self._model_ops = self._model_operations() + self._capability_ops = self._capability_operations() + self._system_ops = self._system_operations() async def close(self) -> None: """Release state owned by settings domains.""" @@ -285,84 +232,94 @@ class WebUISettingsRouter: request: WsRequest, path: str, ) -> Response | None: - if self.is_mutation_path(path) and not getattr( - request, - _WEBUI_MUTATION_REQUEST_ATTR, - False, - ): - return self._error_response( - 405, - "WebUI mutations require an authenticated WebSocket", - ) + if self.is_mutation_path(path): + return self._error_response(405, "WebUI mutations require an authenticated WebSocket") if path == MCP_OAUTH_CALLBACK_PATH: return self._handle_mcp_oauth_callback(request) - if path == "/api/settings/mcp-oauth/start": - return await self._handle_mcp_oauth_start(request) - if path == "/api/settings/mcp-oauth/status": - return await self._handle_mcp_oauth_status(request) - if path == "/api/settings/mcp-oauth/complete": - return self._handle_mcp_oauth_complete(request) - if path == "/api/settings/mcp-oauth/cancel": - return await self._handle_mcp_oauth_cancel(request) - - route = self._route(path) - if route is None: + if path not in {"/api/settings", "/api/settings/usage", "/api/settings/mcp-oauth/status"} and path not in _SETTINGS_ROUTES: return None if not self._authorized(request): return self._unauthorized() - if route == ("root", "settings"): + if path == "/api/settings/mcp-oauth/status": + return await self._handle_mcp_oauth_status(request) + if path == "/api/settings": return await asyncio.to_thread(self._handle_settings) - if route == ("root", "usage"): + if path == "/api/settings/usage": return await asyncio.to_thread(self._handle_settings_usage, request) - domain, action = route + route = _SETTINGS_ROUTES[path] + domain_request = SettingsRequest( + query=self._parse_query(request.path), + local_browser=self._local_browser_for(route.action, connection, request.headers), + ) + result = await self._dispatch_domain(route, domain_request) + response = self._render_result(result) + if route.action.startswith("update-") or route.action == "version-check": + # A saved review is immutable, but its local validity and permission are not. + response.headers["Cache-Control"] = "no-store" + return response + + async def dispatch_mutation( + self, connection: Any, headers: Any, action: str, params: MutationParams, + ) -> MutationResult: + """Dispatch a settings mutation after the WebSocket ingress has authenticated it.""" + route = _SETTINGS_WS_ROUTES.get(action) + channel_name: str | None = None + connect_action = _CHANNEL_CONNECT_WS.get(action) + if connect_action is not None: + channel_name = params.values.get("channel") + if not isinstance(channel_name, str) or _CHANNEL_NAME_RE.fullmatch(channel_name) is None: + return MutationResult.failure(400, "invalid channel name") + route = _SettingsRoute("system", "channel-connect") + if route is None: + return MutationResult.failure(404, "unknown WebUI mutation action") + if route.domain == "oauth": + if route.action == "start": + return await self._handle_mcp_oauth_start(headers, params) + if route.action == "complete": + return self._handle_mcp_oauth_complete(params) + return await self._handle_mcp_oauth_cancel(params) + + domain_request = SettingsRequest( + query=params, + payload=params.values, + local_browser=self._local_browser_for(route.action, connection, headers), + ) + result = await self._dispatch_domain( + route, domain_request, channel_name=channel_name, connect_action=connect_action, + ) + if result.error is not None: + return MutationResult.failure(result.status, result.error) + return MutationResult.success(self._result_payload(result), status=result.status) + + @staticmethod + def _local_browser_for(action: str, connection: Any, headers: Any) -> bool: + return action in _LOCAL_BROWSER_ACTIONS and _is_local_browser_request(connection, headers) + + async def _dispatch_domain( + self, + route: _SettingsRoute, + domain_request: SettingsRequest, + *, + channel_name: str | None = None, + connect_action: str | None = None, + ) -> SettingsRouteResult: + domain, action = route.domain, route.action if action.startswith("update-") and self._runtime_surface == "native": - return self._error_response(409, "Update this installation through Nanobot Desktop.") + return SettingsRouteResult.failure(409, "Update this installation through Nanobot Desktop.") restart_before = ( await asyncio.to_thread(self._restart_values, action) if action in {"runtime-config-update", "image-update", "web-search-update"} else None ) - domain_request = self._domain_request( - connection, - request, - needs_local_browser=( - action in { - "runtime-config-update", - "features-enable", - "channel-configure", - "channel-connect", - "update-channel", - "version-check", - "update-plan-create", - "update-plan-read", - "update-job-prepare", - "update-job-settle", - "update-job-execute", - "update-job-retry", - } - ), - ) if domain == "models": - result = await self._models.handle( - action, - domain_request, - self._model_operations(), - ) + result = await self._models.handle(action, domain_request, self._model_ops) elif domain == "capabilities": - result = await self._capabilities.handle( - action, - domain_request, - self._capability_operations(), - ) + result = await self._capabilities.handle(action, domain_request, self._capability_ops) else: - channel_connect = _channel_connect_route(path) result = await self._system.handle( - action, - domain_request, - self._system_operations(), - channel_name=(channel_connect[0] if channel_connect else None), - connect_action=(channel_connect[1] if channel_connect else None), + action, domain_request, self._system_ops, + channel_name=channel_name, connect_action=connect_action, ) if restart_before is not None and result.error is None and result.payload is not None: restart_after = await asyncio.to_thread(self._restart_values, action) @@ -384,12 +341,7 @@ class WebUISettingsRouter: self._restart_changes[action] = result.restart_section # Reversible changes are tracked separately from installation and reload failures. result.payload["requires_restart"] = False - response = self._render_result(result) - if action.startswith("update-") or action == "version-check": - # A saved review is immutable, but its local validity and permission - # are not. Never reuse a cached success after an installation changes. - response.headers["Cache-Control"] = "no-store" - return response + return result def _restart_values(self, action: str) -> dict[str, Any]: config = self.settings.config.load() @@ -401,46 +353,8 @@ class WebUISettingsRouter: @staticmethod def is_mutation_path(path: str) -> bool: - return path in _SETTINGS_MUTATION_PATHS or _channel_connect_route(path) is not None - - @staticmethod - def _route(path: str) -> tuple[str, str] | None: - if path == "/api/settings": - return "root", "settings" - if path == "/api/settings/usage": - return "root", "usage" - if action := _MODEL_ROUTES.get(path): - return "models", action - if action := _CAPABILITY_ROUTES.get(path): - return "capabilities", action - if action := _SYSTEM_ROUTES.get(path): - return "system", action - if _channel_connect_route(path) is not None: - return "system", "channel-connect" - return None - - def _query(self, request: WsRequest) -> QueryParams: - payload = _mutation_payload(request) - if payload is not None: - return _payload_query(payload) - return self._parse_query(request.path) - - def _domain_request( - self, - connection: Any, - request: WsRequest, - *, - needs_local_browser: bool, - ) -> SettingsRequest: - return SettingsRequest( - query=self._query(request), - payload=_mutation_payload(request), - local_browser=( - _is_local_browser_request(connection, request.headers) - if needs_local_browser - else False - ), - ) + route = _SETTINGS_ROUTES.get(path) + return (route is not None and route.mutation is not None) or _channel_connect_route(path) is not None def _authorized(self, request: WsRequest) -> bool: return self._check_api_token(request) @@ -470,6 +384,9 @@ class WebUISettingsRouter: def _render_result(self, result: SettingsRouteResult) -> Response: if result.error is not None: return self._error_response(result.status, result.error) + return self._json_response(self._result_payload(result)) + + def _result_payload(self, result: SettingsRouteResult) -> dict[str, Any]: assert result.payload is not None payload = result.payload if result.clear_restart_section: @@ -488,7 +405,7 @@ class WebUISettingsRouter: payload, section=result.restart_section, ) - return self._json_response(payload) + return payload def _handle_settings(self) -> Response: return self._json_response( @@ -511,7 +428,7 @@ class WebUISettingsRouter: if revision: etag = f'W/"{revision}"' headers.append(("ETag", etag)) - if request.headers.get("If-None-Match") == etag: + if etag_matches(case_insensitive_header(request.headers, "If-None-Match"), etag): return _http_response( b"", status=304, extra_headers=[*headers, ("Vary", "Accept-Encoding")], ) @@ -637,9 +554,6 @@ class WebUISettingsRouter: "error": str(exc), } - def _parse_mcp_settings_query(self, request: WsRequest) -> QueryParams: - return self._query(request) - def _save_channel_config_values( self, name: str, @@ -656,19 +570,16 @@ class WebUISettingsRouter: ) ) - async def _handle_mcp_oauth_start(self, request: WsRequest) -> Response: - if not self._authorized(request): - return self._unauthorized() + async def _handle_mcp_oauth_start(self, headers: Any, query: MutationParams) -> MutationResult: if self._mcp_oauth_redirect_uri is None: - return self._error_response(500, "MCP OAuth callback is not configured") - query = self._parse_mcp_settings_query(request) + return MutationResult.failure(500, "MCP OAuth callback is not configured") try: name, cfg, network = await asyncio.to_thread( self.settings.mutate, ensure_mcp_oauth_server, query, ) - redirect_uri = self._mcp_oauth_redirect_uri(request) + redirect_uri = self._mcp_oauth_redirect_uri(headers) reset = (_query_first(query, "reset") or "").lower() in {"1", "true", "yes"} payload = await self._mcp_oauth.start( name, @@ -679,56 +590,50 @@ class WebUISettingsRouter: reset_credentials=reset, ) except Exception as exc: - return self._mcp_oauth_error_response(exc, action="start") - return self._json_response(payload) + return self._mcp_oauth_failure(exc, action="start") + return MutationResult.success(payload) async def _handle_mcp_oauth_status(self, request: WsRequest) -> Response: - if not self._authorized(request): - return self._unauthorized() - flow_id = (_query_first(self._query(request), "flow_id") or "").strip() + flow_id = (_query_first(self._parse_query(request.path), "flow_id") or "").strip() if not flow_id: return self._error_response(400, "missing MCP OAuth flow ID") try: payload = await self._mcp_oauth.status(flow_id) except Exception as exc: - return self._mcp_oauth_error_response(exc, action="status") + failure = self._mcp_oauth_failure(exc, action="status") + return self._error_response(failure.status_code, failure.message) return self._json_response(payload) - def _handle_mcp_oauth_complete(self, request: WsRequest) -> Response: - if not self._authorized(request): - return self._unauthorized() - query = self._query(request) + def _handle_mcp_oauth_complete(self, query: MutationParams) -> MutationResult: flow_id = (_query_first(query, "flow_id") or "").strip() if not flow_id: - return self._error_response(400, "missing MCP OAuth flow ID") + return MutationResult.failure(400, "missing MCP OAuth flow ID") callback_url = (_query_first(query, "callback_url") or "").strip() if not callback_url: - return self._error_response(400, "Paste the complete callback URL to continue") + return MutationResult.failure(400, "Paste the complete callback URL to continue") if len(callback_url.encode("utf-8")) > _MCP_OAUTH_CALLBACK_URL_MAX_BYTES: - return self._error_response(400, "The MCP OAuth callback URL is too long") + return MutationResult.failure(400, "The MCP OAuth callback URL is too long") try: payload = self._mcp_oauth.submit_callback_url( flow_id=flow_id, callback_url=callback_url, ) except Exception as exc: - return self._mcp_oauth_error_response(exc, action="complete") - return self._json_response(payload) + return self._mcp_oauth_failure(exc, action="complete") + return MutationResult.success(payload) - async def _handle_mcp_oauth_cancel(self, request: WsRequest) -> Response: - if not self._authorized(request): - return self._unauthorized() - flow_id = (_query_first(self._query(request), "flow_id") or "").strip() + async def _handle_mcp_oauth_cancel(self, query: MutationParams) -> MutationResult: + flow_id = (_query_first(query, "flow_id") or "").strip() if not flow_id: - return self._error_response(400, "missing MCP OAuth flow ID") + return MutationResult.failure(400, "missing MCP OAuth flow ID") try: payload = await self._mcp_oauth.cancel(flow_id) except Exception as exc: - return self._mcp_oauth_error_response(exc, action="cancel") - return self._json_response(payload) + return self._mcp_oauth_failure(exc, action="cancel") + return MutationResult.success(payload) def _handle_mcp_oauth_callback(self, request: WsRequest) -> Response: - query = self._query(request) + query = self._parse_query(request.path) state = (_query_first(query, "state") or "").strip() if not state: return self._mcp_oauth_callback_page( @@ -751,7 +656,7 @@ class WebUISettingsRouter: message=f"Authorization received for {name}. Return to nanobot to finish connecting.", ) - def _mcp_oauth_error_response(self, exc: Exception, *, action: str) -> Response: + def _mcp_oauth_failure(self, exc: Exception, *, action: str) -> MutationResult: raw_status = getattr(exc, "status", 500) status = raw_status if isinstance(raw_status, int) and 400 <= raw_status <= 599 else 500 if status >= 500: @@ -760,7 +665,7 @@ class WebUISettingsRouter: else: raw_message = getattr(exc, "message", None) message = raw_message if isinstance(raw_message, str) else "MCP OAuth request failed" - return self._error_response(status, message) + return MutationResult.failure(status, message) @staticmethod def _mcp_oauth_callback_page( diff --git a/nanobot/webui/settings_system.py b/nanobot/webui/settings_system.py index 3e0c3dddf..36ca15917 100644 --- a/nanobot/webui/settings_system.py +++ b/nanobot/webui/settings_system.py @@ -51,6 +51,7 @@ from nanobot.update_service import ( ) from nanobot.webui.settings_capabilities import network_safety_payload from nanobot.webui.settings_contracts import ( + MutationParams, QueryParams, SettingsRequest, SettingsRouteResult, @@ -1088,7 +1089,16 @@ class SystemSettingsHandler: ) try: - payload = await connector.handle(action, request.query) + query = request.query + if isinstance(query, MutationParams): + # Channel connectors expose a scalar form interface, not structured JSON fields. + query = { + key: [value] + for key in query.values + if key not in {"channel", "values", "authorization_response"} + and (value := query_first(query, key)) is not None + } + payload = await connector.handle(action, query) except ChannelConnectError as exc: return SettingsRouteResult.failure(exc.status, exc.message) except Exception: diff --git a/nanobot/webui/transcript.py b/nanobot/webui/transcript.py index 10664831f..66c660588 100644 --- a/nanobot/webui/transcript.py +++ b/nanobot/webui/transcript.py @@ -1,7 +1,5 @@ from __future__ import annotations -import base64 -import binascii import hashlib import json import re @@ -11,7 +9,6 @@ import time import uuid from bisect import bisect_left from collections import OrderedDict -from dataclasses import dataclass from datetime import datetime from pathlib import Path from typing import Any, Callable, Mapping, NamedTuple, NotRequired, Sequence, TypedDict, cast @@ -32,7 +29,6 @@ from nanobot.session.history_graph import ( decode_graph, decode_snapshot, graph_decoding, - graph_size_adjustment, ) from nanobot.session.history_visibility import is_hidden_history_message from nanobot.session.manager import Session, SessionManager @@ -53,6 +49,34 @@ from nanobot.webui.history import ( from nanobot.webui.metadata import WEBUI_MESSAGE_SOURCE_METADATA_KEY, WEBUI_TURN_METADATA_KEY from nanobot.webui.outbound_wire import project_tool_events from nanobot.webui.session_identity import webui_session_key +from nanobot.webui.transcript_replay import ( + WEBUI_REPLAY_IDENTITY_KEY, + compact_completed_stream_deltas, + encode_page_cursor, + ensure_replay_identities, + parse_replay_identity, + projection_event_id, + read_trace_turn, + select_transcript_page, + split_transcript_turns, +) +from nanobot.webui.transcript_replay import ( + TranscriptReplayStats as TranscriptReplayStats, +) +from nanobot.webui.transcript_replay import ( + compact_legacy_records as compact_legacy_records, +) +from nanobot.webui.transcript_replay import ( + decode_transcript_cursor as decode_transcript_cursor, +) +from nanobot.webui.transcript_trace import ( + TraceProjection, + index_trace_projection, + parse_trace_detail_ref, +) +from nanobot.webui.transcript_trace import ( + tool_trace_lines_from_events as tool_trace_lines_from_events, +) WEBUI_TRANSCRIPT_SCHEMA_VERSION = 3 WEBUI_FORK_MARKER_EVENT = "fork_marker" @@ -63,10 +87,6 @@ _MAX_TRANSCRIPT_PAGE_RECORDS = 4_000 _MAX_TRANSCRIPT_PAGE_BYTES = 20 * 1024 * 1024 _MAX_INLINE_TRACE_DETAIL_BYTES = 32 * 1024 _WEBUI_TURN_ID_RE = re.compile(r"^[A-Za-z0-9._:-]{1,128}$") -_WEBUI_REPLAY_IDENTITY_KEY = "_webui_replay_identity" -_WEBUI_TRACE_DETAIL_REF_RE = re.compile( - r"^(?P\d{1,12})\.(?Phistory-[0-9a-f]{20})$" -) _MARKDOWN_LOCAL_IMAGE_RE = re.compile( r"!\[([^\]]*)\]\((<[^>]+>|[^)\s]+)(\s+(?:\"[^\"]*\"|'[^']*'))?\)" ) @@ -197,309 +217,18 @@ def webui_transcript_revision( return hashlib.sha256(encoded.encode("utf-8")).hexdigest()[:32] -class _TranscriptTurnRef(NamedTuple): - ordinal: int - records: list[dict[str, Any]] - start: int - end: int - total: int - - class _SessionBackfillTurn(NamedTuple): user_event: dict[str, Any] assistant_signature: tuple[str, ...] assistant_records: tuple[dict[str, Any], ...] -class _ProjectionReceipt(TypedDict): - turn_id: str - ranges: list[list[int]] - - -class _DeferredTraceGroup(NamedTuple): - start: int - stop: int - detail_bytes: int - trace_count: int - - -@dataclass(slots=True) -class TranscriptReplayStats: - """Selected-source page diagnostics; canonical recovery reads are separate.""" - - effective_limit: int = 0 - source_bytes: int = 0 - parsed_records: int = 0 - selected_bytes: int = 0 - selected_records: int = 0 - compacted_delta_records: int = 0 - replay_ms: int = 0 - capped_by_bytes: bool = False - capped_by_records: bool = False - truncated_oversized_turn: bool = False - - -def _record_json_line(record: dict[str, Any]) -> str: - return json.dumps(record, ensure_ascii=False, separators=(",", ":")) - - -def _records_bytes(records: list[dict[str, Any]]) -> int: - total = 0 - for record in records: - total += len(_record_json_line(record).encode("utf-8")) + graph_size_adjustment(record) + 1 - return total - - -def _stream_key(record: dict[str, Any], stream: str) -> tuple[str, str, str]: - raw_turn_id = record.get("turn_id") - turn_id = raw_turn_id if isinstance(raw_turn_id, str) else "" - raw_phase = record.get("turn_phase") - phase = raw_phase if isinstance(raw_phase, str) and raw_phase else stream - raw_stream_id = record.get("stream_id") - stream_id = raw_stream_id if isinstance(raw_stream_id, str) else "" - return turn_id, phase, stream_id - - -def _projection_receipts(records: Sequence[Mapping[str, Any]]) -> list[_ProjectionReceipt]: - members: dict[str, set[int]] = {} - for record in records: - turn_id, sequence = record.get("turn_id"), record.get("turn_seq") - if ( - isinstance(turn_id, str) and turn_id - and isinstance(sequence, int) and not isinstance(sequence, bool) and sequence >= 0 - ): - members.setdefault(turn_id, set()).add(sequence) - receipts: list[_ProjectionReceipt] = [] - for turn_id, sequences in members.items(): - ranges: list[list[int]] = [] - for sequence in sorted(sequences): - if ranges and ranges[-1][1] + 1 == sequence: - ranges[-1][1] = sequence - else: - ranges.append([sequence, sequence]) - receipts.append({"turn_id": turn_id, "ranges": ranges}) - return receipts - - -def _compact_completed_stream_deltas( - turn: list[dict[str, Any]], -) -> tuple[list[dict[str, Any]], int]: - if not turn or turn[-1].get("event") != "turn_end": - return turn, 0 - - pending: dict[tuple[str, str, str], list[tuple[int, dict[str, Any]]]] = {} - dropped_indexes: set[int] = set() - replacements: dict[int, dict[str, Any]] = {} - for index, record in enumerate(turn): - event = record.get("event") - if event in {"delta", "reasoning_delta"}: - stream = "answer" if event == "delta" else "reasoning" - pending.setdefault(_stream_key(record, stream), []).append((index, record)) - continue - if event not in {"stream_end", "reasoning_end"}: - continue - stream = "answer" if event == "stream_end" else "reasoning" - chunks = pending.pop(_stream_key(record, stream), []) - if not chunks: - continue - completed = dict(record) - # The sealed snapshot is authoritative even when media rewriting changes - # its text. Only old ends without text need their preceding fragments. - if not isinstance(completed.get("text"), str): - completed["text"] = "".join(str(chunk.get("text") or "") for _, chunk in chunks) - replacements[index] = completed - dropped_indexes.update(chunk_index for chunk_index, _ in chunks) - - if not dropped_indexes: - return turn, 0 - return [ - replacements.get(index, record) - for index, record in enumerate(turn) - if index not in dropped_indexes - ], len(dropped_indexes) - - -def _compact_completed_turns( - turns: list[list[dict[str, Any]]], -) -> tuple[list[list[dict[str, Any]]], int]: - compacted: list[list[dict[str, Any]]] = [] - dropped = 0 - for turn in turns: - next_turn, turn_dropped = _compact_completed_stream_deltas(turn) - compacted.append(next_turn) - dropped += turn_dropped - return compacted, dropped - - - - -def compact_legacy_records(records: list[dict[str, Any]]) -> list[dict[str, Any]]: - turns, _ = _compact_completed_turns(_split_transcript_turns(records)) - return [record for turn in turns for record in turn] - - -def _records_with_replay_identity( - records: list[dict[str, Any]], - *, - turn_ordinal: int, -) -> list[dict[str, Any]]: - return [ - { - **record, - _WEBUI_REPLAY_IDENTITY_KEY: record.get(_WEBUI_REPLAY_IDENTITY_KEY, f"turn:{turn_ordinal}:record:{record_index}"), - } - for record_index, record in enumerate(records) - ] - - -class _PageCursor(NamedTuple): - turn: int - position: int = 0 - - -def _encode_page_cursor(before_turn_ordinal: int, position: int = 0) -> str: - data = {"before_turn": before_turn_ordinal} - if position: - data["position"] = position - raw = json.dumps( - data, - separators=(",", ":"), - ensure_ascii=False, - ).encode("utf-8") - return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=") - - -def decode_transcript_cursor(value: str | None) -> _PageCursor | None: - if not value: - return None - try: - padded = value + "=" * (-len(value) % 4) - data = json.loads(base64.urlsafe_b64decode(padded.encode("ascii")).decode("utf-8")) - except (binascii.Error, json.JSONDecodeError, UnicodeDecodeError, ValueError): - return None - if not isinstance(data, dict): - return None - cursor_data = cast(dict[str, Any], data) - before_turn = cursor_data.get("before_turn") - position = cursor_data.get("position", 0) - if ( - isinstance(before_turn, bool) or not isinstance(before_turn, int) or before_turn < 0 - or isinstance(position, bool) or not isinstance(position, int) or position < 0 - ): - return None - return _PageCursor(before_turn, position) - - def _coerce_page_limit(limit: int | None) -> int: if limit is None: return _DEFAULT_TRANSCRIPT_PAGE_LIMIT return max(1, min(_MAX_TRANSCRIPT_PAGE_LIMIT, int(limit))) -def _transcript_turn_at_ordinal( - ordinal: int, *, history: HistoryReader, -) -> list[dict[str, Any]] | None: - ref = next(history.turns(before=ordinal + 1, after=ordinal), None) - if ref is None or ref.record_count > _MAX_TRANSCRIPT_PAGE_RECORDS or ref.byte_count > _MAX_TRANSCRIPT_PAGE_BYTES: - return None - records, start, end, _ = turn_record_page( - history, ordinal, start=0, end=ref.record_count, reverse=False, - max_records=_MAX_TRANSCRIPT_PAGE_RECORDS, max_bytes=_MAX_TRANSCRIPT_PAGE_BYTES, - ) - return records if start == 0 and end == ref.record_count else None - - -def _select_transcript_page( - *, history: HistoryReader, limit: int | None, - before: str | None, after: str | None = None, stats: TranscriptReplayStats | None = None, -) -> tuple[list[dict[str, Any]], dict[str, Any]]: - stats = stats or TranscriptReplayStats() - page_limit = _coerce_page_limit(limit) - stats.effective_limit = page_limit - total_turns = history.turn_count - before_cursor = decode_transcript_cursor(before) - after_cursor = decode_transcript_cursor(after) - forward = after_cursor is not None - upper = total_turns - if before_cursor is not None: - upper = min(before_cursor.turn + int(before_cursor.position > 0), total_turns) - lower = min(after_cursor.turn, total_turns) if after_cursor is not None else 0 - selected: list[_TranscriptTurnRef] = [] - event_count = record_count = byte_count = 0 - for ref in history.turns(before=upper, after=lower, reverse=not forward): - start, end = 0, ref.record_count - if after_cursor is not None and ref.ordinal == after_cursor.turn: - start = min(after_cursor.position, end) - if before_cursor is not None and ref.ordinal == before_cursor.turn: - end = min(before_cursor.position, end) - if start >= end: - continue - requested_partial = start > 0 or end < ref.record_count - exceeds_records = record_count + end - start > _MAX_TRANSCRIPT_PAGE_RECORDS - exceeds_bytes = byte_count + ref.byte_count > _MAX_TRANSCRIPT_PAGE_BYTES - stats.capped_by_records |= exceeds_records - stats.capped_by_bytes |= exceeds_bytes - if selected and (requested_partial or exceeds_records or exceeds_bytes): - break - remaining_records = _MAX_TRANSCRIPT_PAGE_RECORDS - record_count - remaining_bytes = _MAX_TRANSCRIPT_PAGE_BYTES - byte_count - turn, first_position, end_position, source_bytes = turn_record_page( - history, ref.ordinal, start=start, end=end, reverse=not forward, - max_records=remaining_records, max_bytes=remaining_bytes, - allow_oversized=not selected, - ) - stats.parsed_records += len(turn) - stats.source_bytes += source_bytes - if source_bytes > remaining_bytes or (len(turn) < end - start and len(turn) < remaining_records): - stats.capped_by_bytes = True - if not turn: - break - partial = first_position > 0 or end_position < ref.record_count - # A partial turn is always a page of its own, even when a size estimate - # from older stored metadata understated the actual encoded bytes. - if selected and partial: - break - raw_count = len(turn) - if partial: - stats.truncated_oversized_turn = True - else: - turn, dropped = _compact_completed_stream_deltas(turn) - stats.compacted_delta_records += dropped - selected.append(_TranscriptTurnRef(ref.ordinal, turn, first_position, end_position, ref.record_count)) - record_count += raw_count - byte_count += source_bytes - event_count += _client_projection_page_event_count(turn) - if partial or event_count >= page_limit: - break - chronological = selected if forward else list(reversed(selected)) - records = [record for ref in chronological for record in _records_with_replay_identity( - ref.records, turn_ordinal=ref.ordinal, - )] - stats.selected_records, stats.selected_bytes = len(records), _records_bytes(records) - if not chronological: - return [], {"before_cursor": None, "has_more_before": False, "after_cursor": None, - "has_more_after": False, "loaded_event_count": 0, "user_message_offset": 0} - first, last = chronological[0], chronological[-1] - has_more_before = first.start > 0 or first.ordinal > 0 - has_more_after = last.end < last.total or last.ordinal + 1 < total_turns - revision = history.revision - page: dict[str, Any] = { - "history_generation": revision[0] if revision is not None else None, - "before_cursor": _encode_page_cursor(first.ordinal, first.start) if has_more_before else None, - "has_more_before": has_more_before, - "after_cursor": ( - _encode_page_cursor(last.ordinal, last.end) if last.end < last.total - else _encode_page_cursor(last.ordinal + 1) if has_more_after else None - ), - "has_more_after": has_more_after, "loaded_event_count": 0, - "user_message_offset": history.user_count_before(first.ordinal, first.start), - } - if first.start > 0 or first.end < first.total: - page["truncated_oversized_turn"] = True - page["record_range"] = {"turn": first.ordinal, "start": first.start, "end": first.end} - return records, page - - def read_transcript_lines(session_key: str, *, history: HistoryReader) -> list[dict[str, Any]]: return [record_from_fact(fact, session_key) for fact in history.all_facts()] @@ -872,9 +601,9 @@ def _session_user_event( if isinstance(input_id, str) and _WEBUI_TURN_ID_RE.fullmatch(input_id): event["turn_id"] = input_id event["turn_phase"] = "user" - event[_WEBUI_REPLAY_IDENTITY_KEY] = f"input:{session_key}:{input_id}" + event[WEBUI_REPLAY_IDENTITY_KEY] = f"input:{session_key}:{input_id}" elif canonical_position is not None: - event[_WEBUI_REPLAY_IDENTITY_KEY] = f"canonical:{session_key}:message:{canonical_position}" + event[WEBUI_REPLAY_IDENTITY_KEY] = f"canonical:{session_key}:message:{canonical_position}" return event @@ -958,75 +687,6 @@ def _session_backfill_turns( return turns -def _split_transcript_turns(lines: list[dict[str, Any]]) -> list[list[dict[str, Any]]]: - turns: list[list[dict[str, Any]]] = [] - current: list[dict[str, Any]] = [] - for rec in lines: - current.append(rec) - if rec.get("event") == "turn_end": - turns.append(current) - current = [] - if current: - turns.append(current) - return turns - - -def _stable_record_digest(record: dict[str, Any]) -> str: - persisted = { - key: value - for key, value in record.items() - if key != _WEBUI_REPLAY_IDENTITY_KEY - } - raw = json.dumps( - persisted, - ensure_ascii=False, - separators=(",", ":"), - sort_keys=True, - default=str, - ) - return hashlib.sha256(raw.encode("utf-8")).hexdigest()[:16] - - -def _ensure_replay_identities(lines: list[dict[str, Any]]) -> list[dict[str, Any]]: - annotated: list[dict[str, Any]] = [] - for fallback_turn_index, turn in enumerate(_split_transcript_turns(lines)): - anchor = next( - ( - value - for record in turn - if isinstance( - value := record.get(_WEBUI_REPLAY_IDENTITY_KEY), - str, - ) - and value - ), - None, - ) - if anchor and ":record:" in anchor: - turn_identity = anchor.rsplit(":record:", 1)[0] - else: - turn_digest = hashlib.sha256( - "\n".join(_stable_record_digest(record) for record in turn).encode("ascii") - ).hexdigest()[:16] - turn_identity = f"legacy:{fallback_turn_index}:{turn_digest}" - synthetic_occurrences: dict[str, int] = {} - for record in turn: - identity = record.get(_WEBUI_REPLAY_IDENTITY_KEY) - if isinstance(identity, str) and identity: - annotated.append(record) - continue - digest = _stable_record_digest(record) - occurrence = synthetic_occurrences.get(digest, 0) - synthetic_occurrences[digest] = occurrence + 1 - annotated.append({ - **record, - _WEBUI_REPLAY_IDENTITY_KEY: ( - f"{turn_identity}:synthetic:{digest}:{occurrence}" - ), - }) - return annotated - - def _transcript_turn_signature(records: list[dict[str, Any]]) -> tuple[str, ...]: texts: list[str] = [] stream_parts: list[str] = [] @@ -1135,7 +795,7 @@ def _recover_incomplete_turns( session_turns: list[_SessionBackfillTurn], ) -> list[dict[str, Any]]: recovered: list[dict[str, Any]] = [] - for turn in _split_transcript_turns(lines): + for turn in split_transcript_turns(lines): turn_end = turn[-1] if turn else None if ( not isinstance(turn_end, dict) @@ -1170,7 +830,7 @@ def _needs_user_event_backfill( return any(not history.has_input(input_id) for input_id in referenced_inputs) or legacy and any( not any(record.get("event") == "user" or isinstance(record.get("response_input_ids"), list) for record in turn) and _transcript_turn_signature(turn) - for turn in _split_transcript_turns(display_lines) + for turn in split_transcript_turns(display_lines) ) @@ -1197,50 +857,6 @@ def _with_backfilled_user( return records -def _format_tool_call_trace(call: Any) -> str | None: - if not call or not isinstance(call, dict): - return None - call_data = cast(dict[str, Any], call) - fn = call_data.get("function") - function_data = cast(dict[str, Any], fn) if isinstance(fn, dict) else None - name = function_data.get("name") if function_data is not None else None - if not isinstance(name, str) or not name: - raw_name = call_data.get("name") - name = raw_name if isinstance(raw_name, str) else "" - if not name: - return None - args = ( - function_data.get("arguments") if function_data is not None else None - ) or call_data.get("arguments") - if isinstance(args, str) and args.strip(): - return f"{name}({args})" - if args and isinstance(args, dict): - return f"{name}({json.dumps(args, ensure_ascii=False)})" - return f"{name}()" - - -def tool_trace_lines_from_events(events: Any) -> list[str]: - if not isinstance(events, list): - return [] - lines: list[str] = [] - seen: set[str] = set() - for event in cast(list[Any], events): - if not event or not isinstance(event, dict): - continue - tool_event = cast(dict[str, Any], event) - if tool_event.get("phase") not in {"start", "end", "error"}: - continue - call_id = tool_event.get("call_id") - if isinstance(call_id, str) and call_id: - if call_id in seen: - continue - seen.add(call_id) - t = _format_tool_call_trace(tool_event) - if t: - lines.append(t) - return lines - - def _normalize_tool_events(events: Any) -> list[dict[str, Any]]: if not isinstance(events, list): return [] @@ -1281,28 +897,6 @@ def _media_from_signed_urls(value: Any) -> list[dict[str, Any]]: return media -def _trace_detail_ref(message_id: str, record: Mapping[str, Any]) -> str | None: - identity = record.get(_WEBUI_REPLAY_IDENTITY_KEY) - if not isinstance(identity, str): - return None - match = re.match(r"^turn:(\d+):record:", identity) - return f"{match.group(1)}.{message_id}" if match else None - - -def _truncate_utf8(value: str, max_bytes: int) -> str: - encoded = value.encode("utf-8") - if len(encoded) <= max_bytes: - return value - return encoded[: max_bytes - 3].decode("utf-8", errors="ignore") + "…" - - -def _trace_summary(line: str) -> str: - if len(line.encode("utf-8")) <= 512: - return line - match = re.match(r"^([A-Za-z0-9_.-]+)\(", line.strip()) - return f"{_truncate_utf8(match.group(1), 240)}(…)" if match else _truncate_utf8(line, 240) - - def has_pending_tool_calls( lines: list[dict[str, Any]], *, @@ -1383,44 +977,18 @@ def build_webui_trace_detail_response( *, history: HistoryReader, ) -> dict[str, Any] | None: """Resolve one deferred activity group as canonical projection events.""" - match = _WEBUI_TRACE_DETAIL_REF_RE.fullmatch(detail_ref) - if match is None: + identity = parse_trace_detail_ref(detail_ref) + if identity is None: return None - ordinal = int(match.group("turn")) - message_id = match.group("message") - turn = _transcript_turn_at_ordinal(ordinal, history=history) + ordinal, message_id = identity + turn = read_trace_turn( + ordinal, history=history, + max_records=_MAX_TRANSCRIPT_PAGE_RECORDS, max_bytes=_MAX_TRANSCRIPT_PAGE_BYTES, + ) if turn is None: return None - turn, _ = _compact_completed_stream_deltas(turn) - lines = _records_with_replay_identity(turn, turn_ordinal=ordinal) - for group in _client_projection_deferred_trace_groups(lines).values(): - first = lines[group.start] - if _client_projection_event_id(first) != message_id: - continue - events = [ - event - for record in lines[group.start:group.stop] - if record.get("event") != "model_request" and ( - event := _client_projection_event( - record, - augment_user_media=None, - augment_assistant_media=None, - augment_assistant_text=None, - ) - ) is not None - ] - return {"message_id": message_id, "events": events} - return None - - -def _client_projection_event_id(record: Mapping[str, Any]) -> str: - identity = record.get(_WEBUI_REPLAY_IDENTITY_KEY) - if record.get("event") == "user" and isinstance(input_id := record.get("input_id"), str) and input_id: - identity = f"input:{record.get('chat_id')}:{input_id}" - if not isinstance(identity, str) or not identity: - identity = _stable_record_digest(dict(record)) - digest = hashlib.sha256(f"event\0{identity}".encode("utf-8")).hexdigest()[:20] - return f"history-{digest}" + lines, _ = compact_completed_stream_deltas(turn) + return _index_trace_projection(lines).detail(message_id) def _client_projection_turn_fields(record: Mapping[str, Any]) -> dict[str, Any]: @@ -1442,7 +1010,7 @@ def _client_projection_turn_fields(record: Mapping[str, Any]) -> dict[str, Any]: def _client_projection_common_fields(record: dict[str, Any]) -> dict[str, Any]: fields: dict[str, Any] = { "chat_id": str(record.get("chat_id") or ""), - "projection_id": _client_projection_event_id(record), + "projection_id": projection_event_id(record), **_client_projection_turn_fields(record), } created_at_ms = _valid_created_at_ms(record.get("created_at_ms")) @@ -1468,6 +1036,28 @@ def _client_projection_source(record: dict[str, Any]) -> dict[str, Any] | None: return projected +def _augment_projected_message( + record: dict[str, Any], projected: dict[str, Any], *, + augment_media: Callable[[list[str]], list[dict[str, Any]]] | None, + augment_text: Callable[[str], str] | None, + cached: bool = False, +) -> None: + if augment_text is not None and projected.get("render_as") != "text": + projected["text"] = augment_text(projected["text"]) + if augment_media is not None and isinstance(raw_media := record.get("media"), list): + paths = [path for path in cast(list[object], raw_media) if isinstance(path, str) and path] + if paths: + # When re-signing local paths, do not fall back to stale signed URLs. + media = augment_media(paths) + if media: + projected["media_urls"] = media + else: + projected.pop("media_urls", None) + return + if not cached and (media := _media_from_signed_urls(record.get("media_urls"))): + projected["media_urls"] = media + + def _client_projection_event( record: dict[str, Any], *, @@ -1546,8 +1136,6 @@ def _client_projection_event( text = record.get("text") content = text if isinstance(text, str) else "" render_as_text = record.get("render_as") == "text" - if not render_as_text and augment_assistant_text is not None: - content = augment_assistant_text(content) projected = {"event": "message", **common, "text": content} if render_as_text: projected["render_as"] = "text" @@ -1557,21 +1145,9 @@ def _client_projection_event( tool_events = _normalize_tool_events(record.get("tool_events")) if tool_events: projected["tool_events"] = tool_events - raw_media = record.get("media") - media_paths = [ - path - for path in cast(list[Any], raw_media) - if isinstance(path, str) and path - ] if isinstance(raw_media, list) else [] - media = ( - augment_assistant_media(media_paths) - if media_paths and augment_assistant_media is not None - else [] + _augment_projected_message( + record, projected, augment_media=augment_assistant_media, augment_text=augment_assistant_text, ) - if not media and (not media_paths or augment_assistant_media is None): - media = _media_from_signed_urls(record.get("media_urls")) - if media: - projected["media_urls"] = media latency_ms = record.get("latency_ms") if isinstance(latency_ms, int | float) and latency_ms >= 0: projected["latency_ms"] = int(latency_ms) @@ -1664,78 +1240,14 @@ def _client_projection_event( return None -def _client_projection_deferred_trace_groups( - lines: list[dict[str, Any]], -) -> dict[int, _DeferredTraceGroup]: - groups: dict[int, _DeferredTraceGroup] = {} - start: int | None = None - detail_bytes = 0 - trace_count = 0 - - def flush(stop: int) -> None: - nonlocal start, detail_bytes, trace_count - if ( - start is not None - and detail_bytes > _MAX_INLINE_TRACE_DETAIL_BYTES - ): - groups[start] = _DeferredTraceGroup( - start=start, - stop=stop, - detail_bytes=detail_bytes, - trace_count=max(1, trace_count), - ) - start = None - detail_bytes = 0 - trace_count = 0 - - for index, record in enumerate(lines): - # Usage belongs to the turn, not the activity body. It must not split - # one deferred tool group into many eagerly loaded fragments. - if record.get("event") == "model_request": - continue - is_activity = ( - record.get("event") == "message" - and record.get("kind") in {"tool_hint", "progress"} - ) - if not is_activity: - flush(index) - continue - event = _client_projection_event( - record, - augment_user_media=None, - augment_assistant_media=None, - augment_assistant_text=None, - ) - if event is None: - flush(index) - continue - if start is None: - start = index - detail_bytes += len(_record_json_line(event).encode("utf-8")) - tool_events = _normalize_tool_events(record.get("tool_events")) - traces = tool_trace_lines_from_events(tool_events) - if traces: - trace_count += len(traces) - elif not tool_events and isinstance(record.get("text"), str) and record["text"]: - trace_count += 1 - flush(len(lines)) - return groups +def _project_trace_event(record: dict[str, Any]) -> dict[str, Any] | None: + return _client_projection_event( + record, augment_user_media=None, augment_assistant_media=None, augment_assistant_text=None, + ) -def _client_projection_page_event_count(turn: list[dict[str, Any]]) -> int: - supported = { - "user", - "delta", - "stream_end", - "reasoning_delta", - "reasoning_end", - "message", - "file_edit", - "context_compaction", - "model_request", - "turn_end", - } - return max(1, sum(record.get("event") in supported for record in turn)) +def _index_trace_projection(lines: list[dict[str, Any]]) -> TraceProjection: + return index_trace_projection(lines, _project_trace_event, max_inline_bytes=_MAX_INLINE_TRACE_DETAIL_BYTES) def _client_projection_events( @@ -1748,7 +1260,7 @@ def _client_projection_events( ) -> tuple[list[dict[str, Any]], int | None]: events: list[dict[str, Any]] = [] fork_boundary_event_index: int | None = None - deferred_groups = _client_projection_deferred_trace_groups(lines) if defer_traces else {} + traces = _index_trace_projection(lines) if defer_traces else None deferred_until = 0 for index, record in enumerate(lines): if index < deferred_until and record.get("event") != "model_request": @@ -1757,39 +1269,24 @@ def _client_projection_events( if fork_boundary_event_index is None: fork_boundary_event_index = len(events) continue - event = _client_projection_event( - record, - augment_user_media=augment_user_media, - augment_assistant_media=augment_assistant_media, - augment_assistant_text=augment_assistant_text, - ) + cached = traces.events.get(index) if traces is not None else None + if cached is not None: + event = cached + _augment_projected_message( + record, event, augment_media=augment_assistant_media, + augment_text=augment_assistant_text, cached=True, + ) + else: + event = _client_projection_event( + record, + augment_user_media=augment_user_media, + augment_assistant_media=augment_assistant_media, + augment_assistant_text=augment_assistant_text, + ) if event is None: continue - group = deferred_groups.get(index) - if group is not None: - detail_ref = _trace_detail_ref(_client_projection_event_id(record), record) - last_text = next( - ( - text - for grouped in reversed(lines[group.start:group.stop]) - if isinstance((text := grouped.get("text")), str) and text - ), - "", - ) - event["text"] = _trace_summary(last_text) - event.pop("tool_events", None) - receipts = _projection_receipts([ - grouped for grouped in lines[group.start:group.stop] - if grouped.get("event") != "model_request" - ]) - if receipts: - event["projection_receipts"] = receipts - if detail_ref is not None: - event["trace_detail"] = { - "ref": detail_ref, - "bytes": group.detail_bytes, - "traceCount": group.trace_count, - } + if traces is not None and (group := traces.groups.get(index)) is not None: + traces.summarize(lines, group, event) deferred_until = group.stop events.append(event) return events, fork_boundary_event_index @@ -1849,13 +1346,13 @@ def build_session_thread_response( "activity" if record["event"] == "file_edit" or record.get("kind") in {"progress", "tool_hint"} else "answer", "created_at_ms": created_at_ms, - _WEBUI_REPLAY_IDENTITY_KEY: f"session:{session.key}:{index}:{offset}", + WEBUI_REPLAY_IDENTITY_KEY: f"session:{session.key}:{index}:{offset}", }) rows.append(record) if not active and rows: rows.append({"event": "turn_end", "chat_id": chat_id, "turn_id": turn_id, "latency_ms": latency_ms, - _WEBUI_REPLAY_IDENTITY_KEY: f"session:{session.key}:end"}) + WEBUI_REPLAY_IDENTITY_KEY: f"session:{session.key}:end"}) events = [event for record in rows if (event := _client_projection_event( record, augment_user_media=augment_user_media, augment_assistant_media=augment_assistant_media, augment_assistant_text=augment_assistant_text, @@ -1888,9 +1385,11 @@ def build_webui_thread_response( ) -> dict[str, Any] | None: """Return canonical events, hiding additive request events from old clients.""" replay_stats = stats or TranscriptReplayStats() - lines, page = _select_transcript_page( + lines, page = select_transcript_page( history=history, - limit=limit, + page_limit=_coerce_page_limit(limit), + max_records=_MAX_TRANSCRIPT_PAGE_RECORDS, + max_bytes=_MAX_TRANSCRIPT_PAGE_BYTES, before=before, after=after, stats=replay_stats, @@ -1922,14 +1421,19 @@ def build_webui_thread_response( ) backfill_plan = view.backfill_plan recovered_lines: list[dict[str, Any]] = [] - for turn in _split_transcript_turns(lines): - ordinal = int(turn[0][_WEBUI_REPLAY_IDENTITY_KEY].split(":")[1]) + for turn in split_transcript_turns(lines): + first_identity = parse_replay_identity(turn[0].get(WEBUI_REPLAY_IDENTITY_KEY)) + if first_identity is None: + recovered_lines.extend(turn) + continue + ordinal = first_identity[0] for anchor, user in backfill_plan.get(ordinal, []): if record_range is not None and not record_range["start"] <= anchor < record_range["end"]: continue index = next((i for i, record in enumerate(turn) - if (identity := record.get(_WEBUI_REPLAY_IDENTITY_KEY, "")).startswith(f"turn:{ordinal}:record:") - and int(identity.rsplit(":", 1)[1]) >= anchor), len(turn)) + if (parsed := parse_replay_identity(record.get(WEBUI_REPLAY_IDENTITY_KEY))) is not None + and parsed[0] == ordinal + and parsed[1] >= anchor), len(turn)) turn.insert(index, dict(user)) recovered_lines.extend(turn) lines = recovered_lines @@ -1944,7 +1448,7 @@ def build_webui_thread_response( incomplete = history.incomplete_completion_marker(ordinal, ref.record_count - 1) if incomplete and (position := history.unique_user_position(ordinal)) is not None: identity = f"turn:{ordinal}:record:{position}" - user = next((record for record in lines if record.get(_WEBUI_REPLAY_IDENTITY_KEY) == identity), None) + user = next((record for record in lines if record.get(WEBUI_REPLAY_IDENTITY_KEY) == identity), None) if user is None: records, _, _, _ = turn_record_page( history, ordinal, start=position, end=position + 1, reverse=False, @@ -1986,7 +1490,7 @@ def build_webui_thread_response( and record.get("turn_id") in shell_turns else record for record in lines ] - lines = _ensure_replay_identities(lines) + lines = ensure_replay_identities(lines) payload: dict[str, Any] = { "schemaVersion": WEBUI_TRANSCRIPT_SCHEMA_VERSION, "sessionKey": session_key, @@ -2073,12 +1577,12 @@ def _prompt_summary( record: dict[str, Any], ordinal: int, answer: str, position: int = 0, ) -> PromptSummary: return { - "id": _client_projection_event_id(record), + "id": projection_event_id(record), "inputId": str(record.get("input_id") or ""), "preview": str(record.get("text") or "").strip()[:320], "answerPreview": answer, "createdAt": _valid_created_at_ms(record.get("created_at_ms")) or 0, - "cursor": _encode_page_cursor(ordinal, position), + "cursor": encode_page_cursor(ordinal, position), "turnId": str(record.get("turn_id") or ""), } @@ -2092,7 +1596,7 @@ def _history_prompt_summaries(history: HistoryReader) -> _ChunkPromptView: turns: dict[int, list[dict[str, Any]]] = {} for ordinal, position, fact in history.navigation(): record = record_from_fact(fact, history.key) - record[_WEBUI_REPLAY_IDENTITY_KEY] = f"turn:{ordinal}:record:{position}" + record[WEBUI_REPLAY_IDENTITY_KEY] = f"turn:{ordinal}:record:{position}" turns.setdefault(ordinal, []).append(record) if record.get("event") in {"message", "stream_end"} and not record.get("kind"): if isinstance(references := record.get("response_input_ids"), list): @@ -2114,7 +1618,7 @@ def _history_prompt_summaries(history: HistoryReader) -> _ChunkPromptView: for index, record in enumerate(records): if record.get("event") != "user": continue - position = int(record[_WEBUI_REPLAY_IDENTITY_KEY].rsplit(":", 1)[1]) + position = int(record[WEBUI_REPLAY_IDENTITY_KEY].rsplit(":", 1)[1]) input_id = record.get("input_id") if isinstance(input_id, str) and input_id: input_ids.add(input_id) @@ -2214,18 +1718,18 @@ def _build_prompt_view( plan: dict[int, list[tuple[int, dict[str, Any]]]] = {} for ordinal, records in chunk.turns.items(): users = backfilled_users.get(ordinal, []) - recovered_ids = {_client_projection_event_id(user) for user in users} + recovered_ids = {projection_event_id(user) for user in users} for user in users: records = _with_backfilled_user(records, user) next_anchor = 2**63 - 1 reverse_plan: list[tuple[int, dict[str, Any]]] = [] for position in range(len(records) - 1, -1, -1): record = records[position] - identity = record.get(_WEBUI_REPLAY_IDENTITY_KEY, "") + identity = record.get(WEBUI_REPLAY_IDENTITY_KEY, "") if identity.startswith(f"turn:{ordinal}:record:"): next_anchor = int(identity.rsplit(":", 1)[1]) if record.get("event") == "user": - event_id = _client_projection_event_id(record) + event_id = projection_event_id(record) order[(ordinal, event_id)] = position if event_id in recovered_ids: anchor = next_anchor if any("response_input_ids" in item for item in records) else 0 @@ -2235,8 +1739,8 @@ def _build_prompt_view( for ordinal, prompt, user in entries: if user is not None: anchor = next(anchor for anchor, record in plan[ordinal] - if _client_projection_event_id(record) == prompt["id"]) - prompt["cursor"] = _encode_page_cursor(ordinal, anchor) + if projection_event_id(record) == prompt["id"]) + prompt["cursor"] = encode_page_cursor(ordinal, anchor) entries.sort(key=lambda entry: (entry[0], order.get((entry[0], entry[1]["id"]), 0))) return _PromptView(tuple(prompt for _, prompt, _ in entries), plan, needs_canonical) diff --git a/nanobot/webui/transcript_replay.py b/nanobot/webui/transcript_replay.py new file mode 100644 index 000000000..a4feada52 --- /dev/null +++ b/nanobot/webui/transcript_replay.py @@ -0,0 +1,402 @@ +"""Cursor, source page budgets, and stable replay record identity.""" + +from __future__ import annotations + +import base64 +import binascii +import hashlib +import json +import re +from dataclasses import dataclass, field +from typing import Any, Callable, Mapping, NamedTuple, NotRequired, TypedDict, cast + +from nanobot.session.display_history import HistoryReader +from nanobot.session.history_graph import graph_size_adjustment +from nanobot.webui.history import turn_record_page + +WEBUI_REPLAY_IDENTITY_KEY = "_webui_replay_identity" + + +class _RecordRange(TypedDict): + turn: int + start: int + end: int + + +class ReplayPage(TypedDict): + before_cursor: str | None + has_more_before: bool + after_cursor: str | None + has_more_after: bool + loaded_event_count: int + user_message_offset: int + history_generation: NotRequired[str | None] + truncated_oversized_turn: NotRequired[bool] + record_range: NotRequired[_RecordRange] + recovered_answers: NotRequired[bool] + + +class _TranscriptTurnRef(NamedTuple): + ordinal: int + records: list[dict[str, Any]] + start: int + end: int + total: int + + +class _PageCursor(NamedTuple): + turn: int + position: int = 0 + + +def encode_page_cursor(before_turn_ordinal: int, position: int = 0) -> str: + data = {"before_turn": before_turn_ordinal} + if position: + data["position"] = position + raw = json.dumps( + data, + separators=(",", ":"), + ensure_ascii=False, + ).encode("utf-8") + return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=") + + +def decode_transcript_cursor(value: str | None) -> _PageCursor | None: + if not value: + return None + try: + padded = value + "=" * (-len(value) % 4) + data = json.loads(base64.urlsafe_b64decode(padded.encode("ascii")).decode("utf-8")) + except (binascii.Error, json.JSONDecodeError, UnicodeDecodeError, ValueError): + return None + if not isinstance(data, dict): + return None + cursor_data = cast(dict[str, Any], data) + before_turn = cursor_data.get("before_turn") + position = cursor_data.get("position", 0) + if ( + isinstance(before_turn, bool) or not isinstance(before_turn, int) or before_turn < 0 + or isinstance(position, bool) or not isinstance(position, int) or position < 0 + ): + return None + return _PageCursor(before_turn, position) + + +@dataclass(slots=True) +class TranscriptReplayStats: + """Selected-source page diagnostics; canonical recovery reads are separate.""" + + effective_limit: int = 0 + source_bytes: int = 0 + parsed_records: int = 0 + _selected_bytes: int = 0 + selected_records: int = 0 + compacted_delta_records: int = 0 + replay_ms: int = 0 + capped_by_bytes: bool = False + capped_by_records: bool = False + truncated_oversized_turn: bool = False + _selected_bytes_loader: Callable[[], int] | None = field( + default=None, init=False, repr=False, compare=False, + ) + + @property + def selected_bytes(self) -> int: + if self._selected_bytes_loader is not None: + self._selected_bytes = self._selected_bytes_loader() + self._selected_bytes_loader = None + return self._selected_bytes + + @selected_bytes.setter + def selected_bytes(self, value: int) -> None: + self._selected_bytes = value + self._selected_bytes_loader = None + + def measure_selected(self, records: list[dict[str, Any]]) -> None: + self.selected_records = len(records) + self._selected_bytes = 0 + self._selected_bytes_loader = (lambda: _records_bytes(records)) if records else None + + +def _record_json_line(record: dict[str, Any]) -> str: + return json.dumps(record, ensure_ascii=False, separators=(",", ":")) + + +def _records_bytes(records: list[dict[str, Any]]) -> int: + total = 0 + for record in records: + total += len(_record_json_line(record).encode("utf-8")) + graph_size_adjustment(record) + 1 + return total + + +def _stream_key(record: dict[str, Any], stream: str) -> tuple[str, str, str]: + raw_turn_id = record.get("turn_id") + turn_id = raw_turn_id if isinstance(raw_turn_id, str) else "" + raw_phase = record.get("turn_phase") + phase = raw_phase if isinstance(raw_phase, str) and raw_phase else stream + raw_stream_id = record.get("stream_id") + stream_id = raw_stream_id if isinstance(raw_stream_id, str) else "" + return turn_id, phase, stream_id + + +def compact_completed_stream_deltas( + turn: list[dict[str, Any]], +) -> tuple[list[dict[str, Any]], int]: + if not turn or turn[-1].get("event") != "turn_end": + return turn, 0 + + pending: dict[tuple[str, str, str], list[tuple[int, dict[str, Any]]]] = {} + dropped_indexes: set[int] = set() + replacements: dict[int, dict[str, Any]] = {} + for index, record in enumerate(turn): + event = record.get("event") + if event in {"delta", "reasoning_delta"}: + stream = "answer" if event == "delta" else "reasoning" + pending.setdefault(_stream_key(record, stream), []).append((index, record)) + continue + if event not in {"stream_end", "reasoning_end"}: + continue + stream = "answer" if event == "stream_end" else "reasoning" + chunks = pending.pop(_stream_key(record, stream), []) + if not chunks: + continue + completed = dict(record) + # The sealed snapshot is authoritative even when media rewriting changes + # its text. Only old ends without text need their preceding fragments. + if not isinstance(completed.get("text"), str): + completed["text"] = "".join(str(chunk.get("text") or "") for _, chunk in chunks) + replacements[index] = completed + dropped_indexes.update(chunk_index for chunk_index, _ in chunks) + + if not dropped_indexes: + return turn, 0 + return [ + replacements.get(index, record) + for index, record in enumerate(turn) + if index not in dropped_indexes + ], len(dropped_indexes) + + +def split_transcript_turns(lines: list[dict[str, Any]]) -> list[list[dict[str, Any]]]: + turns: list[list[dict[str, Any]]] = [] + current: list[dict[str, Any]] = [] + for rec in lines: + current.append(rec) + if rec.get("event") == "turn_end": + turns.append(current) + current = [] + if current: + turns.append(current) + return turns + + +def _stable_record_digest(record: dict[str, Any]) -> str: + persisted = { + key: value + for key, value in record.items() + if key != WEBUI_REPLAY_IDENTITY_KEY + } + raw = json.dumps( + persisted, + ensure_ascii=False, + separators=(",", ":"), + sort_keys=True, + default=str, + ) + return hashlib.sha256(raw.encode("utf-8")).hexdigest()[:16] + + +def projection_event_id(record: Mapping[str, Any]) -> str: + identity = record.get(WEBUI_REPLAY_IDENTITY_KEY) + if record.get("event") == "user" and isinstance(input_id := record.get("input_id"), str) and input_id: + identity = f"input:{record.get('chat_id')}:{input_id}" + if not isinstance(identity, str) or not identity: + identity = _stable_record_digest(dict(record)) + digest = hashlib.sha256(f"event\0{identity}".encode("utf-8")).hexdigest()[:20] + return f"history-{digest}" + + +def ensure_replay_identities(lines: list[dict[str, Any]]) -> list[dict[str, Any]]: + annotated: list[dict[str, Any]] = [] + for fallback_turn_index, turn in enumerate(split_transcript_turns(lines)): + anchor = next( + ( + value + for record in turn + if isinstance( + value := record.get(WEBUI_REPLAY_IDENTITY_KEY), + str, + ) + and value + ), + None, + ) + if anchor and ":record:" in anchor: + turn_identity = anchor.rsplit(":record:", 1)[0] + else: + turn_digest = hashlib.sha256( + "\n".join(_stable_record_digest(record) for record in turn).encode("ascii") + ).hexdigest()[:16] + turn_identity = f"legacy:{fallback_turn_index}:{turn_digest}" + synthetic_occurrences: dict[str, int] = {} + for record in turn: + identity = record.get(WEBUI_REPLAY_IDENTITY_KEY) + if isinstance(identity, str) and identity: + annotated.append(record) + continue + digest = _stable_record_digest(record) + occurrence = synthetic_occurrences.get(digest, 0) + synthetic_occurrences[digest] = occurrence + 1 + annotated.append({ + **record, + WEBUI_REPLAY_IDENTITY_KEY: ( + f"{turn_identity}:synthetic:{digest}:{occurrence}" + ), + }) + return annotated + + +def _compact_completed_turns( + turns: list[list[dict[str, Any]]], +) -> tuple[list[list[dict[str, Any]]], int]: + compacted: list[list[dict[str, Any]]] = [] + dropped = 0 + for turn in turns: + next_turn, turn_dropped = compact_completed_stream_deltas(turn) + compacted.append(next_turn) + dropped += turn_dropped + return compacted, dropped + + +def compact_legacy_records(records: list[dict[str, Any]]) -> list[dict[str, Any]]: + turns, _ = _compact_completed_turns(split_transcript_turns(records)) + return [record for turn in turns for record in turn] + + +_REPLAY_TURN_RECORD_RE = re.compile(r"^turn:(\d+):record:(\d+)$") + + +def parse_replay_identity(identity: object) -> tuple[int, int] | None: + if not isinstance(identity, str): + return None + match = _REPLAY_TURN_RECORD_RE.fullmatch(identity) + if match is None: + return None + return int(match.group(1)), int(match.group(2)) + + +def _page_event_count(turn: list[dict[str, Any]]) -> int: + supported = { + "user", + "delta", + "stream_end", + "reasoning_delta", + "reasoning_end", + "message", + "file_edit", + "context_compaction", + "model_request", + "turn_end", + } + return max(1, sum(record.get("event") in supported for record in turn)) + + +def read_trace_turn( + ordinal: int, *, history: HistoryReader, max_records: int, max_bytes: int, +) -> list[dict[str, Any]] | None: + ref = next(history.turns(before=ordinal + 1, after=ordinal), None) + if ref is None or ref.record_count > max_records or ref.byte_count > max_bytes: + return None + records, start, end, _ = turn_record_page( + history, ordinal, start=0, end=ref.record_count, reverse=False, + max_records=max_records, max_bytes=max_bytes, + ) + return records if start == 0 and end == ref.record_count else None + + +def select_transcript_page( + *, history: HistoryReader, page_limit: int, max_records: int, max_bytes: int, + before: str | None, after: str | None, stats: TranscriptReplayStats, +) -> tuple[list[dict[str, Any]], ReplayPage]: + stats.effective_limit = page_limit + total_turns = history.turn_count + before_cursor = decode_transcript_cursor(before) + after_cursor = decode_transcript_cursor(after) + forward = after_cursor is not None + upper = total_turns + if before_cursor is not None: + upper = min(before_cursor.turn + int(before_cursor.position > 0), total_turns) + lower = min(after_cursor.turn, total_turns) if after_cursor is not None else 0 + selected: list[_TranscriptTurnRef] = [] + event_count = record_count = byte_count = 0 + for ref in history.turns(before=upper, after=lower, reverse=not forward): + start, end = 0, ref.record_count + if after_cursor is not None and ref.ordinal == after_cursor.turn: + start = min(after_cursor.position, end) + if before_cursor is not None and ref.ordinal == before_cursor.turn: + end = min(before_cursor.position, end) + if start >= end: + continue + requested_partial = start > 0 or end < ref.record_count + exceeds_records = record_count + end - start > max_records + exceeds_bytes = byte_count + ref.byte_count > max_bytes + stats.capped_by_records |= exceeds_records + stats.capped_by_bytes |= exceeds_bytes + if selected and (requested_partial or exceeds_records or exceeds_bytes): + break + remaining_records = max_records - record_count + remaining_bytes = max_bytes - byte_count + turn, first_position, end_position, source_bytes = turn_record_page( + history, ref.ordinal, start=start, end=end, reverse=not forward, + max_records=remaining_records, max_bytes=remaining_bytes, + allow_oversized=not selected, + ) + stats.parsed_records += len(turn) + stats.source_bytes += source_bytes + if source_bytes > remaining_bytes or (len(turn) < end - start and len(turn) < remaining_records): + stats.capped_by_bytes = True + if not turn: + break + partial = first_position > 0 or end_position < ref.record_count + # A partial turn is always a page of its own, even when a size estimate + # from older stored metadata understated the actual encoded bytes. + if selected and partial: + break + raw_count = len(turn) + if partial: + stats.truncated_oversized_turn = True + else: + turn, dropped = compact_completed_stream_deltas(turn) + stats.compacted_delta_records += dropped + selected.append(_TranscriptTurnRef(ref.ordinal, turn, first_position, end_position, ref.record_count)) + record_count += raw_count + byte_count += source_bytes + event_count += _page_event_count(turn) + if partial or event_count >= page_limit: + break + chronological = selected if forward else list(reversed(selected)) + # turn_record_page has already annotated each raw source position. + records = [record for ref in chronological for record in ref.records] + stats.measure_selected(records) + if not chronological: + return [], {"before_cursor": None, "has_more_before": False, "after_cursor": None, + "has_more_after": False, "loaded_event_count": 0, "user_message_offset": 0} + first, last = chronological[0], chronological[-1] + has_more_before = first.start > 0 or first.ordinal > 0 + has_more_after = last.end < last.total or last.ordinal + 1 < total_turns + revision = history.revision + page: ReplayPage = { + "history_generation": revision[0] if revision is not None else None, + "before_cursor": encode_page_cursor(first.ordinal, first.start) if has_more_before else None, + "has_more_before": has_more_before, + "after_cursor": ( + encode_page_cursor(last.ordinal, last.end) if last.end < last.total + else encode_page_cursor(last.ordinal + 1) if has_more_after else None + ), + "has_more_after": has_more_after, "loaded_event_count": 0, + "user_message_offset": history.user_count_before(first.ordinal, first.start), + } + if first.start > 0 or first.end < first.total: + page["truncated_oversized_turn"] = True + page["record_range"] = {"turn": first.ordinal, "start": first.start, "end": first.end} + return records, page diff --git a/nanobot/webui/transcript_trace.py b/nanobot/webui/transcript_trace.py new file mode 100644 index 000000000..5d9c44167 --- /dev/null +++ b/nanobot/webui/transcript_trace.py @@ -0,0 +1,209 @@ +"""Bounded activity summaries and their unaugmented, replayable detail.""" + +from __future__ import annotations + +import json +import re +from typing import Any, Callable, Mapping, NamedTuple, Sequence, TypedDict, cast + +from nanobot.webui.transcript_replay import WEBUI_REPLAY_IDENTITY_KEY, parse_replay_identity + +_TRACE_CALL_NAME_RE = re.compile(r"^([A-Za-z0-9_.-]+)\(") +_TRACE_DETAIL_REF_RE = re.compile(r"^(?P\d{1,12})\.(?Phistory-[0-9a-f]{20})$") + + +def parse_trace_detail_ref(value: str) -> tuple[int, str] | None: + match = _TRACE_DETAIL_REF_RE.fullmatch(value) + return (int(match.group("turn")), match.group("message")) if match else None + + +class _ProjectionReceipt(TypedDict): + turn_id: str + ranges: list[list[int]] + + +def _projection_receipts(records: Sequence[Mapping[str, Any]]) -> list[_ProjectionReceipt]: + members: dict[str, set[int]] = {} + for record in records: + turn_id, sequence = record.get("turn_id"), record.get("turn_seq") + if ( + isinstance(turn_id, str) and turn_id + and isinstance(sequence, int) and not isinstance(sequence, bool) and sequence >= 0 + ): + members.setdefault(turn_id, set()).add(sequence) + receipts: list[_ProjectionReceipt] = [] + for turn_id, sequences in members.items(): + ranges: list[list[int]] = [] + for sequence in sorted(sequences): + if ranges and ranges[-1][1] + 1 == sequence: + ranges[-1][1] = sequence + else: + ranges.append([sequence, sequence]) + receipts.append({"turn_id": turn_id, "ranges": ranges}) + return receipts + + +class _DeferredTraceGroup(NamedTuple): + start: int + stop: int + detail_bytes: int + trace_count: int + + +def _format_tool_call_trace(call: Any) -> str | None: + if not call or not isinstance(call, dict): + return None + call_data = cast(dict[str, Any], call) + fn = call_data.get("function") + function_data = cast(dict[str, Any], fn) if isinstance(fn, dict) else None + name = function_data.get("name") if function_data is not None else None + if not isinstance(name, str) or not name: + raw_name = call_data.get("name") + name = raw_name if isinstance(raw_name, str) else "" + if not name: + return None + args = ( + function_data.get("arguments") if function_data is not None else None + ) or call_data.get("arguments") + if isinstance(args, str) and args.strip(): + return f"{name}({args})" + if args and isinstance(args, dict): + return f"{name}({json.dumps(args, ensure_ascii=False)})" + return f"{name}()" + + +def tool_trace_lines_from_events(events: Any) -> list[str]: + if not isinstance(events, list): + return [] + lines: list[str] = [] + seen: set[str] = set() + for event in cast(list[Any], events): + if not event or not isinstance(event, dict): + continue + tool_event = cast(dict[str, Any], event) + if tool_event.get("phase") not in {"start", "end", "error"}: + continue + call_id = tool_event.get("call_id") + if isinstance(call_id, str) and call_id: + if call_id in seen: + continue + seen.add(call_id) + t = _format_tool_call_trace(tool_event) + if t: + lines.append(t) + return lines + + +def _truncate_utf8(value: str, max_bytes: int) -> str: + encoded = value.encode("utf-8") + if len(encoded) <= max_bytes: + return value + return encoded[: max_bytes - 3].decode("utf-8", errors="ignore") + "…" + + +def _trace_summary(line: str) -> str: + if len(line.encode("utf-8")) <= 512: + return line + match = _TRACE_CALL_NAME_RE.match(line.strip()) + return f"{_truncate_utf8(match.group(1), 240)}(…)" if match else _truncate_utf8(line, 240) + + +class TraceProjection(NamedTuple): + groups: dict[int, _DeferredTraceGroup] + events: dict[int, dict[str, Any]] + + def detail(self, message_id: str) -> dict[str, Any] | None: + for group in self.groups.values(): + if self.events[group.start]["projection_id"] == message_id: + return { + "message_id": message_id, + "events": [self.events[i] for i in range(group.start, group.stop) if i in self.events], + } + return None + + @staticmethod + def summarize( + lines: list[dict[str, Any]], group: _DeferredTraceGroup, event: dict[str, Any], + ) -> None: + identity = parse_replay_identity(lines[group.start].get(WEBUI_REPLAY_IDENTITY_KEY)) + detail_ref = f"{identity[0]}.{event['projection_id']}" if identity is not None else None + last_text = next( + ( + text + for grouped in reversed(lines[group.start:group.stop]) + if isinstance((text := grouped.get("text")), str) and text + ), + "", + ) + event["text"] = _trace_summary(last_text) + event.pop("tool_events", None) + receipts = _projection_receipts([ + grouped for grouped in lines[group.start:group.stop] + if grouped.get("event") != "model_request" + ]) + if receipts: + event["projection_receipts"] = receipts + if detail_ref is not None: + event["trace_detail"] = { + "ref": detail_ref, + "bytes": group.detail_bytes, + "traceCount": group.trace_count, + } + + +def index_trace_projection( + lines: list[dict[str, Any]], + project: Callable[[dict[str, Any]], dict[str, Any] | None], + *, + max_inline_bytes: int, +) -> TraceProjection: + groups: dict[int, _DeferredTraceGroup] = {} + preprojected: dict[int, dict[str, Any]] = {} + start: int | None = None + detail_bytes = 0 + trace_count = 0 + + def flush(stop: int) -> None: + nonlocal start, detail_bytes, trace_count + if ( + start is not None + and detail_bytes > max_inline_bytes + ): + groups[start] = _DeferredTraceGroup( + start=start, + stop=stop, + detail_bytes=detail_bytes, + trace_count=max(1, trace_count), + ) + start = None + detail_bytes = 0 + trace_count = 0 + + for index, record in enumerate(lines): + # Usage belongs to the turn, not the activity body. It must not split + # one deferred tool group into many eagerly loaded fragments. + if record.get("event") == "model_request": + continue + is_activity = ( + record.get("event") == "message" + and record.get("kind") in {"tool_hint", "progress"} + ) + if not is_activity: + flush(index) + continue + event = project(record) + if event is None: + flush(index) + continue + preprojected[index] = event + if start is None: + start = index + detail_bytes += len(json.dumps(event, ensure_ascii=False, separators=(",", ":")).encode("utf-8")) + tool_events = cast(list[dict[str, Any]], event.get("tool_events") or []) + traces = tool_trace_lines_from_events(tool_events) + if traces: + trace_count += len(traces) + elif not tool_events and isinstance(record.get("text"), str) and record["text"]: + trace_count += 1 + flush(len(lines)) + return TraceProjection(groups, preprojected) diff --git a/nanobot/webui/ws_http.py b/nanobot/webui/ws_http.py index ad4098081..38b94c7e1 100644 --- a/nanobot/webui/ws_http.py +++ b/nanobot/webui/ws_http.py @@ -18,11 +18,11 @@ import time from collections.abc import Awaitable, Callable, Mapping from dataclasses import dataclass, field from pathlib import Path -from typing import TYPE_CHECKING, Any, Protocol, TypeVar, cast -from urllib.parse import parse_qs, quote, unquote, urlsplit, urlunsplit +from typing import TYPE_CHECKING, Any, Literal, Protocol, TypeVar, cast +from urllib.parse import parse_qs, unquote, urlsplit, urlunsplit from loguru import logger -from websockets.datastructures import Headers +from websockets.datastructures import Headers, MultipleValuesError from websockets.http11 import Request as WsRequest from websockets.http11 import Response @@ -30,9 +30,6 @@ from nanobot.agent.subagent import SubagentControlError from nanobot.agent.subagent_status import SubagentSessionError from nanobot.command.application import builtin_command_palette from nanobot.context_graph import ContextGraph -from nanobot.cron.binding import CronBindingError, binding_revision -from nanobot.cron.session_turns import is_bound_cron_job -from nanobot.cron.types import CronJob, CronSchedule from nanobot.runtime_admission import RuntimeMaintenanceError from nanobot.security.workspace_access import WorkspaceScope, WorkspaceScopeError from nanobot.session.display_history import HistoryReader @@ -41,9 +38,7 @@ from nanobot.session.session_handles import ( SessionHandle, SessionHandleResolver, ) -from nanobot.triggers.local_types import LocalTrigger -from nanobot.webui.automation_chats import AutomationChat, automation_chats -from nanobot.webui.automation_results import cron_run_response, trigger_run_response +from nanobot.webui.automation_routes import WebUIAutomationRoutes from nanobot.webui.file_preview import ( WebUIFilePreviewError, file_preview_availability_payload, @@ -59,6 +54,7 @@ from nanobot.webui.http_utils import ( from nanobot.webui.http_utils import ( combined_list_header as _combined_list_header, ) +from nanobot.webui.http_utils import etag_matches as _etag_matches from nanobot.webui.http_utils import ( host_for_url as _host_for_url, ) @@ -98,13 +94,9 @@ from nanobot.webui.http_utils import ( ) from nanobot.webui.ingress_policy import WebUIIngressPolicy from nanobot.webui.media_gateway import WebUIMediaGateway +from nanobot.webui.mutation import MutationResult from nanobot.webui.recovery import RecoveryActionError -from nanobot.webui.session_automations import ( - all_automations_payload, - serialize_automation_jobs, - session_automation_jobs, - session_automations_payload, -) +from nanobot.webui.session_automations import serialize_automation_jobs from nanobot.webui.session_context import session_context_payload from nanobot.webui.session_identity import is_webui_session_key from nanobot.webui.session_list_index import ( @@ -112,6 +104,8 @@ from nanobot.webui.session_list_index import ( indexed_workspace_scope, list_webui_sessions, ) +from nanobot.webui.settings_contracts import MutationParams +from nanobot.webui.settings_contracts import query_first as _mutation_text from nanobot.webui.sidebar_state import ( WebUISidebarState, ensure_webui_archives_imported, @@ -142,8 +136,6 @@ from nanobot.webui.workspace_browser import browse_workspace_directories from nanobot.webui.workspaces import WebUIWorkspaceController _SLOW_WEBUI_HTTP_LOG_MS = 1_000 -_WEBUI_MUTATION_PAYLOAD_ATTR = "_nanobot_webui_mutation_payload" -_WEBUI_MUTATION_REQUEST_ATTR = "_nanobot_webui_mutation_request" _NO_STORE_HEADERS = [("Cache-Control", "no-store")] @@ -151,13 +143,6 @@ def _quoted_etag(revision: str) -> str: return f'"{revision}"' -def _etag_matches(value: str, etag: str) -> bool: - return any( - candidate.strip().removeprefix("W/") in {"*", etag} - for candidate in value.split(",") - ) - - @dataclass(slots=True) class _WebUIThreadDiagnostics: transcript: TranscriptReplayStats = field(default_factory=TranscriptReplayStats) @@ -200,59 +185,8 @@ _WEBUI_MUTATION_PATHS = { "recovery.continue": "/api/webui/recovery/continue", "recovery.dismiss": "/api/webui/recovery/dismiss", "subagent.cancel": "/api/webui/subagents/cancel", - "settings.agent.update": "/api/settings/update", - "settings.model_configuration.create": "/api/settings/model-configurations/create", - "settings.model_configuration.update": "/api/settings/model-configurations/update", - "settings.model_configuration.delete": "/api/settings/model-configurations/delete", - "settings.model_configuration.migrate": "/api/settings/model-configurations/migrate", - "settings.model_call_order.update": "/api/settings/model-call-order/update", - "settings.provider.update": "/api/settings/provider/update", - "settings.provider.create": "/api/settings/provider/create", - "settings.provider.oauth_login": "/api/settings/provider/oauth-login", - "settings.provider.oauth_complete": "/api/settings/provider/oauth-login/complete", - "settings.provider.oauth_logout": "/api/settings/provider/oauth-logout", - "settings.web_search.update": "/api/settings/web-search/update", - "settings.image_generation.update": "/api/settings/image-generation/update", - "settings.transcription.update": "/api/settings/transcription/update", - "settings.runtime_config.update": "/api/settings/runtime-config/update", - "settings.sandbox.check": "/api/settings/sandbox/check", - "settings.network_safety.update": "/api/settings/network-safety/update", - "settings.cli_app.install": "/api/settings/cli-apps/install", - "settings.cli_app.update": "/api/settings/cli-apps/update", - "settings.cli_app.uninstall": "/api/settings/cli-apps/uninstall", - "settings.cli_app.test": "/api/settings/cli-apps/test", - "settings.feature.enable": "/api/settings/nanobot-features/enable", - "settings.feature.disable": "/api/settings/nanobot-features/disable", - "settings.nanobot.update.channel": "/api/settings/nanobot-update/channel", - "settings.nanobot.update.plan": "/api/settings/nanobot-update/plan/create", - "settings.nanobot.update.prepare": "/api/settings/nanobot-update/job/prepare", - "settings.nanobot.update.settle": "/api/settings/nanobot-update/job/settle", - "settings.nanobot.update.execute": "/api/settings/nanobot-update/job/execute", - "settings.nanobot.update.retry": "/api/settings/nanobot-update/job/retry", - "settings.channel.validate": "/api/settings/channels/validate", - "settings.channel.configure": "/api/settings/channels/configure", - "settings.pairing.approve": "/api/settings/pairing/approve", - "settings.pairing.deny": "/api/settings/pairing/deny", - "settings.mcp.enable": "/api/settings/mcp-presets/enable", - "settings.mcp.disable": "/api/settings/mcp-presets/disable", - "settings.mcp.remove": "/api/settings/mcp-presets/remove", - "settings.mcp.test": "/api/settings/mcp-presets/test", - "settings.mcp.reconnect": "/api/settings/mcp-presets/reconnect", - "settings.mcp.proxy": "/api/settings/mcp-presets/proxy", - "settings.mcp.custom": "/api/settings/mcp-presets/custom", - "settings.mcp.import": "/api/settings/mcp-presets/import", - "settings.mcp.import_cursor": "/api/settings/mcp-presets/import-cursor", - "settings.mcp.tools": "/api/settings/mcp-presets/tools", - "settings.mcp.oauth_start": "/api/settings/mcp-oauth/start", - "settings.mcp.oauth_complete": "/api/settings/mcp-oauth/complete", - "settings.mcp.oauth_cancel": "/api/settings/mcp-oauth/cancel", -} - -_WEBUI_CHANNEL_CONNECT_ACTIONS = { - "settings.channel.connect.start": "start", - "settings.channel.connect.poll": "poll", - "settings.channel.connect.cancel": "cancel", } +_WEBUI_STATIC_MUTATION_PATHS = frozenset(_WEBUI_MUTATION_PATHS.values()) # Fix for #5190: On Windows, mimetypes.guess_type() reads the registry key # HKEY_CLASSES_ROOT\.js\Content Type, which is commonly set to 'text/plain' @@ -282,45 +216,30 @@ if TYPE_CHECKING: from nanobot.agent.subagent import SubagentManager from nanobot.bus.queue import MessageBus from nanobot.channels.websocket.runtime import WebSocketConfig - from nanobot.cron.service import CronService - from nanobot.triggers.local_store import LocalTriggerStore from nanobot.webui.settings_services import WebUISettingsServices +_API_KEY_RE = re.compile(r"^[A-Za-z0-9_:.-]{1,128}$") +_UUID_RE = re.compile(r"[0-9a-fA-F]{8}-(?:[0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}") +_SESSION_PROMPTS_RE = re.compile(r"/api/sessions/([^/]+)/webui-thread/prompts") +_SESSION_TRACE_DETAIL_RE = re.compile(r"^/api/sessions/([^/]+)/webui-thread/trace-detail$") +_SESSION_WEBUI_THREAD_RE = re.compile(r"^/api/sessions/([^/]+)/webui-thread$") +_SESSION_CONTEXT_RE = re.compile(r"^/api/sessions/([^/]+)/context$") +_SESSION_FILE_PREVIEW_RE = re.compile(r"^/api/sessions/([^/]+)/file-preview$") +_SESSION_AUTOMATIONS_RE = re.compile(r"^/api/sessions/([^/]+)/automations$") +_SESSION_SUBAGENT_THREAD_RE = re.compile(r"/api/sessions/([^/]+)/subagents/([^/]+)/webui-thread") +_SESSION_SUBAGENTS_RE = re.compile(r"/api/sessions/([^/]+)/subagents") +_SESSION_DELETE_RE = re.compile(r"^/api/sessions/([^/]+)/delete$") +_MEDIA_ROUTE_RE = re.compile(r"^/api/media/([A-Za-z0-9_-]+)/([A-Za-z0-9_-]+)$") +_SKILL_DETAIL_RE = re.compile(r"^/api/webui/skills/([^/]+)$") + + def _decode_api_key(raw_key: str) -> str | None: key = unquote(raw_key) - _api_key_re = re.compile(r"^[A-Za-z0-9_:.-]{1,128}$") - if _api_key_re.match(key) is None: + if _API_KEY_RE.match(key) is None: return None return key -def _mutation_payload(request: WsRequest) -> dict[str, Any] | None: - payload = getattr(request, _WEBUI_MUTATION_PAYLOAD_ATTR, None) - if not isinstance(payload, dict): - return None - return cast(dict[str, Any], payload) - - -def _request_query(request: WsRequest) -> dict[str, list[str]]: - payload = _mutation_payload(request) - if payload is None: - return _parse_query(request.path) - query: dict[str, list[str]] = {} - for key, value in payload.items(): - if not key: - continue - if isinstance(value, bool): - text = "true" if value else "false" - elif value is None: - text = "" - elif isinstance(value, (dict, list)): - text = json.dumps(value, ensure_ascii=False, separators=(",", ":")) - else: - text = str(value) - query[key] = [text] - return query - - def _default_model_name_from_config(config_path: Path | None = None) -> str | None: try: from nanobot.config.loader import load_config @@ -352,7 +271,7 @@ _ProjectionResult = TypeVar("_ProjectionResult", covariant=True) class _HistoryProjection(Protocol[_ProjectionResult]): - def __call__(self, request: WsRequest, key: str, *, history: HistoryReader) -> _ProjectionResult: ... + def __call__(self, request: WsRequest, key: str, /, *, history: HistoryReader) -> _ProjectionResult: ... @dataclass @@ -426,10 +345,7 @@ class GatewayHTTPHandler: settings: WebUISettingsServices, skills_workspace_path: Path, disabled_skills: set[str] | None = None, - cron_service: CronService | None = None, - local_trigger_store: LocalTriggerStore | None = None, - cron_pending_job_ids: Callable[[str], set[str]] | None = None, - local_trigger_pending_ids: Callable[[str], set[str]] | None = None, + automation_routes: WebUIAutomationRoutes, channel_feature_action: Callable[..., Any] | None = None, channel_runtime_status: Callable[[], dict[str, Any]] | None = None, mcp_runtime_status: Callable[[], Mapping[str, str]] | None = None, @@ -468,11 +384,7 @@ class GatewayHTTPHandler: self.subagent_manager = subagent_manager self.discard_session = discard_session self._skill_install_lock = asyncio.Lock() - self.cron_service = cron_service - self.local_trigger_store = local_trigger_store - self.cron_pending_job_ids = cron_pending_job_ids - self.channel_runtime_status = channel_runtime_status - self.local_trigger_pending_ids = local_trigger_pending_ids + self.automation_routes = automation_routes self._log = log self._runtime_surface = runtime_surface @@ -535,85 +447,56 @@ class GatewayHTTPHandler: connection: Any, action: str, payload: dict[str, Any], - ) -> Response: - """Run one explicitly allowlisted mutation for an authenticated WebUI socket.""" - path = self._webui_mutation_path(action, payload) - if isinstance(path, Response): - return path - - source_request = getattr(connection, "request", None) - source_headers = getattr(source_request, "headers", None) - if source_headers is None: - headers = Headers() - else: - try: - headers = Headers(source_headers.raw_items()) - except (AttributeError, TypeError): - try: - headers = Headers(source_headers) - except TypeError: - headers = Headers() - request = WsRequest(path, headers) - setattr(request, "_nanobot_trusted_proxy_authenticated", True) - setattr(request, _WEBUI_MUTATION_REQUEST_ATTR, True) - setattr(request, _WEBUI_MUTATION_PAYLOAD_ATTR, dict(payload)) + ) -> MutationResult: + """Run an allowlisted action from the authenticated WebUI command router.""" + headers = getattr(getattr(connection, "request", None), "headers", None) or Headers() + params = MutationParams(payload) try: - # WebUI mutation tasks already survive a disconnected browser. Keep - # their async/threaded writes busy until that operation really ends. + # The operation outlives its socket; hold admission until the write ends. with self.bus.admission.activity(): - response = await self._dispatch_resolved(connection, request, path) + if action.startswith("settings."): + return await self.settings_routes.dispatch_mutation(connection, headers, action, params) + if action == "session.delete": + key = payload.get("key") + if not isinstance(key, str) or not key.strip(): + return MutationResult.failure(400, "missing session key") + return await self._handle_session_delete(key, params) + if action in _WEBUI_MUTATION_PATHS: + kind, _, operation = action.partition(".") + if kind == "remote": + return await self._mutate_remote_instances(connection, headers, operation, payload) + if kind == "automation": + return await self.automation_routes.mutate(params, operation.replace("_", "-")) + if kind == "recovery": + return await self._mutate_recovery(operation, payload) + if action == "subagent.cancel": + return await self._handle_subagent_cancel(payload) + if action == "sidebar.update": + return await self._handle_webui_sidebar_state_update(payload) + if action == "workspace.favorite": + return await asyncio.to_thread(self._handle_workspace_favorite, payload) + if action == "workspace.resolve_project": + return await asyncio.to_thread(self._handle_workspace_resolve_project, payload) + if action == "skill.install": + return await self._handle_webui_skill_install(connection, headers, params) + if action == "skill.update": + return await self._handle_webui_skill_update(params) + if action == "skill.delete": + return await self._handle_webui_skill_delete(connection, headers, params) + if kind == "star_prompt" and (operation == "claim" or operation == "dismiss"): + return await self._mutate_star_prompt(operation) except RuntimeMaintenanceError: - return _http_error(503, "Gateway update is being verified. Retry shortly.") - if isinstance(response, Response): - return response - return _http_error(404, "WebUI mutation action not found") + return MutationResult.failure(503, "Gateway update is being verified. Retry shortly.") + return MutationResult.failure(404, "unknown WebUI mutation action") def _is_webui_mutation_path(self, path: str) -> bool: if path.startswith("/api/remote-instances/"): return True if self.settings_routes.is_mutation_path(path): return True - if re.match(r"^/api/sessions/[^/]+/delete$", path): + if _SESSION_DELETE_RE.match(path): return True - if re.match(r"^/api/webui/automations/(enable|disable|delete|run|update|change-chat)$", path): - return True - if path in {"/api/webui/recovery/continue", "/api/webui/recovery/dismiss"}: - return True - return path in { - "/api/webui/skills/install", - "/api/webui/skills/update", - "/api/webui/skills/delete", - "/api/webui/star-prompt/claim", - "/api/webui/star-prompt/dismiss", - "/api/webui/sidebar-state/update", - "/api/workspaces/resolve-project", - "/api/workspaces/favorite", - "/api/webui/subagents/cancel", - } - - @staticmethod - def _webui_mutation_path( - action: str, - payload: dict[str, Any], - ) -> str | Response: - path = _WEBUI_MUTATION_PATHS.get(action) - if path is not None: - return path - if action == "session.delete": - key = payload.get("key") - if not isinstance(key, str) or not key.strip(): - return _http_error(400, "missing session key") - return f"/api/sessions/{quote(key, safe='')}/delete" - connect_action = _WEBUI_CHANNEL_CONNECT_ACTIONS.get(action) - if connect_action is not None: - channel = payload.get("channel") - if not isinstance(channel, str) or re.fullmatch( - r"[A-Za-z0-9_-]{1,64}", - channel, - ) is None: - return _http_error(400, "invalid channel name") - return f"/api/settings/channels/{channel}/connect/{connect_action}" - return _http_error(404, "unknown WebUI mutation action") + return path in _WEBUI_STATIC_MUTATION_PATHS async def _dispatch_resolved( self, @@ -627,52 +510,46 @@ class GatewayHTTPHandler: from nanobot.webui.background import load_background_style directory = self.settings.config.path.parent / "webui" + style = await asyncio.to_thread(load_background_style, directory) return _http_json_response( - load_background_style(directory), extra_headers=_NO_STORE_HEADERS, + style, extra_headers=_NO_STORE_HEADERS, ) if got == "/api/settings/background": if not self.check_api_token(request): return _http_error(401, "Unauthorized") path = self.settings.config.path.parent / "webui" / "background.png" try: - body = path.read_bytes() + body = await asyncio.to_thread(path.read_bytes) except FileNotFoundError: return _http_error(404, "Background not found") return _http_response(body, content_type="image/png", extra_headers=[ ("Cache-Control", "no-store"), ("X-Content-Type-Options", "nosniff"), ]) - if got == "/api/remote-instances" or got.startswith("/api/remote-instances/"): - return await self._dispatch_remote_instances(connection, request, got) + if got == "/api/remote-instances": + return await self._read_remote_instances(connection, request) if self.config.token_issue_path: issue_expected = _normalize_config_path(self.config.token_issue_path) if got == issue_expected: return self._handle_token_issue(connection, request) if got == "/webui/bootstrap": - return self._handle_bootstrap(connection, request) + return await self._handle_bootstrap(connection, request) if got == "/webui/terminal": - return self._handle_bootstrap(connection, request, terminal_probe=True) + return await self._handle_bootstrap(connection, request, terminal_probe=True) response = await self.settings_routes.dispatch(connection, request, got) if response is not None: return response - response = await self._dispatch_recovery_route(request, got) - if response is not None: - return response - - if got == "/api/webui/subagents/cancel": - return await self._handle_subagent_cancel(request) - response = await self._dispatch_session_routes(request, got) if response is not None: return response - response = self._dispatch_media_routes(request, got) + response = await self._dispatch_media_routes(request, got) if response is not None: return response - response = await self._dispatch_automation_routes(request, got) + response = await self.automation_routes.dispatch_read(request, got, self.check_api_token) if response is not None: return response @@ -685,7 +562,8 @@ class GatewayHTTPHandler: return _http_error(404, "API route not found") if self.static_dist_path is not None: - response = self._serve_static( + response = await asyncio.to_thread( + self._serve_static, got, accept_encoding=_combined_list_header(request.headers, "Accept-Encoding"), ) @@ -694,51 +572,59 @@ class GatewayHTTPHandler: return connection.respond(404, "Not Found") - async def _dispatch_remote_instances( - self, connection: Any, request: WsRequest, path: str, - ) -> Response: + def _allow_remote_instances(self, connection: Any, headers: Any) -> bool: + # A public/reverse-proxied WebUI must not gain access to host SSH credentials. + if not (_is_loopback_host(self.config.host) + and _is_local_browser_request(connection, headers)): + return False + try: + origin = headers.get("Origin", "") + return isinstance(origin, str) and ( + not origin or _is_loopback_host(urlsplit(origin).hostname or "") + ) + except (MultipleValuesError, ValueError): + return False + + async def _read_remote_instances(self, connection: Any, request: WsRequest) -> Response: + if not self.check_api_token(request): + return _http_error(401, "Unauthorized") + if not self._allow_remote_instances(connection, request.headers): + return _http_error(403, "remote_connections_local_only") + parsed = urlsplit(request.path) + try: + if parsed.fragment or len(parsed.query) > 4096: + raise ValueError + query = parse_qs(parsed.query, keep_blank_values=True, strict_parsing=True, max_num_fields=20) + if query.keys() - {"check"} or any( + _UUID_RE.fullmatch(key) is None for key in query.get("check", []) + ): + raise ValueError + except ValueError: + return _http_error(400, "invalid_health_check") + check = {key.lower() for key in query.get("check", [])} + try: + result = await self.remote_instances.health(check) if check else self.remote_instances.snapshot() + except OSError: + return _http_error(500, "local_io_error") + return _http_json_response(result, extra_headers=_NO_STORE_HEADERS) + + async def _mutate_remote_instances( + self, connection: Any, headers: Any, action: str, payload: dict[str, Any], + ) -> MutationResult: from pydantic import ValidationError from nanobot.webui.remote_ssh import RemoteError - if not self.check_api_token(request): - return _http_error(401, "Unauthorized") - # A public/reverse-proxied WebUI must never gain access to this machine's - # SSH agent, private keys or network. - if not (_is_loopback_host(self.config.host) - and _is_local_browser_request(connection, request.headers)): - return _http_error(403, "remote_connections_local_only") - origin = request.headers.get("Origin", "") - if origin and not _is_loopback_host(urlsplit(origin).hostname or ""): - return _http_error(403, "remote_connections_local_only") + if not self._allow_remote_instances(connection, headers): + return MutationResult.failure(403, "remote_connections_local_only") try: - if path == "/api/remote-instances": - parsed = urlsplit(request.path) - try: - if parsed.fragment or len(parsed.query) > 4096: - raise ValueError - query = parse_qs(parsed.query, keep_blank_values=True, strict_parsing=True, max_num_fields=20) - if query.keys() - {"check"} or any( - re.fullmatch(r"[0-9a-fA-F]{8}-(?:[0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}", key) is None - for key in query.get("check", []) - ): - raise ValueError - except ValueError: - return _http_error(400, "invalid_health_check") - check = {key.lower() for key in query.get("check", [])} - result = await self.remote_instances.health(check) if check else self.remote_instances.snapshot() - return _http_json_response(result, extra_headers=_NO_STORE_HEADERS) - if not getattr(request, _WEBUI_MUTATION_REQUEST_ATTR, False): - return _http_error(405, "WebSocket required") - payload = getattr(request, _WEBUI_MUTATION_PAYLOAD_ATTR, {}) - result = await self.remote_instances.action(path.rsplit("/", 1)[-1], payload) - return _http_json_response(result, extra_headers=_NO_STORE_HEADERS) + return MutationResult.success(await self.remote_instances.action(action, payload)) except RemoteError as exc: - return _http_error(400, str(exc)) + return MutationResult.failure(400, str(exc)) except ValidationError: - return _http_error(400, "invalid_profile") + return MutationResult.failure(400, "invalid_profile") except OSError: - return _http_error(500, "local_io_error") + return MutationResult.failure(500, "local_io_error") def _log_slow_http(self, path: str, response: Any | None, started: float) -> None: elapsed_ms = int((time.perf_counter() - started) * 1000) @@ -784,7 +670,7 @@ class GatewayHTTPHandler: ) - def _handle_bootstrap( + async def _handle_bootstrap( self, connection: Any, request: Any, *, terminal_probe: bool = False, ) -> Response: secret = self.config.token_issue_secret.strip() or self.config.token.strip() @@ -809,16 +695,18 @@ class GatewayHTTPHandler: return _http_json_response(terminal, extra_headers=_NO_STORE_HEADERS) if is_proxy_authenticated: + model_name = await asyncio.to_thread( + _resolve_bootstrap_model_name, + self.runtime_model_name, + self.settings.config.path, + ) payload = { "ws_path": _normalize_config_path(self.config.path), - "ws_url": self._bootstrap_ws_url(request), + "ws_url": self._bootstrap_ws_url(request.headers), "limits": self.ingress.bootstrap_limits( max_frame_bytes=self.config.max_message_bytes, ), - "model_name": _resolve_bootstrap_model_name( - self.runtime_model_name, - self.settings.config.path, - ), + "model_name": model_name, "runtime_surface": self._runtime_surface, "runtime_capabilities": self._capabilities, "terminal": terminal, @@ -840,8 +728,13 @@ class GatewayHTTPHandler: else None ) - ws_url = self._bootstrap_ws_url(request) + ws_url = self._bootstrap_ws_url(request.headers) expected_path = _normalize_config_path(self.config.path) + model_name = await asyncio.to_thread( + _resolve_bootstrap_model_name, + self.runtime_model_name, + self.settings.config.path, + ) payload = { "token": token, "terminal": terminal, @@ -851,10 +744,7 @@ class GatewayHTTPHandler: "limits": self.ingress.bootstrap_limits( max_frame_bytes=self.config.max_message_bytes, ), - "model_name": _resolve_bootstrap_model_name( - self.runtime_model_name, - self.settings.config.path, - ), + "model_name": model_name, "runtime_surface": self._runtime_surface, "runtime_capabilities": self._capabilities, } @@ -862,8 +752,7 @@ class GatewayHTTPHandler: payload["api_token"] = api_token return _http_json_response(payload, extra_headers=_NO_STORE_HEADERS) - def _bootstrap_ws_url(self, request: Any) -> str: - headers = getattr(request, "headers", {}) or {} + def _bootstrap_ws_url(self, headers: Any) -> str: if self.config.public_ws_url: return self.config.public_ws_url host = _safe_host_header(_case_insensitive_header(headers, "Host")) @@ -876,82 +765,72 @@ class GatewayHTTPHandler: expected_path = _normalize_config_path(self.config.path) return f"{scheme}://{host}{expected_path}" - def _mcp_oauth_redirect_uri(self, request: WsRequest) -> str: + def _mcp_oauth_redirect_uri(self, headers: Any) -> str: from nanobot.agent.tools.mcp_oauth import MCP_OAUTH_CALLBACK_PATH - public_ws_url = urlsplit(self._bootstrap_ws_url(request)) + public_ws_url = urlsplit(self._bootstrap_ws_url(headers)) scheme = "https" if public_ws_url.scheme == "wss" else "http" return urlunsplit((scheme, public_ws_url.netloc, MCP_OAUTH_CALLBACK_PATH, "", "")) + def _authorize_websocket_session(self, request: WsRequest, raw_key: str) -> str | Response: + if not self.check_api_token(request): + return _http_error(401, "Unauthorized") + decoded_key = _decode_api_key(raw_key) + if decoded_key is None: + return _http_error(400, "invalid session key") + if not _is_websocket_channel_session_key(decoded_key): + return _http_error(404, "session not found") + return decoded_key + async def _dispatch_session_routes(self, request: WsRequest, got: str) -> Response | None: - m = re.fullmatch(r"/api/sessions/([^/]+)/webui-thread/prompts", got) + m = _SESSION_PROMPTS_RE.fullmatch(got) if m: return await self._project_session_history(request, m.group(1), self._handle_prompt_index_get) - m = re.match(r"^/api/sessions/([^/]+)/webui-thread/trace-detail$", got) + m = _SESSION_TRACE_DETAIL_RE.match(got) if m: return await self._project_session_history(request, m.group(1), self._handle_webui_trace_detail_get) - m = re.match(r"^/api/sessions/([^/]+)/webui-thread$", got) + m = _SESSION_WEBUI_THREAD_RE.match(got) if m: return await self._handle_webui_thread_get_async(request, m.group(1)) - m = re.match(r"^/api/sessions/([^/]+)/context$", got) + m = _SESSION_CONTEXT_RE.match(got) if m: return await self._handle_session_context_get(request, m.group(1)) - m = re.match(r"^/api/sessions/([^/]+)/file-preview$", got) + m = _SESSION_FILE_PREVIEW_RE.match(got) if m: - return self._handle_file_preview(request, m.group(1)) + return await asyncio.to_thread(self._handle_file_preview, request, m.group(1)) - m = re.match(r"^/api/sessions/([^/]+)/automations$", got) + m = _SESSION_AUTOMATIONS_RE.match(got) if m: return self._handle_session_automations(request, m.group(1)) - m = re.fullmatch(r"/api/sessions/([^/]+)/subagents/([^/]+)/webui-thread", got) + m = _SESSION_SUBAGENT_THREAD_RE.fullmatch(got) if m: return await asyncio.to_thread(self._handle_subagent_thread_get, request, m.group(1), m.group(2)) - m = re.fullmatch(r"/api/sessions/([^/]+)/subagents", got) + m = _SESSION_SUBAGENTS_RE.fullmatch(got) if m: return await self._handle_subagents_get(request, m.group(1)) - m = re.match(r"^/api/sessions/([^/]+)/delete$", got) - if m: - return await self._handle_session_delete(request, m.group(1)) - return None - async def _dispatch_recovery_route( - self, - request: WsRequest, - path: str, - ) -> Response | None: - match = re.fullmatch(r"/api/webui/recovery/(continue|dismiss)", path) - if match is None: - return None - if not getattr(request, _WEBUI_MUTATION_REQUEST_ATTR, False): - return _http_error(405, "WebUI recovery actions require an authenticated WebSocket") + async def _mutate_recovery(self, action: str, payload: dict[str, Any]) -> MutationResult: if self.recovery_action is None: - return _http_error(503, "WebUI recovery is unavailable") - payload = _mutation_payload(request) - if payload is None: - return _http_error(400, "invalid recovery payload") + return MutationResult.failure(503, "WebUI recovery is unavailable") try: - result = await self.recovery_action(match.group(1), payload) + result = await self.recovery_action(action, payload) except RecoveryActionError as exc: - return _http_error(exc.status, str(exc)) - return _http_json_response(result) + return MutationResult.failure(exc.status, str(exc)) + return MutationResult.success(result) async def _handle_subagents_get(self, request: WsRequest, key: str) -> Response: - if not self.check_api_token(request): - return _http_error(401, "Unauthorized") - session_key = _decode_api_key(key) - if session_key is None: - return _http_error(400, "invalid session key") - if not is_webui_session_key(session_key): - return _http_error(404, "session not found") + session_key = self._authorize_websocket_session(request, key) + if isinstance(session_key, Response): + return session_key if self.subagent_manager is None: return _http_error(503, "subagent manager unavailable") query = _parse_query(request.path) @@ -976,26 +855,21 @@ class GatewayHTTPHandler: "tasks": [status.as_dict() for status in statuses.values()], }, extra_headers=_NO_STORE_HEADERS) - async def _handle_subagent_cancel(self, request: WsRequest) -> Response: - if not getattr(request, _WEBUI_MUTATION_REQUEST_ATTR, False): - return _http_error(405, "Subagent cancellation requires an authenticated WebSocket") + async def _handle_subagent_cancel(self, payload: dict[str, Any]) -> MutationResult: if self.subagent_manager is None: - return _http_error(503, "subagent manager unavailable") - payload = _mutation_payload(request) - if payload is None: - return _http_error(400, "invalid subagent cancellation payload") + return MutationResult.failure(503, "subagent manager unavailable") session_key, task_id = payload.get("session_key"), payload.get("task_id") if not isinstance(session_key, str) or not is_webui_session_key(session_key): - return _http_error(400, "invalid session key") + return MutationResult.failure(400, "invalid session key") if not isinstance(task_id, str) or not task_id.strip(): - return _http_error(400, "missing task id") + return MutationResult.failure(400, "missing task id") try: status = await self.subagent_manager.cancel(task_id, session_key) except SubagentControlError: - return _http_error(404, "task unavailable") + return MutationResult.failure(404, "task unavailable") except (OSError, SubagentSessionError): - return _http_error(503, "task history unavailable") - return _http_json_response(status.as_dict(), extra_headers=_NO_STORE_HEADERS) + return MutationResult.failure(503, "task history unavailable") + return MutationResult.success(status.as_dict()) def _handle_subagent_thread_get(self, request: WsRequest, key: str, task_id: str) -> Response: if not self.check_api_token(request): @@ -1028,13 +902,9 @@ class GatewayHTTPHandler: return _http_json_response(data, extra_headers=_NO_STORE_HEADERS) async def _handle_session_context_get(self, request: WsRequest, key: str) -> Response: - if not self.check_api_token(request): - return _http_error(401, "Unauthorized") - decoded_key = _decode_api_key(key) - if decoded_key is None: - return _http_error(400, "invalid session key") - if not _is_websocket_channel_session_key(decoded_key): - return _http_error(404, "session not found") + decoded_key = self._authorize_websocket_session(request, key) + if isinstance(decoded_key, Response): + return decoded_key if self.session_manager is None: return _http_error(503, "session manager unavailable") session = await asyncio.to_thread( @@ -1148,29 +1018,18 @@ class GatewayHTTPHandler: async def _project_session_history( self, request: WsRequest, key: str, project: _HistoryProjection[_ProjectionResult], ) -> _ProjectionResult | Response: - if not self.check_api_token(request): - return _http_error(401, "Unauthorized") - decoded = _decode_api_key(key) - if decoded is None: - return _http_error(400, "invalid session key") - if not _is_websocket_channel_session_key(decoded): - return _http_error(404, "session not found") + decoded = self._authorize_websocket_session(request, key) + if isinstance(decoded, Response): + return decoded if self.session_manager is None: return _http_error(503, "session manager unavailable") return await self.session_manager.state.project_history( - decoded, lambda history: project(request, key, history=history), + decoded, lambda history: project(request, decoded, history=history), ) - def _handle_prompt_index_get(self, request: WsRequest, key: str, *, history: HistoryReader) -> Response: + def _handle_prompt_index_get(self, request: WsRequest, decoded_key: str, *, history: HistoryReader) -> Response: from nanobot.webui.transcript import prompt_index_response, prompt_index_revision - if not self.check_api_token(request): - return _http_error(401, "Unauthorized") - decoded_key = _decode_api_key(key) - if decoded_key is None: - return _http_error(400, "invalid session key") - if not _is_websocket_channel_session_key(decoded_key): - return _http_error(404, "session not found") revision = prompt_index_revision(decoded_key, self._read_session_version(decoded_key), history=history) etag = _quoted_etag(revision) if revision else None if etag and _etag_matches(_case_insensitive_header(request.headers, "If-None-Match"), etag): @@ -1273,18 +1132,11 @@ class GatewayHTTPHandler: def _handle_webui_thread_get( self, request: WsRequest, - key: str, + decoded_key: str, *, history: HistoryReader, diagnostics: _WebUIThreadDiagnostics | None = None, ) -> Response | _PreparedThreadResponse: - if not self.check_api_token(request): - return _http_error(401, "Unauthorized") - decoded_key = _decode_api_key(key) - if decoded_key is None: - return _http_error(400, "invalid session key") - if not _is_websocket_channel_session_key(decoded_key): - return _http_error(404, "session not found") if diagnostics is not None: diagnostics.session_hash = hashlib.sha256(decoded_key.encode("utf-8")).hexdigest()[:12] scope = self.workspaces.scope_for_session_key(decoded_key) @@ -1379,14 +1231,7 @@ class GatewayHTTPHandler: data=data, headers=response_headers, ) - def _handle_webui_trace_detail_get(self, request: WsRequest, key: str, *, history: HistoryReader) -> Response: - if not self.check_api_token(request): - return _http_error(401, "Unauthorized") - decoded_key = _decode_api_key(key) - if decoded_key is None: - return _http_error(400, "invalid session key") - if not _is_websocket_channel_session_key(decoded_key): - return _http_error(404, "session not found") + def _handle_webui_trace_detail_get(self, request: WsRequest, decoded_key: str, *, history: HistoryReader) -> Response: detail_ref = _query_first(_parse_query(request.path), "ref") if not detail_ref: return _http_error(400, "missing trace detail ref") @@ -1400,13 +1245,9 @@ class GatewayHTTPHandler: ) def _handle_file_preview(self, request: WsRequest, key: str) -> Response: - if not self.check_api_token(request): - return _http_error(401, "Unauthorized") - decoded_key = _decode_api_key(key) - if decoded_key is None: - return _http_error(400, "invalid session key") - if not _is_websocket_channel_session_key(decoded_key): - return _http_error(404, "session not found") + decoded_key = self._authorize_websocket_session(request, key) + if isinstance(decoded_key, Response): + return decoded_key query = _parse_query(request.path) path = _query_first(query, "path") is_probe = _query_first(query, "probe") == "1" @@ -1426,43 +1267,23 @@ class GatewayHTTPHandler: return _http_json_response(payload, extra_headers=_NO_STORE_HEADERS) def _handle_session_automations(self, request: WsRequest, key: str) -> Response: - if not self.check_api_token(request): - return _http_error(401, "Unauthorized") - decoded_key = _decode_api_key(key) - if decoded_key is None: - return _http_error(400, "invalid session key") - if not _is_websocket_channel_session_key(decoded_key): - return _http_error(404, "session not found") - pending_job_ids = self._pending_automation_ids_for_session(decoded_key) - return _http_json_response( - session_automations_payload( - self.cron_service, - decoded_key, - local_trigger_store=self.local_trigger_store, - session_manager=self.session_manager, - pending_job_ids=pending_job_ids, - ) - ) + decoded_key = self._authorize_websocket_session(request, key) + if isinstance(decoded_key, Response): + return decoded_key + return _http_json_response(self.automation_routes.session_payload(decoded_key)) - async def _handle_session_delete(self, request: WsRequest, key: str) -> Response: - if not self.check_api_token(request): - return _http_error(401, "Unauthorized") + async def _handle_session_delete(self, key: str, params: MutationParams) -> MutationResult: if self.session_manager is None: - return _http_error(503, "session manager unavailable") - decoded_key = _decode_api_key(key) - if decoded_key is None: - return _http_error(400, "invalid session key") + return MutationResult.failure(503, "session manager unavailable") + decoded_key = key + if _API_KEY_RE.fullmatch(decoded_key) is None: + return MutationResult.failure(400, "invalid session key") if not _is_websocket_channel_session_key(decoded_key): - return _http_error(404, "session not found") - query = _request_query(request) - delete_automations = (_query_first(query, "delete_automations") or "").lower() - automation_jobs = session_automation_jobs( - self.cron_service, - decoded_key, - local_trigger_store=self.local_trigger_store, - ) + return MutationResult.failure(404, "session not found") + delete_automations = (_mutation_text(params, "delete_automations") or "").lower() + automation_jobs = self.automation_routes.session_jobs(decoded_key) if automation_jobs and delete_automations not in {"1", "true", "yes"}: - return _http_json_response( + return MutationResult.success( { "deleted": False, "blocked_by_automations": True, @@ -1470,288 +1291,20 @@ class GatewayHTTPHandler: } ) await ensure_webui_archives_imported(self.session_manager.state) - if automation_jobs: - for job in automation_jobs: - if isinstance(job, LocalTrigger): - if self.local_trigger_store is not None: - await asyncio.to_thread(self.local_trigger_store.delete, job.id) - elif self.cron_service is not None: - self.cron_service.remove_job(job.id) + await self.automation_routes.remove_session_jobs(automation_jobs) draft_deleted = self.workspaces.discard_draft_scope(decoded_key) if self.discard_session is not None: await self.discard_session(decoded_key) elif self.subagent_manager is not None: await self.subagent_manager.cancel_by_session(decoded_key) session_deleted = await self.session_manager.state.delete(decoded_key) - return _http_json_response({"deleted": bool(draft_deleted or session_deleted)}) + return MutationResult.success({"deleted": bool(draft_deleted or session_deleted)}) - async def _dispatch_automation_routes( - self, - request: WsRequest, - got: str, - ) -> Response | None: - if got == "/api/webui/automations": - return self._handle_webui_automations(request) - if got == "/api/webui/automations/result": - return await self._handle_webui_automation_result(request) - if got == "/api/webui/automations/chats": - return await self._handle_webui_automation_chats(request) - m = re.match(r"^/api/webui/automations/(enable|disable|delete|run|update|change-chat)$", got) + async def _dispatch_media_routes(self, request: WsRequest, got: str) -> Response | None: + m = _MEDIA_ROUTE_RE.match(got) if m: - return await self._handle_webui_automation_action(request, m.group(1)) - return None - - def _pending_cron_job_ids_for_all(self) -> set[str]: - if self.cron_service is None or self.cron_pending_job_ids is None: - return set() - pending: set[str] = set() - for job in self.cron_service.list_jobs(include_disabled=True): - session_key = job.payload.session_key - if not session_key and job.payload.origin_channel and job.payload.origin_chat_id: - session_key = f"{job.payload.origin_channel}:{job.payload.origin_chat_id}" - if session_key: - pending.update(self.cron_pending_job_ids(session_key)) - return pending - - def _pending_local_trigger_ids_for_all(self) -> set[str]: - if self.local_trigger_store is None or self.local_trigger_pending_ids is None: - return set() - pending: set[str] = set() - for trigger in self.local_trigger_store.list_triggers(include_disabled=True): - session_key = trigger.session_key - if not session_key and trigger.channel and trigger.chat_id: - session_key = f"{trigger.channel}:{trigger.chat_id}" - if session_key: - pending.update(self.local_trigger_pending_ids(session_key)) - return pending - - def _pending_automation_ids_for_session(self, session_key: str) -> set[str]: - pending: set[str] = set() - if self.cron_pending_job_ids is not None: - pending.update(self.cron_pending_job_ids(session_key)) - if self.local_trigger_pending_ids is not None: - pending.update(self.local_trigger_pending_ids(session_key)) - return pending - - def _handle_webui_automations(self, request: WsRequest) -> Response: - if not self.check_api_token(request): - return _http_error(401, "Unauthorized") - pending_job_ids = self._pending_cron_job_ids_for_all() - pending_job_ids.update(self._pending_local_trigger_ids_for_all()) - return _http_json_response( - all_automations_payload( - self.cron_service, - local_trigger_store=self.local_trigger_store, - session_manager=self.session_manager, - pending_job_ids=pending_job_ids, - ) - ) - - async def _automation_chats(self, job: CronJob) -> list[AutomationChat]: - if self.session_manager is None: - return [] - return await automation_chats( - job, self.session_manager, self.workspaces, - self.channel_runtime_status() if self.channel_runtime_status else {}, - ) - - async def _handle_webui_automation_chats(self, request: WsRequest) -> Response: - if not self.check_api_token(request): - return _http_error(401, "Unauthorized") - job_id = _query_first(_request_query(request), "id") or "" - job = self.cron_service.get_job(job_id) if self.cron_service else None - if job is None or not is_bound_cron_job(job): - return _http_error(404, "automation has no movable chat") - chats = await self._automation_chats(job) - current = next((chat for chat in chats - if chat.binding.session_key == job.payload.session_key), None) - return _http_json_response({ - "revision": binding_revision(job), - "current": current.public_payload() if current else None, - "chats": [chat.public_payload() for chat in chats], - }) - - async def _handle_webui_automation_result(self, request: WsRequest) -> Response: - if not self.check_api_token(request): - return _http_error(401, "Unauthorized") - query = _request_query(request) - job_id = (_query_first(query, "id") or "").strip() - try: - run_at_ms = int(_query_first(query, "run_at_ms") or "") - except ValueError: - return _http_error(400, "invalid run timestamp") - if not job_id or run_at_ms < 0: - return _http_error(400, "invalid automation run") - kind = _query_first(query, "kind") or "cron" - try: - if kind == "local_trigger": - trigger = self.local_trigger_store.get(job_id) if self.local_trigger_store else None - if trigger is None or self.local_trigger_store is None: - return _http_error(404, "automation not found") - deliveries = [item for item in trigger.run_history if item.run_at_ms == run_at_ms] - if len(deliveries) != 1: - return _http_error(404, "run not found") - response = await asyncio.to_thread( - trigger_run_response, self.local_trigger_store.runs_dir, trigger, deliveries[0], - ) - elif kind == "cron": - job = self.cron_service.get_job(job_id) if self.cron_service else None - if job is None or self.cron_service is None: - return _http_error(404, "automation not found") - if job.payload.kind == "system_event": - return _http_error(403, "system automation is protected") - runs = [item for item in job.state.run_history if item.run_at_ms == run_at_ms] - if len(runs) != 1: - return _http_error(404, "run not found") - response = await asyncio.to_thread( - cron_run_response, self.cron_service.store_path.parent / "runs", job, runs[0], - ) - else: - return _http_error(400, "invalid automation kind") - except OSError: - self._log.exception("Could not read automation run result") - return _http_error(500, "Could not read run result") - return _http_json_response({"response": response}) - - async def _handle_webui_automation_action( - self, - request: WsRequest, - action: str, - ) -> Response: - if not self.check_api_token(request): - return _http_error(401, "Unauthorized") - if self.cron_service is None and self.local_trigger_store is None: - return _http_error(503, "automation service unavailable") - - query = _request_query(request) - job_id = (_query_first(query, "id") or _query_first(query, "job_id") or "").strip() - if not job_id: - return _http_error(400, "missing automation id") - trigger = self.local_trigger_store.get(job_id) if self.local_trigger_store else None - if trigger is not None: - return self._handle_local_trigger_action(request, action, trigger) - - if self.cron_service is None: - return _http_error(404, "automation not found") - job = self.cron_service.get_job(job_id) - if job is None: - return _http_error(404, "automation not found") - if job.payload.kind == "system_event": - return _http_error(403, "system automation is protected") - if action in {"enable", "run"} and not is_bound_cron_job(job): - return _http_error(409, "automation has no linked chat") - - if action == "enable": - if self.cron_service.enable_job(job_id, enabled=True) is None: - return _http_error(404, "automation not found") - elif action == "disable": - if self.cron_service.enable_job(job_id, enabled=False) is None: - return _http_error(404, "automation not found") - elif action == "delete": - result = self.cron_service.remove_job(job_id) - if result == "not_found": - return _http_error(404, "automation not found") - if result == "protected": - return _http_error(403, "system automation is protected") - elif action == "run": - if not job.enabled: - return _http_error(409, "automation is disabled") - task = asyncio.create_task(self.cron_service.run_job(job_id, force=False)) - task.add_done_callback(self._log_automation_run_result) - elif action == "change-chat": - values = _automation_values_from_request(request) - if (not isinstance(values, dict) - or set(values) != {"target_id", "revision", "message"} - or not all(isinstance(v, str) for v in values.values())): - return _http_error(400, "invalid automation chat payload") - if job.id in self._pending_cron_job_ids_for_all(): - return _http_error(409, "automation_chat_busy") - target = next((chat for chat in await self._automation_chats(job) - if chat.id == values["target_id"]), None) - if target is None or not target.available: - return _http_error(409, "automation_chat_unavailable") - if target.binding.session_key == job.payload.session_key: - return _http_error(400, "choose a different chat") - try: - self.cron_service.change_binding( - job_id, revision=values["revision"], binding=target.binding, - message=values["message"], - ) - except CronBindingError as exc: - return _http_error(409, f"automation_chat_{exc.reason}") - except OSError: - logger.exception("WebUI automation chat save failed") - return _http_error(500, "could not save the chat; try again") - elif action == "update": - values = _automation_values_from_request(request) - if values is None: - return _http_error(400, "invalid automation update payload") - parsed = _parse_automation_update(values, current_job=job) - if isinstance(parsed, str): - return _http_error(400, parsed) - try: - result = self.cron_service.update_job(job_id, **parsed) - except ValueError as exc: - return _http_error(400, str(exc)) - if result == "not_found": - return _http_error(404, "automation not found") - if result == "protected": - return _http_error(403, "system automation is protected") - else: - return _http_error(404, "unknown automation action") - - return self._handle_webui_automations(request) - - def _handle_local_trigger_action( - self, - request: WsRequest, - action: str, - trigger: LocalTrigger, - ) -> Response: - if self.local_trigger_store is None: - return _http_error(503, "trigger service unavailable") - if action == "enable": - if self.local_trigger_store.enable(trigger.id, enabled=True) is None: - return _http_error(404, "automation not found") - elif action == "disable": - if self.local_trigger_store.enable(trigger.id, enabled=False) is None: - return _http_error(404, "automation not found") - elif action == "delete": - if not self.local_trigger_store.delete(trigger.id): - return _http_error(404, "automation not found") - elif action == "run": - return _http_error(409, "local trigger requires a CLI message") - elif action == "update": - values = _automation_values_from_request(request) - if values is None: - return _http_error(400, "invalid automation update payload") - parsed = _parse_local_trigger_update(values) - if isinstance(parsed, str): - return _http_error(400, parsed) - if parsed: - if self.local_trigger_store.update(trigger.id, **parsed) is None: - return _http_error(404, "automation not found") - else: - return _http_error(404, "unknown automation action") - - return self._handle_webui_automations(request) - - @staticmethod - def _log_automation_run_result(task: asyncio.Task[bool]) -> None: - try: - ran = task.result() - except Exception: - logger.exception("WebUI automation run-now task failed") - return - if not ran: - logger.warning("WebUI automation run-now task did not execute") - - - def _dispatch_media_routes(self, request: WsRequest, got: str) -> Response | None: - m = re.match(r"^/api/media/([A-Za-z0-9_-]+)/([A-Za-z0-9_-]+)$", got) - if m: - return self._handle_media_fetch(m.group(1), m.group(2), request) + return await asyncio.to_thread(self._handle_media_fetch, m.group(1), m.group(2), request) return None def _handle_media_fetch( @@ -1772,44 +1325,23 @@ class GatewayHTTPHandler: return await self._handle_sessions_list(request) if got == "/api/commands": return self._handle_commands(request) - if got == "/api/workspaces/favorite": - return self._handle_workspace_favorite(connection, request) - if got == "/api/workspaces/resolve-project": - return await self._handle_workspace_resolve_project(connection, request) if got == "/api/workspaces/directories": return await self._handle_workspace_directories(connection, request) if got == "/api/workspaces": - return self._handle_workspaces(connection, request) + return await asyncio.to_thread(self._handle_workspaces, connection, request) if got == "/api/webui/skills/search": return await self._handle_webui_skills_search(request) if got == "/api/webui/skills/trending": return await self._handle_webui_skills_trending(request) if got == "/api/webui/skills/trends": return await self._handle_webui_skill_trends(request) - if got == "/api/webui/skills/install": - return await self._handle_webui_skill_install(connection, request) - if got == "/api/webui/skills/update": - return await self._handle_webui_skill_update(request) - if got == "/api/webui/skills/delete": - return await self._handle_webui_skill_delete(connection, request) if got == "/api/webui/skills": return await self._handle_webui_skills(request) - m = re.match(r"^/api/webui/skills/([^/]+)$", got) + m = _SKILL_DETAIL_RE.match(got) if m: return await self._handle_webui_skill_detail(request, m.group(1)) - if got in {"/api/webui/star-prompt/claim", "/api/webui/star-prompt/dismiss"}: - if not self.check_api_token(request): - return _http_error(401, "Unauthorized") - try: - show = update_star_prompt("claim" if got.endswith("/claim") else "dismiss") - except (OSError, ValueError, TimeoutError): - self._log.exception("failed to persist star invitation state") - return _http_error(500, "failed to save reminder preference") - return _http_json_response({"show": show}) if got == "/api/webui/sidebar-state": return await self._handle_webui_sidebar_state(request) - if got == "/api/webui/sidebar-state/update": - return await self._handle_webui_sidebar_state_update(request) return None def _handle_commands(self, request: WsRequest) -> Response: @@ -1826,27 +1358,21 @@ class GatewayHTTPHandler: ) ) - def _handle_workspace_favorite(self, connection: Any, request: WsRequest) -> Response: - if not self.check_api_token(request): - return _http_error(401, "Unauthorized") - payload = _mutation_payload(request) or {} + def _handle_workspace_favorite(self, payload: dict[str, Any]) -> MutationResult: try: favorites = self.workspaces.set_favorite_project(payload.get("path"), payload.get("pinned")) except WorkspaceScopeError as exc: - return _http_error(exc.status, exc.message) + return MutationResult.failure(exc.status, exc.message) except OSError: - return _http_error(500, "could not save favorite folders") - return _http_json_response({"favorite_projects": favorites}) + return MutationResult.failure(500, "could not save favorite folders") + return MutationResult.success({"favorite_projects": favorites}) - async def _handle_workspace_resolve_project(self, connection: Any, request: WsRequest) -> Response: - if not self.check_api_token(request): - return _http_error(401, "Unauthorized") - payload = _mutation_payload(request) or {} + def _handle_workspace_resolve_project(self, payload: dict[str, Any]) -> MutationResult: try: project = self.workspaces.resolve_project(payload.get("path")) except WorkspaceScopeError as exc: - return _http_error(exc.status, exc.message) - return _http_json_response(project) + return MutationResult.failure(exc.status, exc.message) + return MutationResult.success(project) async def _handle_workspace_directories(self, connection: Any, request: WsRequest) -> Response: if not self.check_api_token(request): @@ -1926,20 +1452,18 @@ class GatewayHTTPHandler: async def _handle_webui_skill_install( self, connection: Any, - request: WsRequest, - ) -> Response: - if not self.check_api_token(request): - return _http_error(401, "Unauthorized") - if not self._allow_webui_package_install(connection, request): - return _http_error(403, "remote skill installation is disabled") + headers: Any, + params: MutationParams, + ) -> MutationResult: + if not await asyncio.to_thread(self._allow_webui_package_install, connection, headers): + return MutationResult.failure(403, "remote skill installation is disabled") if self._skill_install_lock.locked(): - return _http_error(409, "another skill installation is already in progress") + return MutationResult.failure(409, "another skill installation is already in progress") - query = _request_query(request) - provider = _query_first(query, "provider") or "skills_sh" - source = _query_first(query, "source") or "" - skill_id = _query_first(query, "skill") or "" - version = _query_first(query, "version") or "" + provider = _mutation_text(params, "provider") or "skills_sh" + source = _mutation_text(params, "source") or "" + skill_id = _mutation_text(params, "skill") or "" + version = _mutation_text(params, "version") or "" async with self._skill_install_lock: try: action = await install_marketplace_skill( @@ -1950,17 +1474,17 @@ class GatewayHTTPHandler: version=version, ) except SkillsMarketplaceError as exc: - return _http_error(exc.status, exc.message) + return MutationResult.failure(exc.status, exc.message) except Exception: self._log.exception("skill installation failed") - return _http_error(500, "skill installation failed") - return _http_json_response({ + return MutationResult.failure(500, "skill installation failed") + return MutationResult.success({ **(await self._load_webui_skills()), "last_action": action, }) - def _allow_webui_package_install(self, connection: Any, request: WsRequest) -> bool: - if _is_local_browser_request(connection, request.headers): + def _allow_webui_package_install(self, connection: Any, headers: Any) -> bool: + if _is_local_browser_request(connection, headers): return True try: return bool( @@ -1970,28 +1494,26 @@ class GatewayHTTPHandler: self._log.exception("failed to load remote package install policy") return False - async def _handle_webui_skill_update(self, request: WsRequest) -> Response: - if not self.check_api_token(request): - return _http_error(401, "Unauthorized") - query = _request_query(request) - name = _query_first(query, "name") or "" - raw_enabled = (_query_first(query, "enabled") or "").lower() + async def _handle_webui_skill_update(self, params: MutationParams) -> MutationResult: + name = _mutation_text(params, "name") or "" + raw_enabled = (_mutation_text(params, "enabled") or "").lower() if raw_enabled not in {"true", "false"}: - return _http_error(400, "enabled must be true or false") + return MutationResult.failure(400, "enabled must be true or false") try: - action = self.settings.config.run_serialized( + action = await asyncio.to_thread( + self.settings.config.run_serialized, lambda config_path: set_webui_skill_enabled( self.skills_workspace_path, name, enabled=raw_enabled == "true", disabled_skills=self.disabled_skills, config_path=config_path, - ) + ), ) except SkillManagementError as exc: - return _http_error(exc.status, exc.message) + return MutationResult.failure(exc.status, exc.message) self._apply_skill_state() - return _http_json_response({ + return MutationResult.success({ **(await self._load_webui_skills()), "last_action": action, }) @@ -1999,26 +1521,26 @@ class GatewayHTTPHandler: async def _handle_webui_skill_delete( self, connection: Any, - request: WsRequest, - ) -> Response: - if not self.check_api_token(request): - return _http_error(401, "Unauthorized") - if not _is_local_browser_request(connection, request.headers): - return _http_error(403, "remote skill deletion is disabled") - name = _query_first(_request_query(request), "name") or "" + headers: Any, + params: MutationParams, + ) -> MutationResult: + if not _is_local_browser_request(connection, headers): + return MutationResult.failure(403, "remote skill deletion is disabled") + name = _mutation_text(params, "name") or "" try: - action = self.settings.config.run_serialized( + action = await asyncio.to_thread( + self.settings.config.run_serialized, lambda config_path: delete_webui_skill( self.skills_workspace_path, name, disabled_skills=self.disabled_skills, config_path=config_path, - ) + ), ) except SkillManagementError as exc: - return _http_error(exc.status, exc.message) + return MutationResult.failure(exc.status, exc.message) self._apply_skill_state() - return _http_json_response({ + return MutationResult.success({ **(await self._load_webui_skills()), "last_action": action, }) @@ -2055,25 +1577,30 @@ class GatewayHTTPHandler: return _http_error(500, "failed to read sidebar state") return _http_json_response(state) - async def _handle_webui_sidebar_state_update(self, request: WsRequest) -> Response: - if not self.check_api_token(request): - return _http_error(401, "Unauthorized") - payload = _mutation_payload(request) - state_value = payload.get("state") if payload is not None else None + async def _handle_webui_sidebar_state_update(self, payload: dict[str, Any]) -> MutationResult: + state_value = payload.get("state") if state_value is None: - return _http_error(400, "missing state") + return MutationResult.failure(400, "missing state") if not isinstance(state_value, dict): - return _http_error(400, "state must be an object") + return MutationResult.failure(400, "state must be an object") try: state = await self.sidebar_state.write(cast(dict[str, Any], state_value)) except ValueError as e: - return _http_error(400, str(e)) + return MutationResult.failure(400, str(e)) except OSError: self._log.exception("failed to write webui sidebar state") - return _http_error(500, "failed to write sidebar state") - return _http_json_response(state) + return MutationResult.failure(500, "failed to write sidebar state") + return MutationResult.success(state) + async def _mutate_star_prompt(self, action: Literal["claim", "dismiss"]) -> MutationResult: + try: + show = await asyncio.to_thread(update_star_prompt, action) + except (OSError, ValueError, TimeoutError): + self._log.exception("failed to persist star invitation state") + return MutationResult.failure(500, "failed to save reminder preference") + return MutationResult.success({"show": show}) + def _serve_static( self, request_path: str, @@ -2132,141 +1659,5 @@ class GatewayHTTPHandler: ) -def _automation_values_from_request(request: WsRequest) -> dict[str, Any] | None: - payload = _mutation_payload(request) - if payload is None or "values" not in payload: - return {} - values = payload.get("values") - return cast(dict[str, Any], values) if isinstance(values, dict) else None - - -def _parse_automation_update( - values: dict[str, Any], - *, - current_job: CronJob | None = None, -) -> dict[str, Any] | str: - update: dict[str, Any] = {} - if "name" in values: - raw_name = values.get("name") - if not isinstance(raw_name, str): - return "name must be a string" - name = raw_name.strip() - if not name: - return "name cannot be empty" - update["name"] = name - if "message" in values: - raw_message = values.get("message") - if not isinstance(raw_message, str): - return "message must be a string" - message = raw_message.strip() - if not message: - return "message cannot be empty" - update["message"] = message - if "schedule" in values: - raw_schedule = values.get("schedule") - if not isinstance(raw_schedule, dict): - return "schedule must be an object" - parsed_schedule = _parse_automation_schedule(cast(dict[str, Any], raw_schedule)) - if isinstance(parsed_schedule, str): - return parsed_schedule - if current_job is not None and _schedule_matches_job(parsed_schedule, current_job): - return update - schedule_error = _validate_automation_schedule(parsed_schedule) - if schedule_error: - return schedule_error - update["schedule"] = parsed_schedule - update["delete_after_run"] = parsed_schedule.kind == "at" - return update - - -def _parse_local_trigger_update(values: dict[str, Any]) -> dict[str, Any] | str: - update: dict[str, Any] = {} - if "name" in values: - raw_name = values.get("name") - if not isinstance(raw_name, str): - return "name must be a string" - name = raw_name.strip() - if not name: - return "name cannot be empty" - update["name"] = name - forbidden = [key for key in ("message", "schedule") if key in values] - if forbidden: - return "local trigger updates only support name" - return update - - -def _parse_automation_schedule(values: dict[str, Any]) -> CronSchedule | str: - raw_kind = values.get("kind") - if not isinstance(raw_kind, str): - return "schedule kind must be a string" - kind = raw_kind.strip() - if kind == "every": - every_ms = _positive_int(values.get("every_ms")) - if every_ms is None: - return "every schedule requires positive every_ms" - return CronSchedule(kind="every", every_ms=every_ms) - if kind == "cron": - raw_expr = values.get("expr") - if not isinstance(raw_expr, str): - return "cron schedule requires expr" - expr = raw_expr.strip() - if not expr: - return "cron schedule requires expr" - raw_tz = values.get("tz") - if raw_tz is not None and not isinstance(raw_tz, str): - return "cron schedule timezone must be a string" - tz = raw_tz.strip() if isinstance(raw_tz, str) else "" - return CronSchedule(kind="cron", expr=expr, tz=tz or None) - if kind == "at": - at_ms = _positive_int(values.get("at_ms")) - if at_ms is None: - return "one-time schedule requires positive at_ms" - return CronSchedule(kind="at", at_ms=at_ms) - return "unknown schedule kind" - - -def _schedule_matches_job(schedule: CronSchedule, job: CronJob) -> bool: - current = job.schedule - if schedule.kind != current.kind: - return False - if schedule.kind == "at": - return schedule.at_ms == current.at_ms - if schedule.kind == "every": - return schedule.every_ms == current.every_ms - if schedule.kind == "cron": - return (schedule.expr or "") == (current.expr or "") and ( - schedule.tz or None - ) == (current.tz or None) - return False - - -def _validate_automation_schedule(schedule: CronSchedule) -> str | None: - if schedule.kind == "at": - if not schedule.at_ms or schedule.at_ms <= int(time.time() * 1000): - return "one-time schedule must be in the future" - return None - if schedule.kind != "cron": - return None - - try: - from datetime import datetime - from zoneinfo import ZoneInfo - - from croniter import croniter - - tz = ZoneInfo(schedule.tz) if schedule.tz else datetime.now().astimezone().tzinfo - base = datetime.now(tz=tz) - croniter(cast(str, schedule.expr), base).get_next(datetime) - except Exception: - return "cron schedule is invalid" - return None - - -def _positive_int(value: Any) -> int | None: - if isinstance(value, bool) or not isinstance(value, int): - return None - return value if value > 0 else None - - def _is_websocket_channel_session_key(key: str) -> bool: return is_webui_session_key(key) diff --git a/tests/webui/test_background.py b/tests/webui/test_background.py index cd5e7d9d6..22b3b51b1 100644 --- a/tests/webui/test_background.py +++ b/tests/webui/test_background.py @@ -37,7 +37,6 @@ async def test_background_auth_and_staged_upload(tmp_path): handler.tokens = SimpleNamespace(check_api_token=lambda request: request.headers.get("Authorization") == "Bearer valid") router = WebUICommandRouter.__new__(WebUICommandRouter) router._background_lock = asyncio.Lock() - router._background_references = set() router._http_router = handler router._uploads = SimpleNamespace(store=store, owner=lambda connection: connection) router.request_locks = {} @@ -106,7 +105,6 @@ async def test_background_style_persistence_and_validation(tmp_path): handler.tokens = SimpleNamespace(check_api_token=lambda request: request.headers.get("Authorization") == "Bearer valid") router = WebUICommandRouter.__new__(WebUICommandRouter) router._background_lock = asyncio.Lock() - router._background_references = set() router._http_router = handler router.request_locks = {} path = "/api/settings/background-style" @@ -173,8 +171,6 @@ async def test_background_worker_cancellation_survives_disconnect(tmp_path, monk import asyncio import threading - from nanobot.webui import background - store = AttachmentStore(tmp_path / "staging") body = image_bytes() @@ -184,24 +180,28 @@ async def test_background_worker_cancellation_survives_disconnect(tmp_path, monk ref = await store.upload(chunks(), owner="alice", mime="image/png", size=len(body)) router = WebUICommandRouter.__new__(WebUICommandRouter) router._background_lock = asyncio.Lock() - router._background_references = set() router._http_router = SimpleNamespace(bus=MessageBus(), settings=SimpleNamespace( config=SimpleNamespace(path=tmp_path / "config.json"))) router._uploads = SimpleNamespace(store=store, owner=lambda connection: connection) router.request_locks = {} + staged_path = store.inspect([ref], owner="alice")[0].path started, release = threading.Event(), threading.Event() - original = background.save_background + original_open = type(staged_path).open + event_loop_thread = threading.get_ident() - def slow(*args): - started.set() - assert release.wait(5) - original(*args) + def slow_read(path, mode="r", *args, **kwargs): + if path == staged_path and mode == "rb": + assert threading.get_ident() != event_loop_thread + started.set() + assert release.wait(5) + return original_open(path, mode, *args, **kwargs) - monkeypatch.setattr(background, "save_background", slow) + monkeypatch.setattr(type(staged_path), "open", slow_read) task = asyncio.create_task(router.execute_webui_request("alice", "background.update", {"reference": ref})) assert await asyncio.to_thread(started.wait, 3) - # The event loop remains responsive, and disconnect cannot invalidate the worker's descriptor. + # Disconnect cannot remove the staged source even before the worker opens it. store.discard_owner("alice") + assert staged_path.exists() task.cancel() await asyncio.sleep(0) assert not task.done() @@ -209,6 +209,7 @@ async def test_background_worker_cancellation_survives_disconnect(tmp_path, monk with pytest.raises(asyncio.CancelledError): await task assert (tmp_path / "webui" / "background.png").exists() + assert not staged_path.exists() async def test_background_worker_failure_releases_upload_for_retry(tmp_path, monkeypatch): @@ -223,7 +224,6 @@ async def test_background_worker_failure_releases_upload_for_retry(tmp_path, mon ref = await store.upload(chunks(), owner="alice", mime="image/png", size=len(body)) router = WebUICommandRouter.__new__(WebUICommandRouter) router._background_lock = asyncio.Lock() - router._background_references = set() router._http_router = SimpleNamespace(bus=MessageBus(), settings=SimpleNamespace( config=SimpleNamespace(path=tmp_path / "config.json"))) router._uploads = SimpleNamespace(store=store, owner=lambda connection: connection) @@ -251,7 +251,6 @@ async def test_invalid_background_releases_upload_for_retry(tmp_path): router = WebUICommandRouter.__new__(WebUICommandRouter) router._background_lock = asyncio.Lock() - router._background_references = set() router._http_router = SimpleNamespace(bus=MessageBus(), settings=SimpleNamespace( config=SimpleNamespace(path=tmp_path / "config.json"))) router._uploads = SimpleNamespace(store=store, owner=lambda connection: connection) @@ -281,7 +280,6 @@ async def test_background_waiter_cancelled_does_not_write(tmp_path, monkeypatch) bus = MessageBus() router = WebUICommandRouter.__new__(WebUICommandRouter) router._background_lock = asyncio.Lock() - router._background_references = set() router._http_router = SimpleNamespace(bus=bus, settings=SimpleNamespace( config=SimpleNamespace(path=tmp_path / "config.json"))) router._uploads = SimpleNamespace(store=store, owner=lambda connection: connection) diff --git a/tests/webui/test_gateway_terminal.py b/tests/webui/test_gateway_terminal.py index d344551a9..194c0f1a5 100644 --- a/tests/webui/test_gateway_terminal.py +++ b/tests/webui/test_gateway_terminal.py @@ -10,16 +10,17 @@ from nanobot.webui.gateway_tokens import GatewayTokenStore from nanobot.webui.ws_http import GatewayHTTPHandler -def test_terminal_probe_is_private_stable_and_does_not_issue_credentials(): +async def test_terminal_probe_is_private_stable_and_does_not_issue_credentials(): handler = object.__new__(GatewayHTTPHandler) handler.config = WebSocketConfig(token_issue_secret="fixture-secret") handler.tokens = GatewayTokenStore(max_tokens=0) connection = SimpleNamespace(remote_address=("127.0.0.1", 10000)) request = Request("/webui/terminal", Headers({"Host": "127.0.0.1:8765"})) - assert handler._handle_bootstrap(connection, request, terminal_probe=True).status_code == 401 + denied = await handler._handle_bootstrap(connection, request, terminal_probe=True) + assert denied.status_code == 401 request.headers["X-Nanobot-Auth"] = "fixture-secret" for _ in range(3): - response = handler._handle_bootstrap(connection, request, terminal_probe=True) + response = await handler._handle_bootstrap(connection, request, terminal_probe=True) assert response.status_code == 200 assert json.loads(response.body) == gateway_identity(handler.tokens.instance_id) assert "no-store" in response.headers["Cache-Control"] diff --git a/tests/webui/test_record_pages.py b/tests/webui/test_record_pages.py index 907819934..ed9f4ee51 100644 --- a/tests/webui/test_record_pages.py +++ b/tests/webui/test_record_pages.py @@ -10,7 +10,7 @@ from nanobot.bus.queue import MessageBus from nanobot.channels.websocket.runtime import WebSocketConfig from nanobot.session.display_history import HistoryFact from nanobot.session.history_graph import history_record_size -from nanobot.webui import transcript +from nanobot.webui import transcript, transcript_replay from nanobot.webui.gateway_services import build_gateway_services from nanobot.webui.history import fact_from_record @@ -594,3 +594,57 @@ async def test_http_fragment_recovery_reads_persisted_canonical_history(history, assert pages[-1]["completed_turn_ids"] == ["t"] assert pages[-1]["has_pending_tool_calls"] is False assert history.read(key) == original + + +def test_selected_bytes_are_measured_once_for_the_compacted_source_page(history, monkeypatch): + key = "websocket:replay-metrics" + for record in ( + {"event": "user", "text": "question"}, + {"event": "delta", "text": "partial"}, + {"event": "stream_end", "text": "answer 日本語"}, + {"event": "turn_end"}, + ): + history.append(key, record) + + measured = [] + measure = transcript_replay._records_bytes + + def track_measure(records): + measured.append(records) + return measure(records) + + monkeypatch.setattr(transcript_replay, "_records_bytes", track_measure) + stats = transcript.TranscriptReplayStats() + page = history.build(key, stats=stats) + assert page is not None + assert stats.parsed_records == 4 + assert stats.selected_records == 3 + assert stats.compacted_delta_records == 1 + assert not measured + selected_bytes = stats.selected_bytes + assert stats.selected_bytes == selected_bytes > 0 + assert len(measured) == 1 + assert [record["event"] for record in measured[0]] == ["user", "stream_end", "turn_end"] + assert selected_bytes == sum( + len(json.dumps(record, ensure_ascii=False, separators=(",", ":")).encode("utf-8")) + 1 + for record in measured[0] + ) + + +def test_cached_inline_trace_uses_message_augmentation(history): + key = "websocket:cached-trace-augmentation" + history.append(key, {"event": "user", "text": "question"}) + history.append(key, { + "event": "message", "kind": "progress", "text": "", + "media": ["private.png"], "media_urls": [{"url": "/api/media/old", "name": "private.png"}], + }) + history.append(key, {"event": "message", "kind": "progress", "text": "plain text", "render_as": "text"}) + + result = history.build( + key, + augment_assistant_text=lambda text: f"augmented:{text}", + augment_assistant_media=lambda _paths: [], + ) + progress = [event for event in result["events"] if event.get("kind") == "progress"] + assert [event["text"] for event in progress] == ["augmented:", "plain text"] + assert "media_urls" not in progress[0] diff --git a/tests/webui/test_remote_instances.py b/tests/webui/test_remote_instances.py index 0f9fa9136..83e90111c 100644 --- a/tests/webui/test_remote_instances.py +++ b/tests/webui/test_remote_instances.py @@ -989,6 +989,7 @@ async def test_remote_clients_cannot_open_local_file_picker(gateway, monkeypatch )) result = await gateway.http.dispatch_webui_mutation(connection, "remote.pick_file", {}) assert result.status_code == 403 + assert result.message == "remote_connections_local_only" choose.assert_not_awaited() diff --git a/tests/webui/test_settings_edit_admission.py b/tests/webui/test_settings_edit_admission.py index deca01b82..181aef7a6 100644 --- a/tests/webui/test_settings_edit_admission.py +++ b/tests/webui/test_settings_edit_admission.py @@ -1,7 +1,6 @@ from __future__ import annotations import asyncio -import json import threading from pathlib import Path from types import SimpleNamespace @@ -18,6 +17,7 @@ from nanobot.providers.factory import load_provider_snapshot from nanobot.session.model_selection import SESSION_MODEL_PRESET_METADATA_KEY from nanobot.webui import settings_api from nanobot.webui.http_utils import http_json_response +from nanobot.webui.settings_contracts import MutationParams from nanobot.webui.settings_routes import WebUISettingsRouter from nanobot.webui.settings_services import WebUISettingsServices @@ -96,12 +96,9 @@ async def test_model_save_commits_before_refreshing_next_session_admission( assert prior.context_window_tokens == cached_preset.context_window_tokens == 100_000 assert (await admit("draft-only")).context_window_tokens == 100_000 - path = "/api/settings/model-configurations/update" - request = SimpleNamespace(path=path, headers=Headers()) - request._nanobot_webui_mutation_request = True - request._nanobot_webui_mutation_payload = draft - request._nanobot_trusted_proxy_authenticated = True - pending_save = asyncio.create_task(router.dispatch(None, request, path)) + pending_save = asyncio.create_task(router.dispatch_mutation( + None, Headers(), "settings.model_configuration.update", MutationParams(draft), + )) assert await asyncio.to_thread(before_save.wait, 5) assert not pending_save.done() assert disk_window() == 100_000 @@ -117,7 +114,7 @@ async def test_model_save_commits_before_refreshing_next_session_admission( allow_return.set() response = await asyncio.wait_for(pending_save, 5) - assert response.status_code == 200, json.loads(response.body) + assert response.status_code == 200, response.message assert agent.runtime_resolver.runtime.context_window_tokens == 500_000 next_runtime = await admit("after-success") next_preset = await admit("after-success-preset", explicit_preset=True) diff --git a/tests/webui/test_settings_models.py b/tests/webui/test_settings_models.py index eb7d0609d..b3f889e9d 100644 --- a/tests/webui/test_settings_models.py +++ b/tests/webui/test_settings_models.py @@ -8,12 +8,14 @@ import pytest from nanobot.config.schema import Config from nanobot.providers.registry import find_by_name +from nanobot.webui.settings_contracts import MutationParams from nanobot.webui.settings_models import ( WebUISettingsError, create_model_configuration, model_settings_payload, provider_models_payload, update_agent_model_settings, + update_model_call_order, update_model_configuration, update_provider_settings, ) @@ -367,3 +369,54 @@ def test_known_reasoning_efforts_preserve_default_none_and_custom_roundtrips() - if row["name"] == unknown) assert row["reasoning_effort"] == "future-effort" assert row["reasoning_effort_values"] == ["", "low", "medium", "high"] + + +def test_model_call_order_accepts_json_request_and_legacy_alias() -> None: + config = Config.model_validate({ + "providers": {"openai": {"apiKey": "fixture"}}, + "modelPresets": {name: {"model": "gpt-4o", "provider": "openai"} for name in ("alpha", "beta")}, + }) + assert update_model_call_order( + config, MutationParams({"order": [" beta ", "alpha"]}), oauth_status=_oauth_status, + ) + assert config.agents.defaults.model_preset == "beta" + assert config.agents.defaults.fallback_models == ["alpha"] + assert not update_model_call_order( + config, {"presetNames": ['["beta", "alpha"]']}, oauth_status=_oauth_status, + ) + + with pytest.raises(WebUISettingsError, match="model call order must contain at least one preset"): + update_model_call_order( + config, MutationParams({"order": ["alpha", 5]}), oauth_status=_oauth_status, + ) + with pytest.raises(WebUISettingsError, match="model call order must be a JSON array"): + update_model_call_order(config, {"order": ["broken"]}, oauth_status=_oauth_status) + assert config.agents.defaults.model_preset == "beta" + assert config.agents.defaults.fallback_models == ["alpha"] + + +def test_structured_api_declarations_can_be_set_and_cleared() -> None: + config = Config() + config.providers.openai.api_key = "fixture" + api = {"supportedApis": ["responses"], "preferredApi": "responses"} + changed, _ = update_provider_settings(config, MutationParams({"provider": "openai", "api": api})) + assert changed + assert config.providers.openai.api is not None + assert config.providers.openai.api.preferred_api == "responses" + + name = create_model_configuration( + config, MutationParams({"name": "custom", "provider": "openai", "model": "gpt-4o", "api": api}), + oauth_status=_oauth_status, + ) + saved_api = config.model_presets[name].api + assert saved_api is not None + assert saved_api.model_dump(by_alias=True, mode="json") == api + with pytest.raises(WebUISettingsError, match="api must declare supportedApis"): + update_model_configuration( + config, MutationParams({"name": name, "api": []}), oauth_status=_oauth_status, + ) + assert config.model_presets[name].api == saved_api + assert update_model_configuration( + config, MutationParams({"name": name, "api": None}), oauth_status=_oauth_status, + ) + assert config.model_presets[name].api is None diff --git a/tests/webui/test_settings_routes.py b/tests/webui/test_settings_routes.py index 83d667408..a9cc60fa7 100644 --- a/tests/webui/test_settings_routes.py +++ b/tests/webui/test_settings_routes.py @@ -20,7 +20,8 @@ from nanobot.config.schema import MCPServerConfig from nanobot.runtime_admission import RuntimeBusyError from nanobot.webui.http_utils import http_json_response from nanobot.webui.mcp_presets_api import custom_mcp_action -from nanobot.webui.settings_routes import WebUISettingsRouter +from nanobot.webui.settings_contracts import MutationParams +from nanobot.webui.settings_routes import _SETTINGS_ROUTES, WebUISettingsRouter from nanobot.webui.settings_services import WebUISettingsServices @@ -58,21 +59,27 @@ def _router( ) -def _mutation_request(path: str, payload: dict[str, object]) -> SimpleNamespace: - request = SimpleNamespace(path=path, headers=Headers()) - request._nanobot_webui_mutation_request = True - request._nanobot_webui_mutation_payload = payload - request._nanobot_trusted_proxy_authenticated = True - return request +def _mutation_request(path: str, payload: dict[str, object]) -> tuple[str, MutationParams]: + if path.startswith("/api/settings/channels/") and "/connect/" in path: + _, channel, _, operation = path.rsplit("/", 3) + return f"settings.channel.connect.{operation}", MutationParams({"channel": channel, **payload}) + action = _SETTINGS_ROUTES[path].mutation + assert action is not None + return action, MutationParams(payload) -async def test_sandbox_check_is_authenticated_explicit_and_serialized(tmp_path, monkeypatch): +async def _mutate( + router: WebUISettingsRouter, request: tuple[str, MutationParams], +): + action, params = request + return await router.dispatch_mutation(None, Headers(), action, params) + + +async def test_sandbox_check_is_websocket_only_and_serialized(tmp_path, monkeypatch): path = "/api/settings/sandbox/check" router = _router(config_path=tmp_path / "config.json") response = await router.dispatch(None, SimpleNamespace(path=path, headers=Headers()), path) assert response.status_code == 405 - unauthorized = _router(authorized=False, config_path=tmp_path / "config.json") - assert (await unauthorized.dispatch(None, _mutation_request(path, {}), path)).status_code == 401 started, release = asyncio.Event(), asyncio.Event() async def probe(config, workspace): @@ -81,33 +88,30 @@ async def test_sandbox_check_is_authenticated_explicit_and_serialized(tmp_path, return {"state": "passed", "reason": "", "launcher": "/usr/bin/bwrap", "revision": "test", "supported_backend": "bwrap"} monkeypatch.setattr("nanobot.webui.settings_system.check_sandbox", probe) - first = asyncio.create_task(router.dispatch(None, _mutation_request(path, {}), path)) + first = asyncio.create_task(_mutate(router, _mutation_request(path, {}))) await asyncio.wait_for(started.wait(), 2) try: - assert (await router.dispatch(None, _mutation_request(path, {}), path)).status_code == 409 + assert (await _mutate(router, _mutation_request(path, {}))).status_code == 409 finally: release.set() assert (await first).status_code == 200 - assert (await router.dispatch(None, _mutation_request(path, {}), path)).status_code == 200 + assert (await _mutate(router, _mutation_request(path, {}))).status_code == 200 @pytest.mark.asyncio -async def test_nanobot_update_requires_auth_local_permission_and_websocket(tmp_path, monkeypatch): +async def test_nanobot_update_requires_local_permission_and_websocket(tmp_path, monkeypatch): router = _router(config_path=tmp_path / "config.json") path = "/api/settings/nanobot-update/job/prepare" request = SimpleNamespace(path=path, headers=Headers()) response = await router.dispatch(None, request, path) assert response.status_code == 405 - response = await router.dispatch(None, _mutation_request(path, {}), path) + response = await _mutate(router, _mutation_request(path, {})) assert response.status_code == 403 - unauthorized = _router(authorized=False, config_path=tmp_path / "config.json") - response = await unauthorized.dispatch(None, _mutation_request(path, {}), path) - assert response.status_code == 401 monkeypatch.setattr(router._system, "allow_feature_package_install", lambda _: True) - response = await router.dispatch(None, _mutation_request(path, {"id": "invalid"}), path) + response = await _mutate(router, _mutation_request(path, {"id": "invalid"})) assert response.status_code == 400 router._runtime_surface = "native" - response = await router.dispatch(None, _mutation_request(path, {}), path) + response = await _mutate(router, _mutation_request(path, {})) assert response.status_code == 409 @@ -155,9 +159,9 @@ async def test_provider_login_keeps_maintenance_busy_until_worker_exits(tmp_path )) monkeypatch.setattr("nanobot.webui.settings_api.settings_payload", lambda **_: {}) path = "/api/settings/provider/oauth-login" - response = await router.dispatch(None, _mutation_request(path, {"provider": "github_copilot"}), path) + response = await _mutate(router, _mutation_request(path, {"provider": "github_copilot"})) assert response.status_code == 200 - payload = json.loads(response.body) + payload = response.result with pytest.raises(RuntimeBusyError), router.bus.admission.pause_if_idle(lambda: False): pytest.fail("The authorization prompt still has a live worker") try: @@ -172,9 +176,9 @@ async def test_provider_login_keeps_maintenance_busy_until_worker_exits(tmp_path "/api/settings/provider/oauth-logout" if finish == "logout" else "/api/settings/provider/oauth-login/complete" ) - response = await router.dispatch(None, _mutation_request(path, { + response = await _mutate(router, _mutation_request(path, { "provider": "github_copilot", "flow_id": payload["flow_id"], "cancel": "true", - }), path) + })) assert response.status_code == 200 assert await asyncio.to_thread(stopping.wait, 1) assert router.settings.oauth_flows.get("github_copilot", payload["flow_id"]) is None @@ -207,9 +211,9 @@ async def test_failed_codex_login_start_still_owns_late_worker(tmp_path, monkeyp monkeypatch.setattr(oauth, "login_oauth_interactive", login) path = "/api/settings/provider/oauth-login" try: - response = await router.dispatch(None, _mutation_request(path, { + response = await _mutate(router, _mutation_request(path, { "provider": "openai_codex", "remote_browser": "true", - }), path) + })) assert response.status_code == 502 assert entered.is_set() with pytest.raises(RuntimeBusyError), router.bus.admission.pause_if_idle(lambda: False): @@ -227,7 +231,6 @@ async def test_failed_codex_login_start_still_owns_late_worker(tmp_path, monkeyp async def test_channel_setup_blocks_maintenance_until_confirmed_cleanup( tmp_path, monkeypatch, close_fails, ) -> None: - router = _router(config_path=tmp_path / "config.json") cleanup_started, allow_cleanup = asyncio.Event(), asyncio.Event() class Connector: @@ -248,10 +251,11 @@ async def test_channel_setup_blocks_maintenance_until_confirmed_cleanup( "nanobot.webui.settings_routes.load_channel_plugin", lambda _: SimpleNamespace(load_connector=lambda: connector), ) + router = _router(config_path=tmp_path / "config.json") path = "/api/settings/channels/whatsapp/connect/start" - response = await router.dispatch(None, _mutation_request(path, {}), path) + response = await _mutate(router, _mutation_request(path, {})) assert response.status_code == 200 - assert json.loads(response.body)["status"] == "pending" + assert response.result["status"] == "pending" with pytest.raises(RuntimeBusyError), router.bus.admission.pause_if_idle(lambda: False): pytest.fail("Returning a QR code does not finish its connection") shutdown = asyncio.create_task(router.close()) @@ -275,14 +279,14 @@ async def test_channel_setup_blocks_maintenance_until_confirmed_cleanup( @pytest.mark.asyncio async def test_legacy_connector_can_connect_but_cannot_claim_maintenance_idle(tmp_path, monkeypatch): - router = _router(config_path=tmp_path / "config.json") connector = SimpleNamespace(handle=AsyncMock(return_value={"status": "pending"})) monkeypatch.setattr( "nanobot.webui.settings_routes.load_channel_plugin", lambda _: SimpleNamespace(load_connector=lambda: connector), ) + router = _router(config_path=tmp_path / "config.json") path = "/api/settings/channels/custom/connect/start" - response = await router.dispatch(None, _mutation_request(path, {}), path) + response = await _mutate(router, _mutation_request(path, {})) assert response.status_code == 200 await router.close() with pytest.raises(RuntimeBusyError), router.bus.admission.pause_if_idle(lambda: False): @@ -457,9 +461,9 @@ async def test_settings_shutdown_joins_browser_authorization_and_releases_admiss monkeypatch.setattr("nanobot.webui.mcp_oauth_api.connect_mcp_servers", connect) router = _router(config_path=tmp_path / "config.json") path = "/api/settings/mcp-oauth/start" - response = await router.dispatch(None, _mutation_request(path, {"name": "linear"}), path) + response = await _mutate(router, _mutation_request(path, {"name": "linear"})) assert response.status_code == 200 - assert json.loads(response.body)["status"] == "authorization_required" + assert response.result["status"] == "authorization_required" with pytest.raises(RuntimeBusyError), router.bus.admission.pause_if_idle(lambda: False): pytest.fail("Settings returned, but authorization has not finished") @@ -477,7 +481,7 @@ async def test_settings_shutdown_joins_browser_authorization_and_releases_admiss @pytest.mark.asyncio -async def test_mcp_oauth_start_uses_gateway_callback_and_requires_api_auth(monkeypatch) -> None: +async def test_mcp_oauth_start_uses_gateway_callback_and_sanitizes_errors(monkeypatch) -> None: config = SimpleNamespace( type="streamableHttp", auth="oauth", @@ -501,11 +505,11 @@ async def test_mcp_oauth_start_uses_gateway_callback_and_requires_api_auth(monke {"name": "xmind"}, ) - response = await router.dispatch(None, request, "/api/settings/mcp-oauth/start") + response = await _mutate(router, request) assert response is not None assert response.status_code == 200 - assert json.loads(response.body)["flow_id"] == "flow-123" + assert response.result["flow_id"] == "flow-123" start.assert_awaited_once_with( "xmind", config, @@ -515,20 +519,15 @@ async def test_mcp_oauth_start_uses_gateway_callback_and_requires_api_auth(monke reset_credentials=False, ) - denied = _router(authorized=False) - denied_response = await denied.dispatch(None, request, "/api/settings/mcp-oauth/start") - assert denied_response is not None - assert denied_response.status_code == 401 failed = _router() failed._mcp_oauth = SimpleNamespace( start=AsyncMock(side_effect=RuntimeError("upstream secret response")) ) - failed_response = await failed.dispatch(None, request, "/api/settings/mcp-oauth/start") + failed_response = await _mutate(failed, request) assert failed_response is not None assert failed_response.status_code == 500 - assert json.loads(failed_response.body) == {"error": "MCP OAuth start failed"} - assert b"upstream secret response" not in failed_response.body + assert failed_response.message == "MCP OAuth start failed" @pytest.mark.asyncio @@ -575,22 +574,14 @@ async def test_mcp_oauth_manual_completion_reads_websocket_payload() -> None: {"flow_id": "flow-123", "callback_url": callback_url}, ) - response = await router.dispatch(None, request, "/api/settings/mcp-oauth/complete") + response = await _mutate(router, request) assert response is not None assert response.status_code == 200 - assert json.loads(response.body)["status"] == "connecting" - assert b"oauth-code" not in response.body + assert response.result["status"] == "connecting" + assert "oauth-code" not in json.dumps(response.result) submit.assert_called_once_with(flow_id="flow-123", callback_url=callback_url) - denied = _router(authorized=False) - denied_response = await denied.dispatch( - None, - request, - "/api/settings/mcp-oauth/complete", - ) - assert denied_response is not None - assert denied_response.status_code == 401 @pytest.mark.parametrize( @@ -636,71 +627,58 @@ async def test_oauth_completion_reads_websocket_payload( }, ) - response = await router.dispatch( - None, - request, - "/api/settings/provider/oauth-login/complete", - ) + response = await _mutate(router, request) assert response is not None assert response.status_code == 200 - assert json.loads(response.body) == { + assert response.result == { "status": "pending", "provider": provider, "flow_id": "flow-123", } assert captured == { - "query": {"provider": [provider], "flow_id": ["flow-123"]}, + "query": MutationParams({"provider": provider, "flow_id": "flow-123", "authorization_response": authorization_response}), "authorization_response": authorization_response, } - assert request.path == "/api/settings/provider/oauth-login/complete" - assert not request.headers @pytest.mark.parametrize( - ("route_path", "function_name", "payload", "expected_query"), + ("route_path", "function_name", "payload"), [ ( "/api/settings/update", "update_agent_settings", {"model_preset": "Codex"}, - {"model_preset": ["Codex"]}, ), ( "/api/settings/model-configurations/create", "create_model_configuration", {"name": "Codex", "model": "openai-codex/gpt-5.6"}, - {"name": ["Codex"], "model": ["openai-codex/gpt-5.6"]}, ), ( "/api/settings/model-configurations/delete", "delete_model_configuration", {"name": "spare"}, - {"name": ["spare"]}, ), ( "/api/settings/model-configurations/migrate", "migrate_model_configurations", {}, - {}, ), ( "/api/settings/model-call-order/update", "update_model_call_order", {"order": ["backup"]}, - {"order": ['["backup"]']}, ), ( "/api/settings/provider/create", "create_provider_settings", {"name": "team", "api_base": "https://llm.example/v1"}, - {"name": ["team"], "api_base": ["https://llm.example/v1"]}, ), ( "/api/settings/provider/update", "update_provider_settings", {"provider": "team", "api_base": "https://llm.example/v2"}, - {"provider": ["team"], "api_base": ["https://llm.example/v2"]}, ), ], ) @@ -710,7 +688,6 @@ async def test_runtime_config_mutation_routes_refresh_live_runtime( route_path: str, function_name: str, payload: dict[str, object], - expected_query: dict[str, list[str]], ) -> None: captured: dict[str, object] = {} refresh_runtime_config = MagicMock() @@ -722,14 +699,14 @@ async def test_runtime_config_mutation_routes_refresh_live_runtime( monkeypatch.setattr(f"nanobot.webui.settings_routes.{function_name}", mutate) request = _mutation_request(route_path, payload) - response = await _router( + response = await _mutate(_router( refresh_runtime_config=refresh_runtime_config, - ).dispatch(None, request, route_path) + ), request) assert response is not None assert response.status_code == 200 - assert json.loads(response.body)["routed"] == function_name - assert captured["query"] == expected_query + assert response.result["routed"] == function_name + assert captured["query"] == MutationParams(payload) refresh_runtime_config.assert_called_once_with() @@ -747,19 +724,15 @@ async def test_model_update_route_forwards_session_rename_dependency(monkeypatch path = "/api/settings/model-configurations/update" request = _mutation_request(path, {"name": "openai", "new_name": "Codex"}) - response = await _router( + response = await _mutate(_router( rename_model_preset=rename_model_preset, refresh_runtime_config=refresh_runtime_config, - ).dispatch( - None, - request, - path, - ) + ), request) assert response is not None assert response.status_code == 200 assert captured == { - "query": {"name": ["openai"], "new_name": ["Codex"]}, + "query": MutationParams({"name": "openai", "new_name": "Codex"}), "rename_model_preset": rename_model_preset, } refresh_runtime_config.assert_called_once_with() @@ -775,11 +748,11 @@ async def test_older_client_does_not_partially_update_provider_settings(tmp_path path = "/api/settings/provider/update" request = _mutation_request(path, {"provider": "openai", "apiType": "auto", "apiBase": "https://example.test/v1"}) - response = await router.dispatch(None, request, path) + response = await _mutate(router, request) assert response is not None assert response.status_code == 400 - assert "Update the client" in json.loads(response.body)["error"] + assert "Update the client" in response.message assert config_path.read_text(encoding="utf-8") == before refresh.assert_not_called() @@ -969,25 +942,23 @@ async def test_version_check_owner_is_additive_read_only_and_failure_is_not_a_re assert "secret" not in unavailable.body.decode() -async def test_runtime_config_route_authentication_validation_and_restart(tmp_path): +async def test_runtime_config_requires_websocket_and_tracks_restart(tmp_path): from nanobot.config.loader import load_config path = "/api/settings/runtime-config/update" config_path = tmp_path / "config.json" request = _mutation_request(path, {"values": {"tools.exec.timeout": 19}}) - unauthorized = await _router(authorized=False, config_path=config_path).dispatch(None, request, path) - assert unauthorized.status_code == 401 - assert not config_path.exists() router = _router(config_path=config_path) http_request = SimpleNamespace(path=path, headers=Headers()) assert (await router.dispatch(None, http_request, path)).status_code == 405 - invalid = _mutation_request(path, {"values": {"channels.send_progress": False}}) - assert (await router.dispatch(None, invalid, path)).status_code == 400 assert not config_path.exists() - result = await router.dispatch(None, request, path) + invalid = _mutation_request(path, {"values": {"channels.send_progress": False}}) + assert (await _mutate(router, invalid)).status_code == 400 + assert not config_path.exists() + result = await _mutate(router, request) assert result.status_code == 200 assert load_config(config_path).tools.exec.timeout == 19 - body = json.loads(result.body) + body = result.result assert body["runtime_config"]["tools.exec.timeout"] == 19 assert body["restart_required_sections"] == ["runtime"] refreshed = await router.dispatch(None, SimpleNamespace(path="/api/settings", headers=Headers()), "/api/settings") @@ -998,11 +969,11 @@ async def test_runtime_settings_only_save_without_refreshing_or_rebinding(tmp_pa refresh = MagicMock() router = _router(config_path=tmp_path / "config.json", refresh_runtime_config=refresh) path = "/api/settings/runtime-config/update" - response = await router.dispatch(None, _mutation_request(path, { + response = await _mutate(router, _mutation_request(path, { "values": {"agents.defaults.dream.enabled": False, "gateway.port": 19001}, - }), path) + })) assert response.status_code == 200 - assert json.loads(response.body)["requires_restart"] + assert response.result["requires_restart"] refresh.assert_not_called() @@ -1014,9 +985,9 @@ async def test_reverting_runtime_switch_clears_restart_but_preserves_other_chang path = "/api/settings/runtime-config/update" async def update(values): - response = await router.dispatch(None, _mutation_request(path, {"values": values}), path) + response = await _mutate(router, _mutation_request(path, {"values": values})) assert response.status_code == 200 - return json.loads(response.body) + return response.result assert (await update({"agents.defaults.dream.enabled": not original_memory}))["requires_restart"] await update({"tools.web.enable": not original_web}) @@ -1034,31 +1005,31 @@ async def test_reverting_web_reader_preserves_unrelated_restart_reason(tmp_path) original_reader = config.tools.web.fetch.use_jina_reader original_port = config.gateway.port path = "/api/settings/web-search/update" - first = await router.dispatch(None, _mutation_request(path, { + first = await _mutate(router, _mutation_request(path, { "provider": "duckduckgo", "use_jina_reader": not original_reader, - }), path) + })) assert first.status_code == 200 - assert json.loads(first.body)["restart_required_sections"] == ["browser"] + assert first.result["restart_required_sections"] == ["browser"] runtime_path = "/api/settings/runtime-config/update" - changed = await router.dispatch(None, _mutation_request(runtime_path, { + changed = await _mutate(router, _mutation_request(runtime_path, { "values": {"gateway.port": original_port + 1}, - }), runtime_path) + })) assert changed.status_code == 200 - assert set(json.loads(changed.body)["restart_required_sections"]) == {"browser", "runtime"} + assert set(changed.result["restart_required_sections"]) == {"browser", "runtime"} - restored = await router.dispatch(None, _mutation_request(path, { + restored = await _mutate(router, _mutation_request(path, { "provider": "duckduckgo", "use_jina_reader": original_reader, - }), path) + })) assert restored.status_code == 200 - assert json.loads(restored.body)["restart_required_sections"] == ["runtime"] + assert restored.result["restart_required_sections"] == ["runtime"] refreshed = await router.dispatch(None, SimpleNamespace(path="/api/settings", headers=Headers()), "/api/settings") assert json.loads(refreshed.body)["restart_required_sections"] == ["runtime"] - reverted = await router.dispatch(None, _mutation_request(runtime_path, { + reverted = await _mutate(router, _mutation_request(runtime_path, { "values": {"gateway.port": original_port}, - }), runtime_path) + })) assert reverted.status_code == 200 - assert json.loads(reverted.body)["restart_required_sections"] == [] + assert reverted.result["restart_required_sections"] == [] @pytest.mark.parametrize("enabled", [False, True]) @@ -1077,11 +1048,11 @@ async def test_image_switch_round_trip_clears_restart(tmp_path, enabled): ) router.logger.warning = MagicMock() path = "/api/settings/image-generation/update" - changed = await router.dispatch(None, _mutation_request(path, {"enabled": not enabled}), path) - assert json.loads(changed.body)["requires_restart"] is True - reverted = await router.dispatch(None, _mutation_request(path, {"enabled": enabled}), path) - assert json.loads(reverted.body)["requires_restart"] is False - assert json.loads(reverted.body)["restart_required_sections"] == [] + changed = await _mutate(router, _mutation_request(path, {"enabled": not enabled})) + assert changed.result["requires_restart"] is True + reverted = await _mutate(router, _mutation_request(path, {"enabled": enabled})) + assert reverted.result["requires_restart"] is False + assert reverted.result["restart_required_sections"] == [] @pytest.mark.asyncio @@ -1111,11 +1082,11 @@ async def test_first_mcp_oauth_request_saves_proxy_flag_before_starting_flow(tmp "/api/settings/mcp-oauth/start", {"name": "xmind", "use_proxy": True}, ) - response = await router.dispatch(None, request, "/api/settings/mcp-oauth/start") + response = await _mutate(router, request) assert response is not None assert response.status_code == 200 - assert json.loads(response.body)["flow_id"] == "first-flow" + assert response.result["flow_id"] == "first-flow" assert captured == {"network": "http://shared.example:8080"} @@ -1172,7 +1143,7 @@ async def test_mcp_proxy_mutation_persists_reloads_and_keeps_oauth_credentials( connection, "settings.mcp.proxy", {"name": "team-docs", "use_proxy": str(use_proxy).lower()}, ) assert response.status_code == 200 - payload = json.loads(response.body) + payload = response.result assert payload["hot_reload"]["ok"] is True assert payload["requires_restart"] is False row = next(row for row in payload["presets"] if row["name"] == "team-docs") diff --git a/tests/webui/test_subagent_persistence.py b/tests/webui/test_subagent_persistence.py index 55425f4ce..0d9f0d62a 100644 --- a/tests/webui/test_subagent_persistence.py +++ b/tests/webui/test_subagent_persistence.py @@ -765,7 +765,7 @@ async def test_webui_deletion_cancels_parent_work_and_removes_child_sessions(tmp connection, "session.delete", {"key": "websocket:parent"}, ) assert response.status_code == 200 - assert json.loads(response.body)["deleted"] is True + assert response.result == {"deleted": True} gateway.http.discard_session.assert_awaited_once_with("websocket:parent") assert sessions.read_session_file("websocket:parent") is None assert sessions.read_session_file(child_key) is None diff --git a/tests/webui/test_subagent_tasks.py b/tests/webui/test_subagent_tasks.py index f9e9df109..1bf86b91d 100644 --- a/tests/webui/test_subagent_tasks.py +++ b/tests/webui/test_subagent_tasks.py @@ -71,8 +71,8 @@ async def test_webui_task_access_and_targeted_idempotent_cancel(tmp_path): connection, "subagent.cancel", {"session_key": "websocket:a", "task_id": task_id}, ) assert result.status_code == 404 - errors.append(result.body) - assert errors[0] == errors[1] + errors.append(result.message) + assert errors == ["task unavailable", "task unavailable"] assert manager.check(foreign, "websocket:b").state == "running" for _ in range(2): @@ -80,7 +80,8 @@ async def test_webui_task_access_and_targeted_idempotent_cancel(tmp_path): connection, "subagent.cancel", {"session_key": "websocket:a", "task_id": first}, ) assert result.status_code == 200 - assert json.loads(result.body)["state"] == "cancelled" + assert result.result is not None + assert result.result["state"] == "cancelled" assert manager.check(sibling, "websocket:a").state == "running" assert manager.check(foreign, "websocket:b").state == "running" assert bus.inbound_size == 1 diff --git a/tests/webui/test_update_plans.py b/tests/webui/test_update_plans.py index baa3ce70f..156ef4993 100644 --- a/tests/webui/test_update_plans.py +++ b/tests/webui/test_update_plans.py @@ -60,8 +60,8 @@ async def test_channel_mutation_preserves_authority_and_invalidates_old_reviews( assert response.status_code == 403 assert read_update_channel().revision == 0 response = await gateway.http.dispatch_webui_mutation(connection(local=True), CHANNEL, {"channel": "preview", "revision": 0}) - assert response.status_code == 200, response.body - assert json.loads(response.body) == {"channel": "preview", "revision": 1} + assert response.status_code == 200, response.message + assert response.result == {"channel": "preview", "revision": 1} assert "webui.update-channels.v1" in webui_contract()["capabilities"] reviewed = await fetch(gateway, READ + "?id=" + plan.id) assert json.loads(reviewed.body)["plan"]["validity"] == "channel_changed" @@ -109,7 +109,7 @@ async def test_review_uses_saved_channel_and_rejects_a_change_during_discovery(p monkeypatch.setattr(update_plan, "ReleaseFeed", lambda _: Feed()) response = await gateway.http.dispatch_webui_mutation(connection(local=True), "settings.nanobot.update.plan", {"extras": []}) assert response.status_code == 200 - saved = UpdatePlans(fixture.directory / "plans").load(json.loads(response.body)["plan"]["id"]) + saved = UpdatePlans(fixture.directory / "plans").load(response.result["plan"]["id"]) assert (saved.channel, saved.channel_revision) == ("preview", 1) race = True response = await gateway.http.dispatch_webui_mutation(connection(local=True), "settings.nanobot.update.plan", {"extras": []}) @@ -206,8 +206,8 @@ async def preparation_plan(fixture): response = await gateway.http.dispatch_webui_mutation( connection(local=True), "settings.nanobot.update.plan", {"extras": []}, ) - assert response.status_code == 200, response.body - return gateway, UpdatePlans(fixture.directory / "plans").load(json.loads(response.body)["plan"]["id"]) + assert response.status_code == 200, response.message + return gateway, UpdatePlans(fixture.directory / "plans").load(response.result["plan"]["id"]) async def execution_plan(fixture): @@ -256,12 +256,12 @@ async def test_execution_consent_survives_cancelled_response_and_duplicate_reque assert not operation.done(), "A lost requester cannot abandon a still-running launch thread" fresh = fixture.gateway() duplicate = await fresh.http.dispatch_webui_mutation(connection(local=True), EXECUTE, payload) - assert duplicate.status_code == 200, duplicate.body - assert duplicate.headers["Cache-Control"] == "no-store" - saved = json.loads(duplicate.body)["job"] + assert duplicate.status_code == 200, duplicate.message + saved = duplicate.result["job"] assert saved["execution_confirmation_id"] == confirmation.id assert saved["recorded_phase"] == "checking" and not saved["mutation_started"] restored = await fetch(fresh, JOB + "?id=" + plan.id) + assert restored.headers["Cache-Control"] == "no-store" assert json.loads(restored.body)["job"] == saved finally: release.set() @@ -326,13 +326,12 @@ async def test_retry_is_explicit_authorized_and_old_submissions_only_read_histor assert (await gateway.http.dispatch_webui_mutation(connection(local=True), RETRY, bad)).status_code == 400 assert not calls first = await gateway.http.dispatch_webui_mutation(connection(local=True), RETRY, payload) - assert first.status_code == 200, first.body - assert first.headers["Cache-Control"] == "no-store" - assert json.loads(first.body)["job"]["execution_confirmation_id"] == current.id + assert first.status_code == 200, first.message + assert first.result["job"]["execution_confirmation_id"] == current.id fresh = fixture.gateway() for action, body in ((RETRY, payload), (EXECUTE, {"id": plan.id, "confirm_restart": True})): repeated = await fresh.http.dispatch_webui_mutation(connection(local=True), action, body) - assert repeated.status_code == 200 and json.loads(repeated.body) == json.loads(first.body) + assert repeated.status_code == 200 and repeated.result == first.result assert calls == [previous.id] assert "webui.update-jobs.retry-handoff.v1" in webui_contract()["capabilities"] @@ -349,7 +348,8 @@ async def test_busy_retry_does_not_look_like_an_accepted_new_confirmation(prepar response = await gateway.http.dispatch_webui_mutation(connection(local=True), RETRY, {"id": plan.id, "previous_confirmation_id": previous.id, "confirm_restart": True}) assert response.status_code == 409 - assert b"private lease" not in response.body + assert response.message is not None + assert "private lease" not in response.message assert ExecutionConfirmation.read(directory) == previous @@ -373,10 +373,11 @@ async def test_handoff_settlement_route_preserves_permission_and_reads_cancelled assert (await gateway.http.dispatch_webui_mutation(connection(), SETTLE, {"id": plan.id})).status_code == 403 assert calls == [] response = await gateway.http.dispatch_webui_mutation(connection(local=True), SETTLE, {"id": plan.id}) - assert response.status_code == 200, response.body - assert json.loads(response.body)["job"]["recorded_phase"] == "cancelled" - assert json.loads(response.body)["job"]["execution_confirmation_id"] == previous.id - assert (await fetch(gateway, JOB + "?id=" + plan.id)).body == response.body + assert response.status_code == 200, response.message + assert response.result["job"]["recorded_phase"] == "cancelled" + assert response.result["job"]["execution_confirmation_id"] == previous.id + restored = await fetch(gateway, JOB + "?id=" + plan.id) + assert json.loads(restored.body) == response.result assert calls == [directory] assert "webui.update-jobs.settle-handoff.v1" in webui_contract()["capabilities"] @@ -402,7 +403,7 @@ async def test_execution_refuses_unreviewed_gateway_lifecycle(preparation_gatewa monkeypatch.setattr(update_service, "start_handoff", forbidden) result = await gateway.http.dispatch_webui_mutation(connection(local=True), EXECUTE, {"id": plan.id, "confirm_restart": True}) - assert result.status_code == 409, result.body + assert result.status_code == 409, result.message assert ExecutionConfirmation.read(directory) is None @@ -429,17 +430,18 @@ async def test_preparation_is_durable_idempotent_and_independent_of_browser(prep close = None try: response = await gateway.http.dispatch_webui_mutation(connection(local=True), PREPARE, {"id": plan.id}) - assert response.status_code == 200, response.body - assert json.loads(response.body)["job"]["recorded_phase"] == "preparation_requested" - assert response.headers["Cache-Control"] == "no-store" + assert response.status_code == 200, response.message + assert response.result["job"]["recorded_phase"] == "preparation_requested" directory = fixture.directory / "jobs" / plan.id assert JobStatus.read(directory).phase == Phase.PREPARATION_REQUESTED await asyncio.wait_for(entered.wait(), 5) fresh = fixture.gateway() duplicate = await fresh.http.dispatch_webui_mutation(connection(local=True), PREPARE, {"id": plan.id}) assert duplicate.status_code == 200 - assert json.loads(duplicate.body)["job"]["recorded_phase"] == "preparing" - assert (await fetch(fresh, JOB + "?id=" + plan.id)).status_code == 200 + assert duplicate.result["job"]["recorded_phase"] == "preparing" + restored = await fetch(fresh, JOB + "?id=" + plan.id) + assert restored.status_code == 200 + assert restored.headers["Cache-Control"] == "no-store" assert (await fresh.http.dispatch_webui_mutation(connection(local=True), SETTLE, {"id": plan.id})).status_code == 409 other = plan.model_copy(update={"id": str(uuid4())}) UpdatePlans(fixture.directory / "plans").save(other) @@ -494,8 +496,8 @@ async def test_preparation_revalidation_failure_is_saved_and_never_retried_by_re await gateway.http.settings_routes.close() duplicate = await fixture.gateway().http.dispatch_webui_mutation(connection(local=True), PREPARE, {"id": plan.id}) assert duplicate.status_code == 200 - assert json.loads(duplicate.body)["job"]["recorded_phase"] == "preparation_failed" - assert b"secret" not in duplicate.body + assert duplicate.result["job"]["recorded_phase"] == "preparation_failed" + assert "secret" not in json.dumps(duplicate.result) directory = fixture.directory / "jobs" / plan.id assert "secret" not in (directory / "status.json").read_text() assert targets == [plan.target] @@ -555,20 +557,20 @@ async def test_explicit_settlement_checks_ownership_and_does_not_retry(preparati monkeypatch.setattr(update_service.ReleaseFeed, "revalidate", forbidden) restored = await gateway.http.dispatch_webui_mutation(connection(local=True), PREPARE, {"id": plan.id}) - assert json.loads(restored.body)["job"]["recorded_phase"] == phase.value + assert restored.result["job"]["recorded_phase"] == phase.value lock = "prepare-native.lock" if phase == Phase.PREPARING else "preparation-controller.lock" with file_access(fixture.directory / lock, exclusive=True): blocked = await gateway.http.dispatch_webui_mutation(connection(local=True), SETTLE, {"id": plan.id}) assert blocked.status_code == 409 assert JobStatus.read(directory).phase == phase settled = await gateway.http.dispatch_webui_mutation(connection(local=True), SETTLE, {"id": plan.id}) - assert settled.status_code == 200, settled.body - assert json.loads(settled.body)["job"]["recorded_phase"] == "preparation_failed" + assert settled.status_code == 200, settled.message + assert settled.result["job"]["recorded_phase"] == "preparation_failed" if phase == Phase.PREPARING: assert PreparationProcess.load(directory).active is False assert not (directory / "request.json").exists() duplicate = await fixture.gateway().http.dispatch_webui_mutation(connection(local=True), PREPARE, {"id": plan.id}) - assert json.loads(duplicate.body)["job"]["recorded_phase"] == "preparation_failed" + assert duplicate.result["job"]["recorded_phase"] == "preparation_failed" async def test_exact_review_survives_router_recreation_without_reselection_or_install(review_gateway): @@ -581,9 +583,8 @@ async def test_exact_review_survives_router_recreation_without_reselection_or_in response = await gateway.http.dispatch_webui_mutation( connection(), "settings.nanobot.update.plan", {"channel": "stable", "restart_running": True}, ) - assert response.status_code == 200, response.body - assert response.headers["Cache-Control"] == "no-store" - payload = json.loads(response.body) + assert response.status_code == 200, response.message + payload = response.result review = payload["plan"] assert payload["installation_allowed"] is False assert payload["execution_available"] is False @@ -618,7 +619,7 @@ async def test_live_update_review_requires_this_gateway_and_preserves_owner_poli response = await gateway.http.dispatch_webui_mutation( connection(local=True), "settings.nanobot.update.plan", {"restart_running": True}, ) - payload = json.loads(response.body) + payload = response.result assert payload["installation_allowed"] is True assert payload["execution_available"] is (os.name == "posix") assert payload["plan"]["extras"] == ["webui"] @@ -641,7 +642,7 @@ async def test_review_routes_unverified_uv_versions_to_the_installation_owner(re connection(local=True), "settings.nanobot.update.plan", {"restart_running": True}, ) assert response.status_code == 200 - payload = json.loads(response.body) + payload = response.result assert payload["execution_available"] is False plan = UpdatePlans(fixture.directory / "plans").load(payload["plan"]["id"]) assert update_plan.inline_update_blocked_reason(plan) == "installation_owner" @@ -653,7 +654,7 @@ async def test_review_reports_profile_and_installation_changes_without_replacing gateway = fixture.gateway() created = await gateway.http.dispatch_webui_mutation(connection(local=True), "settings.nanobot.update.plan", {}) assert created.status_code == 200 - payload = json.loads(created.body) + payload = created.result assert payload["installation_allowed"] is True review = payload["plan"] assert not any(item["stop"] or item["restart"] for item in review["profiles"]) @@ -691,7 +692,7 @@ async def test_expired_unknown_and_foreign_plans_have_explicit_results(review_ga fixture = review_gateway gateway = fixture.gateway() response = await gateway.http.dispatch_webui_mutation(connection(), "settings.nanobot.update.plan", {}) - review = json.loads(response.body)["plan"] + review = response.result["plan"] now = time.time() monkeypatch.setattr(update_plan.time, "time", lambda: now + 901) response = await fetch(gateway, READ + "?id=" + review["id"]) @@ -719,7 +720,8 @@ async def test_desktop_and_failed_discovery_do_not_claim_executable_or_current(r monkeypatch.setattr(update_plan, "inspect_installation", failed_probe) failed = await fixture.gateway().http.dispatch_webui_mutation(connection(), "settings.nanobot.update.plan", {}) assert failed.status_code == 409 - assert b"secret" not in failed.body + assert failed.message is not None + assert "secret" not in failed.message assert not (fixture.directory / "plans").exists() @@ -739,7 +741,7 @@ async def test_environment_replaced_during_discovery_does_not_return_a_valid_rev connection(), "settings.nanobot.update.plan", {}, ) assert response.status_code == 409 - assert response.body == b"Could not verify an update plan for this installation. No update was started." + assert response.message == "Could not verify an update plan for this installation. No update was started." assert calls == 2 assert not (fixture.directory / "jobs").exists() @@ -748,7 +750,7 @@ async def test_missing_interpreter_is_not_misreported_as_a_missing_plan(review_g fixture = review_gateway gateway = fixture.gateway() response = await gateway.http.dispatch_webui_mutation(connection(), "settings.nanobot.update.plan", {}) - plan_id = json.loads(response.body)["plan"]["id"] + plan_id = response.result["plan"]["id"] def removed_python(): raise FileNotFoundError("/private/installation/bin/python") @@ -764,7 +766,7 @@ async def test_job_reads_survive_refresh_expiry_and_unavailable_installation(rev fixture = review_gateway gateway = fixture.gateway() response = await gateway.http.dispatch_webui_mutation(connection(), "settings.nanobot.update.plan", {}) - plan_id = json.loads(response.body)["plan"]["id"] + plan_id = response.result["plan"]["id"] plan = UpdatePlans(fixture.directory / "plans").load(plan_id) directory = fixture.directory / "jobs" / plan_id directory.mkdir(parents=True) @@ -828,7 +830,7 @@ async def test_job_reads_reject_missing_foreign_and_corrupt_records(review_gatew fixture = review_gateway gateway = fixture.gateway() response = await gateway.http.dispatch_webui_mutation(connection(), "settings.nanobot.update.plan", {}) - plan_id = json.loads(response.body)["plan"]["id"] + plan_id = response.result["plan"]["id"] plan = UpdatePlans(fixture.directory / "plans").load(plan_id) monkeypatch.setattr(sys, "prefix", fixture.snapshot.environment) for query in ("", "?id=../../config", "?id=not-a-uuid"): @@ -904,7 +906,7 @@ async def test_plan_cannot_invent_restart_ownership_or_replace_manager_extras(re assert not (fixture.directory / "plans").exists() else: assert response.status_code == 200 - payload = json.loads(response.body) + payload = response.result assert payload["execution_available"] is False assert payload["plan"]["execution_blocked_reason"] == ( "external_restart" if os.name == "posix" else "installation_owner" diff --git a/tests/webui/test_ws_http_oauth.py b/tests/webui/test_ws_http_oauth.py index df0a2b27c..49438b7eb 100644 --- a/tests/webui/test_ws_http_oauth.py +++ b/tests/webui/test_ws_http_oauth.py @@ -1,10 +1,6 @@ from __future__ import annotations -from types import SimpleNamespace -from typing import cast - from websockets.datastructures import Headers -from websockets.http11 import Request as WsRequest from nanobot.channels.websocket.runtime import WebSocketConfig from nanobot.webui.ws_http import GatewayHTTPHandler @@ -16,14 +12,10 @@ def _handler(config: WebSocketConfig) -> GatewayHTTPHandler: return handler -def _request(**headers: str) -> WsRequest: - return cast(WsRequest, SimpleNamespace(headers=Headers(headers))) - - def test_mcp_oauth_callback_uses_configured_public_websocket_origin() -> None: handler = _handler(WebSocketConfig(path="/ws", public_ws_url="wss://agent.example/ws")) - redirect_uri = handler._mcp_oauth_redirect_uri(_request(Host="ignored.example")) + redirect_uri = handler._mcp_oauth_redirect_uri(Headers({"Host": "ignored.example"})) assert redirect_uri == "https://agent.example/auth/mcp/callback" @@ -32,7 +24,7 @@ def test_mcp_oauth_callback_uses_safe_forwarded_request_origin() -> None: handler = _handler(WebSocketConfig(path="/ws", host="127.0.0.1", port=8765)) redirect_uri = handler._mcp_oauth_redirect_uri( - _request(Host="nanobot.example:9443", **{"X-Forwarded-Proto": "https"}) + Headers({"Host": "nanobot.example:9443", "X-Forwarded-Proto": "https"}) ) assert redirect_uri == "https://nanobot.example:9443/auth/mcp/callback" diff --git a/webui/src/App.tsx b/webui/src/App.tsx index 33d42116f..907f8ef21 100644 --- a/webui/src/App.tsx +++ b/webui/src/App.tsx @@ -25,11 +25,21 @@ import { invalidateToolsCatalog } from "@/lib/tools-catalog-cache"; import type { SidebarDeleteItem } from "@/components/ChatList"; import type { SettingsSectionKey } from "@/components/settings/SettingsView"; import { StartupShell } from "@/components/StartupShell"; -import { ComposerDraftStore, clearStoredComposerDrafts } from "@/lib/composer-draft"; -import { activateReloadCache, clearReloadCache } from "@/lib/reload-cache"; -import { webuiThreadCache } from "@/lib/webui-thread-cache"; +import { ComposerDraftStore } from "@/lib/composer-draft"; import { ThreadVisibilityContext } from "@/hooks/useThreadVisibility"; import { isAppsSection, type SettingsExitGuard, type SettingsFocusTarget } from "@/components/settings/contracts"; +import { + RESTART_ROUTE_KEY, + RESTART_STARTED_KEY, + changesSettingsSurface, + defaultShellRoute, + readShellRoute, + rememberRestartRoute, + shellViewForSettingsSection, + writeShellRoute, + type ShellRoute, + type ShellView, +} from "@/shell-route"; import { PaneWorkbench } from "@/components/workbench/PaneWorkbench"; import { transitionSession } from "@/components/thread/session-transition"; import { @@ -52,6 +62,7 @@ import { import { ToastProvider, useToast } from "@/components/ui/toast"; import { Sheet, SheetContent, SheetTitle } from "@/components/ui/sheet"; +import { useLocalGateway } from "@/hooks/useLocalGateway"; import { useSessions } from "@/hooks/useSessions"; import { useReconnectRuns } from "@/hooks/useReconnectRuns"; import { useDeferredTitleRefresh } from "@/hooks/useDeferredTitleRefresh"; @@ -63,18 +74,8 @@ import type { SendAttachment, SendOptions } from "@/hooks/useNanobotStream"; import { ThemeProvider, useTheme } from "@/hooks/useTheme"; import { useReadingTypography } from "@/hooks/useReadingTypography"; import { cn } from "@/lib/utils"; -import { - BootstrapAuthRequiredError, - clearSavedSecret, - consumeUrlBootstrapSecret, - deriveWsUrl, - fetchBootstrap, - loadSavedSecret, - saveSecret, -} from "@/lib/bootstrap"; import { displayTitle, sortSessions } from "@/lib/chat-groups"; import { deriveTitle } from "@/lib/format"; -import { NanobotClient } from "@/lib/nanobot-client"; import { BrowserNotifications, useBrowserNotificationLifecycle } from "@/components/BrowserNotifications"; import { ThreadMessageCache } from "@/lib/thread-message-cache"; import { FilePreviewStore } from "@/hooks/useFilePreviewState"; @@ -83,7 +84,6 @@ import { BackgroundProvider } from "@/providers/BackgroundProvider"; import { useVersionCheck } from "@/providers/VersionCheckProvider"; import { useUpdateFlow } from "@/providers/UpdateFlowProvider"; import type { - BootstrapResponse, ChatSummary, RuntimeSurface, SessionAutomationJob, @@ -97,57 +97,20 @@ import { Input } from "@/components/ui/input"; import { Dialog, DialogContent, DialogDescription, DialogTitle, DialogTrigger } from "@/components/ui/dialog"; import { HoverHint } from "@/components/ui/hover-hint"; import { fetchSettings, fetchWorkspaces } from "@/lib/api"; -import { - createRuntimeHost, - isNativeRuntime, - toRuntimeSurface, -} from "@/lib/runtime"; +import { isNativeRuntime } from "@/lib/runtime"; import { projectNameFromPath, scopeWithAccessMode } from "@/lib/workspace"; import { createTemporaryChatSession, deriveTemporaryChatTitle, } from "@/lib/temporary-chat"; -type BootState = - | { status: "loading" } - | { status: "error"; message: string } - | { status: "auth" } - | { - status: "ready"; - client: NanobotClient; - token: string; - tokenExpiresAt: number | null; - modelName: string | null; - ingressLimits: BootstrapResponse["limits"] | null; - runtimeSurface: RuntimeSurface; - webuiCapabilities: string[]; - }; - -function bootstrapCapabilities(boot: BootstrapResponse): string[] { - const capabilities = boot.terminal?.webui?.capabilities; - return Array.isArray(capabilities) ? capabilities.filter((entry) => typeof entry === "string") : []; -} - const SIDEBAR_STORAGE_KEY = "nanobot-webui.sidebar"; const SESSION_UPDATES_STORAGE_KEY = "nanobot-webui.sidebar.session-updates.v1"; const LEGACY_COMPLETED_RUNS_STORAGE_KEY = "nanobot-webui.sidebar.completed-runs.v1"; -const RESTART_STARTED_KEY = "nanobot-webui.restartStartedAt"; -const RESTART_ROUTE_KEY = "nanobot-webui.restartRoute"; -const RESTART_ROUTE_TTL_MS = 5 * 60 * 1000; const SIDEBAR_WIDTH = 272; const SIDEBAR_WIDTH_STORAGE_KEY = "nanobot-webui.sidebar.width"; const SIDEBAR_RAIL_WIDTH = 56; const MOBILE_SIDEBAR_WIDTH = `min(${SIDEBAR_WIDTH}px, calc(100vw - 0.75rem))`; -const TOKEN_REFRESH_MARGIN_MS = 30_000; -const TOKEN_REFRESH_MIN_DELAY_MS = 5_000; -type ShellView = "chat" | "settings" | "apps" | "automations" | "remote"; -type ShellRoute = { - view: ShellView; - activeKey: string | null; - settingsSection: SettingsSectionKey; - settingsFocus?: SettingsFocusTarget; - temporary?: boolean; -}; const loadThreadShell = () => import("@/components/thread/ThreadShell"); const ThreadShell = lazy(() => loadThreadShell().then( (module) => ({ default: module.ThreadShell }), @@ -170,214 +133,6 @@ const RenameDialog = lazy(async () => { return { default: module.RenameDialog }; }); -const SETTINGS_SECTION_KEYS: SettingsSectionKey[] = [ - "capabilities", - "overview", - "about", - "appearance", - "notifications", - "models", - "image", - "voice", - "browser", - "channels", - "apps", - "automations", - "memory", - "skills", - "runtime", - "advanced", -]; - -function isSettingsSectionKey(value: string | null): value is SettingsSectionKey { - return SETTINGS_SECTION_KEYS.includes(value as SettingsSectionKey); -} - -function defaultShellRoute(): ShellRoute { - return { view: "chat", activeKey: null, settingsSection: "overview" }; -} - -function shellViewForSettingsSection(section: SettingsSectionKey): ShellView { - if (isAppsSection(section)) return "apps"; - if (section === "automations") return "automations"; - return "settings"; -} - -function changesSettingsSurface(current: ShellRoute, next: ShellRoute): boolean { - return current.view !== "chat" && current.view !== "remote" && - (current.view !== next.view || current.settingsSection !== next.settingsSection); -} - -function fallbackRestartHash(hash: string): boolean { - return !hash || hash === "/" || hash === "/new"; -} - -function rememberRestartRoute(): void { - if (typeof window === "undefined") return; - try { - window.localStorage.setItem(RESTART_ROUTE_KEY, window.location.hash || "#/new"); - } catch { - // ignore storage errors - } -} - -function maybeRestoreRestartHash(hash: string): string { - if (typeof window === "undefined" || !fallbackRestartHash(hash)) return hash; - try { - const startedAt = Number(window.localStorage.getItem(RESTART_STARTED_KEY) ?? "0"); - const storedHash = window.localStorage.getItem(RESTART_ROUTE_KEY); - if (!startedAt || !storedHash || Date.now() - startedAt > RESTART_ROUTE_TTL_MS) { - window.localStorage.removeItem(RESTART_ROUTE_KEY); - return hash; - } - window.localStorage.removeItem(RESTART_ROUTE_KEY); - const nextHash = storedHash.startsWith("#") ? storedHash : `#${storedHash}`; - window.history.replaceState( - null, - "", - `${window.location.pathname}${window.location.search}${nextHash}`, - ); - return nextHash.slice(1); - } catch { - return hash; - } -} - -function readShellRoute(): ShellRoute { - if (typeof window === "undefined") return defaultShellRoute(); - const currentHash = window.location.hash.startsWith("#") - ? window.location.hash.slice(1) - : window.location.hash; - const hash = maybeRestoreRestartHash(currentHash); - if (!hash || hash === "/" || hash === "/new") return defaultShellRoute(); - - const [path, query = ""] = hash.split("?", 2); - const params = new URLSearchParams(query); - const rawSettingsSection = params.get("section"); - const settingsSection = isSettingsSectionKey(rawSettingsSection) - ? rawSettingsSection - : "overview"; - const saved: unknown = window.history.state?.nanobotReturnChat; - const returnChat = saved && typeof saved === "object" && "hash" in saved - && saved.hash === window.location.hash ? saved : null; - const activeKey = params.get("chat")?.trim() - || (returnChat && "key" in returnChat && typeof returnChat.key === "string" - ? returnChat.key : null); - const temporary = Boolean(returnChat && "temporary" in returnChat && returnChat.temporary === true); - - if (path === "/settings") { - const focus = params.get("focus"); - return { - view: shellViewForSettingsSection(settingsSection), - activeKey, - temporary, - settingsSection, - settingsFocus: settingsSection === "advanced" && (focus === "sandbox" || focus === "sandbox-launcher") - ? focus - : settingsSection === "models" && focus?.startsWith("image-input:") - ? `image-input:${focus.slice("image-input:".length)}` - : undefined, - }; - } - if (path === "/apps") { - return { view: "apps", activeKey, temporary, settingsSection: isAppsSection(settingsSection) ? settingsSection : "apps" }; - } - if (path === "/automations") { - return { view: "automations", activeKey, temporary, settingsSection: "automations" }; - } - if (path === "/channels") { - return { view: "apps", activeKey, temporary, settingsSection: "channels" }; - } - if (path === "/remote") { - return { view: "remote", activeKey, temporary, settingsSection: "overview" }; - } - if (path === "/skills") { - return { view: "apps", activeKey, temporary, settingsSection: "skills" }; - } - if (path.startsWith("/temporary/")) { - const encoded = path.slice("/temporary/".length); - try { - const chatId = decodeURIComponent(encoded).trim(); - return chatId - ? { - view: "chat", - activeKey: `websocket:${chatId}`, - settingsSection: "overview", - temporary: true, - } - : defaultShellRoute(); - } catch { - return defaultShellRoute(); - } - } - if (path.startsWith("/chat/")) { - const encoded = path.slice("/chat/".length); - try { - const key = decodeURIComponent(encoded).trim(); - return key - ? { view: "chat", activeKey: key, settingsSection: "overview" } - : defaultShellRoute(); - } catch { - return defaultShellRoute(); - } - } - return defaultShellRoute(); -} - -function shellRouteHash(route: ShellRoute): string { - if (route.view === "chat") { - if (route.temporary && route.activeKey?.startsWith("websocket:")) { - const chatId = route.activeKey.slice("websocket:".length); - return `#/temporary/${encodeURIComponent(chatId)}`; - } - return route.activeKey - ? `#/chat/${encodeURIComponent(route.activeKey)}` - : "#/new"; - } - const params = new URLSearchParams(); - if (route.view === "settings" && route.settingsSection !== "overview") { - params.set("section", route.settingsSection); - if (route.settingsFocus) params.set("focus", route.settingsFocus); - } - if (route.view === "apps" && route.settingsSection !== "apps") { - params.set("section", route.settingsSection); - } - const query = params.toString(); - return `#/${route.view}${query ? `?${query}` : ""}`; -} - -function writeShellRoute(route: ShellRoute, replace = false): void { - if (typeof window === "undefined") return; - const nextHash = shellRouteHash(route); - const state = { - ...window.history.state, - nanobotReturnChat: route.view === "chat" ? null : { - hash: nextHash, - key: route.activeKey, - temporary: route.temporary === true, - }, - }; - const url = `${window.location.pathname}${window.location.search}${nextHash}`; - if (replace || window.location.hash === nextHash) { - window.history.replaceState(state, "", url); - } else { - window.history.pushState(state, "", url); - } -} - -function bootstrapTokenExpiresAt(expiresInSeconds: number): number { - return Date.now() + Math.max(0, expiresInSeconds) * 1000; -} - -function tokenRefreshDelayMs(expiresAt: number): number { - const remaining = Math.max(0, expiresAt - Date.now()); - const margin = Math.min( - TOKEN_REFRESH_MARGIN_MS, - Math.max(1_000, remaining / 2), - ); - return Math.max(TOKEN_REFRESH_MIN_DELAY_MS, remaining - margin); -} - function AuthForm({ onSecret }: { onSecret: (secret: string, onAuthRejected: () => void) => void; }) { @@ -590,12 +345,6 @@ function normalizeWorkspaceScope(scope: WorkspaceScopePayload): WorkspaceScopePa }; } -function isBootstrapAuthRequired(error: unknown): boolean { - if (error instanceof BootstrapAuthRequiredError) return true; - const msg = error instanceof Error ? error.message : String(error); - return msg.includes("HTTP 401") || msg.includes("HTTP 403"); -} - function HostChrome({ rightAction, }: { @@ -612,12 +361,8 @@ function HostChrome({ ); } -function resolveRuntimeSurface( - surface: RuntimeSurface | null | undefined, - fallback: RuntimeSurface, -): RuntimeSurface { - if (isNativeRuntime(surface)) return "native"; - return surface ? toRuntimeSurface(surface) : fallback; +function prefetchChat() { + if (readShellRoute().view === "chat") void loadThreadShell().catch(() => {}); } export default function App() { @@ -625,129 +370,7 @@ export default function App() { useBrowserNotificationLifecycle(); useReadingTypography(); const { t } = useTranslation(); - const [state, setState] = useState({ status: "loading" }); - const bootstrapSecretRef = useRef(""); - - const refreshReadyClient = useCallback( - async (client: NanobotClient, fallbackSurface: RuntimeSurface, signal?: AbortSignal) => { - const boot = await fetchBootstrap("", bootstrapSecretRef.current); - signal?.throwIfAborted(); - const url = deriveWsUrl(boot.ws_path, boot.token, boot.ws_url); - const runtimeSurface = resolveRuntimeSurface(boot.runtime_surface, fallbackSurface); - const runtimeHost = createRuntimeHost(runtimeSurface, boot.runtime_capabilities); - const tokenExpiresAt = boot.expires_in - ? bootstrapTokenExpiresAt(boot.expires_in) - : null; - if (runtimeHost.socketFactory) { - client.updateUrl(url, runtimeHost.socketFactory); - } else { - client.updateUrl(url); - } - client.updateMaxFrameBytes(boot.limits?.transport.max_frame_bytes); - setState((current) => - current.status === "ready" && current.client === client - ? { - ...current, - token: boot.api_token ?? "", - tokenExpiresAt, - modelName: boot.model_name ?? current.modelName, - ingressLimits: boot.limits ?? current.ingressLimits, - runtimeSurface, - webuiCapabilities: bootstrapCapabilities(boot), - } - : current, - ); - return { token: boot.api_token ?? "", url }; - }, - [], - ); - - const bootstrapWithSecret = useCallback( - (secret: string, onAuthRejected?: () => void) => { - let cancelled = false; - if (readShellRoute().view === "chat") void loadThreadShell().catch(() => {}); - (async () => { - if (!onAuthRejected) setState({ status: "loading" }); - try { - const boot = await fetchBootstrap("", secret); - if (cancelled) return; - if (secret) saveSecret(secret); - const url = deriveWsUrl(boot.ws_path, boot.token, boot.ws_url); - activateReloadCache(url); - const runtimeSurface = resolveRuntimeSurface(boot.runtime_surface, "browser"); - const runtimeHost = createRuntimeHost(runtimeSurface, boot.runtime_capabilities); - const client = new NanobotClient({ - url, - maxFrameBytes: boot.limits?.transport.max_frame_bytes, - socketFactory: runtimeHost.socketFactory, - onReauth: async (signal) => { - try { - const refreshed = await refreshReadyClient(client, runtimeSurface, signal); - return refreshed.url; - } catch { - return null; - } - }, - }); - bootstrapSecretRef.current = secret; - client.connect(); - setState({ - status: "ready", - client, - token: boot.api_token ?? "", - tokenExpiresAt: boot.expires_in - ? bootstrapTokenExpiresAt(boot.expires_in) - : null, - modelName: boot.model_name ?? null, - ingressLimits: boot.limits ?? null, - runtimeSurface, - webuiCapabilities: bootstrapCapabilities(boot), - }); - } catch (e) { - if (cancelled) return; - if (isBootstrapAuthRequired(e)) { - clearReloadCache(); - clearStoredComposerDrafts(); - webuiThreadCache.clear(); - if (onAuthRejected) onAuthRejected(); - else setState({ status: "auth" }); - } else { - setState({ - status: "error", - message: e instanceof Error ? e.message : String(e), - }); - } - } - })(); - return () => { - cancelled = true; - }; - }, - [refreshReadyClient], - ); - - useEffect(() => { - if (state.status !== "ready" || state.tokenExpiresAt === null) return; - const client = state.client; - const timer = window.setTimeout(async () => { - try { - await refreshReadyClient(client, state.runtimeSurface); - } catch (e) { - if (isBootstrapAuthRequired(e)) { - clearReloadCache(); - clearStoredComposerDrafts(); - webuiThreadCache.clear(); - setState({ status: "auth" }); - } - } - }, tokenRefreshDelayMs(state.tokenExpiresAt)); - return () => window.clearTimeout(timer); - }, [refreshReadyClient, state]); - - useEffect(() => { - const saved = consumeUrlBootstrapSecret() || loadSavedSecret(); - return bootstrapWithSecret(saved); - }, [bootstrapWithSecret]); + const { state, bootstrapWithSecret, changeModelName, logout, restartEngine } = useLocalGateway(prefetchChat); if (state.status === "loading") { return ; @@ -769,48 +392,6 @@ export default function App() { ); } - const handleModelNameChange = (modelName: string | null) => { - setState((current) => - current.status === "ready" ? { ...current, modelName } : current, - ); - }; - - const handleLogout = () => { - if (state.status === "ready") { - state.client.close(); - } - clearSavedSecret(); - clearReloadCache(); - clearStoredComposerDrafts(); - webuiThreadCache.clear(); - setState({ status: "auth" }); - }; - - const handleNativeEngineRestart = async (): Promise => { - const runtimeHost = createRuntimeHost(state.runtimeSurface); - if (!runtimeHost.restartEngine) { - throw new Error("native engine restart is unavailable"); - } - rememberRestartRoute(); - try { - window.localStorage.setItem(RESTART_STARTED_KEY, String(Date.now())); - } catch { - // ignore storage errors - } - try { - await runtimeHost.restartEngine(); - const refreshed = await refreshReadyClient(state.client, state.runtimeSurface); - return refreshed.token; - } finally { - try { - window.localStorage.removeItem(RESTART_STARTED_KEY); - window.localStorage.removeItem(RESTART_ROUTE_KEY); - } catch { - // ignore storage errors - } - } - }; - return ( ); diff --git a/webui/src/components/ChatList.tsx b/webui/src/components/ChatList.tsx index d3ffa2de7..0ec6a100a 100644 --- a/webui/src/components/ChatList.tsx +++ b/webui/src/components/ChatList.tsx @@ -32,6 +32,7 @@ import { Unplug, X, } from "lucide-react"; +import { useSidebarGroupMotion } from "@/hooks/useSidebarGroupMotion"; import { useTranslation } from "react-i18next"; import { @@ -342,9 +343,6 @@ export const ChatList = memo(function ChatList({ observer?.disconnect(); }; }, [hasListHeader, loading, sessions.length, temporarySessions.length]); - const layoutRowRefs = useRef(new Map()); - const pendingLayoutRectsRef = useRef | null>(null); - const layoutAnimationsRef = useRef(new Map()); const [collapsedPaneGroups, setCollapsedPaneGroups] = useState>( readCollapsedPaneGroups, ); @@ -551,19 +549,7 @@ export const ChatList = memo(function ChatList({ }); }, [loading, paneGroups]); - const measureLayoutRows = useCallback(() => { - const rects = new Map(); - for (const [key, row] of layoutRowRefs.current) { - rects.set(key, row.getBoundingClientRect()); - } - return rects; - }, []); - - const captureLayout = useCallback(() => { - for (const animation of layoutAnimationsRef.current.values()) animation.cancel(); - layoutAnimationsRef.current.clear(); - pendingLayoutRectsRef.current = measureLayoutRows(); - }, [measureLayoutRows]); + const { registerRow, captureLayout } = useSidebarGroupMotion(collapsedGroups, collapsedPaneGroups); const togglePaneGroup = useCallback((key: string) => { captureLayout(); @@ -581,43 +567,6 @@ export const ChatList = memo(function ChatList({ onToggleGroup(key); }, [captureLayout, onToggleGroup]); - useLayoutEffect(() => { - const previousRects = pendingLayoutRectsRef.current; - if (!previousRects) return; - pendingLayoutRectsRef.current = null; - const nextRects = measureLayoutRows(); - const reduceMotion = typeof window.matchMedia === "function" - && window.matchMedia("(prefers-reduced-motion: reduce)").matches; - if (reduceMotion) return; - for (const [key, nextRect] of nextRects) { - const previousRect = previousRects.get(key); - const row = layoutRowRefs.current.get(key); - if (!previousRect || !row || typeof row.animate !== "function") continue; - const deltaY = previousRect.top - nextRect.top; - if (Math.abs(deltaY) < 0.5) continue; - const animation = row.animate( - [ - { transform: `translateY(${deltaY}px)` }, - { transform: "translateY(0)" }, - ], - { - duration: 180, - easing: "cubic-bezier(0.2, 0, 0, 1)", - }, - ); - layoutAnimationsRef.current.set(key, animation); - animation.addEventListener("finish", () => { - if (layoutAnimationsRef.current.get(key) === animation) { - layoutAnimationsRef.current.delete(key); - } - }, { once: true }); - } - }, [collapsedGroups, collapsedPaneGroups, measureLayoutRows]); - - useEffect(() => () => { - for (const animation of layoutAnimationsRef.current.values()) animation.cancel(); - }, []); - if (initialLoading && sessions.length === 0 && temporarySessions.length === 0) { return ( @@ -796,8 +745,7 @@ export const ChatList = memo(function ChatList({
{ const key = `group:${group.id}`; - if (element) layoutRowRefs.current.set(key, element); - else layoutRowRefs.current.delete(key); + registerRow(key, element); }} data-sidebar-group-header={group.id} > @@ -866,8 +814,7 @@ export const ChatList = memo(function ChatList({
  • { - if (element) layoutRowRefs.current.set(s.key, element); - else layoutRowRefs.current.delete(s.key); + registerRow(s.key, element); }} data-sidebar-tab-group="true" data-pane-group-collapsed={paneGroupCollapsed ? "true" : undefined} @@ -1008,8 +955,7 @@ export const ChatList = memo(function ChatList({
  • { - if (element) layoutRowRefs.current.set(s.key, element); - else layoutRowRefs.current.delete(s.key); + registerRow(s.key, element); }} className="relative min-w-0" > diff --git a/webui/src/components/FileActions.tsx b/webui/src/components/FileActions.tsx index 508c60be5..a3040f56a 100644 --- a/webui/src/components/FileActions.tsx +++ b/webui/src/components/FileActions.tsx @@ -6,6 +6,7 @@ import { floatingItemClassName, floatingItemFocusClassName, floatingSurfaceClass import { useFloatingPortal } from "@/components/ui/floating-portal"; import { useToast } from "@/components/ui/toast"; import { copyTextToClipboard } from "@/lib/clipboard"; +import { useOverlaySurfaceRef } from "@/lib/dom-overlays"; import type { FileReferenceMetadata, FilePreviewPayload } from "@/lib/types"; import { cn } from "@/lib/utils"; @@ -41,6 +42,7 @@ export function FileActions({ const [copyStatus, setCopyStatus] = useState<"copied" | "failed" | null>(null); const resolveMetadata = context?.resolveMetadata; const portal = useFloatingPortal(); + const surfaceRef = useOverlaySurfaceRef("overlay"); const point = useRef({ x: 0, y: 0 }); const anchor = useRef({ getBoundingClientRect: () => new DOMRect(point.current.x, point.current.y, 0, 0) }); const opener = useRef(null); @@ -112,7 +114,7 @@ export function FileActions({ {children} - event.stopPropagation()} diff --git a/webui/src/components/ImageLightbox.tsx b/webui/src/components/ImageLightbox.tsx index 827b6b1f9..bf0a4c4bd 100644 --- a/webui/src/components/ImageLightbox.tsx +++ b/webui/src/components/ImageLightbox.tsx @@ -3,6 +3,7 @@ import * as DialogPrimitive from "@radix-ui/react-dialog"; import { ChevronLeft, ChevronRight, X } from "lucide-react"; import { useTranslation } from "react-i18next"; +import { useOverlaySurfaceRef } from "@/lib/dom-overlays"; import { cn } from "@/lib/utils"; import type { UIImage } from "@/lib/types"; import { ZoomableImage } from "@/components/ZoomableImage"; @@ -38,6 +39,7 @@ export function ImageLightbox({ const total = images.length; const current = index !== null ? images[index] : null; const opener = useRef(null); + const surfaceRef = useOverlaySurfaceRef("dialog"); const go = useCallback( (delta: number) => { @@ -93,6 +95,7 @@ export function ImageLightbox({ )} /> { opener.current = document.activeElement instanceof HTMLElement ? document.activeElement : null; }} diff --git a/webui/src/components/PreviewPane.tsx b/webui/src/components/PreviewPane.tsx index 777f19509..bdd12278a 100644 --- a/webui/src/components/PreviewPane.tsx +++ b/webui/src/components/PreviewPane.tsx @@ -1,5 +1,5 @@ import { surfaceFocusProps } from "@/lib/surface-focus"; -import { useEffect, useId, useRef, type PointerEvent, type ReactNode } from "react"; +import { useEffect, useId, useRef, type PointerEvent, type ReactNode, type Ref } from "react"; import { SidebarPanel } from "@/components/ui/sidebar-panel"; import { PanelRightClose, X } from "lucide-react"; import { useTranslation } from "react-i18next"; @@ -11,7 +11,7 @@ import { cn } from "@/lib/utils"; import { sidePanelSurfaceClassName } from "@/components/ui/floating-surface"; /** One stable sidebar shell: switching targets never replays its opening animation. */ -export function PreviewPane({ tabs, activeId, width, isClosing, onSelect, onCloseTab, onClose, onResizeStart, children }: { +export function PreviewPane({ tabs, activeId, width, isClosing, onSelect, onCloseTab, onClose, panelRef, onResizeStart, children }: { tabs: PreviewTab[]; activeId: string; width: number; @@ -19,6 +19,7 @@ export function PreviewPane({ tabs, activeId, width, isClosing, onSelect, onClos onSelect: (id: string) => void; onCloseTab: (id: string) => void; onClose: () => void; + panelRef?: Ref; onResizeStart: (event: PointerEvent) => void; children: ReactNode; }) { @@ -46,7 +47,7 @@ export function PreviewPane({ tabs, activeId, width, isClosing, onSelect, onClos onCloseTab(tab.id); }; const iconButton = "touch-target inline-flex size-8 shrink-0 items-center justify-center rounded-control text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"; - return
    diff --git a/webui/src/components/StarPrompt.tsx b/webui/src/components/StarPrompt.tsx index 83e357f7c..d25d27f40 100644 --- a/webui/src/components/StarPrompt.tsx +++ b/webui/src/components/StarPrompt.tsx @@ -2,6 +2,7 @@ import { useEffect, useRef, useState } from "react"; import { StarLinkView, StarPromptView } from "@/components/StarPromptView"; import { starPromptAction } from "@/lib/api"; +import { hasAnyDialogMounted } from "@/lib/dom-overlays"; import { useClient } from "@/providers/ClientProvider"; export function StarLink({ onSaved, fullWidth = false }: { @@ -43,10 +44,10 @@ export function StarPrompt({ ready }: { ready: boolean }) { if (status !== "open" || attempted.current) return; attempted.current = true; if (interacted.current || document.visibilityState !== "visible" - || document.querySelector('[role="dialog"], [role="alertdialog"]')) return; + || hasAnyDialogMounted()) return; void starPromptAction(client, "claim").then(({ show }) => { if (cancelled || !show || interacted.current || document.visibilityState !== "visible" - || document.querySelector('[role="dialog"], [role="alertdialog"]')) return; + || hasAnyDialogMounted()) return; previousFocus.current = document.activeElement instanceof HTMLElement ? document.activeElement : null; setOpen(true); diff --git a/webui/src/components/pairing/PairingCodePopup.tsx b/webui/src/components/pairing/PairingCodePopup.tsx index 4bbf937ec..abd29d86e 100644 --- a/webui/src/components/pairing/PairingCodePopup.tsx +++ b/webui/src/components/pairing/PairingCodePopup.tsx @@ -6,6 +6,7 @@ import { channelUiPresentation } from "@/channel-plugins/registry"; import { Button } from "@/components/ui/button"; import { floatingSurfaceElevationClassName } from "@/components/ui/floating-surface"; import { useLogoFallback } from "@/hooks/useLogoFallback"; +import { useOverlaySurfaceRef } from "@/lib/dom-overlays"; import type { PairingRequestInfo } from "@/lib/types"; import { cn } from "@/lib/utils"; @@ -27,6 +28,7 @@ export function PairingCodePopup({ const { t } = useTranslation(); const [value, setValue] = useState(""); const attemptedCode = useRef(null); + const surfaceRef = useOverlaySurfaceRef("dialog"); const normalizedCode = normalizePairingCode(value); const matchedRequest = useMemo( () => requests.find((request) => request.code === normalizedCode) ?? null, @@ -74,6 +76,7 @@ export function PairingCodePopup({ return (
    ; sessionKey?: string | null; children?: (renderControl: ComposerUsageControl | undefined) => ReactNode; open?: boolean; @@ -196,7 +198,7 @@ export function ComposerUsagePopover({ {t("thread.composer.context.panelTitle")} {inspector} - : createPortal( : createPortal( {inspector} , sidebarHost ?? document.body))} diff --git a/webui/src/components/thread/PromptNavigator.tsx b/webui/src/components/thread/PromptNavigator.tsx index bbf576083..dca0b4869 100644 --- a/webui/src/components/thread/PromptNavigator.tsx +++ b/webui/src/components/thread/PromptNavigator.tsx @@ -14,6 +14,7 @@ import { import { fmtDateTime } from "@/lib/format-time"; import type { UIMessage } from "@/lib/types"; import { cn } from "@/lib/utils"; +import { hasOpenDialogSurface } from "@/lib/dom-overlays"; interface PromptNavigatorProps { messages: UIMessage[]; @@ -45,7 +46,7 @@ export function PromptNavigator({ const keyDown = (event: KeyboardEvent) => { if (!shortcutEnabled || !prompts.length || event.defaultPrevented || event.repeat || event.isComposing || event.altKey || event.shiftKey || !(event.ctrlKey || event.metaKey) || event.key.toLowerCase() !== "f") return; - if (!open && (triggerRef.current?.closest("[hidden], [aria-hidden=true]") || document.querySelector("[role=dialog][data-state=open]"))) return; + if (!open && (triggerRef.current?.closest("[hidden], [aria-hidden=true]") || hasOpenDialogSurface())) return; event.preventDefault(); setListTop(0); setOpen(true); inputRef.current?.focus(); inputRef.current?.select(); diff --git a/webui/src/components/thread/ThreadComposer.tsx b/webui/src/components/thread/ThreadComposer.tsx index 3b294f3c7..0253c0c61 100644 --- a/webui/src/components/thread/ThreadComposer.tsx +++ b/webui/src/components/thread/ThreadComposer.tsx @@ -110,7 +110,7 @@ import { useComposerMentionInput } from "@/hooks/useComposerMentionInput"; import { useLogoFallback } from "@/hooks/useLogoFallback"; import { useMediaQuery } from "@/hooks/useMediaQuery"; import type { SendAttachment, SendOptions } from "@/hooks/useNanobotStream"; -import { useVoiceRecorder, type VoiceRecorderErrorKey } from "@/hooks/useVoiceRecorder"; +import { useComposerVoiceInput } from "@/hooks/useComposerVoiceInput"; import type { CliAppInfo, ChatSummary, @@ -144,6 +144,7 @@ import { readDraggedSession, } from "@/lib/session-drag"; import { formatQuotedUserMessage } from "@/lib/user-message-quote"; +import { useOverlaySurfaceRef } from "@/lib/dom-overlays"; import { cn } from "@/lib/utils"; import type { ComposerDraft, ComposerDraftStore } from "@/lib/composer-draft"; import { useLocalPreferences } from "@/hooks/useLocalPreferences"; @@ -155,10 +156,6 @@ import { type QueuedPromptContent, } from "@/components/thread/useQueuedPrompt"; -const VOICE_SHORTCUT_CODE = "KeyD"; -const VOICE_SHORTCUT_ARIA = "Control+Shift+D"; -type VoiceShortcutPlatform = "apple" | "chromeos" | "linux" | "other" | "windows"; - function formatBytes(n: number): string { if (n < 1024) return `${n} B`; if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KiB`; @@ -169,54 +166,6 @@ function utf8Bytes(value: string): number { return new TextEncoder().encode(value).byteLength; } -function isVoiceShortcutDown(event: KeyboardEvent): boolean { - return ( - event.code === VOICE_SHORTCUT_CODE - && event.ctrlKey - && event.shiftKey - && !event.altKey - && !event.metaKey - ); -} - -function isVoiceShortcutRelease(event: KeyboardEvent): boolean { - return ( - event.code === VOICE_SHORTCUT_CODE - || event.key === "Control" - || event.key === "Shift" - ); -} - -function getVoiceShortcutPlatform(): VoiceShortcutPlatform { - if (typeof navigator === "undefined") return "other"; - const userAgentData = (navigator as Navigator & { userAgentData?: { platform?: string } }) - .userAgentData; - const platform = [ - userAgentData?.platform, - navigator.platform, - navigator.userAgent, - ].filter(Boolean).join(" ").toLowerCase(); - const isIpadPretendingToBeMac = - navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1; - if (isIpadPretendingToBeMac || /mac|iphone|ipad|ipod/.test(platform)) return "apple"; - if (/win/.test(platform)) return "windows"; - if (/cros/.test(platform)) return "chromeos"; - if (/linux|x11|android/.test(platform)) return "linux"; - return "other"; -} - -function getVoiceShortcutLabel(): string { - switch (getVoiceShortcutPlatform()) { - case "apple": - return "⌃⇧D"; - case "chromeos": - case "linux": - case "windows": - case "other": - return "Ctrl ⇧ D"; - } -} - interface ThreadComposerProps { onSend: ( content: string, @@ -631,7 +580,6 @@ export function ThreadComposer({ end: number; } | null>(null); const [inlineError, setInlineError] = useState(null); - const [voiceSetupError, setVoiceSetupError] = useState(null); const showToast = useToast(); const [sendPending, setSendPending] = useState(false); const [pathInspection, setPathInspection] = useState<{ @@ -797,9 +745,7 @@ export function ThreadComposer({ const fileInputRef = useRef(null); const chipRefs = useRef(new Map()); const previousPendingQueueKeyRef = useRef(pendingQueueKey); - const voiceShortcutDownRef = useRef(false); const isHero = variant === "hero"; - const voiceShortcutLabel = useMemo(getVoiceShortcutLabel, []); const projectPickerAvailable = !workspaceProjectLocked && !!workspaceDefaultScope @@ -1428,19 +1374,6 @@ export function ThreadComposer({ measureDraft(); }, [readingTextSize, customReadingTextSize, measureDraft]); - // Runs before paint so switching sessions never flashes stale draft text. - useLayoutEffect(() => { - if (previousPendingQueueKeyRef.current === pendingQueueKey) return; - previousPendingQueueKeyRef.current = pendingQueueKey; - setValue(""); - setInlineError(null); - setVoiceSetupError(null); - setSlashMenuDismissed(false); - setCliAppMenuDismissed(false); - setCursorPosition(0); - clear(); - }, [clear, pendingQueueKey]); - const appendTranscription = useCallback((text: string) => { const transcript = text.trim(); if (!transcript) return; @@ -1454,56 +1387,26 @@ export function ThreadComposer({ focusTextarea(); }, [focusTextarea]); - const clearVoiceSetupError = useCallback(() => setVoiceSetupError(null), []); - const setVoiceError = useCallback((key: VoiceRecorderErrorKey) => { - // Setup blockers carry instructions users may need to keep in view while fixing them. - if (key === "insecureContext" || key === "permission" || key === "notConfigured") { - setVoiceSetupError(key); - return; - } - showToast?.({ message: t(`thread.composer.voiceErrors.${key}`), tone: "error", dedupeKey: "voice-input" }); - }, [showToast, t]); - const voiceRecorder = useVoiceRecorder({ - disabled: interactionDisabled, - onClearError: clearVoiceSetupError, - onError: setVoiceError, - onTranscript: appendTranscription, - onTranscribeAudio, + const { + recorder: voiceRecorder, setupError: voiceSetupError, clearSetupError, + shortcutLabel: voiceShortcutLabel, shortcutAria, canSendQueuedPrompt, + } = useComposerVoiceInput({ + disabled: interactionDisabled, onTranscribeAudio, onTranscript: appendTranscription, wantsWav: transcriptionProvider === "xiaomi_mimo", }); - useEffect(() => { - if (!onTranscribeAudio) return; - - function onKeyDown(event: KeyboardEvent): void { - if (!isVoiceShortcutDown(event) || event.repeat || voiceShortcutDownRef.current) return; - event.preventDefault(); - voiceShortcutDownRef.current = true; - voiceRecorder.beginShortcutHold(); - } - - function onKeyUp(event: KeyboardEvent): void { - if (!voiceShortcutDownRef.current || !isVoiceShortcutRelease(event)) return; - event.preventDefault(); - voiceShortcutDownRef.current = false; - voiceRecorder.endShortcutHold(); - } - - function onWindowBlur(): void { - if (!voiceShortcutDownRef.current) return; - voiceShortcutDownRef.current = false; - voiceRecorder.endShortcutHold(); - } - - window.addEventListener("keydown", onKeyDown); - window.addEventListener("keyup", onKeyUp); - window.addEventListener("blur", onWindowBlur); - return () => { - window.removeEventListener("keydown", onKeyDown); - window.removeEventListener("keyup", onKeyUp); - window.removeEventListener("blur", onWindowBlur); - }; - }, [onTranscribeAudio, voiceRecorder.beginShortcutHold, voiceRecorder.endShortcutHold]); + // Runs before paint so switching sessions never flashes stale draft text. + useLayoutEffect(() => { + if (previousPendingQueueKeyRef.current === pendingQueueKey) return; + previousPendingQueueKeyRef.current = pendingQueueKey; + setValue(""); + setInlineError(null); + clearSetupError(); + setSlashMenuDismissed(false); + setCliAppMenuDismissed(false); + setCursorPosition(0); + clear(); + }, [clear, clearSetupError, pendingQueueKey]); const handleStop = useCallback(() => { pauseQueue(); @@ -1890,7 +1793,7 @@ export function ThreadComposer({ && !e.ctrlKey && !e.metaKey ) { - if (!e.repeat && voiceRecorder.state === "idle" && !voiceShortcutDownRef.current) { + if (!e.repeat && canSendQueuedPrompt()) { sendQueuedPrompt(queuedPrompt); } return; @@ -2371,7 +2274,7 @@ export function ThreadComposer({ ? t("thread.composer.configureModel", { defaultValue: "Configure model" }) : isUserShell ? t("thread.composer.shell.run") : t("thread.composer.send") } - aria-keyshortcuts={showVoiceButton ? VOICE_SHORTCUT_ARIA : undefined} + aria-keyshortcuts={showVoiceButton ? shortcutAria : undefined} onPointerDown={showVoiceButton ? voiceRecorder.beginPress : undefined} onPointerUp={showVoiceButton ? voiceRecorder.endPress : undefined} onPointerCancel={showVoiceButton ? voiceRecorder.endPress : undefined} @@ -2653,6 +2556,7 @@ function CliAppMentionPalette({ layout.maxHeight - SLASH_PALETTE_CHROME_PX, ); const listRef = useSelectedOptionScroll(selectedIndex); + const surfaceRef = useOverlaySurfaceRef("overlay"); const groupedCandidates = (["session", "cli", "mcp"] as const) .map((kind) => ({ kind, @@ -2668,6 +2572,7 @@ function CliAppMentionPalette({ .filter((group) => group.items.length > 0); return (
    ("overlay"); return (
    ; messages: UIMessage[]; beforeMessages?: ReactNode; beforeUnit?: { key: string; content: ReactNode }; @@ -82,6 +84,7 @@ export function assistantForkFlags(units: DisplayUnit[]): boolean[] { } export function ThreadMessages({ + historyRows, messages, beforeMessages, beforeUnit, @@ -257,6 +260,7 @@ export function ThreadMessages({ key={unitKeys[index]} unitKey={unitKeys[index]} scrollAnchor={scrollAnchors[index]} + historyRows={historyRows} unit={unit} mobileActions={mobileActions} marginTop={prelude ? "" : marginTop} @@ -370,7 +374,8 @@ function pendingTurnProjection( interface ThreadDisplayUnitProps { mobileActions: boolean; unitKey: string; - scrollAnchor: ScrollAnchorIdentity; + scrollAnchor: HistoryRowIdentity; + historyRows?: WeakMap; unit: DisplayUnit; marginTop: string; userPromptId?: string; @@ -574,6 +579,7 @@ const ThreadDisplayUnit = memo(function ThreadDisplayUnit({ mobileActions, unitKey, scrollAnchor, + historyRows, unit, marginTop, userPromptId, @@ -607,6 +613,12 @@ const ThreadDisplayUnit = memo(function ThreadDisplayUnit({ }: ThreadDisplayUnitProps) { const { t } = useTranslation(); const elementRef = useRef(null); + useLayoutEffect(() => { + const element = elementRef.current; + if (!element || !historyRows) return; + historyRows.set(element, scrollAnchor); + return () => { historyRows.delete(element); }; + }, [historyRows, scrollAnchor]); const activityDetailsId = useId(); const heightRef = useRef(0); const [nearViewport, setNearViewport] = useState(true); @@ -699,8 +711,6 @@ const ThreadDisplayUnit = memo(function ThreadDisplayUnit({ onContextBlockActiveChange(contextBlockKey ?? null); }} data-thread-display-unit={unitKey} - data-thread-scroll-sources={scrollAnchor.sources} - data-thread-scroll-fallback={scrollAnchor.fallback} data-user-prompt-id={userPromptId} data-message-context-block={contextBlockKey} data-context-block-active={contextBlockActive || undefined} @@ -793,8 +803,8 @@ function threadDisplayUnitPropsEqual( ): boolean { return ( displayUnitsEqual(previous.unit, next.unit) - && previous.scrollAnchor.sources === next.scrollAnchor.sources - && previous.scrollAnchor.fallback === next.scrollAnchor.fallback + && previous.historyRows === next.historyRows + && sameHistoryRowIdentity(previous.scrollAnchor, next.scrollAnchor) && previous.mobileActions === next.mobileActions && previous.marginTop === next.marginTop && previous.userPromptId === next.userPromptId @@ -956,39 +966,34 @@ export function unitKeysForDisplay(units: DisplayUnit[]): string[] { }); } -interface ScrollAnchorIdentity { - sources: string; - fallback?: string; -} - -function scrollAnchorsForUnits(units: DisplayUnit[]): ScrollAnchorIdentity[] { +function scrollAnchorsForUnits(units: DisplayUnit[]): HistoryRowIdentity[] { const sourceKeys = units.map((unit) => { const messages = unit.type === "message" ? [unit.message] : unit.messages; // Either edge of an activity cluster can survive when the other grows. const edges = messages.length > 1 ? [messages[0], messages[messages.length - 1]] : messages; - const streams: string[] = []; - const sequences: string[] = []; - const ids: string[] = []; + const streams: HistoryRowSource[] = []; + const sequences: HistoryRowSource[] = []; + const ids: HistoryRowSource[] = []; for (const message of edges) { const stream = unit.type === "message" ? message.streamId : message.reasoningStreamId; - if (message.turnId && stream) streams.push(JSON.stringify([unit.type, "stream", message.turnId, stream])); + if (message.turnId && stream) streams.push({ kind: "stream", key: JSON.stringify([unit.type, "stream", message.turnId, stream]) }); const sequence = message.projectionStartSeq ?? message.turnSeq; if (message.turnId && Number.isFinite(sequence)) { - sequences.push(JSON.stringify([unit.type, "sequence", message.turnId, sequence])); + sequences.push({ kind: "sequence", key: JSON.stringify([unit.type, "sequence", message.turnId, sequence]) }); } - ids.push(JSON.stringify([unit.type, "id", message.id])); + ids.push({ kind: "id", key: JSON.stringify([unit.type, "id", message.id]) }); } - return [...new Set([...streams, ...sequences, ...ids])]; + return Array.from(new Map([...streams, ...sequences, ...ids].map((source) => [source.key, source])).values()); }); const sourceCounts = new Map(); const bases = units.map(unitKeyBase); const baseCounts = new Map(); for (const sources of sourceKeys) for (const source of sources) { - sourceCounts.set(source, (sourceCounts.get(source) ?? 0) + 1); + sourceCounts.set(source.key, (sourceCounts.get(source.key) ?? 0) + 1); } for (const base of bases) baseCounts.set(base, (baseCounts.get(base) ?? 0) + 1); return sourceKeys.map((sources, index) => ({ - sources: JSON.stringify(sources.filter((source) => sourceCounts.get(source) === 1)), + sources: sources.filter((source) => sourceCounts.get(source.key) === 1), // A sole turn/phase row can keep its live identity when replay replaces // both its source id and sequence. Occurrence keys are unsafe otherwise. ...(bases[index].startsWith("turn-") && baseCounts.get(bases[index]) === 1 diff --git a/webui/src/components/thread/ThreadShell.tsx b/webui/src/components/thread/ThreadShell.tsx index 6f39ac1ec..51aed3727 100644 --- a/webui/src/components/thread/ThreadShell.tsx +++ b/webui/src/components/thread/ThreadShell.tsx @@ -1,5 +1,5 @@ import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"; -import type { CSSProperties, PointerEvent as ReactPointerEvent, ReactNode } from "react"; +import type { CSSProperties, ReactNode } from "react"; import { createPortal } from "react-dom"; import { useTranslation } from "react-i18next"; import { composerUsageSnapshots, type ComposerUsageSnapshot } from "@/lib/model-request"; @@ -87,6 +87,8 @@ import { projectWebuiThreadMessages } from "@/lib/thread-display-projection"; import { ThreadMessageCache } from "@/lib/thread-message-cache"; import { providerDisplayLabel } from "@/lib/provider-brand"; import { cn } from "@/lib/utils"; +import { useFilePreviewResize } from "@/hooks/useFilePreviewResize"; +import { hasAnyOverlayMounted } from "@/lib/dom-overlays"; import { composerContextSnapshots } from "@/lib/context-graph"; import { useClient } from "@/providers/ClientProvider"; @@ -187,10 +189,6 @@ function hasInlineDeliveryError( )); } -const FILE_PREVIEW_DEFAULT_WIDTH = 544; -const FILE_PREVIEW_MIN_WIDTH = 360; -const FILE_PREVIEW_MAX_WIDTH = 860; -const FILE_PREVIEW_MIN_MAIN_WIDTH = 420; const FILE_PREVIEW_CLOSE_ANIMATION_MS = 320; type FilePreviewAvailabilityCacheEntry = { @@ -199,20 +197,6 @@ type FilePreviewAvailabilityCacheEntry = { revision: number; }; -function clampFilePreviewWidth(width: number, maxWidth: number): number { - return Math.min(Math.max(width, FILE_PREVIEW_MIN_WIDTH), maxWidth); -} - -function maxFilePreviewWidth(containerWidth: number): number { - return Math.min( - containerWidth > 0 ? containerWidth : FILE_PREVIEW_MIN_WIDTH, - Math.max( - FILE_PREVIEW_MIN_WIDTH, - Math.min(FILE_PREVIEW_MAX_WIDTH, containerWidth - FILE_PREVIEW_MIN_MAIN_WIDTH), - ), - ); -} - const EMPTY_TITLE_OVERRIDES: Record = {}; interface ThreadShellProps { @@ -498,6 +482,7 @@ export function ThreadShell({ }, [multiplePanes, previewSessionKey]); const [sidebarEnterWidth, setSidebarEnterWidth] = useState(0); const [contextSidebarHost, setContextSidebarHost] = useState(null); + const contextSidebarRef = useRef(null); const setSidebarHost = useCallback((node: HTMLElement | null) => { shellRef.current = node; setContextSidebarHost(node); }, []); const [closingPreview, setClosingPreview] = useState<{ key: string; state: FilePreviewState } | null>(null); const filePreviewClosing = closingPreview?.key === previewSessionKey; @@ -525,8 +510,6 @@ export function ThreadShell({ if (range && selection) { selection.removeAllRanges(); selection.addRange(range); } }, [composerDestination, composerMount, inlineComposer]); useLayoutEffect(() => () => composerMount.remove(), [composerMount]); - const [filePreviewMaxWidth, setFilePreviewMaxWidth] = useState(FILE_PREVIEW_MAX_WIDTH); - const filePreviewWidth = clampFilePreviewWidth(previewState.width, filePreviewMaxWidth); const draftKey = session?.key ?? (temporaryChatEnabled ? "new:temporary" : "new:chat"); const persistDraft = session ? !temporary : !temporaryChatEnabled; const [quote, setQuote] = useState<{ key: string; text: string | null } | null>(null); @@ -538,6 +521,9 @@ export function ThreadShell({ }, [draftKey]); const [composerFocusSignal, setComposerFocusSignal] = useState(0); const shellRef = useRef(null); + const { width: filePreviewWidth, panelRef: previewPanelRef, startResize: handleFilePreviewResizeStart, cancelResize: cancelPreviewResize } = useFilePreviewResize( + shellRef, previewOpen, previewState.width, setFilePreviewWidth, + ); const [conversationElement, setConversationElement] = useState(null); const [composerSurface, setComposerSurface] = useState(null); const alignSidebar = useCallback(() => { @@ -556,9 +542,7 @@ export function ThreadShell({ observer.observe(composerSurface); return () => observer.disconnect(); }, [alignSidebar, contextSidebarHost, sidebarOpen, inlineComposer, composerDestination, composerMount, composerSurface]); - const filePreviewWidthRef = useRef(FILE_PREVIEW_DEFAULT_WIDTH); const filePreviewCloseTimerRef = useRef(null); - const filePreviewResizeCleanupRef = useRef<(() => void) | null>(null); const pendingFirstRef = useRef<(PendingFirstMessage & { draft?: ComposerDraft; draftKey: string }) | null>(null); const [restoredFirstDraft, setRestoredFirstDraft] = useState<{ chatId: string; revision: number; error: string } | null>(null); const [pendingFirstTargetChatId, setPendingFirstTargetChatId] = useState(null); @@ -647,18 +631,14 @@ export function ThreadShell({ }, [chatId, historyKey]); useEffect(() => { - filePreviewWidthRef.current = filePreviewWidth; - }, [filePreviewWidth]); - - useEffect(() => { - filePreviewResizeCleanupRef.current?.(); + cancelPreviewResize(); if (filePreviewCloseTimerRef.current !== null) { window.clearTimeout(filePreviewCloseTimerRef.current); filePreviewCloseTimerRef.current = null; } setClosingPreview(null); setSubmittedViewportTurn(null); - }, [previewSessionKey]); + }, [cancelPreviewResize, previewSessionKey]); useEffect(() => { const retained = new Set(temporaryChatIds); @@ -680,7 +660,6 @@ export function ThreadShell({ useEffect(() => { return () => { - filePreviewResizeCleanupRef.current?.(); if (filePreviewCloseTimerRef.current !== null) { window.clearTimeout(filePreviewCloseTimerRef.current); } @@ -1133,7 +1112,7 @@ export function ThreadShell({ const handleCloseFilePreview = useCallback(() => { if (!previewSessionKey || !previewState.activeId || filePreviewClosing) return; - filePreviewResizeCleanupRef.current?.(); + cancelPreviewResize(); setClosingPreview({ key: previewSessionKey, state: previewState }); // Record the closed state immediately, even if navigation interrupts the animation. closePreview(); @@ -1141,23 +1120,24 @@ export function ThreadShell({ filePreviewCloseTimerRef.current = null; setClosingPreview(null); }, FILE_PREVIEW_CLOSE_ANIMATION_MS); - }, [previewSessionKey, filePreviewClosing, previewState, closePreview]); + }, [cancelPreviewResize, previewSessionKey, filePreviewClosing, previewState, closePreview]); const cancelPreviewClose = useCallback(() => { - filePreviewResizeCleanupRef.current?.(); + cancelPreviewResize(); if (filePreviewCloseTimerRef.current !== null) { window.clearTimeout(filePreviewCloseTimerRef.current); filePreviewCloseTimerRef.current = null; } setClosingPreview(null); - }, []); + }, [cancelPreviewResize]); const handleOpenFilePreview = useCallback((path: string) => { - setSidebarEnterWidth(shellRef.current?.querySelector(".file-preview-pane")?.getBoundingClientRect().width ?? 0); + const outgoingSidebar = previewPanelRef.current ?? contextSidebarRef.current; + setSidebarEnterWidth(outgoingSidebar?.getBoundingClientRect().width ?? 0); setContextSidebarOpen(false); cancelPreviewClose(); openFile(path); - }, [cancelPreviewClose, openFile]); + }, [cancelPreviewClose, openFile, previewPanelRef]); const handleContextSidebarOpenChange = useCallback((open: boolean) => { if (open) { @@ -1170,10 +1150,10 @@ export function ThreadShell({ const handleClosePreviewTab = useCallback((id: string) => { if (previewState.tabs.length === 1) handleCloseFilePreview(); else { - filePreviewResizeCleanupRef.current?.(); + cancelPreviewResize(); closeTab(id); } - }, [previewState.tabs.length, handleCloseFilePreview, closeTab]); + }, [cancelPreviewResize, previewState.tabs.length, handleCloseFilePreview, closeTab]); // Markdown blocks can retain rendered links while their text is unchanged. // Keep their callback stable, but always act on the current pane/session state. @@ -1203,7 +1183,7 @@ export function ThreadShell({ const onKeyDown = (event: KeyboardEvent) => { if (event.key !== "Escape" || event.defaultPrevented || event.isComposing) return; // Let a dialog/menu above the pane consume Escape without closing this preview. - if (document.querySelector('[role="dialog"], [role="alertdialog"], [role="menu"], [role="listbox"], [data-radix-popper-content-wrapper]')) return; + if (hasAnyOverlayMounted()) return; event.preventDefault(); handleCloseFilePreview(); }; @@ -1211,84 +1191,6 @@ export function ThreadShell({ return () => window.removeEventListener("keydown", onKeyDown); }, [previewOpen, headerActive, handleCloseFilePreview]); - const handleFilePreviewResizeStart = useCallback((event: ReactPointerEvent) => { - filePreviewResizeCleanupRef.current?.(); - event.preventDefault(); - event.stopPropagation(); - const panel = event.currentTarget.closest("[data-file-preview-panel]"); - const shellRect = shellRef.current?.getBoundingClientRect(); - const rightEdge = shellRect?.right ?? window.innerWidth; - const maxWidth = maxFilePreviewWidth(shellRect?.width ?? window.innerWidth); - const originalBodyCursor = document.body.style.cursor; - const originalBodyUserSelect = document.body.style.userSelect; - const originalPanelTransition = panel?.style.transition ?? ""; - const frameElement = panel?.querySelector("iframe"); - const originalFramePointerEvents = frameElement?.style.pointerEvents ?? ""; - let nextWidth = filePreviewWidthRef.current; - let frame: number | null = null; - - document.body.style.cursor = "col-resize"; - document.body.style.userSelect = "none"; - if (panel) panel.style.transition = "none"; - if (frameElement) frameElement.style.pointerEvents = "none"; - - const applyWidth = (clientX: number) => { - nextWidth = clampFilePreviewWidth(rightEdge - clientX, maxWidth); - filePreviewWidthRef.current = nextWidth; - if (frame !== null) return; - frame = window.requestAnimationFrame(() => { - frame = null; - panel?.style.setProperty("--file-preview-width", `${nextWidth}px`); - panel?.style.setProperty("--file-preview-slot-width", `${nextWidth}px`); - }); - }; - const handlePointerMove = (moveEvent: PointerEvent) => { - moveEvent.preventDefault(); - applyWidth(moveEvent.clientX); - }; - const stopResize = (commit: boolean) => { - if (frame !== null) { - window.cancelAnimationFrame(frame); - frame = null; - } - panel?.style.setProperty("--file-preview-width", `${nextWidth}px`); - panel?.style.setProperty("--file-preview-slot-width", `${nextWidth}px`); - if (panel) panel.style.transition = originalPanelTransition; - if (frameElement) frameElement.style.pointerEvents = originalFramePointerEvents; - if (commit) setFilePreviewWidth(nextWidth); - document.body.style.cursor = originalBodyCursor; - document.body.style.userSelect = originalBodyUserSelect; - window.removeEventListener("pointermove", handlePointerMove); - window.removeEventListener("pointerup", handlePointerUp); - window.removeEventListener("pointercancel", handlePointerUp); - filePreviewResizeCleanupRef.current = null; - }; - const handlePointerUp = () => stopResize(true); - filePreviewResizeCleanupRef.current = () => stopResize(false); - - applyWidth(event.clientX); - window.addEventListener("pointermove", handlePointerMove); - window.addEventListener("pointerup", handlePointerUp); - window.addEventListener("pointercancel", handlePointerUp); - }, [setFilePreviewWidth]); - - useEffect(() => { - if (!previewOpen) return; - const clampToShell = () => { - const shellWidth = shellRef.current?.getBoundingClientRect().width ?? window.innerWidth; - const maxWidth = maxFilePreviewWidth(shellWidth); - setFilePreviewMaxWidth(maxWidth); - }; - clampToShell(); - const observer = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(clampToShell); - if (shellRef.current) observer?.observe(shellRef.current); - window.addEventListener("resize", clampToShell); - return () => { - observer?.disconnect(); - window.removeEventListener("resize", clampToShell); - }; - }, [previewOpen]); - const handleForkFromMessage = useCallback( async (beforeUserIndex: number) => { if (!chatId || !onForkChat) return; @@ -1588,6 +1490,7 @@ export function ThreadShell({ rounds={composerRoundUsage} snapshots={contextGraphSnapshots} sidebarHost={contextSidebarHost} + sidebarRef={contextSidebarRef} open={contextSidebarOpen} onOpenChange={handleContextSidebarOpenChange} onOpenFile={handleOpenFilePreview} @@ -1615,6 +1518,7 @@ export function ThreadShell({ onSelect={selectTab} onCloseTab={handleClosePreviewTab} onClose={handleCloseFilePreview} + panelRef={previewPanelRef} onResizeStart={handleFilePreviewResizeStart} > scrollSourceKind(source) === kind); - const rightKeys = right.filter((source) => scrollSourceKind(source) === kind); - return leftKeys.length > 0 && rightKeys.length > 0 - && !leftKeys.some((source) => rightKeys.includes(source)); -} - function promptTopInset(scroller: HTMLElement): number { const padding = Number.parseFloat(getComputedStyle(scroller).scrollPaddingTop); return Number.isFinite(padding) ? padding : PROMPT_TOP_INSET_PX; @@ -333,6 +322,7 @@ export const ThreadViewport = forwardRef(null); const messageRegionRef = useRef(null); const messageContentRef = useRef(null); + const [historyRows] = useState(() => new WeakMap()); const diffViewport = useMemo(() => ({ scroller: messageRegionRef, content: messageContentRef }), []); const emptyStateRef = useRef(null); const composerDockRef = useRef(null); @@ -558,26 +548,20 @@ export const ThreadViewport = forwardRef { const scroller = scrollRef.current; @@ -588,26 +572,9 @@ export const ThreadViewport = forwardRef= 0.5) { return captureHistoryScrollAnchor(); } - const candidates = Array.from(content.querySelectorAll(THREAD_DISPLAY_UNIT_SELECTOR)); - const bySource = new Map(); - for (const candidate of candidates) { - const sources = JSON.parse(candidate.dataset.threadScrollSources ?? "[]") as string[]; - for (const source of sources) bySource.set(source, { element: candidate, sources }); - } - let element: HTMLElement | undefined; - for (const source of anchor.sources) { - const candidate = bySource.get(source); - if (!candidate) continue; - const kind = scrollSourceKind(source); - // An index-generated replay id can be reused by a different message. - if (kind !== "stream" && scrollSourcesDisagree(anchor.sources, candidate.sources, "stream")) continue; - if (kind === "id" && scrollSourcesDisagree(anchor.sources, candidate.sources, "sequence")) continue; - element = candidate.element; - break; - } - if (!element && anchor.fallback) { - element = candidates.find((candidate) => candidate.dataset.threadScrollFallback === anchor.fallback); - } + const element = matchHistoryRow( + anchor.identity, content.querySelectorAll(THREAD_DISPLAY_UNIT_SELECTOR), historyRows, + ); if (!element) { historyScrollAnchorRef.current = null; return false; @@ -626,7 +593,7 @@ export const ThreadViewport = forwardRef { setHistorySlotKey(null); @@ -1342,6 +1309,7 @@ export const ThreadViewport = forwardRef (
    diff --git a/webui/src/components/thread/history-row-identity.ts b/webui/src/components/thread/history-row-identity.ts new file mode 100644 index 000000000..51331188c --- /dev/null +++ b/webui/src/components/thread/history-row-identity.ts @@ -0,0 +1,45 @@ +type HistorySourceKind = "stream" | "sequence" | "id"; + +export interface HistoryRowSource { + kind: HistorySourceKind; + key: string; +} + +export interface HistoryRowIdentity { + sources: HistoryRowSource[]; + fallback?: string; +} + +export function sameHistoryRowIdentity(left: HistoryRowIdentity, right: HistoryRowIdentity): boolean { + return left.fallback === right.fallback && left.sources.length === right.sources.length + && left.sources.every((source, index) => source.key === right.sources[index].key); +} + +function sourcesDisagree(left: HistoryRowIdentity, right: HistoryRowIdentity, kind: HistorySourceKind): boolean { + const leftKeys = left.sources.filter((source) => source.kind === kind); + const rightKeys = right.sources.filter((source) => source.kind === kind); + return leftKeys.length > 0 && rightKeys.length > 0 + && !leftKeys.some((source) => rightKeys.some((other) => source.key === other.key)); +} + +export function matchHistoryRow( + anchor: HistoryRowIdentity, candidates: Iterable, rows: WeakMap, +): HTMLElement | undefined { + const bySource = new Map(); + let fallback: HTMLElement | undefined; + for (const element of candidates) { + const identity = rows.get(element); + if (!identity) continue; + for (const source of identity.sources) bySource.set(source.key, { element, identity }); + if (!fallback && anchor.fallback && anchor.fallback === identity.fallback) fallback = element; + } + for (const source of anchor.sources) { + const candidate = bySource.get(source.key); + if (!candidate) continue; + // A replay-generated row id may be reused for a different message. + if (source.kind !== "stream" && sourcesDisagree(anchor, candidate.identity, "stream")) continue; + if (source.kind === "id" && sourcesDisagree(anchor, candidate.identity, "sequence")) continue; + return candidate.element; + } + return fallback; +} diff --git a/webui/src/components/ui/alert-dialog.tsx b/webui/src/components/ui/alert-dialog.tsx index 59a25b540..8d43ba425 100644 --- a/webui/src/components/ui/alert-dialog.tsx +++ b/webui/src/components/ui/alert-dialog.tsx @@ -6,6 +6,7 @@ import { modalOverlayClassName, modalSurfaceClassName, } from "@/components/ui/floating-surface"; +import { useOverlaySurfaceRef } from "@/lib/dom-overlays"; import { cn } from "@/lib/utils"; const AlertDialog = AlertDialogPrimitive.Root; @@ -29,22 +30,25 @@ AlertDialogOverlay.displayName = AlertDialogPrimitive.Overlay.displayName; const AlertDialogContent = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef ->(({ className, ...props }, ref) => ( - - -
    - -
    -
    -)); +>(({ className, ...props }, ref) => { + const surfaceRef = useOverlaySurfaceRef("dialog", ref); + return ( + + +
    + +
    +
    + ); +}); AlertDialogContent.displayName = AlertDialogPrimitive.Content.displayName; const AlertDialogHeader = ({ diff --git a/webui/src/components/ui/dialog.tsx b/webui/src/components/ui/dialog.tsx index 4beb7fda3..2d7ce7a81 100644 --- a/webui/src/components/ui/dialog.tsx +++ b/webui/src/components/ui/dialog.tsx @@ -7,6 +7,7 @@ import { modalOverlayClassName, modalSurfaceClassName, } from "@/components/ui/floating-surface"; +import { useOverlaySurfaceRef } from "@/lib/dom-overlays"; import { cn } from "@/lib/utils"; import { FloatingPortalContext } from "@/components/ui/floating-portal"; @@ -47,6 +48,7 @@ const DialogPositionedContent = React.forwardRef< overlayClassName?: string; } >(({ contained, positionerStyle, placement, overlayClassName, ...props }, ref) => { + const surfaceRef = useOverlaySurfaceRef("dialog", ref); const Overlay = contained ? "div" : DialogOverlay; return
    - +
    ; }); diff --git a/webui/src/components/ui/dropdown-menu.tsx b/webui/src/components/ui/dropdown-menu.tsx index d1ff8fca0..8f08f631f 100644 --- a/webui/src/components/ui/dropdown-menu.tsx +++ b/webui/src/components/ui/dropdown-menu.tsx @@ -8,6 +8,7 @@ import { floatingSurfaceClassName, floatingSurfaceMotionClassName, } from "@/components/ui/floating-surface"; +import { useOverlaySurfaceRef } from "@/lib/dom-overlays"; import { cn } from "@/lib/utils"; import { useFloatingPortal } from "@/components/ui/floating-portal"; @@ -29,10 +30,11 @@ const DropdownMenuContent = React.forwardRef< DropdownMenuContentProps >(({ className, sideOffset = 4, portalContainer, ...props }, ref) => { const dialogContainer = useFloatingPortal(); + const surfaceRef = useOverlaySurfaceRef("overlay", ref); return ( , React.ComponentPropsWithoutRef ->(({ className, sideOffset = 6, ...props }, ref) => ( - -)); +>(({ className, sideOffset = 6, ...props }, ref) => { + const surfaceRef = useOverlaySurfaceRef("overlay", ref); + return ( + + ); +}); DropdownMenuSubContent.displayName = DropdownMenuPrimitive.SubContent.displayName; export { diff --git a/webui/src/components/ui/popover.tsx b/webui/src/components/ui/popover.tsx index d49a63935..2dc5d3b5d 100644 --- a/webui/src/components/ui/popover.tsx +++ b/webui/src/components/ui/popover.tsx @@ -5,6 +5,7 @@ import { floatingSurfaceClassName, floatingSurfaceMotionClassName, } from "@/components/ui/floating-surface"; +import { useOverlaySurfaceRef } from "@/lib/dom-overlays"; import { cn } from "@/lib/utils"; import { useFloatingPortal } from "@/components/ui/floating-portal"; @@ -23,10 +24,12 @@ const PopoverContent = React.forwardRef< PopoverContentProps >(({ className, sideOffset = 4, portalContainer, motionClassName = floatingSurfaceMotionClassName, ...props }, ref) => { const dialogContainer = useFloatingPortal(); + // Radix renders Popover.Content as role="dialog". + const surfaceRef = useOverlaySurfaceRef("dialog", ref); return ( ) { const container = useFloatingPortal(); + const surfaceRef = useOverlaySurfaceRef("overlay"); return ( - + {children} diff --git a/webui/src/components/ui/sheet.tsx b/webui/src/components/ui/sheet.tsx index 15f03d6a3..af76e0af2 100644 --- a/webui/src/components/ui/sheet.tsx +++ b/webui/src/components/ui/sheet.tsx @@ -4,6 +4,7 @@ import { X } from "lucide-react"; import { cva, type VariantProps } from "class-variance-authority"; import { useTranslation } from "react-i18next"; +import { useOverlaySurfaceRef } from "@/lib/dom-overlays"; import { cn } from "@/lib/utils"; import { modalOverlayClassName, sidePanelSurfaceClassName } from "./floating-surface"; @@ -84,11 +85,12 @@ const SheetContent = React.forwardRef< ref, ) => { const { t } = useTranslation(); + const surfaceRef = useOverlaySurfaceRef("dialog", ref); return ( , React.ComponentPropsWithoutRef ->(({ className, sideOffset = 4, ...props }, ref) => ( - - - -)); +>(({ className, sideOffset = 4, ...props }, ref) => { + const surfaceRef = useOverlaySurfaceRef("overlay", ref); + return ( + + + + ); +}); TooltipContent.displayName = TooltipPrimitive.Content.displayName; export { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger }; diff --git a/webui/src/globals.css b/webui/src/globals.css index 095454f63..b3c4fe7df 100644 --- a/webui/src/globals.css +++ b/webui/src/globals.css @@ -2153,7 +2153,7 @@ html[data-custom-background] .markdown-inline-code { html[data-custom-background] .thread-history-status { --thread-history-background: hsl(var(--background) / 0.65); } -html[data-custom-background] [data-testid="file-edit-diff"] { +html[data-custom-background] .file-edit-diff-surface { background-color: hsl(var(--background) / 0.78); backdrop-filter: blur(12px); } diff --git a/webui/src/hooks/useComposerVoiceInput.ts b/webui/src/hooks/useComposerVoiceInput.ts new file mode 100644 index 000000000..1db487045 --- /dev/null +++ b/webui/src/hooks/useComposerVoiceInput.ts @@ -0,0 +1,128 @@ +import { useCallback, useEffect, useRef, useState } from "react"; +import { useTranslation } from "react-i18next"; +import { useToast } from "@/components/ui/toast"; +import { useVoiceRecorder, type VoiceRecorderErrorKey } from "@/hooks/useVoiceRecorder"; + +const VOICE_SHORTCUT_CODE = "KeyD"; +const VOICE_SHORTCUT_ARIA = "Control+Shift+D"; +type VoiceShortcutPlatform = "apple" | "chromeos" | "linux" | "other" | "windows"; + +function isVoiceShortcutDown(event: KeyboardEvent): boolean { + return ( + event.code === VOICE_SHORTCUT_CODE + && event.ctrlKey + && event.shiftKey + && !event.altKey + && !event.metaKey + ); +} + +function isVoiceShortcutRelease(event: KeyboardEvent): boolean { + return ( + event.code === VOICE_SHORTCUT_CODE + || event.key === "Control" + || event.key === "Shift" + ); +} + +function getVoiceShortcutPlatform(): VoiceShortcutPlatform { + if (typeof navigator === "undefined") return "other"; + const userAgentData = (navigator as Navigator & { userAgentData?: { platform?: string } }) + .userAgentData; + const platform = [ + userAgentData?.platform, + navigator.platform, + navigator.userAgent, + ].filter(Boolean).join(" ").toLowerCase(); + const isIpadPretendingToBeMac = + navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1; + if (isIpadPretendingToBeMac || /mac|iphone|ipad|ipod/.test(platform)) return "apple"; + if (/win/.test(platform)) return "windows"; + if (/cros/.test(platform)) return "chromeos"; + if (/linux|x11|android/.test(platform)) return "linux"; + return "other"; +} + +function getVoiceShortcutLabel(): string { + switch (getVoiceShortcutPlatform()) { + case "apple": + return "⌃⇧D"; + case "chromeos": + case "linux": + case "windows": + case "other": + return "Ctrl ⇧ D"; + } +} + +type VoiceInputOptions = Pick[0], + "disabled" | "onTranscribeAudio" | "onTranscript" | "wantsWav">; + +/** Owns press/shortcut recording and how the composer presents voice setup errors. */ +export function useComposerVoiceInput({ disabled, onTranscribeAudio, onTranscript, wantsWav }: VoiceInputOptions) { + const { t } = useTranslation(); + const showToast = useToast(); + const [voiceSetupError, setVoiceSetupError] = useState(null); + const [shortcutLabel] = useState(getVoiceShortcutLabel); + const voiceShortcutDownRef = useRef(false); + const clearVoiceSetupError = useCallback(() => setVoiceSetupError(null), []); + const setVoiceError = useCallback((key: VoiceRecorderErrorKey) => { + // Setup blockers carry instructions users may need to keep in view while fixing them. + if (key === "insecureContext" || key === "permission" || key === "notConfigured") { + setVoiceSetupError(key); + return; + } + showToast?.({ message: t(`thread.composer.voiceErrors.${key}`), tone: "error", dedupeKey: "voice-input" }); + }, [showToast, t]); + const voiceRecorder = useVoiceRecorder({ + disabled, + onClearError: clearVoiceSetupError, + onError: setVoiceError, + onTranscript, + onTranscribeAudio, + wantsWav, + }); + + useEffect(() => { + if (!onTranscribeAudio) return; + + function onKeyDown(event: KeyboardEvent): void { + if (!isVoiceShortcutDown(event) || event.repeat || voiceShortcutDownRef.current) return; + event.preventDefault(); + voiceShortcutDownRef.current = true; + voiceRecorder.beginShortcutHold(); + } + + function onKeyUp(event: KeyboardEvent): void { + if (!voiceShortcutDownRef.current || !isVoiceShortcutRelease(event)) return; + event.preventDefault(); + voiceShortcutDownRef.current = false; + voiceRecorder.endShortcutHold(); + } + + function onWindowBlur(): void { + if (!voiceShortcutDownRef.current) return; + voiceShortcutDownRef.current = false; + voiceRecorder.endShortcutHold(); + } + + window.addEventListener("keydown", onKeyDown); + window.addEventListener("keyup", onKeyUp); + window.addEventListener("blur", onWindowBlur); + return () => { + window.removeEventListener("keydown", onKeyDown); + window.removeEventListener("keyup", onKeyUp); + window.removeEventListener("blur", onWindowBlur); + }; + }, [onTranscribeAudio, voiceRecorder.beginShortcutHold, voiceRecorder.endShortcutHold]); + + return { + recorder: voiceRecorder, + setupError: voiceSetupError, + clearSetupError: clearVoiceSetupError, + shortcutLabel, + shortcutAria: VOICE_SHORTCUT_ARIA, + // Includes the interval while the shortcut is held and permission is still pending. + canSendQueuedPrompt: () => voiceRecorder.state === "idle" && !voiceShortcutDownRef.current, + }; +} diff --git a/webui/src/hooks/useFilePreviewResize.ts b/webui/src/hooks/useFilePreviewResize.ts new file mode 100644 index 000000000..9e3cc94a8 --- /dev/null +++ b/webui/src/hooks/useFilePreviewResize.ts @@ -0,0 +1,116 @@ +import { useCallback, useEffect, useRef, useState, type PointerEvent as ReactPointerEvent, type RefObject } from "react"; + +const FILE_PREVIEW_MIN_WIDTH = 360; +const FILE_PREVIEW_MAX_WIDTH = 860; +const FILE_PREVIEW_MIN_MAIN_WIDTH = 420; + +function clampFilePreviewWidth(width: number, maxWidth: number): number { + return Math.min(Math.max(width, FILE_PREVIEW_MIN_WIDTH), maxWidth); +} + +function maxFilePreviewWidth(containerWidth: number): number { + return Math.min( + containerWidth > 0 ? containerWidth : FILE_PREVIEW_MIN_WIDTH, + Math.max( + FILE_PREVIEW_MIN_WIDTH, + Math.min(FILE_PREVIEW_MAX_WIDTH, containerWidth - FILE_PREVIEW_MIN_MAIN_WIDTH), + ), + ); +} + +/** Owns the transient drag, panel geometry and restoration of drag-time styles. */ +export function useFilePreviewResize( + shellRef: RefObject, previewOpen: boolean, storedWidth: number, setFilePreviewWidth: (width: number) => void, +) { + const panelRef = useRef(null); + const [filePreviewMaxWidth, setFilePreviewMaxWidth] = useState(FILE_PREVIEW_MAX_WIDTH); + const filePreviewWidth = clampFilePreviewWidth(storedWidth, filePreviewMaxWidth); + const filePreviewWidthRef = useRef(filePreviewWidth); + const filePreviewResizeCleanupRef = useRef<(() => void) | null>(null); + const cancelResize = useCallback(() => filePreviewResizeCleanupRef.current?.(), []); + useEffect(() => cancelResize, [cancelResize]); + + useEffect(() => { + filePreviewWidthRef.current = filePreviewWidth; + }, [filePreviewWidth]); + + const handleFilePreviewResizeStart = useCallback((event: ReactPointerEvent) => { + filePreviewResizeCleanupRef.current?.(); + event.preventDefault(); + event.stopPropagation(); + const panel = panelRef.current; + const shellRect = shellRef.current?.getBoundingClientRect(); + const rightEdge = shellRect?.right ?? window.innerWidth; + const maxWidth = maxFilePreviewWidth(shellRect?.width ?? window.innerWidth); + const originalBodyCursor = document.body.style.cursor; + const originalBodyUserSelect = document.body.style.userSelect; + const originalPanelTransition = panel?.style.transition ?? ""; + const frameElement = panel?.querySelector("iframe"); + const originalFramePointerEvents = frameElement?.style.pointerEvents ?? ""; + let nextWidth = filePreviewWidthRef.current; + let frame: number | null = null; + + document.body.style.cursor = "col-resize"; + document.body.style.userSelect = "none"; + if (panel) panel.style.transition = "none"; + if (frameElement) frameElement.style.pointerEvents = "none"; + + const applyWidth = (clientX: number) => { + nextWidth = clampFilePreviewWidth(rightEdge - clientX, maxWidth); + filePreviewWidthRef.current = nextWidth; + if (frame !== null) return; + frame = window.requestAnimationFrame(() => { + frame = null; + panel?.style.setProperty("--file-preview-width", `${nextWidth}px`); + panel?.style.setProperty("--file-preview-slot-width", `${nextWidth}px`); + }); + }; + const handlePointerMove = (moveEvent: PointerEvent) => { + moveEvent.preventDefault(); + applyWidth(moveEvent.clientX); + }; + const stopResize = (commit: boolean) => { + if (frame !== null) { + window.cancelAnimationFrame(frame); + frame = null; + } + panel?.style.setProperty("--file-preview-width", `${nextWidth}px`); + panel?.style.setProperty("--file-preview-slot-width", `${nextWidth}px`); + if (panel) panel.style.transition = originalPanelTransition; + if (frameElement) frameElement.style.pointerEvents = originalFramePointerEvents; + if (commit) setFilePreviewWidth(nextWidth); + document.body.style.cursor = originalBodyCursor; + document.body.style.userSelect = originalBodyUserSelect; + window.removeEventListener("pointermove", handlePointerMove); + window.removeEventListener("pointerup", handlePointerUp); + window.removeEventListener("pointercancel", handlePointerUp); + filePreviewResizeCleanupRef.current = null; + }; + const handlePointerUp = () => stopResize(true); + filePreviewResizeCleanupRef.current = () => stopResize(false); + + applyWidth(event.clientX); + window.addEventListener("pointermove", handlePointerMove); + window.addEventListener("pointerup", handlePointerUp); + window.addEventListener("pointercancel", handlePointerUp); + }, [setFilePreviewWidth, shellRef]); + + useEffect(() => { + if (!previewOpen) return; + const clampToShell = () => { + const shellWidth = shellRef.current?.getBoundingClientRect().width ?? window.innerWidth; + const maxWidth = maxFilePreviewWidth(shellWidth); + setFilePreviewMaxWidth(maxWidth); + }; + clampToShell(); + const observer = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(clampToShell); + if (shellRef.current) observer?.observe(shellRef.current); + window.addEventListener("resize", clampToShell); + return () => { + observer?.disconnect(); + window.removeEventListener("resize", clampToShell); + }; + }, [previewOpen, shellRef]); + + return { width: filePreviewWidth, panelRef, startResize: handleFilePreviewResizeStart, cancelResize }; +} diff --git a/webui/src/hooks/useLocalGateway.ts b/webui/src/hooks/useLocalGateway.ts new file mode 100644 index 000000000..d751ee09a --- /dev/null +++ b/webui/src/hooks/useLocalGateway.ts @@ -0,0 +1,205 @@ +import { useCallback, useEffect, useRef, useState } from "react"; +import { + BootstrapAuthRequiredError, + clearSavedSecret, + consumeUrlBootstrapSecret, + deriveWsUrl, + fetchBootstrap, + loadSavedSecret, + saveSecret, +} from "@/lib/bootstrap"; +import { clearStoredComposerDrafts } from "@/lib/composer-draft"; +import { NanobotClient } from "@/lib/nanobot-client"; +import { activateReloadCache, clearReloadCache } from "@/lib/reload-cache"; +import { createRuntimeHost, isNativeRuntime, toRuntimeSurface } from "@/lib/runtime"; +import type { BootstrapResponse, RuntimeSurface } from "@/lib/types"; +import { webuiThreadCache } from "@/lib/webui-thread-cache"; +import { RESTART_ROUTE_KEY, RESTART_STARTED_KEY, rememberRestartRoute } from "@/shell-route"; + +type ReadyGateway = { + status: "ready"; + client: NanobotClient; + token: string; + tokenExpiresAt: number | null; + modelName: string | null; + ingressLimits: BootstrapResponse["limits"] | null; + runtimeSurface: RuntimeSurface; + webuiCapabilities: string[]; +}; + +type GatewayState = ReadyGateway | { status: "loading" } | { status: "auth" } + | { status: "error"; message: string }; + +function bootstrapCredentials(boot: BootstrapResponse, fallbackSurface: RuntimeSurface) { + const capabilities = boot.terminal?.webui?.capabilities; + return { + token: boot.api_token ?? "", + tokenExpiresAt: boot.expires_in ? Date.now() + Math.max(0, boot.expires_in) * 1000 : null, + runtimeSurface: isNativeRuntime(boot.runtime_surface) ? "native" + : boot.runtime_surface ? toRuntimeSurface(boot.runtime_surface) : fallbackSurface, + webuiCapabilities: Array.isArray(capabilities) ? capabilities.filter((entry) => typeof entry === "string") : [], + }; +} + +function tokenRefreshDelayMs(expiresAt: number): number { + const remaining = Math.max(0, expiresAt - Date.now()); + return Math.max(5_000, remaining - Math.min(30_000, Math.max(1_000, remaining / 2))); +} + +function isBootstrapAuthRequired(error: unknown): boolean { + if (error instanceof BootstrapAuthRequiredError) return true; + const msg = error instanceof Error ? error.message : String(error); + return msg.includes("HTTP 401") || msg.includes("HTTP 403"); +} + +function clearGatewayCaches() { + clearReloadCache(); + clearStoredComposerDrafts(); + webuiThreadCache.clear(); +} + +/** Owns the local socket and credentials; remote panes have separate clients. */ +export function useLocalGateway(prefetchChat: () => void) { + const [state, setState] = useState({ status: "loading" }); + const owner = useRef(null); + const attempt = useRef(0); + + const closeClient = useCallback(() => { + const client = owner.current; + owner.current = null; + client?.close(); + }, []); + + const refreshClient = useCallback(async ( + client: NanobotClient, secret: string, fallbackSurface: RuntimeSurface, signal?: AbortSignal, + ) => { + if (owner.current !== client) throw new DOMException("Gateway client changed", "AbortError"); + const boot = await fetchBootstrap("", secret); + signal?.throwIfAborted(); + if (owner.current !== client) throw new DOMException("Gateway client changed", "AbortError"); + const url = deriveWsUrl(boot.ws_path, boot.token, boot.ws_url); + const credentials = bootstrapCredentials(boot, fallbackSurface); + const host = createRuntimeHost(credentials.runtimeSurface, boot.runtime_capabilities); + if (host.socketFactory) client.updateUrl(url, host.socketFactory); + else client.updateUrl(url); + client.updateMaxFrameBytes(boot.limits?.transport.max_frame_bytes); + setState((current) => current.status === "ready" && current.client === client ? { + ...current, + ...credentials, + modelName: boot.model_name ?? current.modelName, + ingressLimits: boot.limits ?? current.ingressLimits, + } : current); + return { token: credentials.token, url }; + }, []); + + const secretRef = useRef(""); + const bootstrapWithSecret = useCallback((secret: string, onAuthRejected?: () => void) => { + const generation = ++attempt.current; + prefetchChat(); + if (!onAuthRejected) setState({ status: "loading" }); + void (async () => { + try { + const boot = await fetchBootstrap("", secret); + if (generation !== attempt.current) return; + if (secret) saveSecret(secret); + const url = deriveWsUrl(boot.ws_path, boot.token, boot.ws_url); + activateReloadCache(url); + const credentials = bootstrapCredentials(boot, "browser"); + const host = createRuntimeHost(credentials.runtimeSurface, boot.runtime_capabilities); + const client: NanobotClient = new NanobotClient({ + url, + maxFrameBytes: boot.limits?.transport.max_frame_bytes, + socketFactory: host.socketFactory, + onReauth: async (signal) => { + try { + return (await refreshClient(client, secret, credentials.runtimeSurface, signal)).url; + } catch { + return null; + } + }, + }); + secretRef.current = secret; + owner.current = client; + client.connect(); + setState({ status: "ready", client, ...credentials, + modelName: boot.model_name ?? null, ingressLimits: boot.limits ?? null }); + } catch (error) { + if (generation !== attempt.current) return; + if (isBootstrapAuthRequired(error)) { + clearGatewayCaches(); + if (onAuthRejected) onAuthRejected(); + else setState({ status: "auth" }); + } else { + setState({ status: "error", message: error instanceof Error ? error.message : String(error) }); + } + } + })(); + }, [prefetchChat, refreshClient]); + + useEffect(() => { + bootstrapWithSecret(consumeUrlBootstrapSecret() || loadSavedSecret()); + return () => { + ++attempt.current; + closeClient(); + }; + }, [bootstrapWithSecret, closeClient]); + + const client = state.status === "ready" ? state.client : null; + const expiresAt = state.status === "ready" ? state.tokenExpiresAt : null; + const runtimeSurface = state.status === "ready" ? state.runtimeSurface : "browser"; + useEffect(() => { + if (!client || expiresAt === null) return; + const controller = new AbortController(); + const timer = window.setTimeout(async () => { + try { + await refreshClient(client, secretRef.current, runtimeSurface, controller.signal); + } catch (error) { + if (controller.signal.aborted || owner.current !== client || !isBootstrapAuthRequired(error)) return; + closeClient(); + clearGatewayCaches(); + setState({ status: "auth" }); + } + }, tokenRefreshDelayMs(expiresAt)); + return () => { + window.clearTimeout(timer); + controller.abort(); + }; + }, [client, closeClient, expiresAt, refreshClient, runtimeSurface]); + + const changeModelName = useCallback((modelName: string | null) => { + setState((current) => current.status === "ready" ? { ...current, modelName } : current); + }, []); + + const logout = useCallback(() => { + ++attempt.current; + closeClient(); + clearSavedSecret(); + clearGatewayCaches(); + setState({ status: "auth" }); + }, [closeClient]); + + const restartEngine = useCallback(async () => { + const host = createRuntimeHost(runtimeSurface); + if (!client || !host.restartEngine) throw new Error("native engine restart is unavailable"); + const secret = secretRef.current; + rememberRestartRoute(); + try { + window.localStorage.setItem(RESTART_STARTED_KEY, String(Date.now())); + } catch { + // ignore storage errors + } + try { + await host.restartEngine(); + return (await refreshClient(client, secret, runtimeSurface)).token; + } finally { + try { + window.localStorage.removeItem(RESTART_STARTED_KEY); + window.localStorage.removeItem(RESTART_ROUTE_KEY); + } catch { + // ignore storage errors + } + } + }, [client, refreshClient, runtimeSurface]); + + return { state, bootstrapWithSecret, changeModelName, logout, restartEngine }; +} diff --git a/webui/src/hooks/useNanobotStream.ts b/webui/src/hooks/useNanobotStream.ts index 418e5d4ac..ee9e5e360 100644 --- a/webui/src/hooks/useNanobotStream.ts +++ b/webui/src/hooks/useNanobotStream.ts @@ -1,6 +1,6 @@ import { acceptsCompactionPhase } from "../../../packages/client-events/notifications"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; -import { useThreadVisibility } from "@/hooks/useThreadVisibility"; +import { useStreamBatch } from "@/hooks/useStreamBatch"; import { useClient } from "@/providers/ClientProvider"; import { hasPendingAgentActivity } from "@/lib/activity-timeline"; @@ -47,9 +47,6 @@ type PendingStreamEvent = | { kind: "delta"; text: string; turn: UIMessageTurnFields; streamId?: string; source?: UIMessage["source"]; responseSources?: UIMessage["responseSources"]; responseInputIds?: string[] } | { kind: "reasoning"; text: string; turn: UIMessageTurnFields; streamId?: string }; -const BACKGROUND_STREAM_FLUSH_INTERVAL_MS = 1_000; -// Markdown and layout work must leave room for input between visible updates. -const VISIBLE_STREAM_FLUSH_INTERVAL_MS = 50; const EMPTY_INITIAL_MESSAGES: UIMessage[] = []; const EMPTY_COMPLETED_TURN_IDS: readonly string[] = []; @@ -173,9 +170,6 @@ export function useNanobotStream( const publishHistory = useCallback(() => setHistoryState(transcriptRef.current.paging), []); const [refreshSeq, setRefreshSeq] = useState(0); const refreshHistory = useCallback(() => setRefreshSeq((value) => value + 1), []); - const threadVisible = useThreadVisibility(); - const threadVisibleRef = useRef(threadVisible); - threadVisibleRef.current = threadVisible; const [runState, setRunState] = useState(() => chatId ? client.getRunState(chatId) : null); const isStreaming = runState?.active ?? false; const runStartedAt = runState?.startedAt ?? null; @@ -216,27 +210,8 @@ export function useNanobotStream( const [recoveryState, setRecoveryState] = useState(null); const [streamError, setStreamError] = useState(null); - const pendingStreamEventsRef = useRef([]); - const streamFrameRef = useRef(null); - const streamTimerRef = useRef(null); - const lastStreamFlushRef = useRef(0); - - const dismissStreamError = useCallback(() => setStreamError(null), []); - const clearPendingStreamWork = useCallback(() => { - if (streamFrameRef.current !== null) { - window.cancelAnimationFrame(streamFrameRef.current); - streamFrameRef.current = null; - } - if (streamTimerRef.current !== null) { - window.clearTimeout(streamTimerRef.current); - streamTimerRef.current = null; - } - pendingStreamEventsRef.current = []; - lastStreamFlushRef.current = 0; - }, []); - const isSideChannelEvent = useCallback((ev: InboundEvent) => { const turnId = eventTurnId(ev); return turnId !== undefined && transcriptRef.current.sideChannelTurnIds.has(turnId); @@ -252,73 +227,6 @@ export function useNanobotStream( return hadActiveAssistant; }, []); - const applyStreamError = useCallback((err: StreamError) => { - // One multiplexed client serves every thread. A correlated send fault - // belongs only to its target chat. An uncorrelated transport close can - // still be shown in the mounted thread, but cannot roll back any turn. - if (!chatId || (err.chatId && err.chatId !== chatId)) return; - setStreamError(err); - if (err.kind === "model_request_failed") return; - if (!err.turnId) return; - - const rejectedTurnId = err.turnId; - pendingStreamEventsRef.current = pendingStreamEventsRef.current.filter( - (event) => event.turn.turnId !== rejectedTurnId, - ); - transcriptRef.current.sideChannelTurnIds.delete(rejectedTurnId); - setMessages((prev) => { - const rejectedRows = prev.filter((message) => message.turnId === rejectedTurnId); - if (rejectedRows.length === 0) return prev; - const rejectedIds = new Set(rejectedRows.map((message) => message.id)); - const rejectedSegments = new Set( - rejectedRows - .map((message) => message.activitySegmentId) - .filter((segmentId): segmentId is string => typeof segmentId === "string"), - ); - const projection = transcriptRef.current.projection; - const closedAssistantIds = new Set(projection.closedAssistantIds); - for (const id of rejectedIds) closedAssistantIds.delete(id); - const nextMessages = prev.flatMap((message) => { - if (message.turnId !== rejectedTurnId) return [message]; - if (message.role !== "user") return []; - return [{ - ...message, - deliveryStatus: "failed" as const, - deliveryErrorKind: err.kind, - }]; - }); - transcriptRef.current.projection = { - ...projection, - messages: nextMessages, - activeAssistantId: projection.activeAssistantId - && rejectedIds.has(projection.activeAssistantId) - ? null - : projection.activeAssistantId, - closedAssistantIds, - activitySegmentId: projection.activitySegmentId - && rejectedSegments.has(projection.activitySegmentId) - ? null - : projection.activitySegmentId, - fileEditSegmentId: projection.fileEditSegmentId - && rejectedSegments.has(projection.fileEditSegmentId) - ? null - : projection.fileEditSegmentId, - }; - transcriptRef.current.rejectTurn(rejectedTurnId); - setExecSourceMessages(nextMessages); - return nextMessages; - }); - - if (!client.getRunState(chatId).active) { - transcriptRef.current.projection = { - ...transcriptRef.current.projection, - suppressUntilTurnEnd: false, - }; - } - }, [chatId, client, setMessages]); - - useEffect(() => client.onError(applyStreamError), [applyStreamError, client]); - const applyPendingStreamEvents = useCallback( (prev: UIMessage[], events: PendingStreamEvent[]): UIMessage[] => { transcriptRef.current.projection = { ...transcriptRef.current.projection, messages: prev }; @@ -389,19 +297,79 @@ export function useNanobotStream( [chatId], ); + const publishStreamBatch = useCallback((events: PendingStreamEvent[]) => { + setMessages((prev) => applyPendingStreamEvents(prev, events)); + }, [applyPendingStreamEvents, setMessages]); + const { enqueue: enqueueStreamEvent, drain: drainStreamEvents, discard: discardStreamEvents } = useStreamBatch(publishStreamBatch); + + const applyStreamError = useCallback((err: StreamError) => { + // One multiplexed client serves every thread. A correlated send fault + // belongs only to its target chat. An uncorrelated transport close can + // still be shown in the mounted thread, but cannot roll back any turn. + if (!chatId || (err.chatId && err.chatId !== chatId)) return; + setStreamError(err); + if (err.kind === "model_request_failed") return; + if (!err.turnId) return; + + const rejectedTurnId = err.turnId; + discardStreamEvents((event) => event.turn.turnId === rejectedTurnId); + transcriptRef.current.sideChannelTurnIds.delete(rejectedTurnId); + setMessages((prev) => { + const rejectedRows = prev.filter((message) => message.turnId === rejectedTurnId); + if (rejectedRows.length === 0) return prev; + const rejectedIds = new Set(rejectedRows.map((message) => message.id)); + const rejectedSegments = new Set( + rejectedRows + .map((message) => message.activitySegmentId) + .filter((segmentId): segmentId is string => typeof segmentId === "string"), + ); + const projection = transcriptRef.current.projection; + const closedAssistantIds = new Set(projection.closedAssistantIds); + for (const id of rejectedIds) closedAssistantIds.delete(id); + const nextMessages = prev.flatMap((message) => { + if (message.turnId !== rejectedTurnId) return [message]; + if (message.role !== "user") return []; + return [{ + ...message, + deliveryStatus: "failed" as const, + deliveryErrorKind: err.kind, + }]; + }); + transcriptRef.current.projection = { + ...projection, + messages: nextMessages, + activeAssistantId: projection.activeAssistantId + && rejectedIds.has(projection.activeAssistantId) + ? null + : projection.activeAssistantId, + closedAssistantIds, + activitySegmentId: projection.activitySegmentId + && rejectedSegments.has(projection.activitySegmentId) + ? null + : projection.activitySegmentId, + fileEditSegmentId: projection.fileEditSegmentId + && rejectedSegments.has(projection.fileEditSegmentId) + ? null + : projection.fileEditSegmentId, + }; + transcriptRef.current.rejectTurn(rejectedTurnId); + setExecSourceMessages(nextMessages); + return nextMessages; + }); + + if (!client.getRunState(chatId).active) { + transcriptRef.current.projection = { + ...transcriptRef.current.projection, + suppressUntilTurnEnd: false, + }; + } + }, [chatId, client, discardStreamEvents, setMessages]); + + useEffect(() => client.onError(applyStreamError), [applyStreamError, client]); + const flushPendingStreamEvents = useCallback((end?: Extract) => { - lastStreamFlushRef.current = 0; - if (streamFrameRef.current !== null) { - window.cancelAnimationFrame(streamFrameRef.current); - streamFrameRef.current = null; - } - if (streamTimerRef.current !== null) { - window.clearTimeout(streamTimerRef.current); - streamTimerRef.current = null; - } - const events = pendingStreamEventsRef.current; + const events = drainStreamEvents(); if (events.length === 0 && !end) return; - pendingStreamEventsRef.current = []; setMessages((prev) => { const nextMessages = events.length > 0 ? applyPendingStreamEvents(prev, events) : prev; transcriptRef.current.projection = { ...transcriptRef.current.projection, messages: nextMessages }; @@ -410,67 +378,7 @@ export function useNanobotStream( }); return transcriptRef.current.messages; }); - }, [applyPendingStreamEvents, setMessages]); - - const schedulePendingStreamFlush = useCallback(function schedule() { - if (streamFrameRef.current !== null || streamTimerRef.current !== null) return; - if (document.visibilityState === "hidden" || !threadVisibleRef.current) { - streamTimerRef.current = window.setTimeout(() => { - streamTimerRef.current = null; - const events = pendingStreamEventsRef.current; - if (events.length === 0) return; - pendingStreamEventsRef.current = []; - setMessages((prev) => applyPendingStreamEvents(prev, events)); - }, BACKGROUND_STREAM_FLUSH_INTERVAL_MS); - return; - } - const delay = VISIBLE_STREAM_FLUSH_INTERVAL_MS - - (performance.now() - lastStreamFlushRef.current); - if (delay > 0) { - streamTimerRef.current = window.setTimeout(() => { - streamTimerRef.current = null; - schedule(); - }, delay); - return; - } - streamFrameRef.current = window.requestAnimationFrame(() => { - streamFrameRef.current = null; - const events = pendingStreamEventsRef.current; - if (events.length === 0) return; - pendingStreamEventsRef.current = []; - lastStreamFlushRef.current = performance.now(); - setMessages((prev) => applyPendingStreamEvents(prev, events)); - }); - }, [applyPendingStreamEvents, setMessages]); - - useEffect(() => { - if (threadVisible) { - flushPendingStreamEvents(); - } else if (streamFrameRef.current !== null || streamTimerRef.current !== null) { - if (streamFrameRef.current !== null) window.cancelAnimationFrame(streamFrameRef.current); - streamFrameRef.current = null; - if (streamTimerRef.current !== null) window.clearTimeout(streamTimerRef.current); - streamTimerRef.current = null; - schedulePendingStreamFlush(); - } - }, [threadVisible, flushPendingStreamEvents, schedulePendingStreamFlush]); - - useEffect(() => { - const onVisibilityChange = () => { - if (pendingStreamEventsRef.current.length === 0) return; - if (document.visibilityState === "visible" && threadVisibleRef.current) { - flushPendingStreamEvents(); - } else { - if (streamFrameRef.current !== null) window.cancelAnimationFrame(streamFrameRef.current); - streamFrameRef.current = null; - if (streamTimerRef.current !== null) window.clearTimeout(streamTimerRef.current); - streamTimerRef.current = null; - schedulePendingStreamFlush(); - } - }; - document.addEventListener("visibilitychange", onVisibilityChange); - return () => document.removeEventListener("visibilitychange", onVisibilityChange); - }, [flushPendingStreamEvents, schedulePendingStreamFlush]); + }, [applyPendingStreamEvents, drainStreamEvents, setMessages]); useEffect(() => { if (!chatId) return; @@ -505,8 +413,8 @@ export function useNanobotStream( setRetryStatus(null); setGoalState(chatId ? client.getGoalState(chatId) : undefined); setRecoveryState(null); - clearPendingStreamWork(); - }, [chatId, client, historyKey, temporary, clearActivitySegment, clearPendingStreamWork, setMessages]); + drainStreamEvents(); + }, [chatId, client, historyKey, temporary, clearActivitySegment, drainStreamEvents, setMessages]); useEffect(() => { if (!chatId || (!hasPendingToolCalls && !initialStreaming)) return; @@ -784,7 +692,7 @@ export function useNanobotStream( if (transcriptRef.current.projection.suppressUntilTurnEnd || transcriptRef.current.represented(ev)) return; const chunk = typeof ev.text === "string" ? ev.text : ""; if (!chunk) return; - pendingStreamEventsRef.current.push({ + enqueueStreamEvent({ kind: "delta", text: chunk, turn: turnFieldsFromEvent(ev, "answer"), @@ -793,7 +701,6 @@ export function useNanobotStream( responseSources: ev.response_sources, responseInputIds: ev.response_input_ids, }); - schedulePendingStreamFlush(); return; } @@ -801,13 +708,12 @@ export function useNanobotStream( if (transcriptRef.current.projection.suppressUntilTurnEnd || transcriptRef.current.represented(ev)) return; const chunk = ev.text; if (!chunk) return; - pendingStreamEventsRef.current.push({ + enqueueStreamEvent({ kind: "reasoning", text: chunk, turn: turnFieldsFromEvent(ev, "reasoning"), streamId: ev.stream_id, }); - schedulePendingStreamFlush(); return; } @@ -935,7 +841,7 @@ export function useNanobotStream( || ev.status === "failed" ) { setRetryStatus(null); - clearPendingStreamWork(); + drainStreamEvents(); closeActiveAssistantStream(); clearActivitySegment(); } @@ -954,7 +860,7 @@ export function useNanobotStream( ev.recovery_state?.status === "awaiting_user" || ev.recovery_state?.status === "failed" ) { - clearPendingStreamWork(); + drainStreamEvents(); closeActiveAssistantStream(); clearActivitySegment(); } @@ -984,14 +890,13 @@ export function useNanobotStream( setLiveInputs(null); // Navigation may happen before the throttled paint. Snapshot the pending // deltas synchronously while they still belong to this subscription. - const pending = pendingStreamEventsRef.current; + const pending = drainStreamEvents(); const snapshot = pending.length > 0 ? applyPendingStreamEvents(messagesRef.current, pending) : messagesRef.current; onStreamDetach?.(snapshot); if (pending.length > 0) setMessages(snapshot); messageCache?.set(chatId, transcriptRef.current.save()); - clearPendingStreamWork(); }; }, [ applyProjectionEvent, @@ -1001,13 +906,13 @@ export function useNanobotStream( closeActiveAssistantStream, client, clearActivitySegment, - clearPendingStreamWork, + drainStreamEvents, flushPendingStreamEvents, isSideChannelEvent, onTurnEnd, onStreamDetach, messageCache, - schedulePendingStreamFlush, + enqueueStreamEvent, setMessages, ]); diff --git a/webui/src/hooks/useSidebarGroupMotion.ts b/webui/src/hooks/useSidebarGroupMotion.ts new file mode 100644 index 000000000..1790c10dd --- /dev/null +++ b/webui/src/hooks/useSidebarGroupMotion.ts @@ -0,0 +1,70 @@ +import { useCallback, useEffect, useLayoutEffect, useRef } from "react"; + +/** Animates already mounted rows when a project or pane group expands or collapses. */ +export function useSidebarGroupMotion( + collapsedGroups: Readonly>, + collapsedPaneGroups: ReadonlySet, +) { + const layoutRowRefs = useRef(new Map()); + const pendingLayoutRectsRef = useRef | null>(null); + const layoutAnimationsRef = useRef(new Map()); + const registerRow = useCallback((key: string, element: HTMLElement | null) => { + if (element) layoutRowRefs.current.set(key, element); + else layoutRowRefs.current.delete(key); + }, []); + + const cancelAnimations = useCallback(() => { + for (const animation of layoutAnimationsRef.current.values()) animation.cancel(); + layoutAnimationsRef.current.clear(); + }, []); + + const measureLayoutRows = useCallback(() => { + const rects = new Map(); + for (const [key, row] of layoutRowRefs.current) { + rects.set(key, row.getBoundingClientRect()); + } + return rects; + }, []); + + const captureLayout = useCallback(() => { + cancelAnimations(); + pendingLayoutRectsRef.current = measureLayoutRows(); + }, [cancelAnimations, measureLayoutRows]); + + useLayoutEffect(() => { + const previousRects = pendingLayoutRectsRef.current; + if (!previousRects) return; + pendingLayoutRectsRef.current = null; + const nextRects = measureLayoutRows(); + const reduceMotion = typeof window.matchMedia === "function" + && window.matchMedia("(prefers-reduced-motion: reduce)").matches; + if (reduceMotion) return; + for (const [key, nextRect] of nextRects) { + const previousRect = previousRects.get(key); + const row = layoutRowRefs.current.get(key); + if (!previousRect || !row || typeof row.animate !== "function") continue; + const deltaY = previousRect.top - nextRect.top; + if (Math.abs(deltaY) < 0.5) continue; + const animation = row.animate( + [ + { transform: `translateY(${deltaY}px)` }, + { transform: "translateY(0)" }, + ], + { + duration: 180, + easing: "cubic-bezier(0.2, 0, 0, 1)", + }, + ); + layoutAnimationsRef.current.set(key, animation); + animation.addEventListener("finish", () => { + if (layoutAnimationsRef.current.get(key) === animation) { + layoutAnimationsRef.current.delete(key); + } + }, { once: true }); + } + }, [collapsedGroups, collapsedPaneGroups, measureLayoutRows]); + + useEffect(() => cancelAnimations, [cancelAnimations]); + + return { captureLayout, registerRow }; +} diff --git a/webui/src/hooks/useStreamBatch.ts b/webui/src/hooks/useStreamBatch.ts new file mode 100644 index 000000000..e9e5b56b2 --- /dev/null +++ b/webui/src/hooks/useStreamBatch.ts @@ -0,0 +1,101 @@ +import { useCallback, useEffect, useRef } from "react"; +import { useThreadVisibility } from "@/hooks/useThreadVisibility"; + +const BACKGROUND_FLUSH_INTERVAL_MS = 1_000; +// Markdown and layout work must leave room for input between visible updates. +const VISIBLE_FLUSH_INTERVAL_MS = 50; + +/** Schedules batch publication; the transcript owner drains synchronously at semantic boundaries. */ +export function useStreamBatch(onFlush: (events: Event[]) => void) { + const visible = useThreadVisibility(); + const visibleRef = useRef(visible); + visibleRef.current = visible; + const pending = useRef([]); + const frame = useRef(null); + const timer = useRef(null); + const lastFlush = useRef(0); + + const take = useCallback(() => { + const events = pending.current; + pending.current = []; + return events; + }, []); + + const cancelScheduled = useCallback(() => { + if (frame.current !== null) window.cancelAnimationFrame(frame.current); + if (timer.current !== null) window.clearTimeout(timer.current); + frame.current = null; + timer.current = null; + }, []); + + const drain = useCallback(() => { + cancelScheduled(); + lastFlush.current = 0; + return take(); + }, [cancelScheduled, take]); + + const discard = useCallback((matches: (event: Event) => boolean) => { + pending.current = pending.current.filter((event) => !matches(event)); + }, []); + + const schedule = useCallback(function schedule() { + if (frame.current !== null || timer.current !== null) return; + if (document.visibilityState === "hidden" || !visibleRef.current) { + timer.current = window.setTimeout(() => { + timer.current = null; + const events = take(); + if (events.length > 0) onFlush(events); + }, BACKGROUND_FLUSH_INTERVAL_MS); + return; + } + const delay = VISIBLE_FLUSH_INTERVAL_MS - (performance.now() - lastFlush.current); + if (delay > 0) { + timer.current = window.setTimeout(() => { + timer.current = null; + schedule(); + }, delay); + return; + } + frame.current = window.requestAnimationFrame(() => { + frame.current = null; + const events = take(); + if (events.length === 0) return; + lastFlush.current = performance.now(); + onFlush(events); + }); + }, [onFlush, take]); + + const enqueue = useCallback((event: Event) => { + pending.current.push(event); + schedule(); + }, [schedule]); + + const flush = useCallback(() => { + const events = drain(); + if (events.length > 0) onFlush(events); + }, [drain, onFlush]); + + useEffect(() => { + if (visible) flush(); + else if (frame.current !== null || timer.current !== null) { + cancelScheduled(); + schedule(); + } + }, [cancelScheduled, flush, schedule, visible]); + + useEffect(() => { + const onVisibilityChange = () => { + if (pending.current.length === 0) return; + if (document.visibilityState === "visible" && visibleRef.current) flush(); + else { + cancelScheduled(); + schedule(); + } + }; + document.addEventListener("visibilitychange", onVisibilityChange); + return () => document.removeEventListener("visibilitychange", onVisibilityChange); + }, [cancelScheduled, flush, schedule]); + + // The subscription drains on detach before saving its last snapshot. + return { enqueue, discard, drain }; +} diff --git a/webui/src/lib/dom-overlays.ts b/webui/src/lib/dom-overlays.ts new file mode 100644 index 000000000..f597bd34d --- /dev/null +++ b/webui/src/lib/dom-overlays.ts @@ -0,0 +1,43 @@ +import { useCallback, useRef, type ForwardedRef, type RefCallback } from "react"; + +type OverlayKind = "dialog" | "overlay"; +const surfaces = new Map(); + +// Track the content node's presence, not the owner's open prop: Radix can keep +// closed content mounted through its exit animation. +export function useOverlaySurfaceRef( + kind: OverlayKind, + forwardedRef?: ForwardedRef, +): RefCallback { + const current = useRef(null); + return useCallback((node) => { + if (current.current) surfaces.delete(current.current); + current.current = node; + if (node) surfaces.set(node, kind); + + if (typeof forwardedRef === "function") forwardedRef(node); + else if (forwardedRef) forwardedRef.current = node; + }, [kind, forwardedRef]); +} + +function hasDialogSurface(includeClosed: boolean): boolean { + for (const [node, kind] of surfaces) { + if (kind === "dialog" && node.isConnected && (includeClosed || node.dataset.state !== "closed")) return true; + } + return false; +} + +export function hasAnyDialogMounted(): boolean { + return hasDialogSurface(true); +} + +export function hasOpenDialogSurface(): boolean { + return hasDialogSurface(false); +} + +export function hasAnyOverlayMounted(): boolean { + for (const node of surfaces.keys()) { + if (node.isConnected) return true; + } + return false; +} diff --git a/webui/src/lib/nanobot-client.ts b/webui/src/lib/nanobot-client.ts index ace7c15e4..380ef6c38 100644 --- a/webui/src/lib/nanobot-client.ts +++ b/webui/src/lib/nanobot-client.ts @@ -33,29 +33,40 @@ function createDefaultSocket(url: string): WebSocket { return new WebSocket(url); } +const WS_DEBUG_CACHE_TTL_MS = 1_000; +let wsDebugCache: { checkedAt: number; enabled: boolean } | null = null; + /** Inbound WebSocket ``console.log`` / parse-failure ``console.warn``. * * - **Dev** (non-production bundle): **on by default** — messages appear at default log level. * - **Production**: off unless ``localStorage.setItem('nanobot_debug_ws','1')`` (or ``true``). * - **Silence anywhere**: ``localStorage.setItem('nanobot_debug_ws','0')`` (or ``false`` / ``off``). - * Values are read on every frame; no reload needed. + * Values are cached briefly so toggling takes effect without reload while avoiding + * synchronous ``localStorage`` reads on every streamed delta frame. */ function wsInboundDebugEnabled(): boolean { if (typeof globalThis === "undefined") return false; + if (import.meta.env.MODE === "test") return false; + const now = Date.now(); + if (wsDebugCache && now - wsDebugCache.checkedAt < WS_DEBUG_CACHE_TTL_MS) { + return wsDebugCache.enabled; + } + let enabled: boolean; try { - if (import.meta.env.MODE === "test") return false; const ls = (globalThis as unknown as { localStorage?: Storage }).localStorage; const raw = ls?.getItem("nanobot_debug_ws")?.trim().toLowerCase() ?? ""; if (raw === "0" || raw === "false" || raw === "off" || raw === "no") { - return false; + enabled = false; + } else if (raw === "1" || raw === "true" || raw === "on" || raw === "yes") { + enabled = true; + } else { + enabled = !import.meta.env.PROD; } - if (raw === "1" || raw === "true" || raw === "on" || raw === "yes") { - return true; - } - return !import.meta.env.PROD; } catch { - return !import.meta.env.PROD; + enabled = !import.meta.env.PROD; } + wsDebugCache = { checkedAt: now, enabled }; + return enabled; } function summarizeInboundWsPayload(ev: InboundEvent): unknown { @@ -247,6 +258,7 @@ export class NanobotClient { /** Inbound frames received while the transcript owner is absent, regardless of observers. */ private pendingInboundByChat = new Map(); private static readonly PENDING_INBOUND_MAX = 2000; + private static readonly PENDING_TEMP_INBOUND_MAX = 20_000; private knownChats = new Set(); /** Temporary chats are connection-owned and intentionally not reattached. */ private temporaryChatIds = new Set(); @@ -1171,11 +1183,13 @@ export class NanobotClient { this.pendingInboundByChat.set(chatId, pending); } pending.push(ev); - // Temporary chats have no canonical history to recover evicted events from. - if (!this.temporaryChatIds.has(chatId)) { - const over = pending.length - NanobotClient.PENDING_INBOUND_MAX; - if (over > 0) pending.splice(0, over); - } + // Temporary chats have no canonical history to recover evicted events from, + // but still keep a generous upper bound so an unmounted chat cannot OOM the tab. + const maxPending = this.temporaryChatIds.has(chatId) + ? NanobotClient.PENDING_TEMP_INBOUND_MAX + : NanobotClient.PENDING_INBOUND_MAX; + const over = pending.length - maxPending; + if (over > 0) pending.splice(0, over); } for (const handler of this.chatHandlers.get(chatId) ?? []) handler(ev); } diff --git a/webui/src/shell-route.ts b/webui/src/shell-route.ts new file mode 100644 index 000000000..1e727c20c --- /dev/null +++ b/webui/src/shell-route.ts @@ -0,0 +1,210 @@ +import { isAppsSection, type SettingsFocusTarget } from "@/components/settings/contracts"; +import type { SettingsSectionKey } from "@/components/settings/SettingsView"; + +export const RESTART_STARTED_KEY = "nanobot-webui.restartStartedAt"; +export const RESTART_ROUTE_KEY = "nanobot-webui.restartRoute"; +const RESTART_ROUTE_TTL_MS = 5 * 60 * 1000; + +export type ShellView = "chat" | "settings" | "apps" | "automations" | "remote"; +export type ShellRoute = { + view: ShellView; + activeKey: string | null; + settingsSection: SettingsSectionKey; + settingsFocus?: SettingsFocusTarget; + temporary?: boolean; +}; + +const SETTINGS_SECTION_KEYS: SettingsSectionKey[] = [ + "capabilities", + "overview", + "about", + "appearance", + "notifications", + "models", + "image", + "voice", + "browser", + "channels", + "apps", + "automations", + "memory", + "skills", + "runtime", + "advanced", +]; + +function isSettingsSectionKey(value: string | null): value is SettingsSectionKey { + return SETTINGS_SECTION_KEYS.includes(value as SettingsSectionKey); +} + +export function defaultShellRoute(): ShellRoute { + return { view: "chat", activeKey: null, settingsSection: "overview" }; +} + +export function shellViewForSettingsSection(section: SettingsSectionKey): ShellView { + if (isAppsSection(section)) return "apps"; + if (section === "automations") return "automations"; + return "settings"; +} + +export function changesSettingsSurface(current: ShellRoute, next: ShellRoute): boolean { + return current.view !== "chat" && current.view !== "remote" && + (current.view !== next.view || current.settingsSection !== next.settingsSection); +} + +function fallbackRestartHash(hash: string): boolean { + return !hash || hash === "/" || hash === "/new"; +} + +export function rememberRestartRoute(): void { + if (typeof window === "undefined") return; + try { + window.localStorage.setItem(RESTART_ROUTE_KEY, window.location.hash || "#/new"); + } catch { + // ignore storage errors + } +} + +function maybeRestoreRestartHash(hash: string): string { + if (typeof window === "undefined" || !fallbackRestartHash(hash)) return hash; + try { + const startedAt = Number(window.localStorage.getItem(RESTART_STARTED_KEY) ?? "0"); + const storedHash = window.localStorage.getItem(RESTART_ROUTE_KEY); + if (!startedAt || !storedHash || Date.now() - startedAt > RESTART_ROUTE_TTL_MS) { + window.localStorage.removeItem(RESTART_ROUTE_KEY); + return hash; + } + window.localStorage.removeItem(RESTART_ROUTE_KEY); + const nextHash = storedHash.startsWith("#") ? storedHash : `#${storedHash}`; + window.history.replaceState( + null, + "", + `${window.location.pathname}${window.location.search}${nextHash}`, + ); + return nextHash.slice(1); + } catch { + return hash; + } +} + +export function readShellRoute(): ShellRoute { + if (typeof window === "undefined") return defaultShellRoute(); + const currentHash = window.location.hash.startsWith("#") + ? window.location.hash.slice(1) + : window.location.hash; + const hash = maybeRestoreRestartHash(currentHash); + if (!hash || hash === "/" || hash === "/new") return defaultShellRoute(); + + const [path, query = ""] = hash.split("?", 2); + const params = new URLSearchParams(query); + const rawSettingsSection = params.get("section"); + const settingsSection = isSettingsSectionKey(rawSettingsSection) + ? rawSettingsSection + : "overview"; + const saved: unknown = window.history.state?.nanobotReturnChat; + const returnChat = saved && typeof saved === "object" && "hash" in saved + && saved.hash === window.location.hash ? saved : null; + const activeKey = params.get("chat")?.trim() + || (returnChat && "key" in returnChat && typeof returnChat.key === "string" + ? returnChat.key : null); + const temporary = Boolean(returnChat && "temporary" in returnChat && returnChat.temporary === true); + + if (path === "/settings") { + const focus = params.get("focus"); + return { + view: shellViewForSettingsSection(settingsSection), + activeKey, + temporary, + settingsSection, + settingsFocus: settingsSection === "advanced" && (focus === "sandbox" || focus === "sandbox-launcher") + ? focus + : settingsSection === "models" && focus?.startsWith("image-input:") + ? `image-input:${focus.slice("image-input:".length)}` + : undefined, + }; + } + if (path === "/apps") { + return { view: "apps", activeKey, temporary, settingsSection: isAppsSection(settingsSection) ? settingsSection : "apps" }; + } + if (path === "/automations") { + return { view: "automations", activeKey, temporary, settingsSection: "automations" }; + } + if (path === "/channels") { + return { view: "apps", activeKey, temporary, settingsSection: "channels" }; + } + if (path === "/remote") { + return { view: "remote", activeKey, temporary, settingsSection: "overview" }; + } + if (path === "/skills") { + return { view: "apps", activeKey, temporary, settingsSection: "skills" }; + } + if (path.startsWith("/temporary/")) { + const encoded = path.slice("/temporary/".length); + try { + const chatId = decodeURIComponent(encoded).trim(); + return chatId + ? { + view: "chat", + activeKey: `websocket:${chatId}`, + settingsSection: "overview", + temporary: true, + } + : defaultShellRoute(); + } catch { + return defaultShellRoute(); + } + } + if (path.startsWith("/chat/")) { + const encoded = path.slice("/chat/".length); + try { + const key = decodeURIComponent(encoded).trim(); + return key + ? { view: "chat", activeKey: key, settingsSection: "overview" } + : defaultShellRoute(); + } catch { + return defaultShellRoute(); + } + } + return defaultShellRoute(); +} + +export function shellRouteHash(route: ShellRoute): string { + if (route.view === "chat") { + if (route.temporary && route.activeKey?.startsWith("websocket:")) { + const chatId = route.activeKey.slice("websocket:".length); + return `#/temporary/${encodeURIComponent(chatId)}`; + } + return route.activeKey + ? `#/chat/${encodeURIComponent(route.activeKey)}` + : "#/new"; + } + const params = new URLSearchParams(); + if (route.view === "settings" && route.settingsSection !== "overview") { + params.set("section", route.settingsSection); + if (route.settingsFocus) params.set("focus", route.settingsFocus); + } + if (route.view === "apps" && route.settingsSection !== "apps") { + params.set("section", route.settingsSection); + } + const query = params.toString(); + return `#/${route.view}${query ? `?${query}` : ""}`; +} + +export function writeShellRoute(route: ShellRoute, replace = false): void { + if (typeof window === "undefined") return; + const nextHash = shellRouteHash(route); + const state = { + ...window.history.state, + nanobotReturnChat: route.view === "chat" ? null : { + hash: nextHash, + key: route.activeKey, + temporary: route.temporary === true, + }, + }; + const url = `${window.location.pathname}${window.location.search}${nextHash}`; + if (replace || window.location.hash === nextHash) { + window.history.replaceState(state, "", url); + } else { + window.history.pushState(state, "", url); + } +} diff --git a/webui/src/tests/app-layout.test.tsx b/webui/src/tests/app-layout.test.tsx index 10b90da84..0e24ed7a4 100644 --- a/webui/src/tests/app-layout.test.tsx +++ b/webui/src/tests/app-layout.test.tsx @@ -4812,6 +4812,28 @@ describe("App layout", () => { unmount(); }); + it("does not apply a timed credential refresh after signing out", async () => { + vi.mocked(fetchBootstrap).mockResolvedValueOnce({ + token: "old", api_token: "old-api", ws_path: "/", expires_in: 0.001, + }); + let complete!: (boot: Awaited>) => void; + vi.mocked(fetchBootstrap).mockImplementationOnce(() => new Promise((resolve) => { complete = resolve; })); + vi.mocked(deriveWsUrl).mockImplementation((_path, token) => `ws://test?token=${token}`); + + mockFetchRoutes({ "/api/settings": baseSettingsPayload() }); + window.history.replaceState(null, "", "/#/settings"); + await import("@/components/settings/SettingsView"); + render(); + const signOut = await screen.findByRole("button", { name: "Sign out" }, { timeout: 4_000 }); + await waitFor(() => expect(fetchBootstrap).toHaveBeenCalledTimes(2), { timeout: 8_000 }); + fireEvent.click(signOut); + await screen.findByLabelText("WebUI password"); + + await act(async () => complete({ token: "late", api_token: "late-api", ws_path: "/" })); + expect(updateUrlSpy).not.toHaveBeenCalled(); + expect(screen.getByLabelText("WebUI password")).toBeInTheDocument(); + }, 10_000); + it("refreshes the bootstrap token before REST settings auth expires", async () => { vi.useFakeTimers(); vi.mocked(fetchBootstrap) diff --git a/webui/src/tests/nanobot-client.test.ts b/webui/src/tests/nanobot-client.test.ts index 46e7e40db..8127c25fa 100644 --- a/webui/src/tests/nanobot-client.test.ts +++ b/webui/src/tests/nanobot-client.test.ts @@ -341,7 +341,7 @@ describe("NanobotClient", () => { expect(notice).toHaveBeenCalledWith({ event, temporary: false }); client.close(); }); - it("bounds regular replay tails but retains temporary events until discard", async () => { + it("retains a larger replay tail for temporary chats and clears it on discard", async () => { const client = new NanobotClient({ url: "ws://test", reconnect: false, socketFactory: (url) => new FakeSocket(url) as unknown as WebSocket, @@ -357,13 +357,20 @@ describe("NanobotClient", () => { socket.fakeMessage({ event: "delta", chat_id: chatId, text: String(index) }); } } + for (let index = 2_010; index < 20_010; index++) { + socket.fakeMessage({ event: "delta", chat_id: "temporary", text: String(index) }); + } const regular = vi.fn(); - const temporary = vi.fn(); + const temporary: string[] = []; client.onTranscript("regular", regular); - const unsubscribe = client.onTranscript("temporary", temporary); + const unsubscribe = client.onTranscript("temporary", (event) => { + if (event.event === "delta") temporary.push(event.text); + }); expect(regular).toHaveBeenCalledTimes(2_000); expect(regular.mock.calls[0][0].text).toBe("10"); - expect(temporary.mock.calls.filter(([event]) => event.event === "delta")).toHaveLength(2_010); + expect(temporary).toHaveLength(20_000); + expect(temporary[0]).toBe("10"); + expect(temporary.at(-1)).toBe("20009"); unsubscribe(); socket.fakeMessage({ event: "delta", chat_id: "temporary", text: "discard me" }); client.discardTemporaryChat("temporary"); diff --git a/webui/src/tests/prompt-navigator.test.tsx b/webui/src/tests/prompt-navigator.test.tsx index 2a3484d64..985345894 100644 --- a/webui/src/tests/prompt-navigator.test.tsx +++ b/webui/src/tests/prompt-navigator.test.tsx @@ -3,6 +3,7 @@ import userEvent from "@testing-library/user-event"; import { afterEach, beforeEach, expect, it, vi } from "vitest"; import { PromptNavigator } from "@/components/thread/PromptNavigator"; +import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"; import { mockBrowserFocus } from "./browser-focus"; let restoreBrowserFocus: () => void; @@ -80,6 +81,29 @@ it("keeps an unknown recovered time blank while the prompt remains navigable", a expect(onJumpToPrompt).toHaveBeenCalledWith("undated"); }); +it("defers Ctrl+F to an open popover but not to its exit animation", async () => { + render(<> + + + Model options + + + + ); + fireEvent.click(screen.getByRole("button", { name: "Model options" })); + const popover = screen.getByRole("dialog", { name: "Model options" }); + const option = screen.getByRole("button", { name: "Choose model" }); + fireEvent.keyDown(option, { key: "f", ctrlKey: true }); + expect(screen.queryByRole("textbox", { name: "Search messages" })).not.toBeInTheDocument(); + + fireEvent.keyDown(option, { key: "Escape" }); + expect(popover).toHaveAttribute("data-state", "closed"); + expect(popover).toBeInTheDocument(); + fireEvent.keyDown(screen.getByRole("button", { name: "Model options" }), { key: "f", ctrlKey: true }); + expect(screen.getByRole("textbox", { name: "Search messages" })).toBeInTheDocument(); +}); + it("returns shortcut-opened search to the interrupted editor", async () => { const user = userEvent.setup(); render(<> ({ path: `/workspace/${path}`, display_path: path, project_path: "/workspace", language: "text", content: `Preview of ${path}`, size: 20, truncated: false, @@ -105,12 +106,16 @@ describe("temporary chat navigation", () => { vi.mocked(fetchBootstrap).mockReset().mockResolvedValue({ token: "test", api_token: "test", ws_path: "/" }); groupedTopics = false; withFiles = false; + withPairing = false; localStorage.clear(); sessionStorage.clear(); window.history.replaceState(null, "", "/"); vi.stubGlobal("WebSocket", TestSocket); vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => { const path = String(input); + if (path === "/api/settings/pairing") { + return Response.json({ requests: withPairing ? [{ code: "ABCD-EFGH", channel: "telegram", sender_id: "1" }] : [] }); + } if (path === "/api/sessions") { return Response.json({ sessions: ["regular", ...(groupedTopics ? ["child"] : [])].map((id) => ({ key: `websocket:${id}`, @@ -345,16 +350,49 @@ describe("temporary chat navigation", () => { expect(screen.getAllByRole("tab")).toHaveLength(1); fireEvent.click(screen.getByRole("button", { name: "notes.txt" })); await screen.findByText("Preview of notes.txt"); - const dialog = document.createElement("div"); - dialog.setAttribute("role", "dialog"); - document.body.append(dialog); - fireEvent.keyDown(window, { key: "Escape" }); + withPairing = true; + act(() => TestSocket.current.receive({ event: "pairing_changed" })); + const dialog = await screen.findByRole("dialog", { name: "Pair account" }); + // This popup does not intercept Escape itself; the preview must still yield. + fireEvent.keyDown(within(dialog).getByRole("textbox", { name: "Pairing code" }), { key: "Escape" }); expect(screen.getByTestId("file-preview-panel")).toBeInTheDocument(); - dialog.remove(); - fireEvent.keyDown(window, { key: "Escape" }); + fireEvent.click(within(dialog).getByRole("button", { name: "Close" })); + await waitFor(() => expect(dialog).not.toBeInTheDocument()); + fireEvent.keyDown(screen.getByRole("button", { name: "notes.txt" }), { key: "Escape" }); await waitFor(() => expect(screen.queryByTestId("file-preview-panel")).not.toBeInTheDocument()); }); + it("commits a file preview drag and restores the page when closing mid-drag", async () => { + withFiles = true; + render(); + await screen.findByRole("button", { name: "Temporary chat" }); + act(() => TestSocket.current.open()); + await selectTopic("Regular topic"); + fireEvent.click(await screen.findByRole("button", { name: "notes.txt" })); + await screen.findByText("Preview of notes.txt"); + + const panel = screen.getByTestId("preview-pane"); + vi.spyOn(panel.parentElement!, "getBoundingClientRect") + .mockReturnValue(DOMRect.fromRect({ width: 1_200 })); + fireEvent(window, new Event("resize")); + const handle = screen.getByRole("button", { name: "Resize file preview" }); + const { cursor, userSelect } = document.body.style; + fireEvent.pointerDown(handle, { clientX: 700 }); + expect(document.body.style.cursor).toBe("col-resize"); + fireEvent.pointerMove(window, { clientX: 570 }); + fireEvent.pointerUp(window); + expect(panel.style.getPropertyValue("--file-preview-width")).toBe("630px"); + expect(document.body.style.cursor).toBe(cursor); + + fireEvent.pointerDown(handle, { clientX: 600 }); + fireEvent.click(screen.getByRole("button", { name: "Close notes.txt" })); + expect(document.body.style.cursor).toBe(cursor); + expect(document.body.style.userSelect).toBe(userSelect); + await waitFor(() => expect(panel).not.toBeInTheDocument()); + fireEvent.click(screen.getByRole("button", { name: "notes.txt" })); + expect(screen.getByTestId("preview-pane").style.getPropertyValue("--file-preview-width")).toBe("630px"); + }); + it("forgets preview paths on temporary close and disconnect", async () => { const update = vi.spyOn(FilePreviewStore.prototype, "open"); render(); diff --git a/webui/src/tests/thread-viewport.test.tsx b/webui/src/tests/thread-viewport.test.tsx index 6405597cd..395d6827e 100644 --- a/webui/src/tests/thread-viewport.test.tsx +++ b/webui/src/tests/thread-viewport.test.tsx @@ -1272,18 +1272,9 @@ describe("ThreadViewport", () => { }); expect(hitTest.mock).toHaveBeenCalled(); - const replacement = anchor.cloneNode(true) as HTMLElement; - anchor.replaceWith(replacement); + // Deferred content grows above the existing row wrapper. anchorDocumentTop += 180; scrollHeight += 180; - Object.defineProperty(replacement, "getBoundingClientRect", { - configurable: true, - value: () => DOMRect.fromRect({ - y: anchorDocumentTop - scroller.scrollTop, - width: 800, - height: 40, - }), - }); const content = screen.getByTestId("thread-message-region").firstElementChild; const observer = resizeObserver.observers.find((candidate) => content ? candidate.elements.includes(content) : false, @@ -1294,10 +1285,9 @@ describe("ThreadViewport", () => { }); expect(scroller.scrollTop).toBe(260); - expect(replacement.getBoundingClientRect().top).toBe(120); + expect(anchor.getBoundingClientRect().top).toBe(120); // ResizeObserver may arrive before the next native scroll event. - hitTarget = replacement; scroller.scrollTop = 240; anchorDocumentTop += 60; scrollHeight += 60;