feat(webui): persist reviewed automation chat changes

This commit is contained in:
Xubin Ren committed 2026-10-07 01:12:23 +08:00
1 parent 707f7eb079
commit 845afe9215
41 files changed
+1210 -626

No files matched your search

+83
View File
@@ -0,0 +1,83 @@
"""Resolve authenticated WebUI choices to existing, same-scope session routes."""
from collections import Counter
from dataclasses import dataclass, replace
from typing import Any, cast
from nanobot.channels.notification_routes import notification_metadata
from nanobot.cron.binding import CronBinding
from nanobot.cron.types import CronJob
from nanobot.session.manager import (
SessionManager,
_metadata_title, # pyright: ignore[reportPrivateUsage]
)
from nanobot.session.session_handles import SessionHandleResolver
from nanobot.webui.session_identity import is_webui_session_key
from nanobot.webui.workspaces import WebUIWorkspaceController
@dataclass(frozen=True)
class AutomationChat:
id: str
title: str
binding: CronBinding
handle: str
available: bool
def public_payload(self) -> dict[str, Any]:
return {"id": self.id, "title": self.title, "channel": self.binding.channel,
**({"unavailable": True} if not self.available else {})}
def automation_chats(
job: CronJob, sessions: SessionManager, workspaces: WebUIWorkspaceController,
channel_status: dict[str, Any],
) -> list[AutomationChat]:
"""Do not infer an external address by splitting an opaque session key.
External chats must have a route captured by a real user turn. Only
address metadata is copied; sender, turn owner and old workspace policy
must never travel from the source job to the selected chat.
"""
if (not job.payload.session_key or not job.payload.origin_channel
or not job.payload.session_key.startswith(f"{job.payload.origin_channel}:")
or job.payload.origin_channel in {"cli", "system"}):
return []
source = workspaces.automation_scope(
job.payload.session_key or "", job.payload.origin_channel or "",
job.payload.origin_metadata,
)
result: list[AutomationChat] = []
for handle in SessionHandleResolver(sessions).list_all():
key = handle.session_key
data = sessions.read_session_metadata(key)
metadata: dict[str, Any] = data.get("metadata", {}) if data else {}
if is_webui_session_key(key):
channel, chat_id = key.split(":", 1)
route_metadata = {}
else:
route = metadata.get("_compaction_route")
if not isinstance(route, dict):
continue
route = cast(dict[str, Any], route)
channel, chat_id = route.get("channel"), route.get("chat_id")
if (not isinstance(channel, str) or not isinstance(chat_id, str)
or not chat_id or not key.startswith(f"{channel}:")
or channel in {"cli", "system", "websocket"}):
continue
route_metadata = notification_metadata(channel, route.get("metadata", {}))
available = channel == "websocket" or bool(channel_status.get(channel, {}).get("running"))
if not available and key != job.payload.session_key:
continue
target = workspaces.automation_scope(key, channel, {})
if source.metadata() != target.metadata():
continue
result.append(AutomationChat(
id=handle.id, title=_metadata_title(metadata) or f"@{handle.name}",
binding=CronBinding(key, channel, chat_id, route_metadata),
handle=handle.name,
available=available,
))
names = Counter(chat.title for chat in result)
return [replace(chat, title=f"{chat.title} · @{chat.handle}")
if names[chat.title] > 1 else chat for chat in result]
+1 -1
View File
@@ -57,7 +57,7 @@ def cron_run_response(runs_dir: Path, job: CronJob, run: CronRunRecord) -> str |
records.append(record)
matching = [record for record in records
if record.get("job_id") == job.id
and record.get("session_key") == job.payload.session_key
and record.get("session_key") == (run.session_key or job.payload.session_key)
and record.get("status") == run.status]
if len(matching) != 1:
return None
+5 -1
View File
@@ -16,6 +16,7 @@ CORE_CAPABILITY = "webui.core.v1"
SUBAGENT_CAPABILITY = "webui.subagents.v1"
SUBAGENT_EVENTS_CAPABILITY = "webui.subagents.events.v1"
SUBAGENT_HISTORY_CAPABILITY = "webui.subagents.history.v1"
AUTOMATION_CHAT_CAPABILITY = "webui.automation-chat.v1"
class Compatibility(TypedDict):
@@ -29,7 +30,10 @@ def webui_contract() -> dict[str, object]:
"version": __version__,
"min_protocol": WEBUI_PROTOCOL,
"max_protocol": WEBUI_PROTOCOL,
"capabilities": [CORE_CAPABILITY, SUBAGENT_CAPABILITY, SUBAGENT_EVENTS_CAPABILITY, SUBAGENT_HISTORY_CAPABILITY],
"capabilities": [
CORE_CAPABILITY, SUBAGENT_CAPABILITY, SUBAGENT_EVENTS_CAPABILITY,
SUBAGENT_HISTORY_CAPABILITY, AUTOMATION_CHAT_CAPABILITY,
],
}
+4
View File
@@ -5,6 +5,8 @@ from __future__ import annotations
from collections.abc import Collection
from typing import Any, Protocol, cast
from nanobot.cron.binding import binding_revision
from nanobot.cron.session_turns import is_bound_cron_job
from nanobot.cron.types import CronJob
from nanobot.session.history_visibility import is_hidden_history_message
from nanobot.session.manager import (
@@ -187,6 +189,8 @@ def _serialize_job(
}
)
payload["origin"] = _origin_payload(job, session_manager)
if is_bound_cron_job(job):
payload["chat_binding_revision"] = binding_revision(job)
return payload
+13
View File
@@ -16,6 +16,7 @@ from nanobot.security.workspace_access import (
WORKSPACE_SCOPE_METADATA_KEY,
WorkspaceScope,
WorkspaceScopeError,
WorkspaceScopeResolver,
build_workspace_scope,
default_workspace_scope,
validate_workspace_scope_payload,
@@ -198,6 +199,18 @@ class WebUIWorkspaceController:
self._default_restrict_to_workspace,
)
def automation_scope(
self, session_key: str, channel: str, message_metadata: dict[str, Any],
) -> WorkspaceScope:
"""Use the runtime's policy, not the browser's draft project selection."""
data = self._sessions.read_session_metadata(session_key) if self._sessions else None
return WorkspaceScopeResolver(
self._default_workspace, self._default_restrict_to_workspace,
).for_turn(
channel=channel, message_metadata=message_metadata,
session_metadata=data.get("metadata", {}) if data else {},
)
def restricted_default_scope(self) -> WorkspaceScope:
"""Return the default workspace with access restricted for this request."""
return build_workspace_scope(
+56 -2
View File
@@ -29,6 +29,7 @@ from websockets.http11 import Response
from nanobot.agent.subagent import SubagentControlError
from nanobot.agent.subagent_status import SubagentSessionError
from nanobot.command.builtin import builtin_command_palette
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.security.workspace_access import WorkspaceScope
@@ -38,6 +39,7 @@ from nanobot.session.session_handles import (
SessionHandleResolver,
)
from nanobot.triggers.local_types import LocalTrigger
from nanobot.webui.automation_chats import AutomationChat, automation_chats
from nanobot.webui.automation_results import cron_run_response, trigger_run_response
from nanobot.webui.file_preview import (
WebUIFilePreviewError,
@@ -187,6 +189,7 @@ _WEBUI_MUTATION_PATHS = {
"automation.delete": "/api/webui/automations/delete",
"automation.run": "/api/webui/automations/run",
"automation.update": "/api/webui/automations/update",
"automation.change_chat": "/api/webui/automations/change-chat",
"skill.install": "/api/webui/skills/install",
"skill.update": "/api/webui/skills/update",
"skill.delete": "/api/webui/skills/delete",
@@ -412,6 +415,7 @@ class GatewayHTTPHandler:
self.cron_service = cron_service
self.local_trigger_store = local_trigger_store
self.cron_pending_job_ids = cron_pending_job_ids
self.channel_runtime_status = channel_runtime_status
self.local_trigger_pending_ids = local_trigger_pending_ids
self._log = log
self._runtime_surface = runtime_surface
@@ -547,7 +551,7 @@ class GatewayHTTPHandler:
return True
if re.match(r"^/api/sessions/[^/]+/delete$", path):
return True
if re.match(r"^/api/webui/automations/(enable|disable|delete|run|update)$", path):
if re.match(r"^/api/webui/automations/(enable|disable|delete|run|update|change-chat)$", path):
return True
if path in {"/api/webui/recovery/continue", "/api/webui/recovery/dismiss"}:
return True
@@ -1359,7 +1363,9 @@ class GatewayHTTPHandler:
return self._handle_webui_automations(request)
if got == "/api/webui/automations/result":
return await self._handle_webui_automation_result(request)
m = re.match(r"^/api/webui/automations/(enable|disable|delete|run|update)$", got)
if got == "/api/webui/automations/chats":
return self._handle_webui_automation_chats(request)
m = re.match(r"^/api/webui/automations/(enable|disable|delete|run|update|change-chat)$", got)
if m:
return await self._handle_webui_automation_action(request, m.group(1))
return None
@@ -1410,6 +1416,30 @@ class GatewayHTTPHandler:
)
)
def _automation_chats(self, job: CronJob) -> list[AutomationChat]:
if self.session_manager is None:
return []
return automation_chats(
job, self.session_manager, self.workspaces,
self.channel_runtime_status() if self.channel_runtime_status else {},
)
def _handle_webui_automation_chats(self, request: WsRequest) -> Response:
if not self.check_api_token(request):
return _http_error(401, "Unauthorized")
job_id = _query_first(_request_query(request), "id") or ""
job = self.cron_service.get_job(job_id) if self.cron_service else None
if job is None or not is_bound_cron_job(job):
return _http_error(404, "automation has no movable chat")
chats = self._automation_chats(job)
current = next((chat for chat in chats
if chat.binding.session_key == job.payload.session_key), None)
return _http_json_response({
"revision": binding_revision(job),
"current": current.public_payload() if current else None,
"chats": [chat.public_payload() for chat in chats],
})
async def _handle_webui_automation_result(self, request: WsRequest) -> Response:
if not self.check_api_token(request):
return _http_error(401, "Unauthorized")
@@ -1497,6 +1527,30 @@ class GatewayHTTPHandler:
return _http_error(409, "automation is disabled")
task = asyncio.create_task(self.cron_service.run_job(job_id, force=False))
task.add_done_callback(self._log_automation_run_result)
elif action == "change-chat":
values = _automation_values_from_request(request)
if (not isinstance(values, dict)
or set(values) != {"target_id", "revision", "message"}
or not all(isinstance(v, str) for v in values.values())):
return _http_error(400, "invalid automation chat payload")
if job.id in self._pending_cron_job_ids_for_all():
return _http_error(409, "automation_chat_busy")
target = next((chat for chat in self._automation_chats(job)
if chat.id == values["target_id"]), None)
if target is None or not target.available:
return _http_error(409, "automation_chat_unavailable")
if target.binding.session_key == job.payload.session_key:
return _http_error(400, "choose a different chat")
try:
self.cron_service.change_binding(
job_id, revision=values["revision"], binding=target.binding,
message=values["message"],
)
except CronBindingError as exc:
return _http_error(409, f"automation_chat_{exc.reason}")
except OSError:
logger.exception("WebUI automation chat save failed")
return _http_error(500, "could not save the chat; try again")
elif action == "update":
values = _automation_values_from_request(request)
if values is None: