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

+29
View File
@@ -0,0 +1,29 @@
"""Identity of a complete scheduled turn, not a separate forwarding address."""
import hashlib
import json
from dataclasses import asdict, dataclass
from typing import Any, Literal
from nanobot.cron.types import CronJob
class CronBindingError(ValueError):
def __init__(self, reason: Literal["busy", "unavailable", "conflict", "empty"], message: str):
super().__init__(message)
self.reason = reason
@dataclass(frozen=True)
class CronBinding:
session_key: str
channel: str
chat_id: str
metadata: dict[str, Any]
def binding_revision(job: CronJob) -> str:
"""Compare all editable state, including changes within the same millisecond."""
value = asdict(job)
value.pop("state")
return hashlib.sha256(json.dumps(value, sort_keys=True).encode()).hexdigest()
+61 -3
View File
@@ -7,6 +7,7 @@ import os
import time
import uuid
from contextlib import suppress
from copy import deepcopy
from dataclasses import asdict
from datetime import datetime
from pathlib import Path
@@ -16,6 +17,7 @@ from typing import Any, Callable, Coroutine, Literal
from filelock import FileLock
from loguru import logger
from nanobot.cron.binding import CronBinding, CronBindingError, binding_revision
from nanobot.cron.session_turns import is_bound_cron_job
from nanobot.cron.types import (
CronJob,
@@ -285,6 +287,10 @@ class CronService:
def _update(params: dict[str, Any]) -> None:
j = CronJob.from_dict(params)
_normalize_agent_turn_job(j)
current = jobs_map.get(j.id)
if current and j.payload.binding_version < current.payload.binding_version:
logger.warning("Cron: ignored stale update for moved job {}", j.id)
return
jobs_map[j.id] = j
def _del(params: dict[str, Any]) -> None:
@@ -378,10 +384,15 @@ class CronService:
# Set this before serialization/write so every exceptional exit keeps
# the in-memory snapshot authoritative until a later save succeeds.
self._store_dirty = True
self._write_store(self._store)
self._store_dirty = False
def _write_store(self, store: CronStore) -> None:
"""Persist a snapshot without publishing it as live state."""
self.store_path.parent.mkdir(parents=True, exist_ok=True)
data = {
"version": self._store.version,
"version": store.version,
"jobs": [
{
"id": j.id,
@@ -405,6 +416,7 @@ class CronService:
"originChannel": j.payload.origin_channel,
"originChatId": j.payload.origin_chat_id,
"originMetadata": j.payload.origin_metadata,
"bindingVersion": j.payload.binding_version,
},
"state": {
"nextRunAtMs": j.state.next_run_at_ms,
@@ -418,6 +430,7 @@ class CronService:
"durationMs": r.duration_ms,
"error": r.error,
"runId": r.run_id,
"sessionKey": r.session_key,
}
for r in j.state.run_history
],
@@ -426,12 +439,11 @@ class CronService:
"updatedAtMs": j.updated_at_ms,
"deleteAfterRun": j.delete_after_run,
}
for j in self._store.jobs
for j in store.jobs
]
}
self._atomic_write(self.store_path, json.dumps(data, indent=2, ensure_ascii=False))
self._store_dirty = False
@staticmethod
def _atomic_write(path: Path, content: str) -> None:
@@ -641,6 +653,7 @@ class CronService:
duration_ms=end_ms - start_ms,
error=job.state.last_error,
run_id=result.run_id if isinstance(result, CronRunResult) else None,
session_key=job.payload.session_key,
))
job.state.run_history = job.state.run_history[-self._MAX_RUN_HISTORY:]
@@ -669,6 +682,51 @@ class CronService:
# ========== Public API ==========
def change_binding(
self, job_id: str, *, revision: str, binding: CronBinding, message: str,
) -> CronJob:
"""Commit a reviewed move before it becomes visible to the scheduler.
This is a live-owner operation. Reject while the scheduler owns any
execution snapshot, including a turn waiting in a session inbox.
No await separates validation, persistence, and publication.
"""
if not self._running or self._active_executions or self._store_dirty:
raise CronBindingError("busy", "automation scheduler is busy; try again when tasks finish")
with self._lock:
store = self._require_store()
job = next((j for j in store.jobs if j.id == job_id), None)
if job is None or not is_bound_cron_job(job):
raise CronBindingError("unavailable", "automation has no movable chat")
if binding_revision(job) != revision:
raise CronBindingError("conflict", "automation changed; reopen it before changing the chat")
if not message.strip():
raise CronBindingError("empty", "automation message must not be empty")
candidate = deepcopy(store)
moved = next(j for j in candidate.jobs if j.id == job_id)
for run in moved.state.run_history:
if run.session_key is None:
run.session_key = job.payload.session_key
moved.payload.session_key = binding.session_key
moved.payload.origin_channel = binding.channel
moved.payload.origin_chat_id = binding.chat_id
moved.payload.origin_metadata = _persistable_origin_metadata(binding.metadata)
moved.payload.binding_version += 1
moved.payload.message = message
moved.updated_at_ms = max(_now_ms(), job.updated_at_ms + 1)
try:
self._write_store(candidate)
except OSError:
# Directory fsync can fail after replace. Reconcile that exact
# commit instead of claiming that the old binding survived.
loaded = self._load_jobs()
if loaded is None or loaded[0] != candidate.jobs:
raise
logger.warning("Cron: binding saved, but directory sync failed for {}", job_id)
self._store = candidate
self._arm_timer()
return moved
def list_jobs(self, include_disabled: bool = False) -> list[CronJob]:
"""List all jobs."""
store = self._require_store()
+4
View File
@@ -61,6 +61,7 @@ class CronPayload:
origin_channel: str | None = None
origin_chat_id: str | None = None
origin_metadata: dict[str, Any] = field(default_factory=dict)
binding_version: int = 0
@classmethod
def from_store_dict(cls, data: dict[str, Any]) -> CronPayload:
@@ -79,6 +80,7 @@ class CronPayload:
origin_metadata=dict(
get_camel_snake(data, "originMetadata", "origin_metadata", {}) or {}
),
binding_version=_store_int(get_camel_snake(data, "bindingVersion", "binding_version", 0)),
)
@@ -98,6 +100,7 @@ class CronRunRecord:
duration_ms: int = 0
error: str | None = None
run_id: str | None = None
session_key: str | None = None
@classmethod
def from_store_dict(cls, data: dict[str, Any]) -> CronRunRecord:
@@ -108,6 +111,7 @@ class CronRunRecord:
duration_ms=_store_int(get_camel_snake(data, "durationMs", "duration_ms", 0)),
error=data.get("error"),
run_id=run_id if isinstance(run_id, str) else None,
session_key=get_camel_snake(data, "sessionKey", "session_key"),
)
+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: