refactor(webui): separate gateway mutations and UI state (#6727)

This commit is contained in:
chengyongru authored and GitHub committed 2026-11-19 22:22:51 +08:00
1 parent ce12bfdd0d
commit 5537bdabd3
70 files changed
+4058 -3650

No files matched your search

@@ -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.model_selection import SESSION_MODEL_PRESET_METADATA_KEY
from nanobot.session.session_handles import session_handle_for_name from nanobot.session.session_handles import session_handle_for_name
from nanobot.webui.gateway_services import GatewayServices, build_gateway_services 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 ( from nanobot.webui.http_utils import (
issue_route_secret_matches as _issue_route_secret_matches, issue_route_secret_matches as _issue_route_secret_matches,
) )
@@ -83,6 +77,7 @@ from nanobot.webui.metadata import (
WEBUI_SYSTEM_COMMAND_TURN_PREFIX, WEBUI_SYSTEM_COMMAND_TURN_PREFIX,
WEBUI_TURN_METADATA_KEY, WEBUI_TURN_METADATA_KEY,
) )
from nanobot.webui.mutation import MutationResult
from nanobot.webui.settings_api import settings_payload, update_provider_settings from nanobot.webui.settings_api import settings_payload, update_provider_settings
from .ws_test_client import http_get as _http_get 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() conn = AsyncMock()
channel._webui_connections.add(conn) channel._webui_connections.add(conn)
channel.gateway.http.dispatch_webui_mutation = AsyncMock( channel.gateway.http.dispatch_webui_mutation = AsyncMock(
return_value=_http_json_response({"saved": True}) return_value=MutationResult.success({"saved": True})
) )
await channel._dispatch_envelope( await channel._dispatch_envelope(
conn, conn,
"webui-client", "webui-client",
@@ -1301,12 +1295,12 @@ async def test_webui_mutations_preserve_request_and_response_order(bus: MagicMoc
_connection: object, _connection: object,
action: str, action: str,
_payload: dict[str, object], _payload: dict[str, object],
) -> Any: ) -> MutationResult:
dispatch_order.append(action) dispatch_order.append(action)
if action == "settings.provider.update": if action == "settings.provider.update":
first_started.set() first_started.set()
await release_first.wait() await release_first.wait()
return _http_json_response({"action": action}) return MutationResult.success({"action": action})
channel.gateway.http.dispatch_webui_mutation = dispatch channel.gateway.http.dispatch_webui_mutation = dispatch
await channel._dispatch_envelope( await channel._dispatch_envelope(
@@ -1360,12 +1354,12 @@ async def test_webui_request_survives_disconnect_and_preserves_reconnect_order(
release = asyncio.Event() release = asyncio.Event()
dispatch_order: list[str] = [] 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) dispatch_order.append(action)
if action == "automation.run": if action == "automation.run":
started.set() started.set()
await release.wait() await release.wait()
return _http_json_response({"action": action}) return MutationResult.success({"action": action})
channel.gateway.http.dispatch_webui_mutation = AsyncMock(side_effect=mutate) channel.gateway.http.dispatch_webui_mutation = AsyncMock(side_effect=mutate)
envelope = { envelope = {
@@ -1424,7 +1418,7 @@ async def test_webui_request_replays_completed_result_after_reconnect(bus: Magic
retry_conn = AsyncMock() retry_conn = AsyncMock()
channel._webui_connections.update({first_conn, retry_conn}) channel._webui_connections.update({first_conn, retry_conn})
channel.gateway.http.dispatch_webui_mutation = AsyncMock( channel.gateway.http.dispatch_webui_mutation = AsyncMock(
return_value=_http_json_response({"installed": True}) return_value=MutationResult.success({"installed": True})
) )
envelope = { envelope = {
"type": "webui_request", "type": "webui_request",
@@ -1456,7 +1450,7 @@ async def test_webui_request_rejects_request_id_reuse_with_different_payload(
retry_conn = AsyncMock() retry_conn = AsyncMock()
channel._webui_connections.update({first_conn, retry_conn}) channel._webui_connections.update({first_conn, retry_conn})
channel.gateway.http.dispatch_webui_mutation = AsyncMock( channel.gateway.http.dispatch_webui_mutation = AsyncMock(
return_value=_http_json_response({"ran": True}) return_value=MutationResult.success({"ran": True})
) )
await channel._dispatch_envelope( await channel._dispatch_envelope(
@@ -1546,9 +1540,6 @@ async def test_webui_request_returns_correlated_route_error(bus: MagicMock) -> N
channel = _ch(bus) channel = _ch(bus)
conn = AsyncMock() conn = AsyncMock()
channel._webui_connections.add(conn) channel._webui_connections.add(conn)
channel.gateway.http.dispatch_webui_mutation = AsyncMock(
return_value=_http_error(400, "invalid settings payload")
)
await channel._dispatch_envelope( await channel._dispatch_envelope(
conn, conn,
@@ -1556,7 +1547,7 @@ async def test_webui_request_returns_correlated_route_error(bus: MagicMock) -> N
{ {
"type": "webui_request", "type": "webui_request",
"request_id": "request-2", "request_id": "request-2",
"action": "settings.agent.update", "action": "session.delete",
"payload": {}, "payload": {},
}, },
) )
@@ -1566,7 +1557,7 @@ async def test_webui_request_returns_correlated_route_error(bus: MagicMock) -> N
"event": "webui_response", "event": "webui_response",
"request_id": "request-2", "request_id": "request-2",
"ok": False, "ok": False,
"error": {"status": 400, "message": "invalid settings payload"}, "error": {"status": 400, "message": "missing session key"},
} }
@@ -25,6 +25,8 @@ from nanobot.session.manager import Session, SessionManager
from nanobot.session.session_handles import SessionHandleResolver from nanobot.session.session_handles import SessionHandleResolver
from nanobot.triggers.local_store import LocalTriggerStore from nanobot.triggers.local_store import LocalTriggerStore
from nanobot.webui.gateway_services import GatewayServices, build_gateway_services 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 InProcessHttpChannel
from .ws_test_client import http_get as _http_get from .ws_test_client import http_get as _http_get
@@ -724,10 +726,10 @@ async def test_webui_skill_management_routes(
headers=headers, headers=headers,
) )
assert update_response.status_code == 200 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( custom = next(
item item
for item in update_response.json()["skills"] for item in update_response.result["skills"]
if item["name"] == "custom-skill" if item["name"] == "custom-skill"
) )
assert custom["enabled"] is False assert custom["enabled"] is False
@@ -739,10 +741,10 @@ async def test_webui_skill_management_routes(
headers=headers, headers=headers,
) )
assert delete_response.status_code == 200 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( assert all(
item["name"] != "custom-skill" item["name"] != "custom-skill"
for item in delete_response.json()["skills"] for item in delete_response.result["skills"]
) )
finally: finally:
await channel.stop() await channel.stop()
@@ -863,7 +865,7 @@ async def test_webui_skills_marketplace_routes_search_and_install(
headers=headers, headers=headers,
) )
assert install_response.status_code == 200 assert install_response.status_code == 200
body = install_response.json() body = install_response.result
assert body["last_action"] == { assert body["last_action"] == {
"installed": True, "installed": True,
"already_installed": False, "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", "source": "vercel-labs/agent-browser", "skill": "agent-browser",
}, headers=headers) }, headers=headers)
assert same.status_code == 200 assert same.status_code == 200
assert same.json()["last_action"]["already_installed"] is True assert same.result["last_action"]["already_installed"] is True
assert any(skill["name"] == "agent-browser" for skill in same.json()["skills"]) assert any(skill["name"] == "agent-browser" for skill in same.result["skills"])
assert (directory / "SKILL.md").read_text(encoding="utf-8") == content assert (directory / "SKILL.md").read_text(encoding="utf-8") == content
finally: finally:
await channel.stop() await channel.stop()
@@ -975,7 +977,7 @@ async def test_webui_skill_install_rejects_overlapping_requests(
) )
assert overlapping.status_code == 409 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 assert install_mock.await_count == 1
finish.set() finish.set()
@@ -1009,7 +1011,7 @@ async def test_webui_skill_delete_remains_local_only(
) )
assert response.status_code == 403 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() 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.status_code == 200
assert response.json()["last_action"]["name"] == "react-testing" assert response.result["last_action"]["name"] == "react-testing"
@pytest.mark.asyncio @pytest.mark.asyncio
@@ -1099,11 +1101,11 @@ async def test_cli_apps_routes_require_token_and_return_payload(
) )
monkeypatch.setattr( monkeypatch.setattr(
"nanobot.webui.settings_routes.cli_apps_action", "nanobot.webui.settings_routes.cli_apps_action",
lambda action, query, *, config_path=None: { lambda action, params, *, config_path=None: {
"apps": [], "apps": [],
"installed_count": 1, "installed_count": 1,
"catalog_updated_at": "2026-04-18", "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) 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"}, {"name": "gimp"},
) )
assert installed.status_code == 200 assert installed.status_code == 200
assert installed.json()["last_action"]["message"] == "install:gimp" assert installed.result["last_action"]["message"] == "install:gimp"
finally: finally:
await channel.stop() await channel.stop()
await server_task await server_task
@@ -1167,7 +1169,7 @@ async def test_nanobot_feature_routes_require_token_and_enable(
{"name": "matrix"}, {"name": "matrix"},
) )
assert enabled.status_code == 200 assert enabled.status_code == 200
body = enabled.json() body = enabled.result
assert body["last_action"]["message"] == "Enabled channel 'matrix'" assert body["last_action"]["message"] == "Enabled channel 'matrix'"
assert body["restart_required_sections"] == ["runtime"] assert body["restart_required_sections"] == ["runtime"]
@@ -1177,7 +1179,7 @@ async def test_nanobot_feature_routes_require_token_and_enable(
{"name": "websocket"}, {"name": "websocket"},
) )
assert disabled_websocket.status_code == 400 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"] assert "websocket" not in json.loads(config_path.read_text(encoding="utf-8"))["channels"]
disabled = await _webui_mutate( disabled = await _webui_mutate(
@@ -1186,7 +1188,7 @@ async def test_nanobot_feature_routes_require_token_and_enable(
{"name": "matrix"}, {"name": "matrix"},
) )
assert disabled.status_code == 200 assert disabled.status_code == 200
body = disabled.json() body = disabled.result
assert body["last_action"]["message"] == "Disabled channel 'matrix'" assert body["last_action"]["message"] == "Disabled channel 'matrix'"
assert body["restart_required_sections"] == ["runtime"] assert body["restart_required_sections"] == ["runtime"]
assert json.loads(config_path.read_text(encoding="utf-8"))["channels"]["matrix"][ 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"}, {"code": "ABCD-EFGH"},
) )
assert approved_response.status_code == 200 assert approved_response.status_code == 200
body = approved_response.json() body = approved_response.result
assert body["last_action"]["action"] == "approve" assert body["last_action"]["action"] == "approve"
assert body["last_action"]["sender_id"] == "ou_123" assert body["last_action"]["sender_id"] == "ou_123"
assert approved == ["ABCD-EFGH"] assert approved == ["ABCD-EFGH"]
@@ -1322,7 +1324,7 @@ async def test_pairing_routes_require_token_and_approve_or_deny(
{"code": "ABCD-EFGH"}, {"code": "ABCD-EFGH"},
) )
assert denied_action.status_code == 200 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"] assert denied == ["ABCD-EFGH"]
missing_code = await _webui_mutate( missing_code = await _webui_mutate(
@@ -1330,7 +1332,7 @@ async def test_pairing_routes_require_token_and_approve_or_deny(
"settings.pairing.approve", "settings.pairing.approve",
) )
assert missing_code.status_code == 400 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 @pytest.mark.asyncio
@@ -1379,7 +1381,7 @@ async def test_nanobot_feature_remote_install_requires_opt_in(
) )
assert blocked.status_code == 403 assert blocked.status_code == 403
assert "remote WebUI is disabled" in blocked.text assert "remote WebUI is disabled" in blocked.message
assert install_calls == [] assert install_calls == []
config_path.write_text( config_path.write_text(
@@ -1463,7 +1465,7 @@ async def test_nanobot_feature_channel_action_can_apply_without_restart(
) )
assert response.status_code == 200 assert response.status_code == 200
body = response.json() body = response.result
assert calls == [("enable", "matrix", None)] assert calls == [("enable", "matrix", None)]
assert body["requires_restart"] is False assert body["requires_restart"] is False
assert body["restart_required_sections"] == [] assert body["restart_required_sections"] == []
@@ -1502,13 +1504,13 @@ async def test_nanobot_feature_install_only_tracks_pending_restart_without_start
def feature_action( def feature_action(
action: str, action: str,
query: dict[str, list[str]], params: MutationParams,
*, *,
allow_install: bool, allow_install: bool,
config_path: Path, config_path: Path,
) -> dict[str, Any]: ) -> dict[str, Any]:
assert action == "enable" assert action == "enable"
assert query == {"name": ["whatsapp"], "install_only": ["true"]} assert params.values == {"name": "whatsapp", "install_only": True}
assert allow_install is True assert allow_install is True
return {**features_payload(), "requires_restart": installed_now} 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 response.status_code == 200
assert runtime_calls == [] assert runtime_calls == []
features = response.json()["features"] features = response.result["features"]
assert features[0]["enabled"] is False assert features[0]["enabled"] is False
assert [feature["restart_pending"] for feature in features] == [installed_now, 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 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 @pytest.mark.asyncio
@@ -1616,7 +1618,7 @@ async def test_whatsapp_connect_reports_libmagic_failure(
) )
assert response.status_code == 400 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 @pytest.mark.asyncio
@@ -1705,7 +1707,7 @@ async def test_feishu_connect_routes_write_config_and_hot_reload(
) )
assert started.status_code == 200 assert started.status_code == 200
start_body = started.json() start_body = started.result
assert start_body["status"] == "pending" assert start_body["status"] == "pending"
assert start_body["instance_id"] == "default" assert start_body["instance_id"] == "default"
assert start_body["qr_url"].startswith("https://accounts.feishu.cn/") 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 assert polled.status_code == 200
body = polled.json() body = polled.result
assert body["status"] == "succeeded" assert body["status"] == "succeeded"
assert body["instance_id"] == "default" assert body["instance_id"] == "default"
assert "app_secret" not in body 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 assert response.status_code == 200
body = response.json() body = response.result
assert body["saved"] is True assert body["saved"] is True
assert body["name"] == "discord" 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 calls == [("enable", "discord", "default")]
assert body["nanobot_features"]["requires_restart"] is False assert body["nanobot_features"]["requires_restart"] is False
data = json.loads(config_path.read_text(encoding="utf-8")) 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 assert response.status_code == 200
body = response.json() body = response.result
assert body["saved_keys"] == ["channels.discord.allowChannels"] assert body["saved_keys"] == ["channels.discord.allowChannels"]
discord = next( discord = next(
feature feature
@@ -2307,37 +2309,37 @@ async def test_mcp_presets_routes_require_token_and_return_payload(
"installed_count": 0, "installed_count": 0,
}, },
) )
preset_queries: list[tuple[str, dict[str, list[str]]]] = [] preset_calls: list[tuple[str, dict[str, Any]]] = []
custom_queries: list[tuple[str, dict[str, list[str]]]] = [] custom_calls: list[tuple[str, dict[str, Any]]] = []
def _mcp_preset_action( def _mcp_preset_action(
action: str, action: str,
query: dict[str, list[str]], params: MutationParams,
*, *,
config_path: Path | None = None, config_path: Path | None = None,
) -> dict[str, Any]: ) -> dict[str, Any]:
preset_queries.append((action, query)) preset_calls.append((action, params.values))
return { return {
"presets": [], "presets": [],
"installed_count": 1, "installed_count": 1,
"requires_restart": action != "test", "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( def _custom_action(
action: str, action: str,
query: dict[str, list[str]], params: MutationParams,
*, *,
config_path: Path | None = None, config_path: Path | None = None,
) -> dict[str, Any]: ) -> dict[str, Any]:
custom_queries.append((action, query)) custom_calls.append((action, params.values))
return { return {
"presets": [], "presets": [],
"installed_count": 1, "installed_count": 1,
"requires_restart": True, "requires_restart": True,
"last_action": { "last_action": {
"ok": True, "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"}, {"name": "browserbase", "browserbase_api_key": "bb_live_secret"},
) )
assert enabled.status_code == 200 assert enabled.status_code == 200
assert preset_queries[-1][1]["browserbase_api_key"] == ["bb_live_secret"] assert preset_calls[-1][1]["browserbase_api_key"] == "bb_live_secret"
body = enabled.json() body = enabled.result
assert "bb_live_secret" not in enabled.text assert "bb_live_secret" not in json.dumps(body)
assert body["last_action"]["message"] == "enable:browserbase MCP config reloaded." assert body["last_action"]["message"] == "enable:browserbase MCP config reloaded."
assert body["hot_reload"]["ok"] is True assert body["hot_reload"]["ok"] is True
assert body["restart_required_sections"] == [] assert body["restart_required_sections"] == []
@@ -2393,7 +2395,7 @@ async def test_mcp_presets_routes_require_token_and_return_payload(
{"name": "browserbase"}, {"name": "browserbase"},
) )
assert disabled.status_code == 200 assert disabled.status_code == 200
assert preset_queries[-1][0] == "disable" assert preset_calls[-1][0] == "disable"
custom = await _webui_mutate( custom = await _webui_mutate(
channel, channel,
@@ -2401,8 +2403,8 @@ async def test_mcp_presets_routes_require_token_and_return_payload(
{"name": "docs", "command": "npx"}, {"name": "docs", "command": "npx"},
) )
assert custom.status_code == 200 assert custom.status_code == 200
assert custom_queries[-1][1]["command"] == ["npx"] assert custom_calls[-1][1]["command"] == "npx"
assert custom.json()["last_action"]["message"] == "custom:docs MCP config reloaded." assert custom.result["last_action"]["message"] == "custom:docs MCP config reloaded."
imported = await _webui_mutate( imported = await _webui_mutate(
channel, channel,
@@ -2410,7 +2412,7 @@ async def test_mcp_presets_routes_require_token_and_return_payload(
{"config": "{}"}, {"config": "{}"},
) )
assert imported.status_code == 200 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( tools = await _webui_mutate(
channel, channel,
@@ -2418,7 +2420,8 @@ async def test_mcp_presets_routes_require_token_and_return_payload(
{"name": "docs", "enabled_tools": []}, {"name": "docs", "enabled_tools": []},
) )
assert tools.status_code == 200 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: finally:
await channel.stop() await channel.stop()
await server_task await server_task
@@ -2517,7 +2520,7 @@ async def test_webui_sidebar_state_routes_are_config_dir_scoped(
{"state": payload}, {"state": payload},
) )
assert updated.status_code == 200 assert updated.status_code == 200
body = updated.json() body = updated.result
assert body["pinned_keys"] == ["websocket:sidebar"] assert body["pinned_keys"] == ["websocket:sidebar"]
assert body["archived_keys"] == ["websocket:old"] assert body["archived_keys"] == ["websocket:old"]
assert await sm.state.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"}, {"key": "websocket:doomed"},
) )
assert resp.status_code == 200 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 sm.read_session_snapshot(session_key) is None
assert history.read(session_key) == [] assert history.read(session_key) == []
finally: finally:
@@ -2595,7 +2598,7 @@ async def test_session_delete_removes_display_without_model_messages(history,
) )
assert response.status_code == 200 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 sm.read_session_snapshot(key) is None
assert history.read(key) == [] assert history.read(key) == []
finally: finally:
@@ -2643,7 +2646,7 @@ async def test_session_delete_removes_unpersisted_new_chat(
response = await _webui_mutate(channel, "session.delete", {"key": key}) response = await _webui_mutate(channel, "session.delete", {"key": key})
assert response.status_code == 200 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() 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 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["name"] == "Updated report"
assert row["payload"]["message"] == "Include the latest figures" assert row["payload"]["message"] == "Include the latest figures"
assert row["state"]["next_run_at_ms"] == due_at 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 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]["name"] == "Daily quiz"
assert by_id[user_job.id]["payload"]["message"] == "Ask the daily quiz" assert by_id[user_job.id]["payload"]["message"] == "Ask the daily quiz"
assert by_id[user_job.id]["schedule"]["kind"] == "cron" 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}, {"id": user_job.id},
) )
assert disabled.status_code == 200 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 assert by_id[user_job.id]["enabled"] is False
disabled_run = await _webui_mutate( 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}, {"id": incomplete_job.id},
) )
assert unbound_run.status_code == 409 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( unbound_enable = await _webui_mutate(
channel, channel,
@@ -3020,7 +3023,7 @@ async def test_webui_automations_route_lists_all_jobs_and_allows_user_actions(
{"id": incomplete_job.id}, {"id": incomplete_job.id},
) )
assert unbound_enable.status_code == 409 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( protected_delete = await _webui_mutate(
channel, channel,
@@ -3047,7 +3050,7 @@ async def test_webui_automations_route_lists_all_jobs_and_allows_user_actions(
{"id": user_job.id}, {"id": user_job.id},
) )
assert enabled.status_code == 200 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 assert by_id[user_job.id]["enabled"] is True
deleted = await _webui_mutate( 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}, {"id": user_job.id},
) )
assert deleted.status_code == 200 assert deleted.status_code == 200
assert user_job.id not 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.json()["jobs"]} assert "heartbeat" in {job["id"] for job in deleted.result["jobs"]}
finally: finally:
await channel.stop() await channel.stop()
await server_task await server_task
@@ -3116,7 +3119,7 @@ async def test_webui_automations_route_manages_local_triggers(
{"id": trigger.id}, {"id": trigger.id},
) )
assert run.status_code == 409 assert run.status_code == 409
assert "CLI message" in run.text assert "CLI message" in run.message
renamed = await _webui_mutate( renamed = await _webui_mutate(
channel, channel,
@@ -3174,7 +3177,7 @@ async def test_session_delete_blocks_when_bound_automation_exists(
) )
assert resp.status_code == 200 assert resp.status_code == 200
body = resp.json() body = resp.result
assert body["deleted"] is False assert body["deleted"] is False
assert body["blocked_by_automations"] is True assert body["blocked_by_automations"] is True
assert [job["name"] for job in body["automations"]] == ["Daily check"] 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"}, {"key": "websocket:doomed"},
) )
assert blocked.status_code == 200 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 assert trigger_store.get(trigger.id) is not None
deleted = await _webui_mutate( deleted = await _webui_mutate(
@@ -3222,7 +3225,7 @@ async def test_session_delete_blocks_and_cascades_local_triggers(
{"key": "websocket:doomed", "delete_automations": True}, {"key": "websocket:doomed", "delete_automations": True},
) )
assert deleted.status_code == 200 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 assert trigger_store.get(trigger.id) is None
finally: finally:
await channel.stop() await channel.stop()
@@ -3262,7 +3265,7 @@ async def test_session_delete_can_cascade_bound_automations(
) )
assert resp.status_code == 200 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 sm.read_session_snapshot(session_key) is None
assert cron.list_bound_cron_jobs_for_session("websocket:doomed") == [] assert cron.list_bound_cron_jobs_for_session("websocket:doomed") == []
assert cron.list_jobs(include_disabled=True) == [] 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 assert resp.status_code == 200
body = resp.json() body = resp.result
assert body["deleted"] is False assert body["deleted"] is False
assert body["blocked_by_automations"] is True assert body["blocked_by_automations"] is True
assert [job["name"] for job in body["automations"]] == ["Chat daily check"] 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"}, {"key": "websocket:encoded-key"},
) )
assert deleted.status_code == 200 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 assert sm.read_session_snapshot(session_key) is None
finally: finally:
await channel.stop() await channel.stop()
@@ -3830,26 +3833,19 @@ async def _webui_mutate(
*, *,
headers: dict[str, str] | None = None, headers: dict[str, str] | None = None,
connection: _FakeConn = _LOCAL, connection: _FakeConn = _LOCAL,
) -> httpx.Response: ) -> MutationResult:
request_headers = {"Host": "127.0.0.1:8765", **(headers or {})} request_headers = {"Host": "127.0.0.1:8765", **(headers or {})}
mutation_connection = _FakeConn(connection.remote_address) mutation_connection = _FakeConn(connection.remote_address)
mutation_connection.request = _FakeReq(request_headers) mutation_connection.request = _FakeReq(request_headers)
response = await channel.gateway.http.dispatch_webui_mutation( return await channel.gateway.http.dispatch_webui_mutation(
mutation_connection, mutation_connection,
action, action,
payload or {}, 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 @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={ recovery_action = AsyncMock(return_value={
"status": "resuming", "status": "resuming",
"recovery_id": "recovery-1", "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.status_code == 200
assert response.json()["status"] == "resuming" assert response.result["status"] == "resuming"
recovery_action.assert_awaited_once_with( recovery_action.assert_awaited_once_with(
"continue", "continue",
{"chat_id": "chat-1", "recovery_id": "recovery-1"}, {"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()) channel = _ch(bus, **_trusted_proxy_config())
for assertion in (None, "", " "): for assertion in (None, "", " "):
headers = {"Cf-Access-Jwt-Assertion": assertion} if assertion is not None else {} 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 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()) channel = _ch(bus, **_trusted_proxy_config())
resp = channel.gateway.http._handle_bootstrap( resp = await channel.gateway.http._handle_bootstrap(
_REMOTE, _REMOTE,
_FakeReq({"Cf-Access-Jwt-Assertion": "spoofed"}), _FakeReq({"Cf-Access-Jwt-Assertion": "spoofed"}),
) )
assert resp.status_code == 403 assert resp.status_code == 403
def test_trusted_proxy_bootstrap_has_no_tokens( async def test_trusted_proxy_bootstrap_has_no_tokens(
bus: MagicMock, bus: MagicMock,
) -> None: ) -> None:
assertion = "opaque-upstream-assertion" assertion = "opaque-upstream-assertion"
channel = _ch(bus, **_trusted_proxy_config()) channel = _ch(bus, **_trusted_proxy_config())
log = MagicMock() log = MagicMock()
channel.gateway.http._log = log channel.gateway.http._log = log
resp = channel.gateway.http._handle_bootstrap( resp = await channel.gateway.http._handle_bootstrap(
_LOCAL, _LOCAL,
_FakeReq( _FakeReq(
{ {
@@ -4024,9 +4020,9 @@ def test_trusted_proxy_authorizes_websocket_without_token(bus: MagicMock) -> Non
assert _LOCAL in channel._webui_connections 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) channel = _ch(bus)
resp = channel.gateway.http._handle_bootstrap( resp = await channel.gateway.http._handle_bootstrap(
_REMOTE, _REMOTE,
_FakeReq( _FakeReq(
{ {
@@ -4040,13 +4036,13 @@ def test_forwarding_headers_alone_never_authorize_bootstrap(bus: MagicMock) -> N
assert resp.status_code == 403 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( channel = _ch(
bus, bus,
tokenIssueSecret="route-secret", tokenIssueSecret="route-secret",
**_trusted_proxy_config(), **_trusted_proxy_config(),
) )
resp = channel.gateway.http._handle_bootstrap( resp = await channel.gateway.http._handle_bootstrap(
_LOCAL, _LOCAL,
_FakeReq({"Cf-Access-Jwt-Assertion": "present"}), _FakeReq({"Cf-Access-Jwt-Assertion": "present"}),
) )
@@ -4130,17 +4126,17 @@ def test_wildcard_ipv6_without_auth_raises(bus: MagicMock) -> None:
_ch(bus, host="::") _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") 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"}) _REMOTE, _FakeReq({"X-Nanobot-Auth": "s3cret"})
) )
assert resp.status_code == 200 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") 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"}) _REMOTE, _FakeReq({"Authorization": "Bearer static-tok"})
) )
assert resp.status_code == 200 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"] 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") 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, _LOCAL,
_FakeReq( _FakeReq(
{ {
@@ -4167,7 +4163,7 @@ def test_bootstrap_ws_url_uses_forwarded_https_host(bus: MagicMock) -> None:
assert body["ws_url"] == "wss://nanobot.example/" 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( channel = _ch(
bus, bus,
host="127.0.0.1", host="127.0.0.1",
@@ -4175,7 +4171,7 @@ def test_bootstrap_ws_url_uses_configured_public_url(bus: MagicMock) -> None:
tokenIssueSecret="s3cret", tokenIssueSecret="s3cret",
publicWsUrl="wss://claw.wasapi.xyz/", publicWsUrl="wss://claw.wasapi.xyz/",
) )
resp = channel.gateway.http._handle_bootstrap( resp = await channel.gateway.http._handle_bootstrap(
_LOCAL, _LOCAL,
_FakeReq( _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") 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 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") channel = _ch(bus, host="127.0.0.1")
resp = channel.gateway.http._handle_bootstrap( resp = await channel.gateway.http._handle_bootstrap(
_LOCAL, _LOCAL,
_FakeReq({"Host": "nanobot.example", "X-Forwarded-For": "203.0.113.42"}), _FakeReq({"Host": "nanobot.example", "X-Forwarded-For": "203.0.113.42"}),
) )
assert resp.status_code == 403 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") 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 assert resp.status_code == 200
body = json.loads(resp.body) body = json.loads(resp.body)
assert body["token"].startswith("nbwt_") 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") 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"}) _LOCAL, _FakeReq({"Authorization": "Bearer s3cret"})
) )
assert resp.status_code == 200 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( monkeypatch.setattr(
"nanobot.webui.ws_http._default_model_name_from_config", "nanobot.webui.ws_http._default_model_name_from_config",
lambda _config_path=None: "from-disk", lambda _config_path=None: "from-disk",
) )
channel = _ch(bus, host="127.0.0.1", runtime_model_name=lambda: " live/model ") 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 assert resp.status_code == 200
body = json.loads(resp.body) body = json.loads(resp.body)
assert body["model_name"] == "live/model" 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( monkeypatch.setattr(
"nanobot.webui.ws_http._default_model_name_from_config", "nanobot.webui.ws_http._default_model_name_from_config",
lambda _config_path=None: "from-disk", lambda _config_path=None: "from-disk",
) )
channel = _ch(bus, host="127.0.0.1", runtime_model_name=lambda: " ") 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 assert resp.status_code == 200
body = json.loads(resp.body) body = json.loads(resp.body)
assert body["model_name"] == "from-disk" 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( monkeypatch.setattr(
"nanobot.webui.ws_http._default_model_name_from_config", "nanobot.webui.ws_http._default_model_name_from_config",
lambda _config_path=None: "from-disk", 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") raise RuntimeError("resolver failed")
channel = _ch(bus, host="127.0.0.1", runtime_model_name=boom) 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 assert resp.status_code == 200
body = json.loads(resp.body) body = json.loads(resp.body)
assert body["model_name"] == "from-disk" 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") 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"}) _REMOTE, _FakeReq({"Authorization": "Bearer wrong"})
) )
assert resp.status_code == 401 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") 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"}) _REMOTE, _FakeReq({"Authorization": "Bearer s3cret"})
) )
assert resp.status_code == 200 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_") 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") 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"}) _REMOTE, _FakeReq({"X-Nanobot-Auth": "s3cret"})
) )
assert resp.status_code == 200 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") 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 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} assert raw.status_code in {401, 405}
first = await _webui_mutate(channel, "star_prompt.claim", {}) first = await _webui_mutate(channel, "star_prompt.claim", {})
assert first.status_code == 200 assert first.status_code == 200
assert first.json() == {"show": True} assert first.result == {"show": True}
second = await _webui_mutate(channel, "star_prompt.claim", {}) 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", {}) dismissed = await _webui_mutate(channel, "star_prompt.dismiss", {})
assert dismissed.status_code == 200 assert dismissed.status_code == 200
assert StarPromptState.model_validate_json(state_path.read_text()).dismissed_forever 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() scope = channel.gateway.workspaces.default_scope()
response = await _webui_mutate(channel, "workspace.resolve_project", {"path": str(project)}, connection=connection) response = await _webui_mutate(channel, "workspace.resolve_project", {"path": str(project)}, connection=connection)
assert response.status_code == 200 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 assert channel.gateway.workspaces.default_scope() == scope
payload = channel.gateway.workspaces.payload(can_change_project=True) payload = channel.gateway.workspaces.payload(can_change_project=True)
assert payload["recent_projects"] == [{"name": "project", "path": str(project)}] 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) channel = _ch(bus, workspace_path=tmp_path)
response = await _webui_mutate(channel, "workspace.favorite", {"path": str(project), "pinned": True}, connection=connection) response = await _webui_mutate(channel, "workspace.favorite", {"path": str(project), "pinned": True}, connection=connection)
assert response.status_code == 200 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) 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["recent_projects"] == []
assert payload["default_scope"]["project_path"] == str(tmp_path) assert payload["default_scope"]["project_path"] == str(tmp_path)
response = await _webui_mutate(channel, "workspace.favorite", {"path": str(project), "pinned": False}, connection=connection) response = await _webui_mutate(channel, "workspace.favorite", {"path": str(project), "pinned": False}, connection=connection)
assert response.status_code == 200 assert response.status_code == 200
assert response.json() == {"favorite_projects": []} assert response.result == {"favorite_projects": []}
@pytest.mark.asyncio @pytest.mark.asyncio
+462
View File
@@ -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
+2 -7
View File
@@ -9,8 +9,8 @@ from typing import Any, cast
from nanobot.apps.cli import CliAppError, CliAppManager, CliAppsRuntimeConfig from nanobot.apps.cli import CliAppError, CliAppManager, CliAppsRuntimeConfig
from nanobot.config.loader import load_config from nanobot.config.loader import load_config
from nanobot.webui.settings_contracts import QueryParams
QueryParams = dict[str, list[str]] 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_NAME_RE = re.compile(r"^[a-z0-9][a-z0-9_-]{0,63}$", re.IGNORECASE)
_CLI_APP_ATTACHMENT_KEYS = ( _CLI_APP_ATTACHMENT_KEYS = (
@@ -84,11 +84,6 @@ def normalize_cli_app_mentions(raw: Any) -> list[dict[str, str]]:
return out 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: def _manager(config_path: Path | None = None) -> CliAppManager:
config = load_config(config_path) if config_path is not None else load_config() config = load_config(config_path) if config_path is not None else load_config()
cli_cfg = config.tools.cli_apps cli_cfg = config.tools.cli_apps
+11 -4
View File
@@ -11,6 +11,7 @@ from nanobot.channels.websocket.attachment_http import AttachmentHTTP
from nanobot.channels.websocket.attachment_store import AttachmentStore from nanobot.channels.websocket.attachment_store import AttachmentStore
from nanobot.config.loader import get_config_path from nanobot.config.loader import get_config_path
from nanobot.config.paths import get_media_dir 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_endpoint import WebUIGatewayEndpoint
from nanobot.webui.gateway_tokens import GatewayTokenStore from nanobot.webui.gateway_tokens import GatewayTokenStore
from nanobot.webui.ingress_policy import DEFAULT_WEBUI_INGRESS_POLICY, WebUIIngressPolicy from nanobot.webui.ingress_policy import DEFAULT_WEBUI_INGRESS_POLICY, WebUIIngressPolicy
@@ -136,10 +137,16 @@ def build_gateway_services(
settings=settings, settings=settings,
skills_workspace_path=workspace_path, skills_workspace_path=workspace_path,
disabled_skills=disabled_skills, disabled_skills=disabled_skills,
cron_service=cron_service, automation_routes=WebUIAutomationRoutes(
local_trigger_store=local_trigger_store, session_manager=session_manager,
cron_pending_job_ids=cron_pending_job_ids, workspaces=workspaces,
local_trigger_pending_ids=local_trigger_pending_ids, 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_feature_action=channel_feature_action,
channel_runtime_status=channel_runtime_status, channel_runtime_status=channel_runtime_status,
mcp_runtime_status=mcp_runtime_status, mcp_runtime_status=mcp_runtime_status,
+8
View File
@@ -86,6 +86,14 @@ def host_for_url(host: str, port: int) -> str:
return f"{host}:{port}" 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: def accepts_gzip(value: str) -> bool:
wildcard_quality: float | None = None wildcard_quality: float | None = None
for item in value.split(","): for item in value.split(","):
+118 -99
View File
@@ -22,7 +22,7 @@ from nanobot.channels.websocket.attachment_policy import validate_attachment_bat
from nanobot.channels.websocket.attachment_store import AttachmentUploadError from nanobot.channels.websocket.attachment_store import AttachmentUploadError
from nanobot.command.application import builtin_command_starts_agent_turn from nanobot.command.application import builtin_command_starts_agent_turn
from nanobot.command.builtin import USER_SHELL_COMMAND 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_admission import RuntimeMaintenanceError
from nanobot.runtime_context import ( from nanobot.runtime_context import (
RUNTIME_CONTEXT_INPUT_META, RUNTIME_CONTEXT_INPUT_META,
@@ -167,7 +167,6 @@ class WebUICommandRouter:
self.request_operations: dict[str, WebUIRequestOperation] = {} self.request_operations: dict[str, WebUIRequestOperation] = {}
self.request_locks: dict[ServerConnection, asyncio.Lock] = {} self.request_locks: dict[ServerConnection, asyncio.Lock] = {}
self._background_lock = asyncio.Lock() self._background_lock = asyncio.Lock()
self._background_references: set[tuple[str, str]] = set()
self._accepted_messages: dict[tuple[str, str], float] = {} self._accepted_messages: dict[tuple[str, str], float] = {}
self._message_locks: dict[tuple[str, str], tuple[asyncio.Lock, int]] = {} self._message_locks: dict[tuple[str, str], tuple[asyncio.Lock, int]] = {}
@@ -560,6 +559,71 @@ class WebUICommandRouter:
else: else:
self._message_locks[key] = (lock, users - 1) 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( async def _dispatch_message_once(
self, self,
connection: ServerConnection, connection: ServerConnection,
@@ -634,37 +698,11 @@ class WebUICommandRouter:
raw_media = envelope.get("media", []) raw_media = envelope.get("media", [])
media_paths: list[str] = [] 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 "" upload_owner = self._uploads.owner(connection) if raw_media else ""
try: try:
if not isinstance(raw_media, list): references, local_paths, media_names, attachment_order = (
raise AttachmentUploadError("malformed") self._parse_inbound_attachments(raw_media)
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)
except AttachmentUploadError as exc: except AttachmentUploadError as exc:
await self._transport.webui_send_event( await self._transport.webui_send_event(
connection, "error", detail="attachment_rejected", reason=str(exc), connection, "error", detail="attachment_rejected", reason=str(exc),
@@ -700,6 +738,7 @@ class WebUICommandRouter:
if scope is None: if scope is None:
return return
# Re-check after awaiting scope resolution in case allowlist access was revoked mid-flight.
if not self._transport.is_allowed(client_id): if not self._transport.is_allowed(client_id):
await self._transport.webui_send_event( await self._transport.webui_send_event(
connection, connection,
@@ -734,31 +773,32 @@ class WebUICommandRouter:
) )
if is_user_shell: if is_user_shell:
metadata[INBOUND_META_USER_SHELL] = True metadata[INBOUND_META_USER_SHELL] = True
if "model_options" in envelope: try:
if not trusted_webui: options = self._model_options_for_message(
await self._transport.webui_send_event( envelope, content, trusted_webui=trusted_webui, is_user_shell=is_user_shell,
connection, "error", detail="model_options requires a trusted WebUI message", )
**rejection_fields, except ValueError as exc:
) await self._transport.webui_send_event(
return connection, "error", detail=str(exc), **rejection_fields,
if not is_user_shell and builtin_command_starts_agent_turn(content): )
try: return
options = ModelOptions.parse(envelope["model_options"]) if options is not None:
except ValueError as exc: metadata[INBOUND_META_MODEL_OPTIONS] = options
await self._transport.webui_send_event(
connection, "error", detail=str(exc), **rejection_fields,
)
return
metadata[INBOUND_META_MODEL_OPTIONS] = options.to_dict()
dispatch_content = ( dispatch_content = (
f"{USER_SHELL_COMMAND} {content[1:].lstrip()}" if is_user_shell else content f"{USER_SHELL_COMMAND} {content[1:].lstrip()}" if is_user_shell else content
) )
cli_apps = normalize_cli_app_mentions(envelope.get("cli_apps")) cli_apps = normalize_cli_app_mentions(envelope.get("cli_apps"))
if cli_apps: if cli_apps:
metadata["cli_apps"] = cli_apps metadata["cli_apps"] = cli_apps
mcp_presets = normalize_mcp_preset_mentions( raw_mcp_presets = envelope.get("mcp_presets")
envelope.get("mcp_presets"), mcp_presets = (
config_path=self.gateway.settings.config.path, 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: if mcp_presets:
metadata["mcp_presets"] = mcp_presets metadata["mcp_presets"] = mcp_presets
@@ -781,8 +821,6 @@ class WebUICommandRouter:
) )
for path in local_paths 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 [] uploaded = self._uploads.store.inspect(references, owner=upload_owner) if references else []
validate_attachment_batch( validate_attachment_batch(
[item["mime"] for item in local] + [item.mime for item in uploaded], [item["mime"] for item in local] + [item.mime for item in uploaded],
@@ -854,20 +892,9 @@ class WebUICommandRouter:
session_mentions=session_mentions or None, session_mentions=session_mentions or None,
) )
if trusted_webui: if trusted_webui:
context_blocks: list[RuntimeContextBlock] = [] context_blocks = self._message_context_blocks(
if not is_user_shell and envelope.get("intent") == "create_automation": envelope, session_mentions, is_user_shell=is_user_shell,
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")}
) )
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: if context_blocks:
metadata[RUNTIME_CONTEXT_INPUT_META] = context_blocks metadata[RUNTIME_CONTEXT_INPUT_META] = context_blocks
await self._transport.webui_dispatch_message( await self._transport.webui_dispatch_message(
@@ -1042,11 +1069,17 @@ class WebUICommandRouter:
if policy is None: if policy is None:
raise TemporaryChatError("temporary_chat_unavailable") raise TemporaryChatError("temporary_chat_unavailable")
if metadata_only: 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: 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: 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: except TemporaryChatError as exc:
await self.send_webui_response( await self.send_webui_response(
connection, request_id, status=404, message=exc.detail, connection, request_id, status=404, message=exc.detail,
@@ -1217,17 +1250,18 @@ class WebUICommandRouter:
owner = self._uploads.owner(connection) owner = self._uploads.owner(connection)
try: try:
entry = self._uploads.store.inspect([reference], owner=owner)[0] entry = self._uploads.store.inspect([reference], owner=owner)[0]
# Snapshot a bounded staged file before yielding so disconnect cleanup # Claim before yielding so disconnect cleanup cannot unlink the worker's source.
# never unlinks an open source handle on Windows. self._uploads.store.commit([reference], owner=owner)
with entry.path.open("rb") as source:
data = source.read(MAX_BYTES + 1) def persist_staged_background() -> None:
key = (owner, reference) try:
self._background_references.add(key) with entry.path.open("rb") as source:
try: data = source.read(MAX_BYTES + 1)
await asyncio.to_thread(save_background, directory, data, entry.mime) save_background(directory, data, entry.mime)
finally: finally:
self._background_references.discard(key) entry.path.unlink(missing_ok=True)
self._uploads.store.discard([reference], owner=owner)
await asyncio.to_thread(persist_staged_background)
except (AttachmentUploadError, ValueError) as exc: except (AttachmentUploadError, ValueError) as exc:
return WebUIRequestResult(status=400, message=str(exc)) return WebUIRequestResult(status=400, message=str(exc))
return WebUIRequestResult(result={"ok": True}) return WebUIRequestResult(result={"ok": True})
@@ -1246,26 +1280,11 @@ class WebUICommandRouter:
action, action,
payload, payload,
) )
status = response.status_code if 200 <= response.status_code < 300:
body = bytes(response.body).decode("utf-8", errors="replace").strip() if action == "sidebar.update":
if 200 <= status < 300: await self.broadcast_webui_event("sidebar_state_updated", state=response.result)
try: return WebUIRequestResult(result=response.result)
result = json.loads(body) return WebUIRequestResult(status=response.status_code, message=response.message)
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,
)
except asyncio.CancelledError: except asyncio.CancelledError:
raise raise
except Exception: except Exception:
+114 -72
View File
@@ -13,6 +13,8 @@ from datetime import datetime, timezone
from pathlib import Path from pathlib import Path
from typing import TYPE_CHECKING, Any, Literal, Mapping, cast from typing import TYPE_CHECKING, Any, Literal, Mapping, cast
from loguru import logger
from nanobot.agent.plugins import ( from nanobot.agent.plugins import (
AgentPlugin, AgentPlugin,
discover_agent_plugins, discover_agent_plugins,
@@ -25,14 +27,15 @@ from nanobot.agent.tools.mcp_oauth import (
from nanobot.agent.tools.registry import ToolRegistry from nanobot.agent.tools.registry import ToolRegistry
from nanobot.apps.cli import CliAppManager from nanobot.apps.cli import CliAppManager
from nanobot.apps.protocol import app_manifest, compact_dict 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.loader import load_config, resolve_config_env_vars, save_config
from nanobot.config.network import NetworkConfig from nanobot.config.network import NetworkConfig
from nanobot.config.paths import get_runtime_subdir from nanobot.config.paths import get_runtime_subdir
from nanobot.config.schema import MCPServerConfig from nanobot.config.schema import MCPServerConfig
from nanobot.utils.helpers import ensure_dir from nanobot.utils.helpers import ensure_dir
from nanobot.webui.mcp_presets import MCP_PRESETS, McpPreset, McpPresetField from nanobot.webui.mcp_presets import MCP_PRESETS, McpPreset, McpPresetField
from nanobot.webui.settings_contracts import QueryParams, parameter_value
QueryParams = dict[str, list[str]] from nanobot.webui.settings_contracts import query_first as _query_first
if TYPE_CHECKING: if TYPE_CHECKING:
from nanobot.webui.settings_services import WebUISettingsConfig 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: def _query_value(query: QueryParams, key: str) -> str | None:
raw = _query_first(query, key) raw = _query_first(query, key)
if raw is None: 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]: def _known_mcp_names(config_path: Path | None = None) -> set[str]:
names = _known_preset_names() names = _known_preset_names()
with suppress(Exception): try:
names.update(load_config(config_path).tools.mcp_servers) 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 return names
@@ -754,13 +754,17 @@ async def mcp_presets_test_action(
preset = _preset_by_name_optional(name) preset = _preset_by_name_optional(name)
display_name = _display_name_for(name, preset) display_name = _display_name_for(name, preset)
try: def _load_resolved_config():
config = resolve_config_env_vars( return resolve_config_env_vars(
load_config(config_path) if config_path is not None else load_config(), load_config(config_path) if config_path is not None else load_config(),
config_path=config_path, config_path=config_path,
) )
try:
config = await asyncio.to_thread(_load_resolved_config)
except ValueError as exc: except ValueError as exc:
return mcp_presets_payload( return await asyncio.to_thread(
mcp_presets_payload,
last_action={ last_action={
"ok": False, "ok": False,
"message": _scrub_test_error(str(exc)), "message": _scrub_test_error(str(exc)),
@@ -776,9 +780,16 @@ async def mcp_presets_test_action(
if cfg is None: if cfg is None:
raise McpPresetError(f"{display_name} is not enabled", status=404) raise McpPresetError(f"{display_name} is not enabled", status=404)
status = _status_for(preset, cfg) if preset is not None else ( def _preflight_status() -> tuple[str, bool]:
"missing_dependency" if cfg.command and not _command_available(cfg.command) else "configured" 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": if status == "missing_credentials":
last_action: dict[str, Any] = { last_action: dict[str, Any] = {
"ok": False, "ok": False,
@@ -788,9 +799,11 @@ async def mcp_presets_test_action(
"tool_names": [], "tool_names": [],
"checked_at": _checked_at(), "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 = { last_action = {
"ok": False, "ok": False,
"message": f"{display_name} requires '{cfg.command}' on PATH.", "message": f"{display_name} requires '{cfg.command}' on PATH.",
@@ -799,7 +812,9 @@ async def mcp_presets_test_action(
"tool_names": [], "tool_names": [],
"checked_at": _checked_at(), "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() registry = ToolRegistry()
stacks: dict[str, Any] = {} stacks: dict[str, Any] = {}
@@ -861,15 +876,20 @@ async def mcp_presets_test_action(
tool_names = last_action.get("tool_names", []) tool_names = last_action.get("tool_names", [])
preview = {name: tool_names} if tool_names else None 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, last_action=last_action,
tool_preview=preview, tool_preview=preview,
config_path=config_path, config_path=config_path,
) )
def _parse_json_value(raw: str | None, *, fallback: Any) -> Any: def _parse_json_value(raw: Any, *, fallback: Any) -> Any:
if raw is None or not raw.strip(): if raw is None:
return fallback
if not isinstance(raw, str):
return raw
if not raw.strip():
return fallback return fallback
try: try:
return json.loads(raw) 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 raise McpPresetError(f"invalid JSON: {exc.msg}") from exc
def _parse_string_list(raw: str | None) -> list[str]: def _parse_string_list(raw: Any) -> list[str]:
if raw is None or not raw.strip(): parsed = _parse_json_value(raw, fallback=[])
return []
parsed = _parse_json_value(raw, fallback=None)
if isinstance(parsed, list): if isinstance(parsed, list):
items = cast(list[object], parsed) items = cast(list[object], parsed)
if all(isinstance(item, str) for item in items): 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") 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={}) parsed = _parse_json_value(raw, fallback={})
if not isinstance(parsed, dict): if not isinstance(parsed, dict):
raise McpPresetError("expected a JSON object") raise McpPresetError("expected a JSON object")
@@ -903,8 +921,8 @@ def _parse_string_map(raw: str | None) -> dict[str, str]:
return out return out
def _parse_enabled_tools(raw: str | None) -> list[str]: def _parse_enabled_tools(raw: Any) -> list[str]:
if raw is None or not raw.strip(): if raw is None or (isinstance(raw, str) and not raw.strip()):
return ["*"] return ["*"]
values = _parse_string_list(raw) values = _parse_string_list(raw)
if "*" in values: if "*" in values:
@@ -966,22 +984,48 @@ def _validated_server_name(name: str) -> str:
return name.strip().lower() 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]: def _custom_server_from_query(query: QueryParams) -> tuple[str, MCPServerConfig]:
name = _validated_server_name((_query_first(query, "name") or "").strip()) name = _validated_server_name((_query_first(query, "name") or "").strip())
command = (_query_first(query, "command") or "").strip() command = (_query_first(query, "command") or "").strip()
url = (_query_first(query, "url") or "").strip() url = (_query_first(query, "url") or "").strip()
transport = _normalize_transport(_query_first(query, "transport"), command=command, url=url) headers = _parse_string_map(parameter_value(query, "headers"))
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,
)
raw_timeout = (_query_first(query, "tool_timeout") or "").strip() raw_timeout = (_query_first(query, "tool_timeout") or "").strip()
tool_timeout = _DEFAULT_CUSTOM_TIMEOUT tool_timeout = _DEFAULT_CUSTOM_TIMEOUT
if raw_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)) tool_timeout = max(5, min(int(raw_timeout), 600))
except ValueError as exc: except ValueError as exc:
raise McpPresetError("tool_timeout must be an integer") from exc raise McpPresetError("tool_timeout must be an integer") from exc
cfg = MCPServerConfig( cfg = _build_mcp_server_config(
type=transport, transport_raw=_query_first(query, "transport"),
auth=auth, command=command,
command=command if transport == "stdio" else "", url=url,
args=_parse_string_list(_query_first(query, "args")), auth_raw=_query_first(query, "auth"),
env=_parse_string_map(_query_first(query, "env")), args=_parse_string_list(parameter_value(query, "args")),
cwd=(_query_first(query, "cwd") or "").strip() if transport == "stdio" else "", env=_parse_string_map(parameter_value(query, "env")),
url=url if transport in {"sse", "streamableHttp"} else "", cwd=(_query_first(query, "cwd") or "").strip(),
headers=headers, headers=headers,
use_proxy=_proxy_enabled(query), use_proxy=_proxy_enabled(query),
tool_timeout=tool_timeout, 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 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() command = str(server.get("command") or "").strip()
url = str(server.get("url") or "").strip() url = str(server.get("url") or "").strip()
transport_value = str(server.get("type", server.get("transport", "")) or "") 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 [] args_value: object = server.get("args") or []
env_value: object = server.get("env") or {} env_value: object = server.get("env") or {}
headers_value: object = server.get("headers") 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)) use_proxy = server.get("useProxy", server.get("use_proxy", False))
if not isinstance(use_proxy, bool): if not isinstance(use_proxy, bool):
raise McpPresetError(f"MCP server '{server_name}' useProxy must be a boolean") 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): if not isinstance(enabled_tools_value, list):
enabled_tools_value = ["*"] enabled_tools_value = ["*"]
else: else:
enabled_tools = cast(list[object], enabled_tools_value) enabled_tools = cast(list[object], enabled_tools_value)
if not all(isinstance(item, str) for item in enabled_tools): if not all(isinstance(item, str) for item in enabled_tools):
enabled_tools_value = ["*"] enabled_tools_value = ["*"]
return server_name, MCPServerConfig( cfg = _build_mcp_server_config(
type=transport, transport_raw=transport_value,
auth=auth, command=command,
command=command if transport == "stdio" else "", url=url,
auth_raw=server.get("auth"),
args=cast(list[str], args), args=cast(list[str], args),
env=cast(dict[str, str], env), env=cast(dict[str, str], env),
cwd=cwd if transport == "stdio" else "", cwd=cwd,
url=url if transport in {"sse", "streamableHttp"} else "",
headers=typed_headers, headers=typed_headers,
use_proxy=use_proxy, use_proxy=use_proxy,
tool_timeout=timeout_int, tool_timeout=timeout_int,
enabled_tools=cast(list[str], enabled_tools_value), 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) parsed = _parse_json_value(raw_json, fallback=None)
if not isinstance(parsed, Mapping): if not isinstance(parsed, Mapping):
raise McpPresetError("MCP config must be a JSON object") raise McpPresetError("MCP config must be a JSON object")
@@ -1125,7 +1163,7 @@ def custom_mcp_action(
return payload return payload
if action in {"import", "import-cursor"}: 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(): for cfg in servers.values():
_validate_proxy(cfg, config.network) _validate_proxy(cfg, config.network)
delete_credentials = [ delete_credentials = [
@@ -1152,7 +1190,7 @@ def custom_mcp_action(
cfg = config.tools.mcp_servers.get(name) cfg = config.tools.mcp_servers.get(name)
if cfg is None: if cfg is None:
raise McpPresetError("unknown MCP server", status=404) 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 config.tools.mcp_servers[name] = cfg
save_config(config, config_path) save_config(config, config_path)
payload = mcp_presets_payload( 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.""" """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 config_path = config.path if config is not None else None
if action is 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, runtime_status=mcp_runtime_status() if mcp_runtime_status is not None else None,
config_path=config_path, config_path=config_path,
) )
name = (_query_first(query, "name") or "").strip() name = (_query_first(query, "name") or "").strip()
if name.startswith("plugin-"): 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-") 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) 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 name not in plugin_config.tools.mcp_servers and plugin is not None:
if action not in {"enable", "disable"}: if action not in {"enable", "disable"}:
@@ -1331,7 +1372,8 @@ async def mcp_presets_settings_action(
action == "enable", action == "enable",
) )
verb = "enabled" if action == "enable" else "disabled" 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}."}, last_action={"ok": True, "message": f"{plugin.display_name} {verb}."},
config_path=config_path, config_path=config_path,
) )
+21
View File
@@ -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)
+1 -3
View File
@@ -11,9 +11,7 @@ from nanobot.optional_features import (
install_optional_feature_support, install_optional_feature_support,
optional_features_payload, optional_features_payload,
) )
from nanobot.webui.http_utils import query_first from nanobot.webui.settings_contracts import QueryParams, query_first
QueryParams = dict[str, list[str]]
def nanobot_features_payload(*, config_path: Path | None = None) -> dict[str, Any]: def nanobot_features_payload(*, config_path: Path | None = None) -> dict[str, Any]:
+8 -3
View File
@@ -438,12 +438,17 @@ class WebUIOutboundDelivery:
chat_id, persisted=persisted, metadata=metadata, phase=phase, 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]: async def _message_payload(self, msg: OutboundMessage, progress: ProgressEvent | None) -> dict[str, Any]:
text = msg.content text = msg.content
user_shell = msg.metadata.get(INBOUND_META_USER_SHELL) is True user_shell = msg.metadata.get(INBOUND_META_USER_SHELL) is True
payload: MessageWirePayload = { payload: MessageWirePayload = {
"event": "message", "chat_id": msg.chat_id, "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: if user_shell:
payload["render_as"] = "text" payload["render_as"] = "text"
@@ -454,7 +459,7 @@ class WebUIOutboundDelivery:
payload["media"] = msg.media payload["media"] = msg.media
urls: list[dict[str, str]] = [] urls: list[dict[str, str]] = []
for entry in msg.media: 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: if signed is not None:
urls.append(signed) urls.append(signed)
if urls: if urls:
@@ -555,7 +560,7 @@ class WebUIOutboundDelivery:
if delta: if delta:
buffered.chunks.append(delta) buffered.chunks.append(delta)
full_text = "".join(buffered.chunks) 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 completed_text = rewritten
if delta or rewritten != full_text: if delta or rewritten != full_text:
payload["text"] = rewritten payload["text"] = rewritten
+8 -7
View File
@@ -5,7 +5,7 @@ import re
from typing import Any, cast from typing import Any, cast
from nanobot.config.schema import ProviderConfig 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 = "••••••••" _REDACTED_PROVIDER_SECRET = "••••••••"
_PROVIDER_STRUCTURED_FIELDS = ("extra_headers", "extra_body", "extra_query") _PROVIDER_STRUCTURED_FIELDS = ("extra_headers", "extra_body", "extra_query")
@@ -45,13 +45,14 @@ def parse_request_object(
snake: str, snake: str,
camel: str, camel: str,
) -> dict[str, Any] | None: ) -> dict[str, Any] | None:
raw = (query_first_alias(query, snake, camel) or "").strip() value = parameter_value(query, snake if snake in query else camel)
if not raw: if value is None or (isinstance(value, str) and not value.strip()):
return None return None
try: if isinstance(value, str):
value: object = json.loads(raw) try:
except json.JSONDecodeError as exc: value = json.loads(value)
raise WebUISettingsError(f"{snake} must be a JSON object") from exc except json.JSONDecodeError as exc:
raise WebUISettingsError(f"{snake} must be a JSON object") from exc
if not isinstance(value, dict): if not isinstance(value, dict):
raise WebUISettingsError(f"{snake} must be a JSON object") raise WebUISettingsError(f"{snake} must be a JSON object")
return cast(dict[str, Any], value) or None return cast(dict[str, Any], value) or None
+35 -2
View File
@@ -1,9 +1,23 @@
from __future__ import annotations from __future__ import annotations
import json
from dataclasses import dataclass from dataclasses import dataclass
from typing import Any 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) @dataclass(frozen=True)
@@ -59,11 +73,30 @@ class WebUISettingsError(ValueError):
self.status = status 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) values = query.get(key)
return values[0] if values else None 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: def query_first_alias(query: QueryParams, snake: str, camel: str) -> str | None:
value = query_first(query, snake) value = query_first(query, snake)
return query_first(query, camel) if value is None else value return query_first(query, camel) if value is None else value
+273
View File
@@ -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,
}
+75 -274
View File
@@ -5,9 +5,6 @@ updates, model discovery, and OAuth workflows. It deliberately has no
dependency on the WebSocket transport. dependency on the WebSocket transport.
""" """
# oauth-cli-kit does not publish type stubs.
# pyright: reportMissingTypeStubs=false
from __future__ import annotations from __future__ import annotations
import asyncio import asyncio
@@ -15,9 +12,7 @@ import json
import math import math
import os import os
import re import re
import secrets
import time import time
from contextlib import suppress
from dataclasses import dataclass from dataclasses import dataclass
from datetime import date, datetime, timezone from datetime import date, datetime, timezone
from pathlib import Path from pathlib import Path
@@ -39,7 +34,6 @@ from nanobot.providers.model_options import (
CodexFastMode, CodexFastMode,
codex_supports_ultrafast, codex_supports_ultrafast,
) )
from nanobot.providers.oauth_guidance import OAUTH_CLI_KIT_MISSING_MESSAGE
from nanobot.providers.oauth_model_catalog import ( from nanobot.providers.oauth_model_catalog import (
get_oauth_model_catalog, get_oauth_model_catalog,
invalidate_oauth_model_catalog, invalidate_oauth_model_catalog,
@@ -61,11 +55,20 @@ from nanobot.webui.settings_contracts import (
SettingsRequest, SettingsRequest,
SettingsRouteResult, SettingsRouteResult,
WebUISettingsError, WebUISettingsError,
parameter_json,
parameter_value,
parse_bool, parse_bool,
query_first, query_first,
query_first_alias, query_first_alias,
query_has_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: if TYPE_CHECKING:
from nanobot.webui.settings_services import ( from nanobot.webui.settings_services import (
@@ -129,8 +132,6 @@ class ProviderModelRowPayload(ProviderModelMetadataPayload):
description: NotRequired[str] 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_-]+") _MODEL_CONFIGURATION_SLUG_RE = re.compile(r"[^a-z0-9_-]+")
_ENV_REF_RE = re.compile(r"\$\{([A-Za-z_][A-Za-z0-9_]*)\}") _ENV_REF_RE = re.compile(r"\$\{([A-Za-z_][A-Za-z0-9_]*)\}")
_PROVIDER_STRUCTURED_FIELDS = ("extra_headers", "extra_body", "extra_query") _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) updates[snake] = request_settings.parse_request_object(query, snake, camel)
if query_has_alias(query, "api", "api"): if query_has_alias(query, "api", "api"):
try: try:
updates["api"] = json.loads(query_first(query, "api") or "null") updates["api"] = parameter_json(query, "api")
except ValueError as exc: except ValueError as exc:
raise WebUISettingsError("api must declare supportedApis and a preferredApi from that list") from exc raise WebUISettingsError("api must declare supportedApis and a preferredApi from that list") from exc
return updates 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) 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( def provider_configured_for_settings(
spec: Any, spec: Any,
provider_config: Any, provider_config: Any,
@@ -353,7 +274,8 @@ def _provider_advanced_field_names(spec: ProviderSpec) -> list[str]:
fields.append("extra_body") fields.append("extra_body")
if spec.backend in {"openai_compat", "anthropic"}: if spec.backend in {"openai_compat", "anthropic"}:
fields.extend(("extra_query", "use_proxy")) 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") fields.append("use_proxy")
if spec.backend == "bedrock": if spec.backend == "bedrock":
fields.extend(("region", "profile")) fields.extend(("region", "profile"))
@@ -1323,7 +1245,7 @@ def update_agent_model_settings(
defaults.context_window_tokens = context_window_tokens defaults.context_window_tokens = context_window_tokens
changed = True changed = True
if "api" in query: 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: if defaults.api != api:
defaults.api = api defaults.api = api
changed = True changed = True
@@ -1333,12 +1255,10 @@ def update_agent_model_settings(
def _parse_preset_api( def _parse_preset_api(
config: Config, model: str, provider: str, raw: str | None, config: Config, model: str, provider: str, query: QueryParams,
) -> ModelAPIConfig | None: ) -> ModelAPIConfig | None:
if not raw:
return None
try: try:
value: object = json.loads(raw) value: object = parameter_json(query, "api")
api = ModelAPIConfig.model_validate(value) if value is not None else None api = ModelAPIConfig.model_validate(value) if value is not None else None
except ValueError: except ValueError:
raise WebUISettingsError( raise WebUISettingsError(
@@ -1419,7 +1339,7 @@ def create_model_configuration(
supports_images=parse_bool( supports_images=parse_bool(
query_first_alias(query, "supports_images", "supportsImages") or "true", "supports_images", 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) config.model_presets[name] = _preset_with_request_updates(config, candidate, query)
if activate_as_primary: if activate_as_primary:
@@ -1518,7 +1438,7 @@ def update_model_configuration(
preset.supports_images = supports_images preset.supports_images = supports_images
changed = True changed = True
if "api" in query: 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: if preset.api != api:
preset.api = api preset.api = api
changed = True changed = True
@@ -1538,31 +1458,44 @@ def update_model_configuration(
return changed 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( def update_model_call_order(
config: Config, config: Config,
query: QueryParams, query: QueryParams,
*, *,
oauth_status: OAuthStatusReader, oauth_status: OAuthStatusReader,
) -> bool: ) -> bool:
raw_order = query_first_alias(query, "order", "presetNames") request = _ModelCallOrderRequest.from_query(query)
if raw_order is None: return _set_model_call_order(config, list(request.order), oauth_status=oauth_status)
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)
def append_model_call_order(config: Config, name: str, *, oauth_status: OAuthStatusReader) -> None: 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: except ValueError as exc:
raise WebUISettingsError(str(exc)) from None raise WebUISettingsError(str(exc)) from None
if spec.is_oauth: 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") raise WebUISettingsError("unknown provider")
unsupported = set(updates) - {"use_proxy", "extra_body"} unsupported = set(updates) - {"use_proxy", "extra_body"}
if unsupported: if unsupported:
@@ -1805,6 +1739,21 @@ def update_provider_settings(
return changed, restart_required 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( def login_oauth_provider(
config: Config, config: Config,
query: QueryParams, query: QueryParams,
@@ -1812,115 +1761,13 @@ def login_oauth_provider(
oauth_flows: WebUIOAuthFlowRegistry, oauth_flows: WebUIOAuthFlowRegistry,
config_path: Path | None, config_path: Path | None,
) -> dict[str, Any]: ) -> dict[str, Any]:
provider_name = (query_first(query, "provider") or "").strip() spec, adapter = _requested_oauth_provider(query, "login")
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": def remote_browser() -> bool:
try: value = query_first(query, "remote_browser")
from nanobot.providers.openai_codex_oauth import OpenAICodexOAuthLoginFlow return parse_bool(value, "remote_browser") if value is not None else False
except ImportError:
raise WebUISettingsError(OAUTH_CLI_KIT_MISSING_MESSAGE, status=500) from None
try: return adapter.start_login(spec.name, config, config_path, remote_browser, oauth_flows)
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")
def complete_oauth_provider( def complete_oauth_provider(
@@ -1931,11 +1778,8 @@ def complete_oauth_provider(
config_path: Path | None, config_path: Path | None,
settings_payload: SettingsPayloadBuilder, settings_payload: SettingsPayloadBuilder,
) -> dict[str, Any]: ) -> 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() 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: if not flow_id:
raise WebUISettingsError("flow_id is required") raise WebUISettingsError("flow_id is required")
@@ -1949,15 +1793,7 @@ def complete_oauth_provider(
return {"status": "cancelled", "provider": spec.name, "flow_id": flow_id} return {"status": "cancelled", "provider": spec.name, "flow_id": flow_id}
try: try:
if spec.name == "openai_codex": token = adapter.complete(flow, authorization_response)
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)
except WebUISettingsError: except WebUISettingsError:
raise raise
except Exception as exc: except Exception as exc:
@@ -1986,43 +1822,8 @@ def logout_oauth_provider(
config_path: Path | None, config_path: Path | None,
settings_payload: SettingsPayloadBuilder, settings_payload: SettingsPayloadBuilder,
) -> dict[str, Any]: ) -> dict[str, Any]:
provider_name = (query_first(query, "provider") or "").strip() spec, adapter = _requested_oauth_provider(query, "logout")
if not provider_name: adapter.logout(spec.name, oauth_flows)
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()
invalidate_oauth_model_catalog(spec.name) invalidate_oauth_model_catalog(spec.name)
return settings_payload(config_path=config_path) return settings_payload(config_path=config_path)
+183 -278
View File
@@ -2,8 +2,9 @@ from __future__ import annotations
import asyncio import asyncio
import html import html
import json import re
from collections.abc import Awaitable, Callable, Mapping from collections.abc import Awaitable, Callable, Mapping
from dataclasses import dataclass
from functools import partial from functools import partial
from typing import Any, cast 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_models as model_domain
from nanobot.webui import settings_system as system_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.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 http_response as _http_response
from nanobot.webui.http_utils import is_local_browser_request as _is_local_browser_request from nanobot.webui.http_utils import is_local_browser_request as _is_local_browser_request
from nanobot.webui.mcp_oauth_api import McpOAuthManager from nanobot.webui.mcp_oauth_api import McpOAuthManager
@@ -29,6 +34,7 @@ from nanobot.webui.mcp_presets_api import (
ensure_mcp_oauth_server, ensure_mcp_oauth_server,
mcp_presets_settings_action, mcp_presets_settings_action,
) )
from nanobot.webui.mutation import MutationResult
from nanobot.webui.nanobot_features_api import ( from nanobot.webui.nanobot_features_api import (
nanobot_feature_instance_target, nanobot_feature_instance_target,
nanobot_features_action, nanobot_features_action,
@@ -58,7 +64,8 @@ from nanobot.webui.settings_api import (
update_web_search_settings, update_web_search_settings,
) )
from nanobot.webui.settings_contracts import ( from nanobot.webui.settings_contracts import (
QueryParams, HttpQuery,
MutationParams,
SettingsRequest, SettingsRequest,
SettingsRouteResult, SettingsRouteResult,
) )
@@ -66,8 +73,6 @@ from nanobot.webui.settings_runtime import runtime_config_payload
from nanobot.webui.settings_services import WebUISettingsServices from nanobot.webui.settings_services import WebUISettingsServices
from nanobot.webui.version_check import check_for_update 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"}) _CHANNEL_CONNECT_ACTIONS = frozenset({"start", "poll", "cancel"})
_MCP_OAUTH_CALLBACK_URL_MAX_BYTES = 8 * 1024 _MCP_OAUTH_CALLBACK_URL_MAX_BYTES = 8 * 1024
_MCP_RELOAD_TIMEOUT_SECONDS = 15.0 _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 return (channel_name, parts[2]) if channel_name else None
_MCP_PRESET_ACTIONS_BY_PATH = { @dataclass(frozen=True, slots=True)
"/api/settings/mcp-presets/enable": "enable", class _SettingsRoute:
"/api/settings/mcp-presets/disable": "disable", domain: str
"/api/settings/mcp-presets/remove": "remove", action: str
"/api/settings/mcp-presets/test": "test", mutation: str | None = None
"/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",
}
_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 = { _SETTINGS_ROUTES = {
"/api/settings/web-search/update": "web-search-update", "/api/settings/update": _SettingsRoute("models", "agent-update", "settings.agent.update"),
"/api/settings/image-generation/update": "image-update", "/api/settings/model-configurations/create": _SettingsRoute("models", "model-create", "settings.model_configuration.create"),
"/api/settings/transcription/update": "transcription-update", "/api/settings/model-configurations/update": _SettingsRoute("models", "model-update", "settings.model_configuration.update"),
"/api/settings/network-safety/update": "network-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"),
} }
_SETTINGS_WS_ROUTES = {route.mutation: route for route in _SETTINGS_ROUTES.values() if route.mutation}
_SYSTEM_ROUTES = { _CHANNEL_CONNECT_WS = {f"settings.channel.connect.{action}": action for action in _CHANNEL_CONNECT_ACTIONS}
"/api/settings/sandbox/check": "sandbox-check", _CHANNEL_NAME_RE = re.compile(r"[A-Za-z0-9_-]{1,64}")
"/api/settings/runtime-config/update": "runtime-config-update", _LOCAL_BROWSER_ACTIONS = frozenset({
"/api/settings/cli-apps": "cli-list", "runtime-config-update", "features-enable", "channel-configure", "channel-connect",
"/api/settings/cli-apps/install": "cli-install", "update-channel", "version-check", "update-plan-create", "update-plan-read",
"/api/settings/cli-apps/update": "cli-update", "update-job-prepare", "update-job-settle", "update-job-execute", "update-job-retry",
"/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,
}) })
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: class WebUISettingsRouter:
"""Authenticate and dispatch settings requests to transport-neutral domains.""" """Authenticate and dispatch settings requests to transport-neutral domains."""
@@ -235,7 +179,7 @@ class WebUISettingsRouter:
bus: MessageBus, bus: MessageBus,
logger: Any, logger: Any,
check_api_token: Callable[[WsRequest], bool], check_api_token: Callable[[WsRequest], bool],
parse_query: Callable[[str], QueryParams], parse_query: Callable[[str], HttpQuery],
json_response: Callable[[dict[str, Any]], Response], json_response: Callable[[dict[str, Any]], Response],
error_response: Callable[[int, str | None], Response], error_response: Callable[[int, str | None], Response],
runtime_surface: str, runtime_surface: str,
@@ -245,7 +189,7 @@ class WebUISettingsRouter:
mcp_runtime_status: Callable[[], Mapping[str, str]] | None = None, mcp_runtime_status: Callable[[], Mapping[str, str]] | None = None,
mcp_reload: Callable[[], Awaitable[dict[str, Any]]] | None = None, mcp_reload: Callable[[], Awaitable[dict[str, Any]]] | None = None,
image_generation_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: ) -> None:
self.settings = settings self.settings = settings
self.bus = bus self.bus = bus
@@ -272,6 +216,9 @@ class WebUISettingsRouter:
logger, logger,
) )
self._system = system_domain.SystemSettingsHandler(settings, logger, bus.admission) 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: async def close(self) -> None:
"""Release state owned by settings domains.""" """Release state owned by settings domains."""
@@ -285,84 +232,94 @@ class WebUISettingsRouter:
request: WsRequest, request: WsRequest,
path: str, path: str,
) -> Response | None: ) -> Response | None:
if self.is_mutation_path(path) and not getattr( if self.is_mutation_path(path):
request, return self._error_response(405, "WebUI mutations require an authenticated WebSocket")
_WEBUI_MUTATION_REQUEST_ATTR,
False,
):
return self._error_response(
405,
"WebUI mutations require an authenticated WebSocket",
)
if path == MCP_OAUTH_CALLBACK_PATH: if path == MCP_OAUTH_CALLBACK_PATH:
return self._handle_mcp_oauth_callback(request) return self._handle_mcp_oauth_callback(request)
if path == "/api/settings/mcp-oauth/start": if path not in {"/api/settings", "/api/settings/usage", "/api/settings/mcp-oauth/status"} and path not in _SETTINGS_ROUTES:
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:
return None return None
if not self._authorized(request): if not self._authorized(request):
return self._unauthorized() 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) 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) 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": 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 = ( restart_before = (
await asyncio.to_thread(self._restart_values, action) await asyncio.to_thread(self._restart_values, action)
if action in {"runtime-config-update", "image-update", "web-search-update"} if action in {"runtime-config-update", "image-update", "web-search-update"}
else None 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": if domain == "models":
result = await self._models.handle( result = await self._models.handle(action, domain_request, self._model_ops)
action,
domain_request,
self._model_operations(),
)
elif domain == "capabilities": elif domain == "capabilities":
result = await self._capabilities.handle( result = await self._capabilities.handle(action, domain_request, self._capability_ops)
action,
domain_request,
self._capability_operations(),
)
else: else:
channel_connect = _channel_connect_route(path)
result = await self._system.handle( result = await self._system.handle(
action, action, domain_request, self._system_ops,
domain_request, channel_name=channel_name, connect_action=connect_action,
self._system_operations(),
channel_name=(channel_connect[0] if channel_connect else None),
connect_action=(channel_connect[1] if channel_connect else None),
) )
if restart_before is not None and result.error is None and result.payload is not None: 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) restart_after = await asyncio.to_thread(self._restart_values, action)
@@ -384,12 +341,7 @@ class WebUISettingsRouter:
self._restart_changes[action] = result.restart_section self._restart_changes[action] = result.restart_section
# Reversible changes are tracked separately from installation and reload failures. # Reversible changes are tracked separately from installation and reload failures.
result.payload["requires_restart"] = False result.payload["requires_restart"] = False
response = self._render_result(result) return 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
def _restart_values(self, action: str) -> dict[str, Any]: def _restart_values(self, action: str) -> dict[str, Any]:
config = self.settings.config.load() config = self.settings.config.load()
@@ -401,46 +353,8 @@ class WebUISettingsRouter:
@staticmethod @staticmethod
def is_mutation_path(path: str) -> bool: def is_mutation_path(path: str) -> bool:
return path in _SETTINGS_MUTATION_PATHS or _channel_connect_route(path) is not None route = _SETTINGS_ROUTES.get(path)
return (route is not None and route.mutation is not None) 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
),
)
def _authorized(self, request: WsRequest) -> bool: def _authorized(self, request: WsRequest) -> bool:
return self._check_api_token(request) return self._check_api_token(request)
@@ -470,6 +384,9 @@ class WebUISettingsRouter:
def _render_result(self, result: SettingsRouteResult) -> Response: def _render_result(self, result: SettingsRouteResult) -> Response:
if result.error is not None: if result.error is not None:
return self._error_response(result.status, result.error) 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 assert result.payload is not None
payload = result.payload payload = result.payload
if result.clear_restart_section: if result.clear_restart_section:
@@ -488,7 +405,7 @@ class WebUISettingsRouter:
payload, payload,
section=result.restart_section, section=result.restart_section,
) )
return self._json_response(payload) return payload
def _handle_settings(self) -> Response: def _handle_settings(self) -> Response:
return self._json_response( return self._json_response(
@@ -511,7 +428,7 @@ class WebUISettingsRouter:
if revision: if revision:
etag = f'W/"{revision}"' etag = f'W/"{revision}"'
headers.append(("ETag", etag)) 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( return _http_response(
b"", status=304, extra_headers=[*headers, ("Vary", "Accept-Encoding")], b"", status=304, extra_headers=[*headers, ("Vary", "Accept-Encoding")],
) )
@@ -637,9 +554,6 @@ class WebUISettingsRouter:
"error": str(exc), "error": str(exc),
} }
def _parse_mcp_settings_query(self, request: WsRequest) -> QueryParams:
return self._query(request)
def _save_channel_config_values( def _save_channel_config_values(
self, self,
name: str, name: str,
@@ -656,19 +570,16 @@ class WebUISettingsRouter:
) )
) )
async def _handle_mcp_oauth_start(self, request: WsRequest) -> Response: async def _handle_mcp_oauth_start(self, headers: Any, query: MutationParams) -> MutationResult:
if not self._authorized(request):
return self._unauthorized()
if self._mcp_oauth_redirect_uri is None: if self._mcp_oauth_redirect_uri is None:
return self._error_response(500, "MCP OAuth callback is not configured") return MutationResult.failure(500, "MCP OAuth callback is not configured")
query = self._parse_mcp_settings_query(request)
try: try:
name, cfg, network = await asyncio.to_thread( name, cfg, network = await asyncio.to_thread(
self.settings.mutate, self.settings.mutate,
ensure_mcp_oauth_server, ensure_mcp_oauth_server,
query, 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"} reset = (_query_first(query, "reset") or "").lower() in {"1", "true", "yes"}
payload = await self._mcp_oauth.start( payload = await self._mcp_oauth.start(
name, name,
@@ -679,56 +590,50 @@ class WebUISettingsRouter:
reset_credentials=reset, reset_credentials=reset,
) )
except Exception as exc: except Exception as exc:
return self._mcp_oauth_error_response(exc, action="start") return self._mcp_oauth_failure(exc, action="start")
return self._json_response(payload) return MutationResult.success(payload)
async def _handle_mcp_oauth_status(self, request: WsRequest) -> Response: async def _handle_mcp_oauth_status(self, request: WsRequest) -> Response:
if not self._authorized(request): flow_id = (_query_first(self._parse_query(request.path), "flow_id") or "").strip()
return self._unauthorized()
flow_id = (_query_first(self._query(request), "flow_id") or "").strip()
if not flow_id: if not flow_id:
return self._error_response(400, "missing MCP OAuth flow ID") return self._error_response(400, "missing MCP OAuth flow ID")
try: try:
payload = await self._mcp_oauth.status(flow_id) payload = await self._mcp_oauth.status(flow_id)
except Exception as exc: 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) return self._json_response(payload)
def _handle_mcp_oauth_complete(self, request: WsRequest) -> Response: def _handle_mcp_oauth_complete(self, query: MutationParams) -> MutationResult:
if not self._authorized(request):
return self._unauthorized()
query = self._query(request)
flow_id = (_query_first(query, "flow_id") or "").strip() flow_id = (_query_first(query, "flow_id") or "").strip()
if not flow_id: 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() callback_url = (_query_first(query, "callback_url") or "").strip()
if not callback_url: 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: 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: try:
payload = self._mcp_oauth.submit_callback_url( payload = self._mcp_oauth.submit_callback_url(
flow_id=flow_id, flow_id=flow_id,
callback_url=callback_url, callback_url=callback_url,
) )
except Exception as exc: except Exception as exc:
return self._mcp_oauth_error_response(exc, action="complete") return self._mcp_oauth_failure(exc, action="complete")
return self._json_response(payload) return MutationResult.success(payload)
async def _handle_mcp_oauth_cancel(self, request: WsRequest) -> Response: async def _handle_mcp_oauth_cancel(self, query: MutationParams) -> MutationResult:
if not self._authorized(request): flow_id = (_query_first(query, "flow_id") or "").strip()
return self._unauthorized()
flow_id = (_query_first(self._query(request), "flow_id") or "").strip()
if not flow_id: if not flow_id:
return self._error_response(400, "missing MCP OAuth flow ID") return MutationResult.failure(400, "missing MCP OAuth flow ID")
try: try:
payload = await self._mcp_oauth.cancel(flow_id) payload = await self._mcp_oauth.cancel(flow_id)
except Exception as exc: except Exception as exc:
return self._mcp_oauth_error_response(exc, action="cancel") return self._mcp_oauth_failure(exc, action="cancel")
return self._json_response(payload) return MutationResult.success(payload)
def _handle_mcp_oauth_callback(self, request: WsRequest) -> Response: 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() state = (_query_first(query, "state") or "").strip()
if not state: if not state:
return self._mcp_oauth_callback_page( return self._mcp_oauth_callback_page(
@@ -751,7 +656,7 @@ class WebUISettingsRouter:
message=f"Authorization received for {name}. Return to nanobot to finish connecting.", 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) raw_status = getattr(exc, "status", 500)
status = raw_status if isinstance(raw_status, int) and 400 <= raw_status <= 599 else 500 status = raw_status if isinstance(raw_status, int) and 400 <= raw_status <= 599 else 500
if status >= 500: if status >= 500:
@@ -760,7 +665,7 @@ class WebUISettingsRouter:
else: else:
raw_message = getattr(exc, "message", None) raw_message = getattr(exc, "message", None)
message = raw_message if isinstance(raw_message, str) else "MCP OAuth request failed" 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 @staticmethod
def _mcp_oauth_callback_page( def _mcp_oauth_callback_page(
+11 -1
View File
@@ -51,6 +51,7 @@ from nanobot.update_service import (
) )
from nanobot.webui.settings_capabilities import network_safety_payload from nanobot.webui.settings_capabilities import network_safety_payload
from nanobot.webui.settings_contracts import ( from nanobot.webui.settings_contracts import (
MutationParams,
QueryParams, QueryParams,
SettingsRequest, SettingsRequest,
SettingsRouteResult, SettingsRouteResult,
@@ -1088,7 +1089,16 @@ class SystemSettingsHandler:
) )
try: 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: except ChannelConnectError as exc:
return SettingsRouteResult.failure(exc.status, exc.message) return SettingsRouteResult.failure(exc.status, exc.message)
except Exception: except Exception:
+115 -611
View File
@@ -1,7 +1,5 @@
from __future__ import annotations from __future__ import annotations
import base64
import binascii
import hashlib import hashlib
import json import json
import re import re
@@ -11,7 +9,6 @@ import time
import uuid import uuid
from bisect import bisect_left from bisect import bisect_left
from collections import OrderedDict from collections import OrderedDict
from dataclasses import dataclass
from datetime import datetime from datetime import datetime
from pathlib import Path from pathlib import Path
from typing import Any, Callable, Mapping, NamedTuple, NotRequired, Sequence, TypedDict, cast from typing import Any, Callable, Mapping, NamedTuple, NotRequired, Sequence, TypedDict, cast
@@ -32,7 +29,6 @@ from nanobot.session.history_graph import (
decode_graph, decode_graph,
decode_snapshot, decode_snapshot,
graph_decoding, graph_decoding,
graph_size_adjustment,
) )
from nanobot.session.history_visibility import is_hidden_history_message from nanobot.session.history_visibility import is_hidden_history_message
from nanobot.session.manager import Session, SessionManager 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.metadata import WEBUI_MESSAGE_SOURCE_METADATA_KEY, WEBUI_TURN_METADATA_KEY
from nanobot.webui.outbound_wire import project_tool_events from nanobot.webui.outbound_wire import project_tool_events
from nanobot.webui.session_identity import webui_session_key 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_TRANSCRIPT_SCHEMA_VERSION = 3
WEBUI_FORK_MARKER_EVENT = "fork_marker" WEBUI_FORK_MARKER_EVENT = "fork_marker"
@@ -63,10 +87,6 @@ _MAX_TRANSCRIPT_PAGE_RECORDS = 4_000
_MAX_TRANSCRIPT_PAGE_BYTES = 20 * 1024 * 1024 _MAX_TRANSCRIPT_PAGE_BYTES = 20 * 1024 * 1024
_MAX_INLINE_TRACE_DETAIL_BYTES = 32 * 1024 _MAX_INLINE_TRACE_DETAIL_BYTES = 32 * 1024
_WEBUI_TURN_ID_RE = re.compile(r"^[A-Za-z0-9._:-]{1,128}$") _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<turn>\d{1,12})\.(?P<message>history-[0-9a-f]{20})$"
)
_MARKDOWN_LOCAL_IMAGE_RE = re.compile( _MARKDOWN_LOCAL_IMAGE_RE = re.compile(
r"!\[([^\]]*)\]\((<[^>]+>|[^)\s]+)(\s+(?:\"[^\"]*\"|'[^']*'))?\)" r"!\[([^\]]*)\]\((<[^>]+>|[^)\s]+)(\s+(?:\"[^\"]*\"|'[^']*'))?\)"
) )
@@ -197,309 +217,18 @@ def webui_transcript_revision(
return hashlib.sha256(encoded.encode("utf-8")).hexdigest()[:32] 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): class _SessionBackfillTurn(NamedTuple):
user_event: dict[str, Any] user_event: dict[str, Any]
assistant_signature: tuple[str, ...] assistant_signature: tuple[str, ...]
assistant_records: tuple[dict[str, Any], ...] 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: def _coerce_page_limit(limit: int | None) -> int:
if limit is None: if limit is None:
return _DEFAULT_TRANSCRIPT_PAGE_LIMIT return _DEFAULT_TRANSCRIPT_PAGE_LIMIT
return max(1, min(_MAX_TRANSCRIPT_PAGE_LIMIT, int(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]]: 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()] 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): if isinstance(input_id, str) and _WEBUI_TURN_ID_RE.fullmatch(input_id):
event["turn_id"] = input_id event["turn_id"] = input_id
event["turn_phase"] = "user" 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: 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 return event
@@ -958,75 +687,6 @@ def _session_backfill_turns(
return 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, ...]: def _transcript_turn_signature(records: list[dict[str, Any]]) -> tuple[str, ...]:
texts: list[str] = [] texts: list[str] = []
stream_parts: list[str] = [] stream_parts: list[str] = []
@@ -1135,7 +795,7 @@ def _recover_incomplete_turns(
session_turns: list[_SessionBackfillTurn], session_turns: list[_SessionBackfillTurn],
) -> list[dict[str, Any]]: ) -> list[dict[str, Any]]:
recovered: 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 turn_end = turn[-1] if turn else None
if ( if (
not isinstance(turn_end, dict) 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( 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) not any(record.get("event") == "user" or isinstance(record.get("response_input_ids"), list) for record in turn)
and _transcript_turn_signature(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 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]]: def _normalize_tool_events(events: Any) -> list[dict[str, Any]]:
if not isinstance(events, list): if not isinstance(events, list):
return [] return []
@@ -1281,28 +897,6 @@ def _media_from_signed_urls(value: Any) -> list[dict[str, Any]]:
return media 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( def has_pending_tool_calls(
lines: list[dict[str, Any]], lines: list[dict[str, Any]],
*, *,
@@ -1383,44 +977,18 @@ def build_webui_trace_detail_response(
*, history: HistoryReader, *, history: HistoryReader,
) -> dict[str, Any] | None: ) -> dict[str, Any] | None:
"""Resolve one deferred activity group as canonical projection events.""" """Resolve one deferred activity group as canonical projection events."""
match = _WEBUI_TRACE_DETAIL_REF_RE.fullmatch(detail_ref) identity = parse_trace_detail_ref(detail_ref)
if match is None: if identity is None:
return None return None
ordinal = int(match.group("turn")) ordinal, message_id = identity
message_id = match.group("message") turn = read_trace_turn(
turn = _transcript_turn_at_ordinal(ordinal, history=history) ordinal, history=history,
max_records=_MAX_TRANSCRIPT_PAGE_RECORDS, max_bytes=_MAX_TRANSCRIPT_PAGE_BYTES,
)
if turn is None: if turn is None:
return None return None
turn, _ = _compact_completed_stream_deltas(turn) lines, _ = compact_completed_stream_deltas(turn)
lines = _records_with_replay_identity(turn, turn_ordinal=ordinal) return _index_trace_projection(lines).detail(message_id)
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}"
def _client_projection_turn_fields(record: Mapping[str, Any]) -> dict[str, Any]: 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]: def _client_projection_common_fields(record: dict[str, Any]) -> dict[str, Any]:
fields: dict[str, Any] = { fields: dict[str, Any] = {
"chat_id": str(record.get("chat_id") or ""), "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), **_client_projection_turn_fields(record),
} }
created_at_ms = _valid_created_at_ms(record.get("created_at_ms")) 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 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( def _client_projection_event(
record: dict[str, Any], record: dict[str, Any],
*, *,
@@ -1546,8 +1136,6 @@ def _client_projection_event(
text = record.get("text") text = record.get("text")
content = text if isinstance(text, str) else "" content = text if isinstance(text, str) else ""
render_as_text = record.get("render_as") == "text" 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} projected = {"event": "message", **common, "text": content}
if render_as_text: if render_as_text:
projected["render_as"] = "text" projected["render_as"] = "text"
@@ -1557,21 +1145,9 @@ def _client_projection_event(
tool_events = _normalize_tool_events(record.get("tool_events")) tool_events = _normalize_tool_events(record.get("tool_events"))
if tool_events: if tool_events:
projected["tool_events"] = tool_events projected["tool_events"] = tool_events
raw_media = record.get("media") _augment_projected_message(
media_paths = [ record, projected, augment_media=augment_assistant_media, augment_text=augment_assistant_text,
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 []
) )
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") latency_ms = record.get("latency_ms")
if isinstance(latency_ms, int | float) and latency_ms >= 0: if isinstance(latency_ms, int | float) and latency_ms >= 0:
projected["latency_ms"] = int(latency_ms) projected["latency_ms"] = int(latency_ms)
@@ -1664,78 +1240,14 @@ def _client_projection_event(
return None return None
def _client_projection_deferred_trace_groups( def _project_trace_event(record: dict[str, Any]) -> dict[str, Any] | None:
lines: list[dict[str, Any]], return _client_projection_event(
) -> dict[int, _DeferredTraceGroup]: record, augment_user_media=None, augment_assistant_media=None, augment_assistant_text=None,
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 _client_projection_page_event_count(turn: list[dict[str, Any]]) -> int: def _index_trace_projection(lines: list[dict[str, Any]]) -> TraceProjection:
supported = { return index_trace_projection(lines, _project_trace_event, max_inline_bytes=_MAX_INLINE_TRACE_DETAIL_BYTES)
"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 _client_projection_events( def _client_projection_events(
@@ -1748,7 +1260,7 @@ def _client_projection_events(
) -> tuple[list[dict[str, Any]], int | None]: ) -> tuple[list[dict[str, Any]], int | None]:
events: list[dict[str, Any]] = [] events: list[dict[str, Any]] = []
fork_boundary_event_index: int | None = None 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 deferred_until = 0
for index, record in enumerate(lines): for index, record in enumerate(lines):
if index < deferred_until and record.get("event") != "model_request": 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: if fork_boundary_event_index is None:
fork_boundary_event_index = len(events) fork_boundary_event_index = len(events)
continue continue
event = _client_projection_event( cached = traces.events.get(index) if traces is not None else None
record, if cached is not None:
augment_user_media=augment_user_media, event = cached
augment_assistant_media=augment_assistant_media, _augment_projected_message(
augment_assistant_text=augment_assistant_text, 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: if event is None:
continue continue
group = deferred_groups.get(index) if traces is not None and (group := traces.groups.get(index)) is not None:
if group is not None: traces.summarize(lines, group, event)
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,
}
deferred_until = group.stop deferred_until = group.stop
events.append(event) events.append(event)
return events, fork_boundary_event_index 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"} "activity" if record["event"] == "file_edit" or record.get("kind") in {"progress", "tool_hint"}
else "answer", else "answer",
"created_at_ms": created_at_ms, "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) rows.append(record)
if not active and rows: if not active and rows:
rows.append({"event": "turn_end", "chat_id": chat_id, rows.append({"event": "turn_end", "chat_id": chat_id,
"turn_id": turn_id, "latency_ms": latency_ms, "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( events = [event for record in rows if (event := _client_projection_event(
record, augment_user_media=augment_user_media, augment_assistant_media=augment_assistant_media, record, augment_user_media=augment_user_media, augment_assistant_media=augment_assistant_media,
augment_assistant_text=augment_assistant_text, augment_assistant_text=augment_assistant_text,
@@ -1888,9 +1385,11 @@ def build_webui_thread_response(
) -> dict[str, Any] | None: ) -> dict[str, Any] | None:
"""Return canonical events, hiding additive request events from old clients.""" """Return canonical events, hiding additive request events from old clients."""
replay_stats = stats or TranscriptReplayStats() replay_stats = stats or TranscriptReplayStats()
lines, page = _select_transcript_page( lines, page = select_transcript_page(
history=history, history=history,
limit=limit, page_limit=_coerce_page_limit(limit),
max_records=_MAX_TRANSCRIPT_PAGE_RECORDS,
max_bytes=_MAX_TRANSCRIPT_PAGE_BYTES,
before=before, before=before,
after=after, after=after,
stats=replay_stats, stats=replay_stats,
@@ -1922,14 +1421,19 @@ def build_webui_thread_response(
) )
backfill_plan = view.backfill_plan backfill_plan = view.backfill_plan
recovered_lines: list[dict[str, Any]] = [] recovered_lines: list[dict[str, Any]] = []
for turn in _split_transcript_turns(lines): for turn in split_transcript_turns(lines):
ordinal = int(turn[0][_WEBUI_REPLAY_IDENTITY_KEY].split(":")[1]) 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, []): for anchor, user in backfill_plan.get(ordinal, []):
if record_range is not None and not record_range["start"] <= anchor < record_range["end"]: if record_range is not None and not record_range["start"] <= anchor < record_range["end"]:
continue continue
index = next((i for i, record in enumerate(turn) index = next((i for i, record in enumerate(turn)
if (identity := record.get(_WEBUI_REPLAY_IDENTITY_KEY, "")).startswith(f"turn:{ordinal}:record:") if (parsed := parse_replay_identity(record.get(WEBUI_REPLAY_IDENTITY_KEY))) is not None
and int(identity.rsplit(":", 1)[1]) >= anchor), len(turn)) and parsed[0] == ordinal
and parsed[1] >= anchor), len(turn))
turn.insert(index, dict(user)) turn.insert(index, dict(user))
recovered_lines.extend(turn) recovered_lines.extend(turn)
lines = recovered_lines lines = recovered_lines
@@ -1944,7 +1448,7 @@ def build_webui_thread_response(
incomplete = history.incomplete_completion_marker(ordinal, ref.record_count - 1) incomplete = history.incomplete_completion_marker(ordinal, ref.record_count - 1)
if incomplete and (position := history.unique_user_position(ordinal)) is not None: if incomplete and (position := history.unique_user_position(ordinal)) is not None:
identity = f"turn:{ordinal}:record:{position}" 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: if user is None:
records, _, _, _ = turn_record_page( records, _, _, _ = turn_record_page(
history, ordinal, start=position, end=position + 1, reverse=False, 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 and record.get("turn_id") in shell_turns else record
for record in lines for record in lines
] ]
lines = _ensure_replay_identities(lines) lines = ensure_replay_identities(lines)
payload: dict[str, Any] = { payload: dict[str, Any] = {
"schemaVersion": WEBUI_TRANSCRIPT_SCHEMA_VERSION, "schemaVersion": WEBUI_TRANSCRIPT_SCHEMA_VERSION,
"sessionKey": session_key, "sessionKey": session_key,
@@ -2073,12 +1577,12 @@ def _prompt_summary(
record: dict[str, Any], ordinal: int, answer: str, position: int = 0, record: dict[str, Any], ordinal: int, answer: str, position: int = 0,
) -> PromptSummary: ) -> PromptSummary:
return { return {
"id": _client_projection_event_id(record), "id": projection_event_id(record),
"inputId": str(record.get("input_id") or ""), "inputId": str(record.get("input_id") or ""),
"preview": str(record.get("text") or "").strip()[:320], "preview": str(record.get("text") or "").strip()[:320],
"answerPreview": answer, "answerPreview": answer,
"createdAt": _valid_created_at_ms(record.get("created_at_ms")) or 0, "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 ""), "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]]] = {} turns: dict[int, list[dict[str, Any]]] = {}
for ordinal, position, fact in history.navigation(): for ordinal, position, fact in history.navigation():
record = record_from_fact(fact, history.key) 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) turns.setdefault(ordinal, []).append(record)
if record.get("event") in {"message", "stream_end"} and not record.get("kind"): if record.get("event") in {"message", "stream_end"} and not record.get("kind"):
if isinstance(references := record.get("response_input_ids"), list): 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): for index, record in enumerate(records):
if record.get("event") != "user": if record.get("event") != "user":
continue 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") input_id = record.get("input_id")
if isinstance(input_id, str) and input_id: if isinstance(input_id, str) and input_id:
input_ids.add(input_id) input_ids.add(input_id)
@@ -2214,18 +1718,18 @@ def _build_prompt_view(
plan: dict[int, list[tuple[int, dict[str, Any]]]] = {} plan: dict[int, list[tuple[int, dict[str, Any]]]] = {}
for ordinal, records in chunk.turns.items(): for ordinal, records in chunk.turns.items():
users = backfilled_users.get(ordinal, []) 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: for user in users:
records = _with_backfilled_user(records, user) records = _with_backfilled_user(records, user)
next_anchor = 2**63 - 1 next_anchor = 2**63 - 1
reverse_plan: list[tuple[int, dict[str, Any]]] = [] reverse_plan: list[tuple[int, dict[str, Any]]] = []
for position in range(len(records) - 1, -1, -1): for position in range(len(records) - 1, -1, -1):
record = records[position] record = records[position]
identity = record.get(_WEBUI_REPLAY_IDENTITY_KEY, "") identity = record.get(WEBUI_REPLAY_IDENTITY_KEY, "")
if identity.startswith(f"turn:{ordinal}:record:"): if identity.startswith(f"turn:{ordinal}:record:"):
next_anchor = int(identity.rsplit(":", 1)[1]) next_anchor = int(identity.rsplit(":", 1)[1])
if record.get("event") == "user": if record.get("event") == "user":
event_id = _client_projection_event_id(record) event_id = projection_event_id(record)
order[(ordinal, event_id)] = position order[(ordinal, event_id)] = position
if event_id in recovered_ids: if event_id in recovered_ids:
anchor = next_anchor if any("response_input_ids" in item for item in records) else 0 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: for ordinal, prompt, user in entries:
if user is not None: if user is not None:
anchor = next(anchor for anchor, record in plan[ordinal] anchor = next(anchor for anchor, record in plan[ordinal]
if _client_projection_event_id(record) == prompt["id"]) if projection_event_id(record) == prompt["id"])
prompt["cursor"] = _encode_page_cursor(ordinal, anchor) prompt["cursor"] = encode_page_cursor(ordinal, anchor)
entries.sort(key=lambda entry: (entry[0], order.get((entry[0], entry[1]["id"]), 0))) 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) return _PromptView(tuple(prompt for _, prompt, _ in entries), plan, needs_canonical)
+402
View File
@@ -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
+209
View File
@@ -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<turn>\d{1,12})\.(?P<message>history-[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)
+267 -876
View File
File diff suppressed because it is too large. Load diff
+13 -15
View File
@@ -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") handler.tokens = SimpleNamespace(check_api_token=lambda request: request.headers.get("Authorization") == "Bearer valid")
router = WebUICommandRouter.__new__(WebUICommandRouter) router = WebUICommandRouter.__new__(WebUICommandRouter)
router._background_lock = asyncio.Lock() router._background_lock = asyncio.Lock()
router._background_references = set()
router._http_router = handler router._http_router = handler
router._uploads = SimpleNamespace(store=store, owner=lambda connection: connection) router._uploads = SimpleNamespace(store=store, owner=lambda connection: connection)
router.request_locks = {} 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") handler.tokens = SimpleNamespace(check_api_token=lambda request: request.headers.get("Authorization") == "Bearer valid")
router = WebUICommandRouter.__new__(WebUICommandRouter) router = WebUICommandRouter.__new__(WebUICommandRouter)
router._background_lock = asyncio.Lock() router._background_lock = asyncio.Lock()
router._background_references = set()
router._http_router = handler router._http_router = handler
router.request_locks = {} router.request_locks = {}
path = "/api/settings/background-style" path = "/api/settings/background-style"
@@ -173,8 +171,6 @@ async def test_background_worker_cancellation_survives_disconnect(tmp_path, monk
import asyncio import asyncio
import threading import threading
from nanobot.webui import background
store = AttachmentStore(tmp_path / "staging") store = AttachmentStore(tmp_path / "staging")
body = image_bytes() 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)) ref = await store.upload(chunks(), owner="alice", mime="image/png", size=len(body))
router = WebUICommandRouter.__new__(WebUICommandRouter) router = WebUICommandRouter.__new__(WebUICommandRouter)
router._background_lock = asyncio.Lock() router._background_lock = asyncio.Lock()
router._background_references = set()
router._http_router = SimpleNamespace(bus=MessageBus(), settings=SimpleNamespace( router._http_router = SimpleNamespace(bus=MessageBus(), settings=SimpleNamespace(
config=SimpleNamespace(path=tmp_path / "config.json"))) config=SimpleNamespace(path=tmp_path / "config.json")))
router._uploads = SimpleNamespace(store=store, owner=lambda connection: connection) router._uploads = SimpleNamespace(store=store, owner=lambda connection: connection)
router.request_locks = {} router.request_locks = {}
staged_path = store.inspect([ref], owner="alice")[0].path
started, release = threading.Event(), threading.Event() 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): def slow_read(path, mode="r", *args, **kwargs):
started.set() if path == staged_path and mode == "rb":
assert release.wait(5) assert threading.get_ident() != event_loop_thread
original(*args) 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})) task = asyncio.create_task(router.execute_webui_request("alice", "background.update", {"reference": ref}))
assert await asyncio.to_thread(started.wait, 3) 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") store.discard_owner("alice")
assert staged_path.exists()
task.cancel() task.cancel()
await asyncio.sleep(0) await asyncio.sleep(0)
assert not task.done() assert not task.done()
@@ -209,6 +209,7 @@ async def test_background_worker_cancellation_survives_disconnect(tmp_path, monk
with pytest.raises(asyncio.CancelledError): with pytest.raises(asyncio.CancelledError):
await task await task
assert (tmp_path / "webui" / "background.png").exists() 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): 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)) ref = await store.upload(chunks(), owner="alice", mime="image/png", size=len(body))
router = WebUICommandRouter.__new__(WebUICommandRouter) router = WebUICommandRouter.__new__(WebUICommandRouter)
router._background_lock = asyncio.Lock() router._background_lock = asyncio.Lock()
router._background_references = set()
router._http_router = SimpleNamespace(bus=MessageBus(), settings=SimpleNamespace( router._http_router = SimpleNamespace(bus=MessageBus(), settings=SimpleNamespace(
config=SimpleNamespace(path=tmp_path / "config.json"))) config=SimpleNamespace(path=tmp_path / "config.json")))
router._uploads = SimpleNamespace(store=store, owner=lambda connection: connection) 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 = WebUICommandRouter.__new__(WebUICommandRouter)
router._background_lock = asyncio.Lock() router._background_lock = asyncio.Lock()
router._background_references = set()
router._http_router = SimpleNamespace(bus=MessageBus(), settings=SimpleNamespace( router._http_router = SimpleNamespace(bus=MessageBus(), settings=SimpleNamespace(
config=SimpleNamespace(path=tmp_path / "config.json"))) config=SimpleNamespace(path=tmp_path / "config.json")))
router._uploads = SimpleNamespace(store=store, owner=lambda connection: connection) 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() bus = MessageBus()
router = WebUICommandRouter.__new__(WebUICommandRouter) router = WebUICommandRouter.__new__(WebUICommandRouter)
router._background_lock = asyncio.Lock() router._background_lock = asyncio.Lock()
router._background_references = set()
router._http_router = SimpleNamespace(bus=bus, settings=SimpleNamespace( router._http_router = SimpleNamespace(bus=bus, settings=SimpleNamespace(
config=SimpleNamespace(path=tmp_path / "config.json"))) config=SimpleNamespace(path=tmp_path / "config.json")))
router._uploads = SimpleNamespace(store=store, owner=lambda connection: connection) router._uploads = SimpleNamespace(store=store, owner=lambda connection: connection)
+4 -3
View File
@@ -10,16 +10,17 @@ from nanobot.webui.gateway_tokens import GatewayTokenStore
from nanobot.webui.ws_http import GatewayHTTPHandler 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 = object.__new__(GatewayHTTPHandler)
handler.config = WebSocketConfig(token_issue_secret="fixture-secret") handler.config = WebSocketConfig(token_issue_secret="fixture-secret")
handler.tokens = GatewayTokenStore(max_tokens=0) handler.tokens = GatewayTokenStore(max_tokens=0)
connection = SimpleNamespace(remote_address=("127.0.0.1", 10000)) connection = SimpleNamespace(remote_address=("127.0.0.1", 10000))
request = Request("/webui/terminal", Headers({"Host": "127.0.0.1:8765"})) 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" request.headers["X-Nanobot-Auth"] = "fixture-secret"
for _ in range(3): 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 response.status_code == 200
assert json.loads(response.body) == gateway_identity(handler.tokens.instance_id) assert json.loads(response.body) == gateway_identity(handler.tokens.instance_id)
assert "no-store" in response.headers["Cache-Control"] assert "no-store" in response.headers["Cache-Control"]
+55 -1
View File
@@ -10,7 +10,7 @@ from nanobot.bus.queue import MessageBus
from nanobot.channels.websocket.runtime import WebSocketConfig from nanobot.channels.websocket.runtime import WebSocketConfig
from nanobot.session.display_history import HistoryFact from nanobot.session.display_history import HistoryFact
from nanobot.session.history_graph import history_record_size 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.gateway_services import build_gateway_services
from nanobot.webui.history import fact_from_record 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]["completed_turn_ids"] == ["t"]
assert pages[-1]["has_pending_tool_calls"] is False assert pages[-1]["has_pending_tool_calls"] is False
assert history.read(key) == original 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]
+1
View File
@@ -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", {}) result = await gateway.http.dispatch_webui_mutation(connection, "remote.pick_file", {})
assert result.status_code == 403 assert result.status_code == 403
assert result.message == "remote_connections_local_only"
choose.assert_not_awaited() choose.assert_not_awaited()
+5 -8
View File
@@ -1,7 +1,6 @@
from __future__ import annotations from __future__ import annotations
import asyncio import asyncio
import json
import threading import threading
from pathlib import Path from pathlib import Path
from types import SimpleNamespace 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.session.model_selection import SESSION_MODEL_PRESET_METADATA_KEY
from nanobot.webui import settings_api from nanobot.webui import settings_api
from nanobot.webui.http_utils import http_json_response 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_routes import WebUISettingsRouter
from nanobot.webui.settings_services import WebUISettingsServices 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 prior.context_window_tokens == cached_preset.context_window_tokens == 100_000
assert (await admit("draft-only")).context_window_tokens == 100_000 assert (await admit("draft-only")).context_window_tokens == 100_000
path = "/api/settings/model-configurations/update" pending_save = asyncio.create_task(router.dispatch_mutation(
request = SimpleNamespace(path=path, headers=Headers()) None, Headers(), "settings.model_configuration.update", MutationParams(draft),
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))
assert await asyncio.to_thread(before_save.wait, 5) assert await asyncio.to_thread(before_save.wait, 5)
assert not pending_save.done() assert not pending_save.done()
assert disk_window() == 100_000 assert disk_window() == 100_000
@@ -117,7 +114,7 @@ async def test_model_save_commits_before_refreshing_next_session_admission(
allow_return.set() allow_return.set()
response = await asyncio.wait_for(pending_save, 5) 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 assert agent.runtime_resolver.runtime.context_window_tokens == 500_000
next_runtime = await admit("after-success") next_runtime = await admit("after-success")
next_preset = await admit("after-success-preset", explicit_preset=True) next_preset = await admit("after-success-preset", explicit_preset=True)
+53
View File
@@ -8,12 +8,14 @@ import pytest
from nanobot.config.schema import Config from nanobot.config.schema import Config
from nanobot.providers.registry import find_by_name from nanobot.providers.registry import find_by_name
from nanobot.webui.settings_contracts import MutationParams
from nanobot.webui.settings_models import ( from nanobot.webui.settings_models import (
WebUISettingsError, WebUISettingsError,
create_model_configuration, create_model_configuration,
model_settings_payload, model_settings_payload,
provider_models_payload, provider_models_payload,
update_agent_model_settings, update_agent_model_settings,
update_model_call_order,
update_model_configuration, update_model_configuration,
update_provider_settings, update_provider_settings,
) )
@@ -367,3 +369,54 @@ def test_known_reasoning_efforts_preserve_default_none_and_custom_roundtrips() -
if row["name"] == unknown) if row["name"] == unknown)
assert row["reasoning_effort"] == "future-effort" assert row["reasoning_effort"] == "future-effort"
assert row["reasoning_effort_values"] == ["", "low", "medium", "high"] 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
+89 -118
View File
@@ -20,7 +20,8 @@ from nanobot.config.schema import MCPServerConfig
from nanobot.runtime_admission import RuntimeBusyError from nanobot.runtime_admission import RuntimeBusyError
from nanobot.webui.http_utils import http_json_response from nanobot.webui.http_utils import http_json_response
from nanobot.webui.mcp_presets_api import custom_mcp_action 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 from nanobot.webui.settings_services import WebUISettingsServices
@@ -58,21 +59,27 @@ def _router(
) )
def _mutation_request(path: str, payload: dict[str, object]) -> SimpleNamespace: def _mutation_request(path: str, payload: dict[str, object]) -> tuple[str, MutationParams]:
request = SimpleNamespace(path=path, headers=Headers()) if path.startswith("/api/settings/channels/") and "/connect/" in path:
request._nanobot_webui_mutation_request = True _, channel, _, operation = path.rsplit("/", 3)
request._nanobot_webui_mutation_payload = payload return f"settings.channel.connect.{operation}", MutationParams({"channel": channel, **payload})
request._nanobot_trusted_proxy_authenticated = True action = _SETTINGS_ROUTES[path].mutation
return request 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" path = "/api/settings/sandbox/check"
router = _router(config_path=tmp_path / "config.json") router = _router(config_path=tmp_path / "config.json")
response = await router.dispatch(None, SimpleNamespace(path=path, headers=Headers()), path) response = await router.dispatch(None, SimpleNamespace(path=path, headers=Headers()), path)
assert response.status_code == 405 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() started, release = asyncio.Event(), asyncio.Event()
async def probe(config, workspace): 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"} return {"state": "passed", "reason": "", "launcher": "/usr/bin/bwrap", "revision": "test", "supported_backend": "bwrap"}
monkeypatch.setattr("nanobot.webui.settings_system.check_sandbox", probe) 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) await asyncio.wait_for(started.wait(), 2)
try: try:
assert (await router.dispatch(None, _mutation_request(path, {}), path)).status_code == 409 assert (await _mutate(router, _mutation_request(path, {}))).status_code == 409
finally: finally:
release.set() release.set()
assert (await first).status_code == 200 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 @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") router = _router(config_path=tmp_path / "config.json")
path = "/api/settings/nanobot-update/job/prepare" path = "/api/settings/nanobot-update/job/prepare"
request = SimpleNamespace(path=path, headers=Headers()) request = SimpleNamespace(path=path, headers=Headers())
response = await router.dispatch(None, request, path) response = await router.dispatch(None, request, path)
assert response.status_code == 405 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 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) 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 assert response.status_code == 400
router._runtime_surface = "native" 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 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 **_: {}) monkeypatch.setattr("nanobot.webui.settings_api.settings_payload", lambda **_: {})
path = "/api/settings/provider/oauth-login" 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 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): with pytest.raises(RuntimeBusyError), router.bus.admission.pause_if_idle(lambda: False):
pytest.fail("The authorization prompt still has a live worker") pytest.fail("The authorization prompt still has a live worker")
try: 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" "/api/settings/provider/oauth-logout" if finish == "logout"
else "/api/settings/provider/oauth-login/complete" 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", "provider": "github_copilot", "flow_id": payload["flow_id"], "cancel": "true",
}), path) }))
assert response.status_code == 200 assert response.status_code == 200
assert await asyncio.to_thread(stopping.wait, 1) assert await asyncio.to_thread(stopping.wait, 1)
assert router.settings.oauth_flows.get("github_copilot", payload["flow_id"]) is None 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) monkeypatch.setattr(oauth, "login_oauth_interactive", login)
path = "/api/settings/provider/oauth-login" path = "/api/settings/provider/oauth-login"
try: try:
response = await router.dispatch(None, _mutation_request(path, { response = await _mutate(router, _mutation_request(path, {
"provider": "openai_codex", "remote_browser": "true", "provider": "openai_codex", "remote_browser": "true",
}), path) }))
assert response.status_code == 502 assert response.status_code == 502
assert entered.is_set() assert entered.is_set()
with pytest.raises(RuntimeBusyError), router.bus.admission.pause_if_idle(lambda: False): 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( async def test_channel_setup_blocks_maintenance_until_confirmed_cleanup(
tmp_path, monkeypatch, close_fails, tmp_path, monkeypatch, close_fails,
) -> None: ) -> None:
router = _router(config_path=tmp_path / "config.json")
cleanup_started, allow_cleanup = asyncio.Event(), asyncio.Event() cleanup_started, allow_cleanup = asyncio.Event(), asyncio.Event()
class Connector: class Connector:
@@ -248,10 +251,11 @@ async def test_channel_setup_blocks_maintenance_until_confirmed_cleanup(
"nanobot.webui.settings_routes.load_channel_plugin", "nanobot.webui.settings_routes.load_channel_plugin",
lambda _: SimpleNamespace(load_connector=lambda: connector), lambda _: SimpleNamespace(load_connector=lambda: connector),
) )
router = _router(config_path=tmp_path / "config.json")
path = "/api/settings/channels/whatsapp/connect/start" 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 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): with pytest.raises(RuntimeBusyError), router.bus.admission.pause_if_idle(lambda: False):
pytest.fail("Returning a QR code does not finish its connection") pytest.fail("Returning a QR code does not finish its connection")
shutdown = asyncio.create_task(router.close()) shutdown = asyncio.create_task(router.close())
@@ -275,14 +279,14 @@ async def test_channel_setup_blocks_maintenance_until_confirmed_cleanup(
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_legacy_connector_can_connect_but_cannot_claim_maintenance_idle(tmp_path, monkeypatch): 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"})) connector = SimpleNamespace(handle=AsyncMock(return_value={"status": "pending"}))
monkeypatch.setattr( monkeypatch.setattr(
"nanobot.webui.settings_routes.load_channel_plugin", "nanobot.webui.settings_routes.load_channel_plugin",
lambda _: SimpleNamespace(load_connector=lambda: connector), lambda _: SimpleNamespace(load_connector=lambda: connector),
) )
router = _router(config_path=tmp_path / "config.json")
path = "/api/settings/channels/custom/connect/start" 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 assert response.status_code == 200
await router.close() await router.close()
with pytest.raises(RuntimeBusyError), router.bus.admission.pause_if_idle(lambda: False): 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) monkeypatch.setattr("nanobot.webui.mcp_oauth_api.connect_mcp_servers", connect)
router = _router(config_path=tmp_path / "config.json") router = _router(config_path=tmp_path / "config.json")
path = "/api/settings/mcp-oauth/start" 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 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): with pytest.raises(RuntimeBusyError), router.bus.admission.pause_if_idle(lambda: False):
pytest.fail("Settings returned, but authorization has not finished") 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 @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( config = SimpleNamespace(
type="streamableHttp", type="streamableHttp",
auth="oauth", auth="oauth",
@@ -501,11 +505,11 @@ async def test_mcp_oauth_start_uses_gateway_callback_and_requires_api_auth(monke
{"name": "xmind"}, {"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 is not None
assert response.status_code == 200 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( start.assert_awaited_once_with(
"xmind", "xmind",
config, config,
@@ -515,20 +519,15 @@ async def test_mcp_oauth_start_uses_gateway_callback_and_requires_api_auth(monke
reset_credentials=False, 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 = _router()
failed._mcp_oauth = SimpleNamespace( failed._mcp_oauth = SimpleNamespace(
start=AsyncMock(side_effect=RuntimeError("upstream secret response")) 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 is not None
assert failed_response.status_code == 500 assert failed_response.status_code == 500
assert json.loads(failed_response.body) == {"error": "MCP OAuth start failed"} assert failed_response.message == "MCP OAuth start failed"
assert b"upstream secret response" not in failed_response.body
@pytest.mark.asyncio @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}, {"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 is not None
assert response.status_code == 200 assert response.status_code == 200
assert json.loads(response.body)["status"] == "connecting" assert response.result["status"] == "connecting"
assert b"oauth-code" not in response.body assert "oauth-code" not in json.dumps(response.result)
submit.assert_called_once_with(flow_id="flow-123", callback_url=callback_url) 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( @pytest.mark.parametrize(
@@ -636,71 +627,58 @@ async def test_oauth_completion_reads_websocket_payload(
}, },
) )
response = await router.dispatch( response = await _mutate(router, request)
None,
request,
"/api/settings/provider/oauth-login/complete",
)
assert response is not None assert response is not None
assert response.status_code == 200 assert response.status_code == 200
assert json.loads(response.body) == { assert response.result == {
"status": "pending", "status": "pending",
"provider": provider, "provider": provider,
"flow_id": "flow-123", "flow_id": "flow-123",
} }
assert captured == { 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, "authorization_response": authorization_response,
} }
assert request.path == "/api/settings/provider/oauth-login/complete"
assert not request.headers
@pytest.mark.parametrize( @pytest.mark.parametrize(
("route_path", "function_name", "payload", "expected_query"), ("route_path", "function_name", "payload"),
[ [
( (
"/api/settings/update", "/api/settings/update",
"update_agent_settings", "update_agent_settings",
{"model_preset": "Codex"}, {"model_preset": "Codex"},
{"model_preset": ["Codex"]},
), ),
( (
"/api/settings/model-configurations/create", "/api/settings/model-configurations/create",
"create_model_configuration", "create_model_configuration",
{"name": "Codex", "model": "openai-codex/gpt-5.6"}, {"name": "Codex", "model": "openai-codex/gpt-5.6"},
{"name": ["Codex"], "model": ["openai-codex/gpt-5.6"]},
), ),
( (
"/api/settings/model-configurations/delete", "/api/settings/model-configurations/delete",
"delete_model_configuration", "delete_model_configuration",
{"name": "spare"}, {"name": "spare"},
{"name": ["spare"]},
), ),
( (
"/api/settings/model-configurations/migrate", "/api/settings/model-configurations/migrate",
"migrate_model_configurations", "migrate_model_configurations",
{}, {},
{},
), ),
( (
"/api/settings/model-call-order/update", "/api/settings/model-call-order/update",
"update_model_call_order", "update_model_call_order",
{"order": ["backup"]}, {"order": ["backup"]},
{"order": ['["backup"]']},
), ),
( (
"/api/settings/provider/create", "/api/settings/provider/create",
"create_provider_settings", "create_provider_settings",
{"name": "team", "api_base": "https://llm.example/v1"}, {"name": "team", "api_base": "https://llm.example/v1"},
{"name": ["team"], "api_base": ["https://llm.example/v1"]},
), ),
( (
"/api/settings/provider/update", "/api/settings/provider/update",
"update_provider_settings", "update_provider_settings",
{"provider": "team", "api_base": "https://llm.example/v2"}, {"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, route_path: str,
function_name: str, function_name: str,
payload: dict[str, object], payload: dict[str, object],
expected_query: dict[str, list[str]],
) -> None: ) -> None:
captured: dict[str, object] = {} captured: dict[str, object] = {}
refresh_runtime_config = MagicMock() 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) monkeypatch.setattr(f"nanobot.webui.settings_routes.{function_name}", mutate)
request = _mutation_request(route_path, payload) request = _mutation_request(route_path, payload)
response = await _router( response = await _mutate(_router(
refresh_runtime_config=refresh_runtime_config, refresh_runtime_config=refresh_runtime_config,
).dispatch(None, request, route_path) ), request)
assert response is not None assert response is not None
assert response.status_code == 200 assert response.status_code == 200
assert json.loads(response.body)["routed"] == function_name assert response.result["routed"] == function_name
assert captured["query"] == expected_query assert captured["query"] == MutationParams(payload)
refresh_runtime_config.assert_called_once_with() 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" path = "/api/settings/model-configurations/update"
request = _mutation_request(path, {"name": "openai", "new_name": "Codex"}) request = _mutation_request(path, {"name": "openai", "new_name": "Codex"})
response = await _router( response = await _mutate(_router(
rename_model_preset=rename_model_preset, rename_model_preset=rename_model_preset,
refresh_runtime_config=refresh_runtime_config, refresh_runtime_config=refresh_runtime_config,
).dispatch( ), request)
None,
request,
path,
)
assert response is not None assert response is not None
assert response.status_code == 200 assert response.status_code == 200
assert captured == { assert captured == {
"query": {"name": ["openai"], "new_name": ["Codex"]}, "query": MutationParams({"name": "openai", "new_name": "Codex"}),
"rename_model_preset": rename_model_preset, "rename_model_preset": rename_model_preset,
} }
refresh_runtime_config.assert_called_once_with() 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" path = "/api/settings/provider/update"
request = _mutation_request(path, {"provider": "openai", "apiType": "auto", "apiBase": "https://example.test/v1"}) 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 is not None
assert response.status_code == 400 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 assert config_path.read_text(encoding="utf-8") == before
refresh.assert_not_called() 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() 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 from nanobot.config.loader import load_config
path = "/api/settings/runtime-config/update" path = "/api/settings/runtime-config/update"
config_path = tmp_path / "config.json" config_path = tmp_path / "config.json"
request = _mutation_request(path, {"values": {"tools.exec.timeout": 19}}) 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) router = _router(config_path=config_path)
http_request = SimpleNamespace(path=path, headers=Headers()) http_request = SimpleNamespace(path=path, headers=Headers())
assert (await router.dispatch(None, http_request, path)).status_code == 405 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() 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 result.status_code == 200
assert load_config(config_path).tools.exec.timeout == 19 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["runtime_config"]["tools.exec.timeout"] == 19
assert body["restart_required_sections"] == ["runtime"] assert body["restart_required_sections"] == ["runtime"]
refreshed = await router.dispatch(None, SimpleNamespace(path="/api/settings", headers=Headers()), "/api/settings") 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() refresh = MagicMock()
router = _router(config_path=tmp_path / "config.json", refresh_runtime_config=refresh) router = _router(config_path=tmp_path / "config.json", refresh_runtime_config=refresh)
path = "/api/settings/runtime-config/update" 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}, "values": {"agents.defaults.dream.enabled": False, "gateway.port": 19001},
}), path) }))
assert response.status_code == 200 assert response.status_code == 200
assert json.loads(response.body)["requires_restart"] assert response.result["requires_restart"]
refresh.assert_not_called() 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" path = "/api/settings/runtime-config/update"
async def update(values): 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 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"] assert (await update({"agents.defaults.dream.enabled": not original_memory}))["requires_restart"]
await update({"tools.web.enable": not original_web}) 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_reader = config.tools.web.fetch.use_jina_reader
original_port = config.gateway.port original_port = config.gateway.port
path = "/api/settings/web-search/update" 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, "provider": "duckduckgo", "use_jina_reader": not original_reader,
}), path) }))
assert first.status_code == 200 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" 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}, "values": {"gateway.port": original_port + 1},
}), runtime_path) }))
assert changed.status_code == 200 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, "provider": "duckduckgo", "use_jina_reader": original_reader,
}), path) }))
assert restored.status_code == 200 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") refreshed = await router.dispatch(None, SimpleNamespace(path="/api/settings", headers=Headers()), "/api/settings")
assert json.loads(refreshed.body)["restart_required_sections"] == ["runtime"] 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}, "values": {"gateway.port": original_port},
}), runtime_path) }))
assert reverted.status_code == 200 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]) @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() router.logger.warning = MagicMock()
path = "/api/settings/image-generation/update" path = "/api/settings/image-generation/update"
changed = await router.dispatch(None, _mutation_request(path, {"enabled": not enabled}), path) changed = await _mutate(router, _mutation_request(path, {"enabled": not enabled}))
assert json.loads(changed.body)["requires_restart"] is True assert changed.result["requires_restart"] is True
reverted = await router.dispatch(None, _mutation_request(path, {"enabled": enabled}), path) reverted = await _mutate(router, _mutation_request(path, {"enabled": enabled}))
assert json.loads(reverted.body)["requires_restart"] is False assert reverted.result["requires_restart"] is False
assert json.loads(reverted.body)["restart_required_sections"] == [] assert reverted.result["restart_required_sections"] == []
@pytest.mark.asyncio @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", "/api/settings/mcp-oauth/start",
{"name": "xmind", "use_proxy": True}, {"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 is not None
assert response.status_code == 200 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"} 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()}, connection, "settings.mcp.proxy", {"name": "team-docs", "use_proxy": str(use_proxy).lower()},
) )
assert response.status_code == 200 assert response.status_code == 200
payload = json.loads(response.body) payload = response.result
assert payload["hot_reload"]["ok"] is True assert payload["hot_reload"]["ok"] is True
assert payload["requires_restart"] is False assert payload["requires_restart"] is False
row = next(row for row in payload["presets"] if row["name"] == "team-docs") row = next(row for row in payload["presets"] if row["name"] == "team-docs")
+1 -1
View File
@@ -765,7 +765,7 @@ async def test_webui_deletion_cancels_parent_work_and_removes_child_sessions(tmp
connection, "session.delete", {"key": "websocket:parent"}, connection, "session.delete", {"key": "websocket:parent"},
) )
assert response.status_code == 200 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") gateway.http.discard_session.assert_awaited_once_with("websocket:parent")
assert sessions.read_session_file("websocket:parent") is None assert sessions.read_session_file("websocket:parent") is None
assert sessions.read_session_file(child_key) is None assert sessions.read_session_file(child_key) is None
+4 -3
View File
@@ -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}, connection, "subagent.cancel", {"session_key": "websocket:a", "task_id": task_id},
) )
assert result.status_code == 404 assert result.status_code == 404
errors.append(result.body) errors.append(result.message)
assert errors[0] == errors[1] assert errors == ["task unavailable", "task unavailable"]
assert manager.check(foreign, "websocket:b").state == "running" assert manager.check(foreign, "websocket:b").state == "running"
for _ in range(2): 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}, connection, "subagent.cancel", {"session_key": "websocket:a", "task_id": first},
) )
assert result.status_code == 200 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(sibling, "websocket:a").state == "running"
assert manager.check(foreign, "websocket:b").state == "running" assert manager.check(foreign, "websocket:b").state == "running"
assert bus.inbound_size == 1 assert bus.inbound_size == 1
+44 -42
View File
@@ -60,8 +60,8 @@ async def test_channel_mutation_preserves_authority_and_invalidates_old_reviews(
assert response.status_code == 403 assert response.status_code == 403
assert read_update_channel().revision == 0 assert read_update_channel().revision == 0
response = await gateway.http.dispatch_webui_mutation(connection(local=True), CHANNEL, {"channel": "preview", "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 response.status_code == 200, response.message
assert json.loads(response.body) == {"channel": "preview", "revision": 1} assert response.result == {"channel": "preview", "revision": 1}
assert "webui.update-channels.v1" in webui_contract()["capabilities"] assert "webui.update-channels.v1" in webui_contract()["capabilities"]
reviewed = await fetch(gateway, READ + "?id=" + plan.id) reviewed = await fetch(gateway, READ + "?id=" + plan.id)
assert json.loads(reviewed.body)["plan"]["validity"] == "channel_changed" 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()) monkeypatch.setattr(update_plan, "ReleaseFeed", lambda _: Feed())
response = await gateway.http.dispatch_webui_mutation(connection(local=True), "settings.nanobot.update.plan", {"extras": []}) response = await gateway.http.dispatch_webui_mutation(connection(local=True), "settings.nanobot.update.plan", {"extras": []})
assert response.status_code == 200 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) assert (saved.channel, saved.channel_revision) == ("preview", 1)
race = True race = True
response = await gateway.http.dispatch_webui_mutation(connection(local=True), "settings.nanobot.update.plan", {"extras": []}) 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( response = await gateway.http.dispatch_webui_mutation(
connection(local=True), "settings.nanobot.update.plan", {"extras": []}, connection(local=True), "settings.nanobot.update.plan", {"extras": []},
) )
assert response.status_code == 200, response.body assert response.status_code == 200, response.message
return gateway, UpdatePlans(fixture.directory / "plans").load(json.loads(response.body)["plan"]["id"]) return gateway, UpdatePlans(fixture.directory / "plans").load(response.result["plan"]["id"])
async def execution_plan(fixture): 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" assert not operation.done(), "A lost requester cannot abandon a still-running launch thread"
fresh = fixture.gateway() fresh = fixture.gateway()
duplicate = await fresh.http.dispatch_webui_mutation(connection(local=True), EXECUTE, payload) duplicate = await fresh.http.dispatch_webui_mutation(connection(local=True), EXECUTE, payload)
assert duplicate.status_code == 200, duplicate.body assert duplicate.status_code == 200, duplicate.message
assert duplicate.headers["Cache-Control"] == "no-store" saved = duplicate.result["job"]
saved = json.loads(duplicate.body)["job"]
assert saved["execution_confirmation_id"] == confirmation.id assert saved["execution_confirmation_id"] == confirmation.id
assert saved["recorded_phase"] == "checking" and not saved["mutation_started"] assert saved["recorded_phase"] == "checking" and not saved["mutation_started"]
restored = await fetch(fresh, JOB + "?id=" + plan.id) restored = await fetch(fresh, JOB + "?id=" + plan.id)
assert restored.headers["Cache-Control"] == "no-store"
assert json.loads(restored.body)["job"] == saved assert json.loads(restored.body)["job"] == saved
finally: finally:
release.set() 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 (await gateway.http.dispatch_webui_mutation(connection(local=True), RETRY, bad)).status_code == 400
assert not calls assert not calls
first = await gateway.http.dispatch_webui_mutation(connection(local=True), RETRY, payload) first = await gateway.http.dispatch_webui_mutation(connection(local=True), RETRY, payload)
assert first.status_code == 200, first.body assert first.status_code == 200, first.message
assert first.headers["Cache-Control"] == "no-store" assert first.result["job"]["execution_confirmation_id"] == current.id
assert json.loads(first.body)["job"]["execution_confirmation_id"] == current.id
fresh = fixture.gateway() fresh = fixture.gateway()
for action, body in ((RETRY, payload), (EXECUTE, {"id": plan.id, "confirm_restart": True})): 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) 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 calls == [previous.id]
assert "webui.update-jobs.retry-handoff.v1" in webui_contract()["capabilities"] 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, response = await gateway.http.dispatch_webui_mutation(connection(local=True), RETRY,
{"id": plan.id, "previous_confirmation_id": previous.id, "confirm_restart": True}) {"id": plan.id, "previous_confirmation_id": previous.id, "confirm_restart": True})
assert response.status_code == 409 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 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 (await gateway.http.dispatch_webui_mutation(connection(), SETTLE, {"id": plan.id})).status_code == 403
assert calls == [] assert calls == []
response = await gateway.http.dispatch_webui_mutation(connection(local=True), SETTLE, {"id": plan.id}) response = await gateway.http.dispatch_webui_mutation(connection(local=True), SETTLE, {"id": plan.id})
assert response.status_code == 200, response.body assert response.status_code == 200, response.message
assert json.loads(response.body)["job"]["recorded_phase"] == "cancelled" assert response.result["job"]["recorded_phase"] == "cancelled"
assert json.loads(response.body)["job"]["execution_confirmation_id"] == previous.id assert response.result["job"]["execution_confirmation_id"] == previous.id
assert (await fetch(gateway, JOB + "?id=" + plan.id)).body == response.body restored = await fetch(gateway, JOB + "?id=" + plan.id)
assert json.loads(restored.body) == response.result
assert calls == [directory] assert calls == [directory]
assert "webui.update-jobs.settle-handoff.v1" in webui_contract()["capabilities"] 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) monkeypatch.setattr(update_service, "start_handoff", forbidden)
result = await gateway.http.dispatch_webui_mutation(connection(local=True), EXECUTE, result = await gateway.http.dispatch_webui_mutation(connection(local=True), EXECUTE,
{"id": plan.id, "confirm_restart": True}) {"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 assert ExecutionConfirmation.read(directory) is None
@@ -429,17 +430,18 @@ async def test_preparation_is_durable_idempotent_and_independent_of_browser(prep
close = None close = None
try: try:
response = await gateway.http.dispatch_webui_mutation(connection(local=True), PREPARE, {"id": plan.id}) response = await gateway.http.dispatch_webui_mutation(connection(local=True), PREPARE, {"id": plan.id})
assert response.status_code == 200, response.body assert response.status_code == 200, response.message
assert json.loads(response.body)["job"]["recorded_phase"] == "preparation_requested" assert response.result["job"]["recorded_phase"] == "preparation_requested"
assert response.headers["Cache-Control"] == "no-store"
directory = fixture.directory / "jobs" / plan.id directory = fixture.directory / "jobs" / plan.id
assert JobStatus.read(directory).phase == Phase.PREPARATION_REQUESTED assert JobStatus.read(directory).phase == Phase.PREPARATION_REQUESTED
await asyncio.wait_for(entered.wait(), 5) await asyncio.wait_for(entered.wait(), 5)
fresh = fixture.gateway() fresh = fixture.gateway()
duplicate = await fresh.http.dispatch_webui_mutation(connection(local=True), PREPARE, {"id": plan.id}) duplicate = await fresh.http.dispatch_webui_mutation(connection(local=True), PREPARE, {"id": plan.id})
assert duplicate.status_code == 200 assert duplicate.status_code == 200
assert json.loads(duplicate.body)["job"]["recorded_phase"] == "preparing" assert duplicate.result["job"]["recorded_phase"] == "preparing"
assert (await fetch(fresh, JOB + "?id=" + plan.id)).status_code == 200 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 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())}) other = plan.model_copy(update={"id": str(uuid4())})
UpdatePlans(fixture.directory / "plans").save(other) 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() await gateway.http.settings_routes.close()
duplicate = await fixture.gateway().http.dispatch_webui_mutation(connection(local=True), PREPARE, {"id": plan.id}) duplicate = await fixture.gateway().http.dispatch_webui_mutation(connection(local=True), PREPARE, {"id": plan.id})
assert duplicate.status_code == 200 assert duplicate.status_code == 200
assert json.loads(duplicate.body)["job"]["recorded_phase"] == "preparation_failed" assert duplicate.result["job"]["recorded_phase"] == "preparation_failed"
assert b"secret" not in duplicate.body assert "secret" not in json.dumps(duplicate.result)
directory = fixture.directory / "jobs" / plan.id directory = fixture.directory / "jobs" / plan.id
assert "secret" not in (directory / "status.json").read_text() assert "secret" not in (directory / "status.json").read_text()
assert targets == [plan.target] 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) monkeypatch.setattr(update_service.ReleaseFeed, "revalidate", forbidden)
restored = await gateway.http.dispatch_webui_mutation(connection(local=True), PREPARE, {"id": plan.id}) 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" lock = "prepare-native.lock" if phase == Phase.PREPARING else "preparation-controller.lock"
with file_access(fixture.directory / lock, exclusive=True): with file_access(fixture.directory / lock, exclusive=True):
blocked = await gateway.http.dispatch_webui_mutation(connection(local=True), SETTLE, {"id": plan.id}) blocked = await gateway.http.dispatch_webui_mutation(connection(local=True), SETTLE, {"id": plan.id})
assert blocked.status_code == 409 assert blocked.status_code == 409
assert JobStatus.read(directory).phase == phase assert JobStatus.read(directory).phase == phase
settled = await gateway.http.dispatch_webui_mutation(connection(local=True), SETTLE, {"id": plan.id}) settled = await gateway.http.dispatch_webui_mutation(connection(local=True), SETTLE, {"id": plan.id})
assert settled.status_code == 200, settled.body assert settled.status_code == 200, settled.message
assert json.loads(settled.body)["job"]["recorded_phase"] == "preparation_failed" assert settled.result["job"]["recorded_phase"] == "preparation_failed"
if phase == Phase.PREPARING: if phase == Phase.PREPARING:
assert PreparationProcess.load(directory).active is False assert PreparationProcess.load(directory).active is False
assert not (directory / "request.json").exists() assert not (directory / "request.json").exists()
duplicate = await fixture.gateway().http.dispatch_webui_mutation(connection(local=True), PREPARE, {"id": plan.id}) 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): 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( response = await gateway.http.dispatch_webui_mutation(
connection(), "settings.nanobot.update.plan", {"channel": "stable", "restart_running": True}, connection(), "settings.nanobot.update.plan", {"channel": "stable", "restart_running": True},
) )
assert response.status_code == 200, response.body assert response.status_code == 200, response.message
assert response.headers["Cache-Control"] == "no-store" payload = response.result
payload = json.loads(response.body)
review = payload["plan"] review = payload["plan"]
assert payload["installation_allowed"] is False assert payload["installation_allowed"] is False
assert payload["execution_available"] 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( response = await gateway.http.dispatch_webui_mutation(
connection(local=True), "settings.nanobot.update.plan", {"restart_running": True}, 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["installation_allowed"] is True
assert payload["execution_available"] is (os.name == "posix") assert payload["execution_available"] is (os.name == "posix")
assert payload["plan"]["extras"] == ["webui"] 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}, connection(local=True), "settings.nanobot.update.plan", {"restart_running": True},
) )
assert response.status_code == 200 assert response.status_code == 200
payload = json.loads(response.body) payload = response.result
assert payload["execution_available"] is False assert payload["execution_available"] is False
plan = UpdatePlans(fixture.directory / "plans").load(payload["plan"]["id"]) plan = UpdatePlans(fixture.directory / "plans").load(payload["plan"]["id"])
assert update_plan.inline_update_blocked_reason(plan) == "installation_owner" 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() gateway = fixture.gateway()
created = await gateway.http.dispatch_webui_mutation(connection(local=True), "settings.nanobot.update.plan", {}) created = await gateway.http.dispatch_webui_mutation(connection(local=True), "settings.nanobot.update.plan", {})
assert created.status_code == 200 assert created.status_code == 200
payload = json.loads(created.body) payload = created.result
assert payload["installation_allowed"] is True assert payload["installation_allowed"] is True
review = payload["plan"] review = payload["plan"]
assert not any(item["stop"] or item["restart"] for item in review["profiles"]) 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 fixture = review_gateway
gateway = fixture.gateway() gateway = fixture.gateway()
response = await gateway.http.dispatch_webui_mutation(connection(), "settings.nanobot.update.plan", {}) 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() now = time.time()
monkeypatch.setattr(update_plan.time, "time", lambda: now + 901) monkeypatch.setattr(update_plan.time, "time", lambda: now + 901)
response = await fetch(gateway, READ + "?id=" + review["id"]) 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) monkeypatch.setattr(update_plan, "inspect_installation", failed_probe)
failed = await fixture.gateway().http.dispatch_webui_mutation(connection(), "settings.nanobot.update.plan", {}) failed = await fixture.gateway().http.dispatch_webui_mutation(connection(), "settings.nanobot.update.plan", {})
assert failed.status_code == 409 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() 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", {}, connection(), "settings.nanobot.update.plan", {},
) )
assert response.status_code == 409 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 calls == 2
assert not (fixture.directory / "jobs").exists() 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 fixture = review_gateway
gateway = fixture.gateway() gateway = fixture.gateway()
response = await gateway.http.dispatch_webui_mutation(connection(), "settings.nanobot.update.plan", {}) 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(): def removed_python():
raise FileNotFoundError("/private/installation/bin/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 fixture = review_gateway
gateway = fixture.gateway() gateway = fixture.gateway()
response = await gateway.http.dispatch_webui_mutation(connection(), "settings.nanobot.update.plan", {}) 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) plan = UpdatePlans(fixture.directory / "plans").load(plan_id)
directory = fixture.directory / "jobs" / plan_id directory = fixture.directory / "jobs" / plan_id
directory.mkdir(parents=True) directory.mkdir(parents=True)
@@ -828,7 +830,7 @@ async def test_job_reads_reject_missing_foreign_and_corrupt_records(review_gatew
fixture = review_gateway fixture = review_gateway
gateway = fixture.gateway() gateway = fixture.gateway()
response = await gateway.http.dispatch_webui_mutation(connection(), "settings.nanobot.update.plan", {}) 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) plan = UpdatePlans(fixture.directory / "plans").load(plan_id)
monkeypatch.setattr(sys, "prefix", fixture.snapshot.environment) monkeypatch.setattr(sys, "prefix", fixture.snapshot.environment)
for query in ("", "?id=../../config", "?id=not-a-uuid"): 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() assert not (fixture.directory / "plans").exists()
else: else:
assert response.status_code == 200 assert response.status_code == 200
payload = json.loads(response.body) payload = response.result
assert payload["execution_available"] is False assert payload["execution_available"] is False
assert payload["plan"]["execution_blocked_reason"] == ( assert payload["plan"]["execution_blocked_reason"] == (
"external_restart" if os.name == "posix" else "installation_owner" "external_restart" if os.name == "posix" else "installation_owner"
+2 -10
View File
@@ -1,10 +1,6 @@
from __future__ import annotations from __future__ import annotations
from types import SimpleNamespace
from typing import cast
from websockets.datastructures import Headers from websockets.datastructures import Headers
from websockets.http11 import Request as WsRequest
from nanobot.channels.websocket.runtime import WebSocketConfig from nanobot.channels.websocket.runtime import WebSocketConfig
from nanobot.webui.ws_http import GatewayHTTPHandler from nanobot.webui.ws_http import GatewayHTTPHandler
@@ -16,14 +12,10 @@ def _handler(config: WebSocketConfig) -> GatewayHTTPHandler:
return handler 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: def test_mcp_oauth_callback_uses_configured_public_websocket_origin() -> None:
handler = _handler(WebSocketConfig(path="/ws", public_ws_url="wss://agent.example/ws")) 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" 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)) handler = _handler(WebSocketConfig(path="/ws", host="127.0.0.1", port=8765))
redirect_uri = handler._mcp_oauth_redirect_uri( 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" assert redirect_uri == "https://nanobot.example:9443/auth/mcp/callback"
+21 -440
View File
@@ -25,11 +25,21 @@ import { invalidateToolsCatalog } from "@/lib/tools-catalog-cache";
import type { SidebarDeleteItem } from "@/components/ChatList"; import type { SidebarDeleteItem } from "@/components/ChatList";
import type { SettingsSectionKey } from "@/components/settings/SettingsView"; import type { SettingsSectionKey } from "@/components/settings/SettingsView";
import { StartupShell } from "@/components/StartupShell"; import { StartupShell } from "@/components/StartupShell";
import { ComposerDraftStore, clearStoredComposerDrafts } from "@/lib/composer-draft"; import { ComposerDraftStore } from "@/lib/composer-draft";
import { activateReloadCache, clearReloadCache } from "@/lib/reload-cache";
import { webuiThreadCache } from "@/lib/webui-thread-cache";
import { ThreadVisibilityContext } from "@/hooks/useThreadVisibility"; import { ThreadVisibilityContext } from "@/hooks/useThreadVisibility";
import { isAppsSection, type SettingsExitGuard, type SettingsFocusTarget } from "@/components/settings/contracts"; 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 { PaneWorkbench } from "@/components/workbench/PaneWorkbench";
import { transitionSession } from "@/components/thread/session-transition"; import { transitionSession } from "@/components/thread/session-transition";
import { import {
@@ -52,6 +62,7 @@ import {
import { ToastProvider, useToast } from "@/components/ui/toast"; import { ToastProvider, useToast } from "@/components/ui/toast";
import { Sheet, SheetContent, SheetTitle } from "@/components/ui/sheet"; import { Sheet, SheetContent, SheetTitle } from "@/components/ui/sheet";
import { useLocalGateway } from "@/hooks/useLocalGateway";
import { useSessions } from "@/hooks/useSessions"; import { useSessions } from "@/hooks/useSessions";
import { useReconnectRuns } from "@/hooks/useReconnectRuns"; import { useReconnectRuns } from "@/hooks/useReconnectRuns";
import { useDeferredTitleRefresh } from "@/hooks/useDeferredTitleRefresh"; import { useDeferredTitleRefresh } from "@/hooks/useDeferredTitleRefresh";
@@ -63,18 +74,8 @@ import type { SendAttachment, SendOptions } from "@/hooks/useNanobotStream";
import { ThemeProvider, useTheme } from "@/hooks/useTheme"; import { ThemeProvider, useTheme } from "@/hooks/useTheme";
import { useReadingTypography } from "@/hooks/useReadingTypography"; import { useReadingTypography } from "@/hooks/useReadingTypography";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import {
BootstrapAuthRequiredError,
clearSavedSecret,
consumeUrlBootstrapSecret,
deriveWsUrl,
fetchBootstrap,
loadSavedSecret,
saveSecret,
} from "@/lib/bootstrap";
import { displayTitle, sortSessions } from "@/lib/chat-groups"; import { displayTitle, sortSessions } from "@/lib/chat-groups";
import { deriveTitle } from "@/lib/format"; import { deriveTitle } from "@/lib/format";
import { NanobotClient } from "@/lib/nanobot-client";
import { BrowserNotifications, useBrowserNotificationLifecycle } from "@/components/BrowserNotifications"; import { BrowserNotifications, useBrowserNotificationLifecycle } from "@/components/BrowserNotifications";
import { ThreadMessageCache } from "@/lib/thread-message-cache"; import { ThreadMessageCache } from "@/lib/thread-message-cache";
import { FilePreviewStore } from "@/hooks/useFilePreviewState"; import { FilePreviewStore } from "@/hooks/useFilePreviewState";
@@ -83,7 +84,6 @@ import { BackgroundProvider } from "@/providers/BackgroundProvider";
import { useVersionCheck } from "@/providers/VersionCheckProvider"; import { useVersionCheck } from "@/providers/VersionCheckProvider";
import { useUpdateFlow } from "@/providers/UpdateFlowProvider"; import { useUpdateFlow } from "@/providers/UpdateFlowProvider";
import type { import type {
BootstrapResponse,
ChatSummary, ChatSummary,
RuntimeSurface, RuntimeSurface,
SessionAutomationJob, SessionAutomationJob,
@@ -97,57 +97,20 @@ import { Input } from "@/components/ui/input";
import { Dialog, DialogContent, DialogDescription, DialogTitle, DialogTrigger } from "@/components/ui/dialog"; import { Dialog, DialogContent, DialogDescription, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { HoverHint } from "@/components/ui/hover-hint"; import { HoverHint } from "@/components/ui/hover-hint";
import { fetchSettings, fetchWorkspaces } from "@/lib/api"; import { fetchSettings, fetchWorkspaces } from "@/lib/api";
import { import { isNativeRuntime } from "@/lib/runtime";
createRuntimeHost,
isNativeRuntime,
toRuntimeSurface,
} from "@/lib/runtime";
import { projectNameFromPath, scopeWithAccessMode } from "@/lib/workspace"; import { projectNameFromPath, scopeWithAccessMode } from "@/lib/workspace";
import { import {
createTemporaryChatSession, createTemporaryChatSession,
deriveTemporaryChatTitle, deriveTemporaryChatTitle,
} from "@/lib/temporary-chat"; } 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 SIDEBAR_STORAGE_KEY = "nanobot-webui.sidebar";
const SESSION_UPDATES_STORAGE_KEY = "nanobot-webui.sidebar.session-updates.v1"; const SESSION_UPDATES_STORAGE_KEY = "nanobot-webui.sidebar.session-updates.v1";
const LEGACY_COMPLETED_RUNS_STORAGE_KEY = "nanobot-webui.sidebar.completed-runs.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 = 272;
const SIDEBAR_WIDTH_STORAGE_KEY = "nanobot-webui.sidebar.width"; const SIDEBAR_WIDTH_STORAGE_KEY = "nanobot-webui.sidebar.width";
const SIDEBAR_RAIL_WIDTH = 56; const SIDEBAR_RAIL_WIDTH = 56;
const MOBILE_SIDEBAR_WIDTH = `min(${SIDEBAR_WIDTH}px, calc(100vw - 0.75rem))`; 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 loadThreadShell = () => import("@/components/thread/ThreadShell");
const ThreadShell = lazy(() => loadThreadShell().then( const ThreadShell = lazy(() => loadThreadShell().then(
(module) => ({ default: module.ThreadShell }), (module) => ({ default: module.ThreadShell }),
@@ -170,214 +133,6 @@ const RenameDialog = lazy(async () => {
return { default: module.RenameDialog }; 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 }: { function AuthForm({ onSecret }: {
onSecret: (secret: string, onAuthRejected: () => void) => void; 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({ function HostChrome({
rightAction, rightAction,
}: { }: {
@@ -612,12 +361,8 @@ function HostChrome({
); );
} }
function resolveRuntimeSurface( function prefetchChat() {
surface: RuntimeSurface | null | undefined, if (readShellRoute().view === "chat") void loadThreadShell().catch(() => {});
fallback: RuntimeSurface,
): RuntimeSurface {
if (isNativeRuntime(surface)) return "native";
return surface ? toRuntimeSurface(surface) : fallback;
} }
export default function App() { export default function App() {
@@ -625,129 +370,7 @@ export default function App() {
useBrowserNotificationLifecycle(); useBrowserNotificationLifecycle();
useReadingTypography(); useReadingTypography();
const { t } = useTranslation(); const { t } = useTranslation();
const [state, setState] = useState<BootState>({ status: "loading" }); const { state, bootstrapWithSecret, changeModelName, logout, restartEngine } = useLocalGateway(prefetchChat);
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]);
if (state.status === "loading") { if (state.status === "loading") {
return <StartupShell />; return <StartupShell />;
@@ -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<string> => {
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 ( return (
<ClientProvider <ClientProvider
client={state.client} client={state.client}
@@ -823,9 +404,9 @@ export default function App() {
<BrowserNotifications client={state.client} /> <BrowserNotifications client={state.client} />
<BackgroundProvider><RemoteInstances><ToastProvider><Shell <BackgroundProvider><RemoteInstances><ToastProvider><Shell
runtimeSurface={state.runtimeSurface} runtimeSurface={state.runtimeSurface}
onModelNameChange={handleModelNameChange} onModelNameChange={changeModelName}
onLogout={handleLogout} onLogout={logout}
onNativeEngineRestart={handleNativeEngineRestart} onNativeEngineRestart={restartEngine}
/></ToastProvider></RemoteInstances></BackgroundProvider> /></ToastProvider></RemoteInstances></BackgroundProvider>
</ClientProvider> </ClientProvider>
); );
+5 -59
View File
@@ -32,6 +32,7 @@ import {
Unplug, Unplug,
X, X,
} from "lucide-react"; } from "lucide-react";
import { useSidebarGroupMotion } from "@/hooks/useSidebarGroupMotion";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { import {
@@ -342,9 +343,6 @@ export const ChatList = memo(function ChatList({
observer?.disconnect(); observer?.disconnect();
}; };
}, [hasListHeader, loading, sessions.length, temporarySessions.length]); }, [hasListHeader, loading, sessions.length, temporarySessions.length]);
const layoutRowRefs = useRef(new Map<string, HTMLElement>());
const pendingLayoutRectsRef = useRef<Map<string, DOMRect> | null>(null);
const layoutAnimationsRef = useRef(new Map<string, Animation>());
const [collapsedPaneGroups, setCollapsedPaneGroups] = useState<Set<string>>( const [collapsedPaneGroups, setCollapsedPaneGroups] = useState<Set<string>>(
readCollapsedPaneGroups, readCollapsedPaneGroups,
); );
@@ -551,19 +549,7 @@ export const ChatList = memo(function ChatList({
}); });
}, [loading, paneGroups]); }, [loading, paneGroups]);
const measureLayoutRows = useCallback(() => { const { registerRow, captureLayout } = useSidebarGroupMotion(collapsedGroups, collapsedPaneGroups);
const rects = new Map<string, DOMRect>();
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 togglePaneGroup = useCallback((key: string) => { const togglePaneGroup = useCallback((key: string) => {
captureLayout(); captureLayout();
@@ -581,43 +567,6 @@ export const ChatList = memo(function ChatList({
onToggleGroup(key); onToggleGroup(key);
}, [captureLayout, onToggleGroup]); }, [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) { if (initialLoading && sessions.length === 0 && temporarySessions.length === 0) {
return ( return (
<SkeletonStatus label={t("chat.loading")} className="px-2 py-1.5"> <SkeletonStatus label={t("chat.loading")} className="px-2 py-1.5">
@@ -796,8 +745,7 @@ export const ChatList = memo(function ChatList({
<div <div
ref={(element) => { ref={(element) => {
const key = `group:${group.id}`; const key = `group:${group.id}`;
if (element) layoutRowRefs.current.set(key, element); registerRow(key, element);
else layoutRowRefs.current.delete(key);
}} }}
data-sidebar-group-header={group.id} data-sidebar-group-header={group.id}
> >
@@ -866,8 +814,7 @@ export const ChatList = memo(function ChatList({
<li <li
key={s.key} key={s.key}
ref={(element) => { ref={(element) => {
if (element) layoutRowRefs.current.set(s.key, element); registerRow(s.key, element);
else layoutRowRefs.current.delete(s.key);
}} }}
data-sidebar-tab-group="true" data-sidebar-tab-group="true"
data-pane-group-collapsed={paneGroupCollapsed ? "true" : undefined} data-pane-group-collapsed={paneGroupCollapsed ? "true" : undefined}
@@ -1008,8 +955,7 @@ export const ChatList = memo(function ChatList({
<li <li
key={s.key} key={s.key}
ref={(element) => { ref={(element) => {
if (element) layoutRowRefs.current.set(s.key, element); registerRow(s.key, element);
else layoutRowRefs.current.delete(s.key);
}} }}
className="relative min-w-0" className="relative min-w-0"
> >
+3 -1
View File
@@ -6,6 +6,7 @@ import { floatingItemClassName, floatingItemFocusClassName, floatingSurfaceClass
import { useFloatingPortal } from "@/components/ui/floating-portal"; import { useFloatingPortal } from "@/components/ui/floating-portal";
import { useToast } from "@/components/ui/toast"; import { useToast } from "@/components/ui/toast";
import { copyTextToClipboard } from "@/lib/clipboard"; import { copyTextToClipboard } from "@/lib/clipboard";
import { useOverlaySurfaceRef } from "@/lib/dom-overlays";
import type { FileReferenceMetadata, FilePreviewPayload } from "@/lib/types"; import type { FileReferenceMetadata, FilePreviewPayload } from "@/lib/types";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
@@ -41,6 +42,7 @@ export function FileActions({
const [copyStatus, setCopyStatus] = useState<"copied" | "failed" | null>(null); const [copyStatus, setCopyStatus] = useState<"copied" | "failed" | null>(null);
const resolveMetadata = context?.resolveMetadata; const resolveMetadata = context?.resolveMetadata;
const portal = useFloatingPortal(); const portal = useFloatingPortal();
const surfaceRef = useOverlaySurfaceRef<HTMLDivElement>("overlay");
const point = useRef({ x: 0, y: 0 }); const point = useRef({ x: 0, y: 0 });
const anchor = useRef({ getBoundingClientRect: () => new DOMRect(point.current.x, point.current.y, 0, 0) }); const anchor = useRef({ getBoundingClientRect: () => new DOMRect(point.current.x, point.current.y, 0, 0) });
const opener = useRef<HTMLElement | null>(null); const opener = useRef<HTMLElement | null>(null);
@@ -112,7 +114,7 @@ export function FileActions({
{children} {children}
</span> </span>
<Menu.Portal container={portal ?? undefined}> <Menu.Portal container={portal ?? undefined}>
<Menu.Content aria-label={t("fileActions.menu", { name: path.split(/[\\/]/).pop() || path })} <Menu.Content ref={surfaceRef} aria-label={t("fileActions.menu", { name: path.split(/[\\/]/).pop() || path })}
align="start" sideOffset={4} collisionPadding={12} align="start" sideOffset={4} collisionPadding={12}
className={cn(floatingSurfaceClassName, floatingSurfaceMotionClassName, "min-w-40 origin-[var(--radix-popper-transform-origin)] rounded-control p-1 [&_[role=menuitem]]:py-1.5")} className={cn(floatingSurfaceClassName, floatingSurfaceMotionClassName, "min-w-40 origin-[var(--radix-popper-transform-origin)] rounded-control p-1 [&_[role=menuitem]]:py-1.5")}
onClick={(event) => event.stopPropagation()} onClick={(event) => event.stopPropagation()}
+3
View File
@@ -3,6 +3,7 @@ import * as DialogPrimitive from "@radix-ui/react-dialog";
import { ChevronLeft, ChevronRight, X } from "lucide-react"; import { ChevronLeft, ChevronRight, X } from "lucide-react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { useOverlaySurfaceRef } from "@/lib/dom-overlays";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import type { UIImage } from "@/lib/types"; import type { UIImage } from "@/lib/types";
import { ZoomableImage } from "@/components/ZoomableImage"; import { ZoomableImage } from "@/components/ZoomableImage";
@@ -38,6 +39,7 @@ export function ImageLightbox({
const total = images.length; const total = images.length;
const current = index !== null ? images[index] : null; const current = index !== null ? images[index] : null;
const opener = useRef<HTMLElement | null>(null); const opener = useRef<HTMLElement | null>(null);
const surfaceRef = useOverlaySurfaceRef<HTMLDivElement>("dialog");
const go = useCallback( const go = useCallback(
(delta: number) => { (delta: number) => {
@@ -93,6 +95,7 @@ export function ImageLightbox({
)} )}
/> />
<DialogPrimitive.Content <DialogPrimitive.Content
ref={surfaceRef}
aria-label={current.name ?? t("lightbox.title")} aria-label={current.name ?? t("lightbox.title")}
aria-describedby={undefined} aria-describedby={undefined}
onOpenAutoFocus={() => { opener.current = document.activeElement instanceof HTMLElement ? document.activeElement : null; }} onOpenAutoFocus={() => { opener.current = document.activeElement instanceof HTMLElement ? document.activeElement : null; }}
+4 -3
View File
@@ -1,5 +1,5 @@
import { surfaceFocusProps } from "@/lib/surface-focus"; 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 { SidebarPanel } from "@/components/ui/sidebar-panel";
import { PanelRightClose, X } from "lucide-react"; import { PanelRightClose, X } from "lucide-react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
@@ -11,7 +11,7 @@ import { cn } from "@/lib/utils";
import { sidePanelSurfaceClassName } from "@/components/ui/floating-surface"; import { sidePanelSurfaceClassName } from "@/components/ui/floating-surface";
/** One stable sidebar shell: switching targets never replays its opening animation. */ /** 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[]; tabs: PreviewTab[];
activeId: string; activeId: string;
width: number; width: number;
@@ -19,6 +19,7 @@ export function PreviewPane({ tabs, activeId, width, isClosing, onSelect, onClos
onSelect: (id: string) => void; onSelect: (id: string) => void;
onCloseTab: (id: string) => void; onCloseTab: (id: string) => void;
onClose: () => void; onClose: () => void;
panelRef?: Ref<HTMLElement>;
onResizeStart: (event: PointerEvent<HTMLButtonElement>) => void; onResizeStart: (event: PointerEvent<HTMLButtonElement>) => void;
children: ReactNode; children: ReactNode;
}) { }) {
@@ -46,7 +47,7 @@ export function PreviewPane({ tabs, activeId, width, isClosing, onSelect, onClos
onCloseTab(tab.id); 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"; 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 <SidebarPanel aria-label={t("previewTabs.title")} data-testid="preview-pane" data-file-preview-panel return <SidebarPanel ref={panelRef} aria-label={t("previewTabs.title")} data-testid="preview-pane" data-file-preview-panel
width={width} isClosing={isClosing} contentClassName={sidePanelSurfaceClassName} width={width} isClosing={isClosing} contentClassName={sidePanelSurfaceClassName}
header={<> header={<>
<div ref={tabList} role="tablist" aria-label={t("previewTabs.title")} className="min-w-0 flex-1 overflow-x-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden"> <div ref={tabList} role="tablist" aria-label={t("previewTabs.title")} className="min-w-0 flex-1 overflow-x-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
+3 -2
View File
@@ -2,6 +2,7 @@ import { useEffect, useRef, useState } from "react";
import { StarLinkView, StarPromptView } from "@/components/StarPromptView"; import { StarLinkView, StarPromptView } from "@/components/StarPromptView";
import { starPromptAction } from "@/lib/api"; import { starPromptAction } from "@/lib/api";
import { hasAnyDialogMounted } from "@/lib/dom-overlays";
import { useClient } from "@/providers/ClientProvider"; import { useClient } from "@/providers/ClientProvider";
export function StarLink({ onSaved, fullWidth = false }: { export function StarLink({ onSaved, fullWidth = false }: {
@@ -43,10 +44,10 @@ export function StarPrompt({ ready }: { ready: boolean }) {
if (status !== "open" || attempted.current) return; if (status !== "open" || attempted.current) return;
attempted.current = true; attempted.current = true;
if (interacted.current || document.visibilityState !== "visible" if (interacted.current || document.visibilityState !== "visible"
|| document.querySelector('[role="dialog"], [role="alertdialog"]')) return; || hasAnyDialogMounted()) return;
void starPromptAction(client, "claim").then(({ show }) => { void starPromptAction(client, "claim").then(({ show }) => {
if (cancelled || !show || interacted.current || document.visibilityState !== "visible" if (cancelled || !show || interacted.current || document.visibilityState !== "visible"
|| document.querySelector('[role="dialog"], [role="alertdialog"]')) return; || hasAnyDialogMounted()) return;
previousFocus.current = document.activeElement instanceof HTMLElement previousFocus.current = document.activeElement instanceof HTMLElement
? document.activeElement : null; ? document.activeElement : null;
setOpen(true); setOpen(true);
@@ -6,6 +6,7 @@ import { channelUiPresentation } from "@/channel-plugins/registry";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { floatingSurfaceElevationClassName } from "@/components/ui/floating-surface"; import { floatingSurfaceElevationClassName } from "@/components/ui/floating-surface";
import { useLogoFallback } from "@/hooks/useLogoFallback"; import { useLogoFallback } from "@/hooks/useLogoFallback";
import { useOverlaySurfaceRef } from "@/lib/dom-overlays";
import type { PairingRequestInfo } from "@/lib/types"; import type { PairingRequestInfo } from "@/lib/types";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
@@ -27,6 +28,7 @@ export function PairingCodePopup({
const { t } = useTranslation(); const { t } = useTranslation();
const [value, setValue] = useState(""); const [value, setValue] = useState("");
const attemptedCode = useRef<string | null>(null); const attemptedCode = useRef<string | null>(null);
const surfaceRef = useOverlaySurfaceRef<HTMLDivElement>("dialog");
const normalizedCode = normalizePairingCode(value); const normalizedCode = normalizePairingCode(value);
const matchedRequest = useMemo( const matchedRequest = useMemo(
() => requests.find((request) => request.code === normalizedCode) ?? null, () => requests.find((request) => request.code === normalizedCode) ?? null,
@@ -74,6 +76,7 @@ export function PairingCodePopup({
return ( return (
<div <div
ref={surfaceRef}
role="dialog" role="dialog"
aria-live="polite" aria-live="polite"
aria-label={t("app.pairing.title", { defaultValue: "Pair a chat user" })} aria-label={t("app.pairing.title", { defaultValue: "Pair a chat user" })}
@@ -12,6 +12,7 @@ import { useToast } from "@/components/ui/toast";
import { useClient } from "@/providers/ClientProvider"; import { useClient } from "@/providers/ClientProvider";
import { groupRemoteProfiles, isCompatibilityError, remoteAction, type RemoteInspection, type RemoteProfile } from "@/lib/remote-instances"; import { groupRemoteProfiles, isCompatibilityError, remoteAction, type RemoteInspection, type RemoteProfile } from "@/lib/remote-instances";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { hasOpenDialogSurface } from "@/lib/dom-overlays";
import { parseSSHAddress } from "@/lib/ssh-address"; import { parseSSHAddress } from "@/lib/ssh-address";
import { clearPairReturn, readPairReturn, subscribePairReturn } from "@/lib/remote-pair-return"; import { clearPairReturn, readPairReturn, subscribePairReturn } from "@/lib/remote-pair-return";
import { useRemoteConnections } from "./remote-context"; import { useRemoteConnections } from "./remote-context";
@@ -197,7 +198,7 @@ export function RemoteConnectionsPage({ mainNavigationExpanded = false, hostChro
if (reason instanceof Error && reason.message === "same_instance" && showToast if (reason instanceof Error && reason.message === "same_instance" && showToast
&& !editorOpen && !fingerprint && !detailsOpen && page.current && !editorOpen && !fingerprint && !detailsOpen && page.current
&& !page.current.closest("[hidden], [inert], [aria-hidden='true']") && !page.current.closest("[hidden], [inert], [aria-hidden='true']")
&& !document.querySelector(":is([role='dialog'], [role='alertdialog']):not([data-state='closed'])")) { && !hasOpenDialogSurface()) {
showToast({ message: t("remote.errors.same_instance"), tone: "error", dedupeKey: "remote-same-instance" }); showToast({ message: t("remote.errors.same_instance"), tone: "error", dedupeKey: "remote-same-instance" });
return; return;
} }
@@ -1,4 +1,4 @@
import { useEffect, useId, useRef, useState, type KeyboardEvent, type ReactNode } from "react"; import { useEffect, useId, useRef, useState, type KeyboardEvent, type ReactNode, type Ref } from "react";
import { createPortal } from "react-dom"; import { createPortal } from "react-dom";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip"; import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
@@ -30,6 +30,7 @@ export function ComposerUsagePopover({
showLabel = false, showLabel = false,
compactLabel = false, compactLabel = false,
sidebarHost, sidebarHost,
sidebarRef,
sessionKey, sessionKey,
children, children,
open: controlledOpen, open: controlledOpen,
@@ -42,6 +43,7 @@ export function ComposerUsagePopover({
showLabel?: boolean; showLabel?: boolean;
compactLabel?: boolean; compactLabel?: boolean;
sidebarHost?: HTMLElement | null; sidebarHost?: HTMLElement | null;
sidebarRef?: Ref<HTMLElement>;
sessionKey?: string | null; sessionKey?: string | null;
children?: (renderControl: ComposerUsageControl | undefined) => ReactNode; children?: (renderControl: ComposerUsageControl | undefined) => ReactNode;
open?: boolean; open?: boolean;
@@ -196,7 +198,7 @@ export function ComposerUsagePopover({
<DialogTitle className="sr-only">{t("thread.composer.context.panelTitle")}</DialogTitle> <DialogTitle className="sr-only">{t("thread.composer.context.panelTitle")}</DialogTitle>
{inspector} {inspector}
</DialogContent> </DialogContent>
</Dialog> : createPortal(<SidebarPanel open={open} width={420} floating={!sidebarHost} id={panelId} </Dialog> : createPortal(<SidebarPanel ref={sidebarRef} open={open} width={420} floating={!sidebarHost} id={panelId}
aria-label={t("thread.composer.context.panelTitle")} data-testid="context-sidebar" onKeyDown={onPanelKeyDown}> aria-label={t("thread.composer.context.panelTitle")} data-testid="context-sidebar" onKeyDown={onPanelKeyDown}>
{inspector} {inspector}
</SidebarPanel>, sidebarHost ?? document.body))} </SidebarPanel>, sidebarHost ?? document.body))}
@@ -14,6 +14,7 @@ import {
import { fmtDateTime } from "@/lib/format-time"; import { fmtDateTime } from "@/lib/format-time";
import type { UIMessage } from "@/lib/types"; import type { UIMessage } from "@/lib/types";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { hasOpenDialogSurface } from "@/lib/dom-overlays";
interface PromptNavigatorProps { interface PromptNavigatorProps {
messages: UIMessage[]; messages: UIMessage[];
@@ -45,7 +46,7 @@ export function PromptNavigator({
const keyDown = (event: KeyboardEvent) => { const keyDown = (event: KeyboardEvent) => {
if (!shortcutEnabled || !prompts.length || event.defaultPrevented || event.repeat || event.isComposing if (!shortcutEnabled || !prompts.length || event.defaultPrevented || event.repeat || event.isComposing
|| event.altKey || event.shiftKey || !(event.ctrlKey || event.metaKey) || event.key.toLowerCase() !== "f") return; || 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(); event.preventDefault();
setListTop(0); setOpen(true); setListTop(0); setOpen(true);
inputRef.current?.focus(); inputRef.current?.select(); inputRef.current?.focus(); inputRef.current?.select();
+25 -118
View File
@@ -110,7 +110,7 @@ import { useComposerMentionInput } from "@/hooks/useComposerMentionInput";
import { useLogoFallback } from "@/hooks/useLogoFallback"; import { useLogoFallback } from "@/hooks/useLogoFallback";
import { useMediaQuery } from "@/hooks/useMediaQuery"; import { useMediaQuery } from "@/hooks/useMediaQuery";
import type { SendAttachment, SendOptions } from "@/hooks/useNanobotStream"; import type { SendAttachment, SendOptions } from "@/hooks/useNanobotStream";
import { useVoiceRecorder, type VoiceRecorderErrorKey } from "@/hooks/useVoiceRecorder"; import { useComposerVoiceInput } from "@/hooks/useComposerVoiceInput";
import type { import type {
CliAppInfo, CliAppInfo,
ChatSummary, ChatSummary,
@@ -144,6 +144,7 @@ import {
readDraggedSession, readDraggedSession,
} from "@/lib/session-drag"; } from "@/lib/session-drag";
import { formatQuotedUserMessage } from "@/lib/user-message-quote"; import { formatQuotedUserMessage } from "@/lib/user-message-quote";
import { useOverlaySurfaceRef } from "@/lib/dom-overlays";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import type { ComposerDraft, ComposerDraftStore } from "@/lib/composer-draft"; import type { ComposerDraft, ComposerDraftStore } from "@/lib/composer-draft";
import { useLocalPreferences } from "@/hooks/useLocalPreferences"; import { useLocalPreferences } from "@/hooks/useLocalPreferences";
@@ -155,10 +156,6 @@ import {
type QueuedPromptContent, type QueuedPromptContent,
} from "@/components/thread/useQueuedPrompt"; } 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 { function formatBytes(n: number): string {
if (n < 1024) return `${n} B`; if (n < 1024) return `${n} B`;
if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KiB`; 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; 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 { interface ThreadComposerProps {
onSend: ( onSend: (
content: string, content: string,
@@ -631,7 +580,6 @@ export function ThreadComposer({
end: number; end: number;
} | null>(null); } | null>(null);
const [inlineError, setInlineError] = useState<string | null>(null); const [inlineError, setInlineError] = useState<string | null>(null);
const [voiceSetupError, setVoiceSetupError] = useState<VoiceRecorderErrorKey | null>(null);
const showToast = useToast(); const showToast = useToast();
const [sendPending, setSendPending] = useState(false); const [sendPending, setSendPending] = useState(false);
const [pathInspection, setPathInspection] = useState<{ const [pathInspection, setPathInspection] = useState<{
@@ -797,9 +745,7 @@ export function ThreadComposer({
const fileInputRef = useRef<HTMLInputElement>(null); const fileInputRef = useRef<HTMLInputElement>(null);
const chipRefs = useRef(new Map<string, HTMLButtonElement>()); const chipRefs = useRef(new Map<string, HTMLButtonElement>());
const previousPendingQueueKeyRef = useRef(pendingQueueKey); const previousPendingQueueKeyRef = useRef(pendingQueueKey);
const voiceShortcutDownRef = useRef(false);
const isHero = variant === "hero"; const isHero = variant === "hero";
const voiceShortcutLabel = useMemo(getVoiceShortcutLabel, []);
const projectPickerAvailable = const projectPickerAvailable =
!workspaceProjectLocked !workspaceProjectLocked
&& !!workspaceDefaultScope && !!workspaceDefaultScope
@@ -1428,19 +1374,6 @@ export function ThreadComposer({
measureDraft(); measureDraft();
}, [readingTextSize, customReadingTextSize, 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 appendTranscription = useCallback((text: string) => {
const transcript = text.trim(); const transcript = text.trim();
if (!transcript) return; if (!transcript) return;
@@ -1454,56 +1387,26 @@ export function ThreadComposer({
focusTextarea(); focusTextarea();
}, [focusTextarea]); }, [focusTextarea]);
const clearVoiceSetupError = useCallback(() => setVoiceSetupError(null), []); const {
const setVoiceError = useCallback((key: VoiceRecorderErrorKey) => { recorder: voiceRecorder, setupError: voiceSetupError, clearSetupError,
// Setup blockers carry instructions users may need to keep in view while fixing them. shortcutLabel: voiceShortcutLabel, shortcutAria, canSendQueuedPrompt,
if (key === "insecureContext" || key === "permission" || key === "notConfigured") { } = useComposerVoiceInput({
setVoiceSetupError(key); disabled: interactionDisabled, onTranscribeAudio, onTranscript: appendTranscription,
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,
wantsWav: transcriptionProvider === "xiaomi_mimo", wantsWav: transcriptionProvider === "xiaomi_mimo",
}); });
useEffect(() => { // Runs before paint so switching sessions never flashes stale draft text.
if (!onTranscribeAudio) return; useLayoutEffect(() => {
if (previousPendingQueueKeyRef.current === pendingQueueKey) return;
function onKeyDown(event: KeyboardEvent): void { previousPendingQueueKeyRef.current = pendingQueueKey;
if (!isVoiceShortcutDown(event) || event.repeat || voiceShortcutDownRef.current) return; setValue("");
event.preventDefault(); setInlineError(null);
voiceShortcutDownRef.current = true; clearSetupError();
voiceRecorder.beginShortcutHold(); setSlashMenuDismissed(false);
} setCliAppMenuDismissed(false);
setCursorPosition(0);
function onKeyUp(event: KeyboardEvent): void { clear();
if (!voiceShortcutDownRef.current || !isVoiceShortcutRelease(event)) return; }, [clear, clearSetupError, pendingQueueKey]);
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]);
const handleStop = useCallback(() => { const handleStop = useCallback(() => {
pauseQueue(); pauseQueue();
@@ -1890,7 +1793,7 @@ export function ThreadComposer({
&& !e.ctrlKey && !e.ctrlKey
&& !e.metaKey && !e.metaKey
) { ) {
if (!e.repeat && voiceRecorder.state === "idle" && !voiceShortcutDownRef.current) { if (!e.repeat && canSendQueuedPrompt()) {
sendQueuedPrompt(queuedPrompt); sendQueuedPrompt(queuedPrompt);
} }
return; return;
@@ -2371,7 +2274,7 @@ export function ThreadComposer({
? t("thread.composer.configureModel", { defaultValue: "Configure model" }) ? t("thread.composer.configureModel", { defaultValue: "Configure model" })
: isUserShell ? t("thread.composer.shell.run") : t("thread.composer.send") : 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} onPointerDown={showVoiceButton ? voiceRecorder.beginPress : undefined}
onPointerUp={showVoiceButton ? voiceRecorder.endPress : undefined} onPointerUp={showVoiceButton ? voiceRecorder.endPress : undefined}
onPointerCancel={showVoiceButton ? voiceRecorder.endPress : undefined} onPointerCancel={showVoiceButton ? voiceRecorder.endPress : undefined}
@@ -2653,6 +2556,7 @@ function CliAppMentionPalette({
layout.maxHeight - SLASH_PALETTE_CHROME_PX, layout.maxHeight - SLASH_PALETTE_CHROME_PX,
); );
const listRef = useSelectedOptionScroll(selectedIndex); const listRef = useSelectedOptionScroll(selectedIndex);
const surfaceRef = useOverlaySurfaceRef<HTMLDivElement>("overlay");
const groupedCandidates = (["session", "cli", "mcp"] as const) const groupedCandidates = (["session", "cli", "mcp"] as const)
.map((kind) => ({ .map((kind) => ({
kind, kind,
@@ -2668,6 +2572,7 @@ function CliAppMentionPalette({
.filter((group) => group.items.length > 0); .filter((group) => group.items.length > 0);
return ( return (
<div <div
ref={surfaceRef}
role="listbox" role="listbox"
aria-label={t("thread.composer.mentions.ariaLabel")} aria-label={t("thread.composer.mentions.ariaLabel")}
style={{ maxHeight: layout.maxHeight }} style={{ maxHeight: layout.maxHeight }}
@@ -2817,8 +2722,10 @@ function SlashCommandPalette({
layout.maxHeight - SLASH_PALETTE_CHROME_PX, layout.maxHeight - SLASH_PALETTE_CHROME_PX,
); );
const listRef = useSelectedOptionScroll(selectedIndex); const listRef = useSelectedOptionScroll(selectedIndex);
const surfaceRef = useOverlaySurfaceRef<HTMLDivElement>("overlay");
return ( return (
<div <div
ref={surfaceRef}
role="listbox" role="listbox"
aria-label={t("thread.composer.slash.ariaLabel")} aria-label={t("thread.composer.slash.ariaLabel")}
style={{ maxHeight: layout.maxHeight }} style={{ maxHeight: layout.maxHeight }}
+25 -20
View File
@@ -8,6 +8,7 @@ import {
completedActivityDurationMs, completedActivityDurationMs,
formatActivityDuration, formatActivityDuration,
} from "@/components/thread/AgentActivityCluster"; } from "@/components/thread/AgentActivityCluster";
import { sameHistoryRowIdentity, type HistoryRowIdentity, type HistoryRowSource } from "@/components/thread/history-row-identity";
import { AssistantSelectionAction } from "@/components/thread/AssistantSelectionAction"; import { AssistantSelectionAction } from "@/components/thread/AssistantSelectionAction";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"; import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Dialog, DialogContent, DialogTitle, DialogTrigger } from "@/components/ui/dialog"; import { Dialog, DialogContent, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
@@ -22,6 +23,7 @@ import { cn } from "@/lib/utils";
import type { CliAppInfo, McpPresetInfo, RetryStatus, SlashCommand, UIMessage } from "@/lib/types"; import type { CliAppInfo, McpPresetInfo, RetryStatus, SlashCommand, UIMessage } from "@/lib/types";
interface ThreadMessagesProps { interface ThreadMessagesProps {
historyRows?: WeakMap<HTMLElement, HistoryRowIdentity>;
messages: UIMessage[]; messages: UIMessage[];
beforeMessages?: ReactNode; beforeMessages?: ReactNode;
beforeUnit?: { key: string; content: ReactNode }; beforeUnit?: { key: string; content: ReactNode };
@@ -82,6 +84,7 @@ export function assistantForkFlags(units: DisplayUnit[]): boolean[] {
} }
export function ThreadMessages({ export function ThreadMessages({
historyRows,
messages, messages,
beforeMessages, beforeMessages,
beforeUnit, beforeUnit,
@@ -257,6 +260,7 @@ export function ThreadMessages({
key={unitKeys[index]} key={unitKeys[index]}
unitKey={unitKeys[index]} unitKey={unitKeys[index]}
scrollAnchor={scrollAnchors[index]} scrollAnchor={scrollAnchors[index]}
historyRows={historyRows}
unit={unit} unit={unit}
mobileActions={mobileActions} mobileActions={mobileActions}
marginTop={prelude ? "" : marginTop} marginTop={prelude ? "" : marginTop}
@@ -370,7 +374,8 @@ function pendingTurnProjection(
interface ThreadDisplayUnitProps { interface ThreadDisplayUnitProps {
mobileActions: boolean; mobileActions: boolean;
unitKey: string; unitKey: string;
scrollAnchor: ScrollAnchorIdentity; scrollAnchor: HistoryRowIdentity;
historyRows?: WeakMap<HTMLElement, HistoryRowIdentity>;
unit: DisplayUnit; unit: DisplayUnit;
marginTop: string; marginTop: string;
userPromptId?: string; userPromptId?: string;
@@ -574,6 +579,7 @@ const ThreadDisplayUnit = memo(function ThreadDisplayUnit({
mobileActions, mobileActions,
unitKey, unitKey,
scrollAnchor, scrollAnchor,
historyRows,
unit, unit,
marginTop, marginTop,
userPromptId, userPromptId,
@@ -607,6 +613,12 @@ const ThreadDisplayUnit = memo(function ThreadDisplayUnit({
}: ThreadDisplayUnitProps) { }: ThreadDisplayUnitProps) {
const { t } = useTranslation(); const { t } = useTranslation();
const elementRef = useRef<HTMLDivElement>(null); const elementRef = useRef<HTMLDivElement>(null);
useLayoutEffect(() => {
const element = elementRef.current;
if (!element || !historyRows) return;
historyRows.set(element, scrollAnchor);
return () => { historyRows.delete(element); };
}, [historyRows, scrollAnchor]);
const activityDetailsId = useId(); const activityDetailsId = useId();
const heightRef = useRef(0); const heightRef = useRef(0);
const [nearViewport, setNearViewport] = useState(true); const [nearViewport, setNearViewport] = useState(true);
@@ -699,8 +711,6 @@ const ThreadDisplayUnit = memo(function ThreadDisplayUnit({
onContextBlockActiveChange(contextBlockKey ?? null); onContextBlockActiveChange(contextBlockKey ?? null);
}} }}
data-thread-display-unit={unitKey} data-thread-display-unit={unitKey}
data-thread-scroll-sources={scrollAnchor.sources}
data-thread-scroll-fallback={scrollAnchor.fallback}
data-user-prompt-id={userPromptId} data-user-prompt-id={userPromptId}
data-message-context-block={contextBlockKey} data-message-context-block={contextBlockKey}
data-context-block-active={contextBlockActive || undefined} data-context-block-active={contextBlockActive || undefined}
@@ -793,8 +803,8 @@ function threadDisplayUnitPropsEqual(
): boolean { ): boolean {
return ( return (
displayUnitsEqual(previous.unit, next.unit) displayUnitsEqual(previous.unit, next.unit)
&& previous.scrollAnchor.sources === next.scrollAnchor.sources && previous.historyRows === next.historyRows
&& previous.scrollAnchor.fallback === next.scrollAnchor.fallback && sameHistoryRowIdentity(previous.scrollAnchor, next.scrollAnchor)
&& previous.mobileActions === next.mobileActions && previous.mobileActions === next.mobileActions
&& previous.marginTop === next.marginTop && previous.marginTop === next.marginTop
&& previous.userPromptId === next.userPromptId && previous.userPromptId === next.userPromptId
@@ -956,39 +966,34 @@ export function unitKeysForDisplay(units: DisplayUnit[]): string[] {
}); });
} }
interface ScrollAnchorIdentity { function scrollAnchorsForUnits(units: DisplayUnit[]): HistoryRowIdentity[] {
sources: string;
fallback?: string;
}
function scrollAnchorsForUnits(units: DisplayUnit[]): ScrollAnchorIdentity[] {
const sourceKeys = units.map((unit) => { const sourceKeys = units.map((unit) => {
const messages = unit.type === "message" ? [unit.message] : unit.messages; const messages = unit.type === "message" ? [unit.message] : unit.messages;
// Either edge of an activity cluster can survive when the other grows. // 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 edges = messages.length > 1 ? [messages[0], messages[messages.length - 1]] : messages;
const streams: string[] = []; const streams: HistoryRowSource[] = [];
const sequences: string[] = []; const sequences: HistoryRowSource[] = [];
const ids: string[] = []; const ids: HistoryRowSource[] = [];
for (const message of edges) { for (const message of edges) {
const stream = unit.type === "message" ? message.streamId : message.reasoningStreamId; 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; const sequence = message.projectionStartSeq ?? message.turnSeq;
if (message.turnId && Number.isFinite(sequence)) { 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<string, number>(); const sourceCounts = new Map<string, number>();
const bases = units.map(unitKeyBase); const bases = units.map(unitKeyBase);
const baseCounts = new Map<string, number>(); const baseCounts = new Map<string, number>();
for (const sources of sourceKeys) for (const source of sources) { 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); for (const base of bases) baseCounts.set(base, (baseCounts.get(base) ?? 0) + 1);
return sourceKeys.map((sources, index) => ({ 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 // A sole turn/phase row can keep its live identity when replay replaces
// both its source id and sequence. Occurrence keys are unsafe otherwise. // both its source id and sequence. Occurrence keys are unsafe otherwise.
...(bases[index].startsWith("turn-") && baseCounts.get(bases[index]) === 1 ...(bases[index].startsWith("turn-") && baseCounts.get(bases[index]) === 1
+21 -117
View File
@@ -1,5 +1,5 @@
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"; 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 { createPortal } from "react-dom";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { composerUsageSnapshots, type ComposerUsageSnapshot } from "@/lib/model-request"; 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 { ThreadMessageCache } from "@/lib/thread-message-cache";
import { providerDisplayLabel } from "@/lib/provider-brand"; import { providerDisplayLabel } from "@/lib/provider-brand";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { useFilePreviewResize } from "@/hooks/useFilePreviewResize";
import { hasAnyOverlayMounted } from "@/lib/dom-overlays";
import { composerContextSnapshots } from "@/lib/context-graph"; import { composerContextSnapshots } from "@/lib/context-graph";
import { useClient } from "@/providers/ClientProvider"; 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; const FILE_PREVIEW_CLOSE_ANIMATION_MS = 320;
type FilePreviewAvailabilityCacheEntry = { type FilePreviewAvailabilityCacheEntry = {
@@ -199,20 +197,6 @@ type FilePreviewAvailabilityCacheEntry = {
revision: number; 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<string, string> = {}; const EMPTY_TITLE_OVERRIDES: Record<string, string> = {};
interface ThreadShellProps { interface ThreadShellProps {
@@ -498,6 +482,7 @@ export function ThreadShell({
}, [multiplePanes, previewSessionKey]); }, [multiplePanes, previewSessionKey]);
const [sidebarEnterWidth, setSidebarEnterWidth] = useState(0); const [sidebarEnterWidth, setSidebarEnterWidth] = useState(0);
const [contextSidebarHost, setContextSidebarHost] = useState<HTMLElement | null>(null); const [contextSidebarHost, setContextSidebarHost] = useState<HTMLElement | null>(null);
const contextSidebarRef = useRef<HTMLElement>(null);
const setSidebarHost = useCallback((node: HTMLElement | null) => { shellRef.current = node; setContextSidebarHost(node); }, []); const setSidebarHost = useCallback((node: HTMLElement | null) => { shellRef.current = node; setContextSidebarHost(node); }, []);
const [closingPreview, setClosingPreview] = useState<{ key: string; state: FilePreviewState } | null>(null); const [closingPreview, setClosingPreview] = useState<{ key: string; state: FilePreviewState } | null>(null);
const filePreviewClosing = closingPreview?.key === previewSessionKey; const filePreviewClosing = closingPreview?.key === previewSessionKey;
@@ -525,8 +510,6 @@ export function ThreadShell({
if (range && selection) { selection.removeAllRanges(); selection.addRange(range); } if (range && selection) { selection.removeAllRanges(); selection.addRange(range); }
}, [composerDestination, composerMount, inlineComposer]); }, [composerDestination, composerMount, inlineComposer]);
useLayoutEffect(() => () => composerMount.remove(), [composerMount]); 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 draftKey = session?.key ?? (temporaryChatEnabled ? "new:temporary" : "new:chat");
const persistDraft = session ? !temporary : !temporaryChatEnabled; const persistDraft = session ? !temporary : !temporaryChatEnabled;
const [quote, setQuote] = useState<{ key: string; text: string | null } | null>(null); const [quote, setQuote] = useState<{ key: string; text: string | null } | null>(null);
@@ -538,6 +521,9 @@ export function ThreadShell({
}, [draftKey]); }, [draftKey]);
const [composerFocusSignal, setComposerFocusSignal] = useState(0); const [composerFocusSignal, setComposerFocusSignal] = useState(0);
const shellRef = useRef<HTMLElement | null>(null); const shellRef = useRef<HTMLElement | null>(null);
const { width: filePreviewWidth, panelRef: previewPanelRef, startResize: handleFilePreviewResizeStart, cancelResize: cancelPreviewResize } = useFilePreviewResize(
shellRef, previewOpen, previewState.width, setFilePreviewWidth,
);
const [conversationElement, setConversationElement] = useState<HTMLDivElement | null>(null); const [conversationElement, setConversationElement] = useState<HTMLDivElement | null>(null);
const [composerSurface, setComposerSurface] = useState<HTMLDivElement | null>(null); const [composerSurface, setComposerSurface] = useState<HTMLDivElement | null>(null);
const alignSidebar = useCallback(() => { const alignSidebar = useCallback(() => {
@@ -556,9 +542,7 @@ export function ThreadShell({
observer.observe(composerSurface); observer.observe(composerSurface);
return () => observer.disconnect(); return () => observer.disconnect();
}, [alignSidebar, contextSidebarHost, sidebarOpen, inlineComposer, composerDestination, composerMount, composerSurface]); }, [alignSidebar, contextSidebarHost, sidebarOpen, inlineComposer, composerDestination, composerMount, composerSurface]);
const filePreviewWidthRef = useRef(FILE_PREVIEW_DEFAULT_WIDTH);
const filePreviewCloseTimerRef = useRef<number | null>(null); const filePreviewCloseTimerRef = useRef<number | null>(null);
const filePreviewResizeCleanupRef = useRef<(() => void) | null>(null);
const pendingFirstRef = useRef<(PendingFirstMessage & { draft?: ComposerDraft; draftKey: string }) | 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 [restoredFirstDraft, setRestoredFirstDraft] = useState<{ chatId: string; revision: number; error: string } | null>(null);
const [pendingFirstTargetChatId, setPendingFirstTargetChatId] = useState<string | null>(null); const [pendingFirstTargetChatId, setPendingFirstTargetChatId] = useState<string | null>(null);
@@ -647,18 +631,14 @@ export function ThreadShell({
}, [chatId, historyKey]); }, [chatId, historyKey]);
useEffect(() => { useEffect(() => {
filePreviewWidthRef.current = filePreviewWidth; cancelPreviewResize();
}, [filePreviewWidth]);
useEffect(() => {
filePreviewResizeCleanupRef.current?.();
if (filePreviewCloseTimerRef.current !== null) { if (filePreviewCloseTimerRef.current !== null) {
window.clearTimeout(filePreviewCloseTimerRef.current); window.clearTimeout(filePreviewCloseTimerRef.current);
filePreviewCloseTimerRef.current = null; filePreviewCloseTimerRef.current = null;
} }
setClosingPreview(null); setClosingPreview(null);
setSubmittedViewportTurn(null); setSubmittedViewportTurn(null);
}, [previewSessionKey]); }, [cancelPreviewResize, previewSessionKey]);
useEffect(() => { useEffect(() => {
const retained = new Set(temporaryChatIds); const retained = new Set(temporaryChatIds);
@@ -680,7 +660,6 @@ export function ThreadShell({
useEffect(() => { useEffect(() => {
return () => { return () => {
filePreviewResizeCleanupRef.current?.();
if (filePreviewCloseTimerRef.current !== null) { if (filePreviewCloseTimerRef.current !== null) {
window.clearTimeout(filePreviewCloseTimerRef.current); window.clearTimeout(filePreviewCloseTimerRef.current);
} }
@@ -1133,7 +1112,7 @@ export function ThreadShell({
const handleCloseFilePreview = useCallback(() => { const handleCloseFilePreview = useCallback(() => {
if (!previewSessionKey || !previewState.activeId || filePreviewClosing) return; if (!previewSessionKey || !previewState.activeId || filePreviewClosing) return;
filePreviewResizeCleanupRef.current?.(); cancelPreviewResize();
setClosingPreview({ key: previewSessionKey, state: previewState }); setClosingPreview({ key: previewSessionKey, state: previewState });
// Record the closed state immediately, even if navigation interrupts the animation. // Record the closed state immediately, even if navigation interrupts the animation.
closePreview(); closePreview();
@@ -1141,23 +1120,24 @@ export function ThreadShell({
filePreviewCloseTimerRef.current = null; filePreviewCloseTimerRef.current = null;
setClosingPreview(null); setClosingPreview(null);
}, FILE_PREVIEW_CLOSE_ANIMATION_MS); }, FILE_PREVIEW_CLOSE_ANIMATION_MS);
}, [previewSessionKey, filePreviewClosing, previewState, closePreview]); }, [cancelPreviewResize, previewSessionKey, filePreviewClosing, previewState, closePreview]);
const cancelPreviewClose = useCallback(() => { const cancelPreviewClose = useCallback(() => {
filePreviewResizeCleanupRef.current?.(); cancelPreviewResize();
if (filePreviewCloseTimerRef.current !== null) { if (filePreviewCloseTimerRef.current !== null) {
window.clearTimeout(filePreviewCloseTimerRef.current); window.clearTimeout(filePreviewCloseTimerRef.current);
filePreviewCloseTimerRef.current = null; filePreviewCloseTimerRef.current = null;
} }
setClosingPreview(null); setClosingPreview(null);
}, []); }, [cancelPreviewResize]);
const handleOpenFilePreview = useCallback((path: string) => { 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); setContextSidebarOpen(false);
cancelPreviewClose(); cancelPreviewClose();
openFile(path); openFile(path);
}, [cancelPreviewClose, openFile]); }, [cancelPreviewClose, openFile, previewPanelRef]);
const handleContextSidebarOpenChange = useCallback((open: boolean) => { const handleContextSidebarOpenChange = useCallback((open: boolean) => {
if (open) { if (open) {
@@ -1170,10 +1150,10 @@ export function ThreadShell({
const handleClosePreviewTab = useCallback((id: string) => { const handleClosePreviewTab = useCallback((id: string) => {
if (previewState.tabs.length === 1) handleCloseFilePreview(); if (previewState.tabs.length === 1) handleCloseFilePreview();
else { else {
filePreviewResizeCleanupRef.current?.(); cancelPreviewResize();
closeTab(id); closeTab(id);
} }
}, [previewState.tabs.length, handleCloseFilePreview, closeTab]); }, [cancelPreviewResize, previewState.tabs.length, handleCloseFilePreview, closeTab]);
// Markdown blocks can retain rendered links while their text is unchanged. // Markdown blocks can retain rendered links while their text is unchanged.
// Keep their callback stable, but always act on the current pane/session state. // Keep their callback stable, but always act on the current pane/session state.
@@ -1203,7 +1183,7 @@ export function ThreadShell({
const onKeyDown = (event: KeyboardEvent) => { const onKeyDown = (event: KeyboardEvent) => {
if (event.key !== "Escape" || event.defaultPrevented || event.isComposing) return; if (event.key !== "Escape" || event.defaultPrevented || event.isComposing) return;
// Let a dialog/menu above the pane consume Escape without closing this preview. // 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(); event.preventDefault();
handleCloseFilePreview(); handleCloseFilePreview();
}; };
@@ -1211,84 +1191,6 @@ export function ThreadShell({
return () => window.removeEventListener("keydown", onKeyDown); return () => window.removeEventListener("keydown", onKeyDown);
}, [previewOpen, headerActive, handleCloseFilePreview]); }, [previewOpen, headerActive, handleCloseFilePreview]);
const handleFilePreviewResizeStart = useCallback((event: ReactPointerEvent<HTMLButtonElement>) => {
filePreviewResizeCleanupRef.current?.();
event.preventDefault();
event.stopPropagation();
const panel = event.currentTarget.closest<HTMLElement>("[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( const handleForkFromMessage = useCallback(
async (beforeUserIndex: number) => { async (beforeUserIndex: number) => {
if (!chatId || !onForkChat) return; if (!chatId || !onForkChat) return;
@@ -1588,6 +1490,7 @@ export function ThreadShell({
rounds={composerRoundUsage} rounds={composerRoundUsage}
snapshots={contextGraphSnapshots} snapshots={contextGraphSnapshots}
sidebarHost={contextSidebarHost} sidebarHost={contextSidebarHost}
sidebarRef={contextSidebarRef}
open={contextSidebarOpen} open={contextSidebarOpen}
onOpenChange={handleContextSidebarOpenChange} onOpenChange={handleContextSidebarOpenChange}
onOpenFile={handleOpenFilePreview} onOpenFile={handleOpenFilePreview}
@@ -1615,6 +1518,7 @@ export function ThreadShell({
onSelect={selectTab} onSelect={selectTab}
onCloseTab={handleClosePreviewTab} onCloseTab={handleClosePreviewTab}
onClose={handleCloseFilePreview} onClose={handleCloseFilePreview}
panelRef={previewPanelRef}
onResizeStart={handleFilePreviewResizeStart} onResizeStart={handleFilePreviewResizeStart}
> >
<FilePreviewPanel <FilePreviewPanel
+12 -44
View File
@@ -13,6 +13,7 @@ import { ArrowDown } from "lucide-react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { PromptRail } from "@/components/thread/PromptRail"; import { PromptRail } from "@/components/thread/PromptRail";
import { matchHistoryRow, type HistoryRowIdentity } from "@/components/thread/history-row-identity";
import { SubagentThreadMessages } from "@/components/thread/SubagentTaskResults"; import { SubagentThreadMessages } from "@/components/thread/SubagentTaskResults";
import { DiagramScope } from "@/components/markdown-diagrams/context"; import { DiagramScope } from "@/components/markdown-diagrams/context";
import { DiffViewportContext } from "./activity/DiffViewportContext"; import { DiffViewportContext } from "./activity/DiffViewportContext";
@@ -93,25 +94,13 @@ export const INITIAL_HISTORY_WINDOW = 120;
export const HISTORY_WINDOW_INCREMENT = 120; export const HISTORY_WINDOW_INCREMENT = 120;
interface HistoryScrollAnchor { interface HistoryScrollAnchor {
sources: string[]; identity: HistoryRowIdentity;
fallback?: string;
offsetTop: number; offsetTop: number;
scrollTop: number; scrollTop: number;
} }
const THREAD_DISPLAY_UNIT_SELECTOR = "[data-thread-display-unit]"; const THREAD_DISPLAY_UNIT_SELECTOR = "[data-thread-display-unit]";
function scrollSourceKind(source: string): string {
return (JSON.parse(source) as string[])[1];
}
function scrollSourcesDisagree(left: string[], right: string[], kind: string): boolean {
const leftKeys = left.filter((source) => 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 { function promptTopInset(scroller: HTMLElement): number {
const padding = Number.parseFloat(getComputedStyle(scroller).scrollPaddingTop); const padding = Number.parseFloat(getComputedStyle(scroller).scrollPaddingTop);
return Number.isFinite(padding) ? padding : PROMPT_TOP_INSET_PX; return Number.isFinite(padding) ? padding : PROMPT_TOP_INSET_PX;
@@ -333,6 +322,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
const contentRef = useRef<HTMLDivElement>(null); const contentRef = useRef<HTMLDivElement>(null);
const messageRegionRef = useRef<HTMLDivElement | null>(null); const messageRegionRef = useRef<HTMLDivElement | null>(null);
const messageContentRef = useRef<HTMLDivElement>(null); const messageContentRef = useRef<HTMLDivElement>(null);
const [historyRows] = useState(() => new WeakMap<HTMLElement, HistoryRowIdentity>());
const diffViewport = useMemo(() => ({ scroller: messageRegionRef, content: messageContentRef }), []); const diffViewport = useMemo(() => ({ scroller: messageRegionRef, content: messageContentRef }), []);
const emptyStateRef = useRef<HTMLDivElement>(null); const emptyStateRef = useRef<HTMLDivElement>(null);
const composerDockRef = useRef<HTMLDivElement>(null); const composerDockRef = useRef<HTMLDivElement>(null);
@@ -558,26 +548,20 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
} }
const viewport = scroller.getBoundingClientRect(); const viewport = scroller.getBoundingClientRect();
const element = visibleHistoryUnit(content, viewport); const element = visibleHistoryUnit(content, viewport);
if (!element?.dataset.threadScrollSources) { const identity = element ? historyRows.get(element) : undefined;
historyScrollAnchorRef.current = null; if (!element || !identity || (identity.sources.length === 0 && !identity.fallback)) {
return false;
}
const sources = JSON.parse(element.dataset.threadScrollSources) as string[];
const fallback = element.dataset.threadScrollFallback;
if (sources.length === 0 && !fallback) {
historyScrollAnchorRef.current = null; historyScrollAnchorRef.current = null;
return false; return false;
} }
historyScrollAnchorRef.current = { historyScrollAnchorRef.current = {
sources, identity,
fallback,
scrollTop: scroller.scrollTop, scrollTop: scroller.scrollTop,
// Normalize out the reveal lease, even when reading above its inline slot. // Normalize out the reveal lease, even when reading above its inline slot.
offsetTop: element.getBoundingClientRect().top - viewport.top offsetTop: element.getBoundingClientRect().top - viewport.top
- (historySlotRef.current ? HISTORY_HOLD_PX : 0), - (historySlotRef.current ? HISTORY_HOLD_PX : 0),
}; };
return true; return true;
}, []); }, [historyRows]);
const reconcileHistoryScrollAnchor = useCallback(() => { const reconcileHistoryScrollAnchor = useCallback(() => {
const scroller = scrollRef.current; const scroller = scrollRef.current;
@@ -588,26 +572,9 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
if (Math.abs(scroller.scrollTop - Math.min(anchor.scrollTop, maxScrollTop)) >= 0.5) { if (Math.abs(scroller.scrollTop - Math.min(anchor.scrollTop, maxScrollTop)) >= 0.5) {
return captureHistoryScrollAnchor(); return captureHistoryScrollAnchor();
} }
const candidates = Array.from(content.querySelectorAll<HTMLElement>(THREAD_DISPLAY_UNIT_SELECTOR)); const element = matchHistoryRow(
const bySource = new Map<string, { element: HTMLElement; sources: string[] }>(); anchor.identity, content.querySelectorAll<HTMLElement>(THREAD_DISPLAY_UNIT_SELECTOR), historyRows,
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);
}
if (!element) { if (!element) {
historyScrollAnchorRef.current = null; historyScrollAnchorRef.current = null;
return false; return false;
@@ -626,7 +593,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
// A clamped layout is the new reading position, not space owed by a later prepend. // A clamped layout is the new reading position, not space owed by a later prepend.
anchor.offsetTop += requestedTop - nextTop; anchor.offsetTop += requestedTop - nextTop;
return true; return true;
}, [captureHistoryScrollAnchor]); }, [captureHistoryScrollAnchor, historyRows]);
const resetHistoryHeader = useCallback(() => { const resetHistoryHeader = useCallback(() => {
setHistorySlotKey(null); setHistorySlotKey(null);
@@ -1342,6 +1309,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
<DiffViewportContext.Provider value={diffViewport}> <DiffViewportContext.Provider value={diffViewport}>
<DiagramScope identity={conversationKey}> <DiagramScope identity={conversationKey}>
<SubagentThreadMessages <SubagentThreadMessages
historyRows={historyRows}
key={messagesKey} key={messagesKey}
messages={visibleMessages} messages={visibleMessages}
topInset={PROMPT_TOP_INSET_PX} topInset={PROMPT_TOP_INSET_PX}
@@ -206,7 +206,7 @@ function FileUnifiedDiff({
const renderBody = () => ( const renderBody = () => (
<div <div
className="mt-1 overflow-hidden rounded-md border border-border/55 bg-background/80 shadow-[0_1px_0_rgba(15,23,42,0.03)]" className="file-edit-diff-surface mt-1 overflow-hidden rounded-md border border-border/55 bg-background/80 shadow-[0_1px_0_rgba(15,23,42,0.03)]"
data-testid="file-edit-diff" data-testid="file-edit-diff"
> >
<DiffSyntaxHighlight language={language} text={diff.text!} diff={renderableDiff} lineLimit={lineLimit} /> <DiffSyntaxHighlight language={language} text={diff.text!} diff={renderableDiff} lineLimit={lineLimit} />
@@ -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<HTMLElement>, rows: WeakMap<HTMLElement, HistoryRowIdentity>,
): HTMLElement | undefined {
const bySource = new Map<string, { element: HTMLElement; identity: HistoryRowIdentity }>();
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;
}
+20 -16
View File
@@ -6,6 +6,7 @@ import {
modalOverlayClassName, modalOverlayClassName,
modalSurfaceClassName, modalSurfaceClassName,
} from "@/components/ui/floating-surface"; } from "@/components/ui/floating-surface";
import { useOverlaySurfaceRef } from "@/lib/dom-overlays";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
const AlertDialog = AlertDialogPrimitive.Root; const AlertDialog = AlertDialogPrimitive.Root;
@@ -29,22 +30,25 @@ AlertDialogOverlay.displayName = AlertDialogPrimitive.Overlay.displayName;
const AlertDialogContent = React.forwardRef< const AlertDialogContent = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Content>, React.ElementRef<typeof AlertDialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Content> React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Content>
>(({ className, ...props }, ref) => ( >(({ className, ...props }, ref) => {
<AlertDialogPortal> const surfaceRef = useOverlaySurfaceRef("dialog", ref);
<AlertDialogOverlay /> return (
<div className="fixed inset-0 z-50 flex items-center justify-center p-4"> <AlertDialogPortal>
<AlertDialogPrimitive.Content <AlertDialogOverlay />
ref={ref} <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
className={cn( <AlertDialogPrimitive.Content
modalSurfaceClassName, ref={surfaceRef}
"grid w-full max-w-lg origin-center gap-4 rounded-modal p-6 duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95", className={cn(
className, modalSurfaceClassName,
)} "grid w-full max-w-lg origin-center gap-4 rounded-modal p-6 duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95",
{...props} className,
/> )}
</div> {...props}
</AlertDialogPortal> />
)); </div>
</AlertDialogPortal>
);
});
AlertDialogContent.displayName = AlertDialogPrimitive.Content.displayName; AlertDialogContent.displayName = AlertDialogPrimitive.Content.displayName;
const AlertDialogHeader = ({ const AlertDialogHeader = ({
+3 -1
View File
@@ -7,6 +7,7 @@ import {
modalOverlayClassName, modalOverlayClassName,
modalSurfaceClassName, modalSurfaceClassName,
} from "@/components/ui/floating-surface"; } from "@/components/ui/floating-surface";
import { useOverlaySurfaceRef } from "@/lib/dom-overlays";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { FloatingPortalContext } from "@/components/ui/floating-portal"; import { FloatingPortalContext } from "@/components/ui/floating-portal";
@@ -47,6 +48,7 @@ const DialogPositionedContent = React.forwardRef<
overlayClassName?: string; overlayClassName?: string;
} }
>(({ contained, positionerStyle, placement, overlayClassName, ...props }, ref) => { >(({ contained, positionerStyle, placement, overlayClassName, ...props }, ref) => {
const surfaceRef = useOverlaySurfaceRef("dialog", ref);
const Overlay = contained ? "div" : DialogOverlay; const Overlay = contained ? "div" : DialogOverlay;
return <Overlay data-dialog-backdrop {...(contained ? {} : { forceMount: true })} className={cn(contained && "absolute inset-0 z-50", overlayClassName)}> return <Overlay data-dialog-backdrop {...(contained ? {} : { forceMount: true })} className={cn(contained && "absolute inset-0 z-50", overlayClassName)}>
<div className={cn("fixed inset-0 z-50 flex items-start justify-center overscroll-contain", placement === "bottom" ? "overflow-clip" : "overflow-y-auto p-4", contained && "absolute")} style={{ <div className={cn("fixed inset-0 z-50 flex items-start justify-center overscroll-contain", placement === "bottom" ? "overflow-clip" : "overflow-y-auto p-4", contained && "absolute")} style={{
@@ -55,7 +57,7 @@ const DialogPositionedContent = React.forwardRef<
bottom: "auto", bottom: "auto",
...(contained ? { top: 0, height: "100%" } : positionerStyle), ...(contained ? { top: 0, height: "100%" } : positionerStyle),
}}> }}>
<DialogPrimitive.Content ref={ref} {...props} /> <DialogPrimitive.Content ref={surfaceRef} {...props} />
</div> </div>
</Overlay>; </Overlay>;
}); });
+19 -14
View File
@@ -8,6 +8,7 @@ import {
floatingSurfaceClassName, floatingSurfaceClassName,
floatingSurfaceMotionClassName, floatingSurfaceMotionClassName,
} from "@/components/ui/floating-surface"; } from "@/components/ui/floating-surface";
import { useOverlaySurfaceRef } from "@/lib/dom-overlays";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { useFloatingPortal } from "@/components/ui/floating-portal"; import { useFloatingPortal } from "@/components/ui/floating-portal";
@@ -29,10 +30,11 @@ const DropdownMenuContent = React.forwardRef<
DropdownMenuContentProps DropdownMenuContentProps
>(({ className, sideOffset = 4, portalContainer, ...props }, ref) => { >(({ className, sideOffset = 4, portalContainer, ...props }, ref) => {
const dialogContainer = useFloatingPortal(); const dialogContainer = useFloatingPortal();
const surfaceRef = useOverlaySurfaceRef("overlay", ref);
return ( return (
<DropdownMenuPrimitive.Portal container={portalContainer ?? dialogContainer ?? undefined}> <DropdownMenuPrimitive.Portal container={portalContainer ?? dialogContainer ?? undefined}>
<DropdownMenuPrimitive.Content <DropdownMenuPrimitive.Content
ref={ref} ref={surfaceRef}
sideOffset={sideOffset} sideOffset={sideOffset}
className={cn( className={cn(
floatingSurfaceClassName, floatingSurfaceClassName,
@@ -140,19 +142,22 @@ DropdownMenuSubTrigger.displayName = DropdownMenuPrimitive.SubTrigger.displayNam
const DropdownMenuSubContent = React.forwardRef< const DropdownMenuSubContent = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.SubContent>, React.ElementRef<typeof DropdownMenuPrimitive.SubContent>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubContent> React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubContent>
>(({ className, sideOffset = 6, ...props }, ref) => ( >(({ className, sideOffset = 6, ...props }, ref) => {
<DropdownMenuPrimitive.SubContent const surfaceRef = useOverlaySurfaceRef("overlay", ref);
ref={ref} return (
sideOffset={sideOffset} <DropdownMenuPrimitive.SubContent
className={cn( ref={surfaceRef}
floatingSurfaceClassName, sideOffset={sideOffset}
floatingSurfaceMotionClassName, className={cn(
"origin-[var(--radix-dropdown-menu-content-transform-origin)] max-h-[min(var(--radix-dropdown-menu-content-available-height),22rem)] min-w-[11rem] overflow-y-auto", floatingSurfaceClassName,
className, floatingSurfaceMotionClassName,
)} "origin-[var(--radix-dropdown-menu-content-transform-origin)] max-h-[min(var(--radix-dropdown-menu-content-available-height),22rem)] min-w-[11rem] overflow-y-auto",
{...props} className,
/> )}
)); {...props}
/>
);
});
DropdownMenuSubContent.displayName = DropdownMenuPrimitive.SubContent.displayName; DropdownMenuSubContent.displayName = DropdownMenuPrimitive.SubContent.displayName;
export { export {
+4 -1
View File
@@ -5,6 +5,7 @@ import {
floatingSurfaceClassName, floatingSurfaceClassName,
floatingSurfaceMotionClassName, floatingSurfaceMotionClassName,
} from "@/components/ui/floating-surface"; } from "@/components/ui/floating-surface";
import { useOverlaySurfaceRef } from "@/lib/dom-overlays";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { useFloatingPortal } from "@/components/ui/floating-portal"; import { useFloatingPortal } from "@/components/ui/floating-portal";
@@ -23,10 +24,12 @@ const PopoverContent = React.forwardRef<
PopoverContentProps PopoverContentProps
>(({ className, sideOffset = 4, portalContainer, motionClassName = floatingSurfaceMotionClassName, ...props }, ref) => { >(({ className, sideOffset = 4, portalContainer, motionClassName = floatingSurfaceMotionClassName, ...props }, ref) => {
const dialogContainer = useFloatingPortal(); const dialogContainer = useFloatingPortal();
// Radix renders Popover.Content as role="dialog".
const surfaceRef = useOverlaySurfaceRef("dialog", ref);
return ( return (
<PopoverPrimitive.Portal container={portalContainer ?? dialogContainer ?? undefined}> <PopoverPrimitive.Portal container={portalContainer ?? dialogContainer ?? undefined}>
<PopoverPrimitive.Content <PopoverPrimitive.Content
ref={ref} ref={surfaceRef}
sideOffset={sideOffset} sideOffset={sideOffset}
className={cn( className={cn(
floatingSurfaceClassName, floatingSurfaceClassName,
+3 -1
View File
@@ -4,6 +4,7 @@ import { Check, ChevronDown, ChevronUp } from "lucide-react";
import { floatingSurfaceElevationClassName, floatingItemClassName } from "@/components/ui/floating-surface"; import { floatingSurfaceElevationClassName, floatingItemClassName } from "@/components/ui/floating-surface";
import { useFloatingPortal } from "@/components/ui/floating-portal"; import { useFloatingPortal } from "@/components/ui/floating-portal";
import { useOverlaySurfaceRef } from "@/lib/dom-overlays";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { ControlChevron } from "@/components/ui/control-chevron"; import { ControlChevron } from "@/components/ui/control-chevron";
@@ -28,9 +29,10 @@ export function SelectContent({ children, ...props }: Pick<
"children" | "onPointerUpCapture" | "onPointerDownOutside" | "onKeyDownCapture" | "onEscapeKeyDown" | "onCloseAutoFocus" "children" | "onPointerUpCapture" | "onPointerDownOutside" | "onKeyDownCapture" | "onEscapeKeyDown" | "onCloseAutoFocus"
>) { >) {
const container = useFloatingPortal(); const container = useFloatingPortal();
const surfaceRef = useOverlaySurfaceRef<HTMLDivElement>("overlay");
return ( return (
<SelectPrimitive.Portal container={container ?? undefined}> <SelectPrimitive.Portal container={container ?? undefined}>
<SelectPrimitive.Content {...props} position="item-aligned" className={cn("z-50 max-h-[min(24rem,calc(100dvh-2rem))] min-w-[10rem] overflow-hidden rounded-control border border-transparent", floatingSurfaceElevationClassName)}> <SelectPrimitive.Content ref={surfaceRef} {...props} position="item-aligned" className={cn("z-50 max-h-[min(24rem,calc(100dvh-2rem))] min-w-[10rem] overflow-hidden rounded-control border border-transparent", floatingSurfaceElevationClassName)}>
<SelectPrimitive.ScrollUpButton className="flex h-6 items-center justify-center"><ChevronUp className="h-3.5 w-3.5" /></SelectPrimitive.ScrollUpButton> <SelectPrimitive.ScrollUpButton className="flex h-6 items-center justify-center"><ChevronUp className="h-3.5 w-3.5" /></SelectPrimitive.ScrollUpButton>
<SelectPrimitive.Viewport className="p-1"> <SelectPrimitive.Viewport className="p-1">
{children} {children}
+3 -1
View File
@@ -4,6 +4,7 @@ import { X } from "lucide-react";
import { cva, type VariantProps } from "class-variance-authority"; import { cva, type VariantProps } from "class-variance-authority";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { useOverlaySurfaceRef } from "@/lib/dom-overlays";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { modalOverlayClassName, sidePanelSurfaceClassName } from "./floating-surface"; import { modalOverlayClassName, sidePanelSurfaceClassName } from "./floating-surface";
@@ -84,11 +85,12 @@ const SheetContent = React.forwardRef<
ref, ref,
) => { ) => {
const { t } = useTranslation(); const { t } = useTranslation();
const surfaceRef = useOverlaySurfaceRef("dialog", ref);
return ( return (
<SheetPortal> <SheetPortal>
<SheetOverlay className={cn((side === "right" || side === "left") && modalOverlayClassName, overlayClassName)} /> <SheetOverlay className={cn((side === "right" || side === "left") && modalOverlayClassName, overlayClassName)} />
<DialogPrimitive.Content <DialogPrimitive.Content
ref={ref} ref={surfaceRef}
className={cn( className={cn(
sheetVariants({ side }), sheetVariants({ side }),
"data-[state=open]:animate-in data-[state=closed]:animate-out", "data-[state=open]:animate-in data-[state=closed]:animate-out",
+18 -14
View File
@@ -2,6 +2,7 @@ import * as React from "react";
import * as TooltipPrimitive from "@radix-ui/react-tooltip"; import * as TooltipPrimitive from "@radix-ui/react-tooltip";
import { floatingSurfaceElevationClassName } from "@/components/ui/floating-surface"; import { floatingSurfaceElevationClassName } from "@/components/ui/floating-surface";
import { useOverlaySurfaceRef } from "@/lib/dom-overlays";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
function TooltipProvider({ function TooltipProvider({
@@ -16,20 +17,23 @@ const TooltipTrigger = TooltipPrimitive.Trigger;
const TooltipContent = React.forwardRef< const TooltipContent = React.forwardRef<
React.ElementRef<typeof TooltipPrimitive.Content>, React.ElementRef<typeof TooltipPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof TooltipPrimitive.Content> React.ComponentPropsWithoutRef<typeof TooltipPrimitive.Content>
>(({ className, sideOffset = 4, ...props }, ref) => ( >(({ className, sideOffset = 4, ...props }, ref) => {
<TooltipPrimitive.Portal> const surfaceRef = useOverlaySurfaceRef("overlay", ref);
<TooltipPrimitive.Content return (
ref={ref} <TooltipPrimitive.Portal>
sideOffset={sideOffset} <TooltipPrimitive.Content
className={cn( ref={surfaceRef}
floatingSurfaceElevationClassName, sideOffset={sideOffset}
"z-50 origin-[var(--radix-tooltip-content-transform-origin)] overflow-hidden rounded-control px-3 py-1.5 text-caption animate-in fade-in-0 zoom-in-95 motion-reduce:animate-none", className={cn(
className, floatingSurfaceElevationClassName,
)} "z-50 origin-[var(--radix-tooltip-content-transform-origin)] overflow-hidden rounded-control px-3 py-1.5 text-caption animate-in fade-in-0 zoom-in-95 motion-reduce:animate-none",
{...props} className,
/> )}
</TooltipPrimitive.Portal> {...props}
)); />
</TooltipPrimitive.Portal>
);
});
TooltipContent.displayName = TooltipPrimitive.Content.displayName; TooltipContent.displayName = TooltipPrimitive.Content.displayName;
export { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger }; export { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger };
+1 -1
View File
@@ -2153,7 +2153,7 @@ html[data-custom-background] .markdown-inline-code {
html[data-custom-background] .thread-history-status { html[data-custom-background] .thread-history-status {
--thread-history-background: hsl(var(--background) / 0.65); --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); background-color: hsl(var(--background) / 0.78);
backdrop-filter: blur(12px); backdrop-filter: blur(12px);
} }
+128
View File
@@ -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<Parameters<typeof useVoiceRecorder>[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<VoiceRecorderErrorKey | null>(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,
};
}
+116
View File
@@ -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<HTMLElement>, previewOpen: boolean, storedWidth: number, setFilePreviewWidth: (width: number) => void,
) {
const panelRef = useRef<HTMLElement>(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<HTMLButtonElement>) => {
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 };
}
+205
View File
@@ -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<GatewayState>({ status: "loading" });
const owner = useRef<NanobotClient | null>(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 };
}
+82 -177
View File
@@ -1,6 +1,6 @@
import { acceptsCompactionPhase } from "../../../packages/client-events/notifications"; import { acceptsCompactionPhase } from "../../../packages/client-events/notifications";
import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useThreadVisibility } from "@/hooks/useThreadVisibility"; import { useStreamBatch } from "@/hooks/useStreamBatch";
import { useClient } from "@/providers/ClientProvider"; import { useClient } from "@/providers/ClientProvider";
import { hasPendingAgentActivity } from "@/lib/activity-timeline"; 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: "delta"; text: string; turn: UIMessageTurnFields; streamId?: string; source?: UIMessage["source"]; responseSources?: UIMessage["responseSources"]; responseInputIds?: string[] }
| { kind: "reasoning"; text: string; turn: UIMessageTurnFields; streamId?: 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_INITIAL_MESSAGES: UIMessage[] = [];
const EMPTY_COMPLETED_TURN_IDS: readonly string[] = []; const EMPTY_COMPLETED_TURN_IDS: readonly string[] = [];
@@ -173,9 +170,6 @@ export function useNanobotStream(
const publishHistory = useCallback(() => setHistoryState(transcriptRef.current.paging), []); const publishHistory = useCallback(() => setHistoryState(transcriptRef.current.paging), []);
const [refreshSeq, setRefreshSeq] = useState(0); const [refreshSeq, setRefreshSeq] = useState(0);
const refreshHistory = useCallback(() => setRefreshSeq((value) => value + 1), []); 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 [runState, setRunState] = useState(() => chatId ? client.getRunState(chatId) : null);
const isStreaming = runState?.active ?? false; const isStreaming = runState?.active ?? false;
const runStartedAt = runState?.startedAt ?? null; const runStartedAt = runState?.startedAt ?? null;
@@ -216,27 +210,8 @@ export function useNanobotStream(
const [recoveryState, setRecoveryState] = useState<RecoveryState | null>(null); const [recoveryState, setRecoveryState] = useState<RecoveryState | null>(null);
const [streamError, setStreamError] = useState<StreamError | null>(null); const [streamError, setStreamError] = useState<StreamError | null>(null);
const pendingStreamEventsRef = useRef<PendingStreamEvent[]>([]);
const streamFrameRef = useRef<number | null>(null);
const streamTimerRef = useRef<number | null>(null);
const lastStreamFlushRef = useRef(0);
const dismissStreamError = useCallback(() => setStreamError(null), []); 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 isSideChannelEvent = useCallback((ev: InboundEvent) => {
const turnId = eventTurnId(ev); const turnId = eventTurnId(ev);
return turnId !== undefined && transcriptRef.current.sideChannelTurnIds.has(turnId); return turnId !== undefined && transcriptRef.current.sideChannelTurnIds.has(turnId);
@@ -252,73 +227,6 @@ export function useNanobotStream(
return hadActiveAssistant; 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<UIMessage>((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( const applyPendingStreamEvents = useCallback(
(prev: UIMessage[], events: PendingStreamEvent[]): UIMessage[] => { (prev: UIMessage[], events: PendingStreamEvent[]): UIMessage[] => {
transcriptRef.current.projection = { ...transcriptRef.current.projection, messages: prev }; transcriptRef.current.projection = { ...transcriptRef.current.projection, messages: prev };
@@ -389,19 +297,79 @@ export function useNanobotStream(
[chatId], [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<UIMessage>((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<ThreadProjectionEvent, { event: "stream_end" }>) => { const flushPendingStreamEvents = useCallback((end?: Extract<ThreadProjectionEvent, { event: "stream_end" }>) => {
lastStreamFlushRef.current = 0; const events = drainStreamEvents();
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;
if (events.length === 0 && !end) return; if (events.length === 0 && !end) return;
pendingStreamEventsRef.current = [];
setMessages((prev) => { setMessages((prev) => {
const nextMessages = events.length > 0 ? applyPendingStreamEvents(prev, events) : prev; const nextMessages = events.length > 0 ? applyPendingStreamEvents(prev, events) : prev;
transcriptRef.current.projection = { ...transcriptRef.current.projection, messages: nextMessages }; transcriptRef.current.projection = { ...transcriptRef.current.projection, messages: nextMessages };
@@ -410,67 +378,7 @@ export function useNanobotStream(
}); });
return transcriptRef.current.messages; return transcriptRef.current.messages;
}); });
}, [applyPendingStreamEvents, setMessages]); }, [applyPendingStreamEvents, drainStreamEvents, 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]);
useEffect(() => { useEffect(() => {
if (!chatId) return; if (!chatId) return;
@@ -505,8 +413,8 @@ export function useNanobotStream(
setRetryStatus(null); setRetryStatus(null);
setGoalState(chatId ? client.getGoalState(chatId) : undefined); setGoalState(chatId ? client.getGoalState(chatId) : undefined);
setRecoveryState(null); setRecoveryState(null);
clearPendingStreamWork(); drainStreamEvents();
}, [chatId, client, historyKey, temporary, clearActivitySegment, clearPendingStreamWork, setMessages]); }, [chatId, client, historyKey, temporary, clearActivitySegment, drainStreamEvents, setMessages]);
useEffect(() => { useEffect(() => {
if (!chatId || (!hasPendingToolCalls && !initialStreaming)) return; if (!chatId || (!hasPendingToolCalls && !initialStreaming)) return;
@@ -784,7 +692,7 @@ export function useNanobotStream(
if (transcriptRef.current.projection.suppressUntilTurnEnd || transcriptRef.current.represented(ev)) return; if (transcriptRef.current.projection.suppressUntilTurnEnd || transcriptRef.current.represented(ev)) return;
const chunk = typeof ev.text === "string" ? ev.text : ""; const chunk = typeof ev.text === "string" ? ev.text : "";
if (!chunk) return; if (!chunk) return;
pendingStreamEventsRef.current.push({ enqueueStreamEvent({
kind: "delta", kind: "delta",
text: chunk, text: chunk,
turn: turnFieldsFromEvent(ev, "answer"), turn: turnFieldsFromEvent(ev, "answer"),
@@ -793,7 +701,6 @@ export function useNanobotStream(
responseSources: ev.response_sources, responseSources: ev.response_sources,
responseInputIds: ev.response_input_ids, responseInputIds: ev.response_input_ids,
}); });
schedulePendingStreamFlush();
return; return;
} }
@@ -801,13 +708,12 @@ export function useNanobotStream(
if (transcriptRef.current.projection.suppressUntilTurnEnd || transcriptRef.current.represented(ev)) return; if (transcriptRef.current.projection.suppressUntilTurnEnd || transcriptRef.current.represented(ev)) return;
const chunk = ev.text; const chunk = ev.text;
if (!chunk) return; if (!chunk) return;
pendingStreamEventsRef.current.push({ enqueueStreamEvent({
kind: "reasoning", kind: "reasoning",
text: chunk, text: chunk,
turn: turnFieldsFromEvent(ev, "reasoning"), turn: turnFieldsFromEvent(ev, "reasoning"),
streamId: ev.stream_id, streamId: ev.stream_id,
}); });
schedulePendingStreamFlush();
return; return;
} }
@@ -935,7 +841,7 @@ export function useNanobotStream(
|| ev.status === "failed" || ev.status === "failed"
) { ) {
setRetryStatus(null); setRetryStatus(null);
clearPendingStreamWork(); drainStreamEvents();
closeActiveAssistantStream(); closeActiveAssistantStream();
clearActivitySegment(); clearActivitySegment();
} }
@@ -954,7 +860,7 @@ export function useNanobotStream(
ev.recovery_state?.status === "awaiting_user" ev.recovery_state?.status === "awaiting_user"
|| ev.recovery_state?.status === "failed" || ev.recovery_state?.status === "failed"
) { ) {
clearPendingStreamWork(); drainStreamEvents();
closeActiveAssistantStream(); closeActiveAssistantStream();
clearActivitySegment(); clearActivitySegment();
} }
@@ -984,14 +890,13 @@ export function useNanobotStream(
setLiveInputs(null); setLiveInputs(null);
// Navigation may happen before the throttled paint. Snapshot the pending // Navigation may happen before the throttled paint. Snapshot the pending
// deltas synchronously while they still belong to this subscription. // deltas synchronously while they still belong to this subscription.
const pending = pendingStreamEventsRef.current; const pending = drainStreamEvents();
const snapshot = pending.length > 0 const snapshot = pending.length > 0
? applyPendingStreamEvents(messagesRef.current, pending) ? applyPendingStreamEvents(messagesRef.current, pending)
: messagesRef.current; : messagesRef.current;
onStreamDetach?.(snapshot); onStreamDetach?.(snapshot);
if (pending.length > 0) setMessages(snapshot); if (pending.length > 0) setMessages(snapshot);
messageCache?.set(chatId, transcriptRef.current.save()); messageCache?.set(chatId, transcriptRef.current.save());
clearPendingStreamWork();
}; };
}, [ }, [
applyProjectionEvent, applyProjectionEvent,
@@ -1001,13 +906,13 @@ export function useNanobotStream(
closeActiveAssistantStream, closeActiveAssistantStream,
client, client,
clearActivitySegment, clearActivitySegment,
clearPendingStreamWork, drainStreamEvents,
flushPendingStreamEvents, flushPendingStreamEvents,
isSideChannelEvent, isSideChannelEvent,
onTurnEnd, onTurnEnd,
onStreamDetach, onStreamDetach,
messageCache, messageCache,
schedulePendingStreamFlush, enqueueStreamEvent,
setMessages, setMessages,
]); ]);
+70
View File
@@ -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<Record<string, boolean>>,
collapsedPaneGroups: ReadonlySet<string>,
) {
const layoutRowRefs = useRef(new Map<string, HTMLElement>());
const pendingLayoutRectsRef = useRef<Map<string, DOMRect> | null>(null);
const layoutAnimationsRef = useRef(new Map<string, Animation>());
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<string, DOMRect>();
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 };
}
+101
View File
@@ -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<Event>(onFlush: (events: Event[]) => void) {
const visible = useThreadVisibility();
const visibleRef = useRef(visible);
visibleRef.current = visible;
const pending = useRef<Event[]>([]);
const frame = useRef<number | null>(null);
const timer = useRef<number | null>(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 };
}
+43
View File
@@ -0,0 +1,43 @@
import { useCallback, useRef, type ForwardedRef, type RefCallback } from "react";
type OverlayKind = "dialog" | "overlay";
const surfaces = new Map<HTMLElement, OverlayKind>();
// 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<T extends HTMLElement>(
kind: OverlayKind,
forwardedRef?: ForwardedRef<T>,
): RefCallback<T> {
const current = useRef<T | null>(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;
}
+27 -13
View File
@@ -33,29 +33,40 @@ function createDefaultSocket(url: string): WebSocket {
return new WebSocket(url); 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``. /** Inbound WebSocket ``console.log`` / parse-failure ``console.warn``.
* *
* - **Dev** (non-production bundle): **on by default** — messages appear at default log level. * - **Dev** (non-production bundle): **on by default** — messages appear at default log level.
* - **Production**: off unless ``localStorage.setItem('nanobot_debug_ws','1')`` (or ``true``). * - **Production**: off unless ``localStorage.setItem('nanobot_debug_ws','1')`` (or ``true``).
* - **Silence anywhere**: ``localStorage.setItem('nanobot_debug_ws','0')`` (or ``false`` / ``off``). * - **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 { function wsInboundDebugEnabled(): boolean {
if (typeof globalThis === "undefined") return false; 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 { try {
if (import.meta.env.MODE === "test") return false;
const ls = (globalThis as unknown as { localStorage?: Storage }).localStorage; const ls = (globalThis as unknown as { localStorage?: Storage }).localStorage;
const raw = ls?.getItem("nanobot_debug_ws")?.trim().toLowerCase() ?? ""; const raw = ls?.getItem("nanobot_debug_ws")?.trim().toLowerCase() ?? "";
if (raw === "0" || raw === "false" || raw === "off" || raw === "no") { 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 { } catch {
return !import.meta.env.PROD; enabled = !import.meta.env.PROD;
} }
wsDebugCache = { checkedAt: now, enabled };
return enabled;
} }
function summarizeInboundWsPayload(ev: InboundEvent): unknown { function summarizeInboundWsPayload(ev: InboundEvent): unknown {
@@ -247,6 +258,7 @@ export class NanobotClient {
/** Inbound frames received while the transcript owner is absent, regardless of observers. */ /** Inbound frames received while the transcript owner is absent, regardless of observers. */
private pendingInboundByChat = new Map<string, InboundEvent[]>(); private pendingInboundByChat = new Map<string, InboundEvent[]>();
private static readonly PENDING_INBOUND_MAX = 2000; private static readonly PENDING_INBOUND_MAX = 2000;
private static readonly PENDING_TEMP_INBOUND_MAX = 20_000;
private knownChats = new Set<string>(); private knownChats = new Set<string>();
/** Temporary chats are connection-owned and intentionally not reattached. */ /** Temporary chats are connection-owned and intentionally not reattached. */
private temporaryChatIds = new Set<string>(); private temporaryChatIds = new Set<string>();
@@ -1171,11 +1183,13 @@ export class NanobotClient {
this.pendingInboundByChat.set(chatId, pending); this.pendingInboundByChat.set(chatId, pending);
} }
pending.push(ev); pending.push(ev);
// Temporary chats have no canonical history to recover evicted events from. // Temporary chats have no canonical history to recover evicted events from,
if (!this.temporaryChatIds.has(chatId)) { // but still keep a generous upper bound so an unmounted chat cannot OOM the tab.
const over = pending.length - NanobotClient.PENDING_INBOUND_MAX; const maxPending = this.temporaryChatIds.has(chatId)
if (over > 0) pending.splice(0, over); ? 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); for (const handler of this.chatHandlers.get(chatId) ?? []) handler(ev);
} }
+210
View File
@@ -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);
}
}
+22
View File
@@ -4812,6 +4812,28 @@ describe("App layout", () => {
unmount(); 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<ReturnType<typeof fetchBootstrap>>) => 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(<App />);
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 () => { it("refreshes the bootstrap token before REST settings auth expires", async () => {
vi.useFakeTimers(); vi.useFakeTimers();
vi.mocked(fetchBootstrap) vi.mocked(fetchBootstrap)
+11 -4
View File
@@ -341,7 +341,7 @@ describe("NanobotClient", () => {
expect(notice).toHaveBeenCalledWith({ event, temporary: false }); expect(notice).toHaveBeenCalledWith({ event, temporary: false });
client.close(); 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({ const client = new NanobotClient({
url: "ws://test", reconnect: false, url: "ws://test", reconnect: false,
socketFactory: (url) => new FakeSocket(url) as unknown as WebSocket, 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) }); 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 regular = vi.fn();
const temporary = vi.fn(); const temporary: string[] = [];
client.onTranscript("regular", regular); 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).toHaveBeenCalledTimes(2_000);
expect(regular.mock.calls[0][0].text).toBe("10"); 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(); unsubscribe();
socket.fakeMessage({ event: "delta", chat_id: "temporary", text: "discard me" }); socket.fakeMessage({ event: "delta", chat_id: "temporary", text: "discard me" });
client.discardTemporaryChat("temporary"); client.discardTemporaryChat("temporary");
+24
View File
@@ -3,6 +3,7 @@ import userEvent from "@testing-library/user-event";
import { afterEach, beforeEach, expect, it, vi } from "vitest"; import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { PromptNavigator } from "@/components/thread/PromptNavigator"; import { PromptNavigator } from "@/components/thread/PromptNavigator";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { mockBrowserFocus } from "./browser-focus"; import { mockBrowserFocus } from "./browser-focus";
let restoreBrowserFocus: () => void; let restoreBrowserFocus: () => void;
@@ -80,6 +81,29 @@ it("keeps an unknown recovered time blank while the prompt remains navigable", a
expect(onJumpToPrompt).toHaveBeenCalledWith("undated"); expect(onJumpToPrompt).toHaveBeenCalledWith("undated");
}); });
it("defers Ctrl+F to an open popover but not to its exit animation", async () => {
render(<>
<style>{`.test-popover[data-state="open"] { animation-name: enter; }
.test-popover[data-state="closed"] { animation-name: exit; }`}</style>
<Popover>
<PopoverTrigger>Model options</PopoverTrigger>
<PopoverContent aria-label="Model options" className="test-popover"><button>Choose model</button></PopoverContent>
</Popover>
<PromptNavigator messages={[{ id: "one", role: "user", content: "alpha", createdAt: 1 }]} onJumpToPrompt={vi.fn()} />
</>);
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 () => { it("returns shortcut-opened search to the interrupted editor", async () => {
const user = userEvent.setup(); const user = userEvent.setup();
render(<><input aria-label="Draft" /><PromptNavigator messages={[ render(<><input aria-label="Draft" /><PromptNavigator messages={[
@@ -10,6 +10,7 @@ import { canonicalThreadPayload } from "./thread-test-payload";
let groupedTopics = false; let groupedTopics = false;
let withFiles = false; let withFiles = false;
let withPairing = false;
const previewFile = (path: string) => ({ const previewFile = (path: string) => ({
path: `/workspace/${path}`, display_path: path, project_path: "/workspace", path: `/workspace/${path}`, display_path: path, project_path: "/workspace",
language: "text", content: `Preview of ${path}`, size: 20, truncated: false, 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: "/" }); vi.mocked(fetchBootstrap).mockReset().mockResolvedValue({ token: "test", api_token: "test", ws_path: "/" });
groupedTopics = false; groupedTopics = false;
withFiles = false; withFiles = false;
withPairing = false;
localStorage.clear(); localStorage.clear();
sessionStorage.clear(); sessionStorage.clear();
window.history.replaceState(null, "", "/"); window.history.replaceState(null, "", "/");
vi.stubGlobal("WebSocket", TestSocket); vi.stubGlobal("WebSocket", TestSocket);
vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => { vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => {
const path = String(input); 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") { if (path === "/api/sessions") {
return Response.json({ sessions: ["regular", ...(groupedTopics ? ["child"] : [])].map((id) => ({ return Response.json({ sessions: ["regular", ...(groupedTopics ? ["child"] : [])].map((id) => ({
key: `websocket:${id}`, key: `websocket:${id}`,
@@ -345,16 +350,49 @@ describe("temporary chat navigation", () => {
expect(screen.getAllByRole("tab")).toHaveLength(1); expect(screen.getAllByRole("tab")).toHaveLength(1);
fireEvent.click(screen.getByRole("button", { name: "notes.txt" })); fireEvent.click(screen.getByRole("button", { name: "notes.txt" }));
await screen.findByText("Preview of notes.txt"); await screen.findByText("Preview of notes.txt");
const dialog = document.createElement("div"); withPairing = true;
dialog.setAttribute("role", "dialog"); act(() => TestSocket.current.receive({ event: "pairing_changed" }));
document.body.append(dialog); const dialog = await screen.findByRole("dialog", { name: "Pair account" });
fireEvent.keyDown(window, { key: "Escape" }); // 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(); expect(screen.getByTestId("file-preview-panel")).toBeInTheDocument();
dialog.remove(); fireEvent.click(within(dialog).getByRole("button", { name: "Close" }));
fireEvent.keyDown(window, { key: "Escape" }); 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()); 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(<App />);
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 () => { it("forgets preview paths on temporary close and disconnect", async () => {
const update = vi.spyOn(FilePreviewStore.prototype, "open"); const update = vi.spyOn(FilePreviewStore.prototype, "open");
render(<App />); render(<App />);
+2 -12
View File
@@ -1272,18 +1272,9 @@ describe("ThreadViewport", () => {
}); });
expect(hitTest.mock).toHaveBeenCalled(); expect(hitTest.mock).toHaveBeenCalled();
const replacement = anchor.cloneNode(true) as HTMLElement; // Deferred content grows above the existing row wrapper.
anchor.replaceWith(replacement);
anchorDocumentTop += 180; anchorDocumentTop += 180;
scrollHeight += 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 content = screen.getByTestId("thread-message-region").firstElementChild;
const observer = resizeObserver.observers.find((candidate) => const observer = resizeObserver.observers.find((candidate) =>
content ? candidate.elements.includes(content) : false, content ? candidate.elements.includes(content) : false,
@@ -1294,10 +1285,9 @@ describe("ThreadViewport", () => {
}); });
expect(scroller.scrollTop).toBe(260); 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. // ResizeObserver may arrive before the next native scroll event.
hitTarget = replacement;
scroller.scrollTop = 240; scroller.scrollTop = 240;
anchorDocumentTop += 60; anchorDocumentTop += 60;
scrollHeight += 60; scrollHeight += 60;