diff --git a/docs/automations.md b/docs/automations.md index 56d779bd5..e3155ade8 100644 --- a/docs/automations.md +++ b/docs/automations.md @@ -132,6 +132,50 @@ Local triggers do not have a WebUI "Run now" action because each run needs a message. Copy the `nanobot trigger ...` command from the WebUI and replace `"message"` with the content that should be delivered. +### Change the Chat for a Scheduled Task + +Open a scheduled task in **Automations**. **Task chat** shows its saved chat, +with the channel logo and name. To change it: + +1. Select another chat from **Task chat**. +2. Review the task instructions. Remove old instructions that send messages to + a different chat. Members of the new chat can see future task messages and results. +3. Select **Confirm change**. Wait for the saved confirmation. + +Future runs use the new chat's history and reply there by default. Previous +messages stay in their original chat. Previous run results remain available. +Changing the chat does not run the task, enable it, or change its schedule. + +The list contains existing chats on the same gateway with the same effective +workspace and access mode. Chat-app targets need a running channel and a saved +reply route from an earlier incoming message. If a chat is missing, send nanobot +a message there and check that its channel is running. Raw recipient IDs, +cross-host moves, unified sessions, system jobs, and local triggers are not +supported by this selector. An older gateway keeps the existing read-only view. + +If a scheduled turn is running or queued, wait for it to finish before changing +the chat. The current scheduler also rejects a change while another scheduled +turn is active. If another editor changes the task, reopen the task and review +the latest instructions. A rejected save leaves the draft visible. + +This changes the whole task chat, not a separate forwarding address. Explicit +`message` tool instructions can still send elsewhere. Shared workspace files +and memory remain shared; changing the chat does not create a new security boundary. + +### Back Up Before Downgrading + +Chat changes store a binding version and the session used by each previous run. +Existing jobs do not need a manual migration when upgrading. Older nanobot +versions can discard these new fields when they write the cron store. After a +chat change, that can make old run results unavailable in the WebUI and remove +protection against stale CLI updates. + +Before trying this feature, stop the gateway and other cron writers, then back +up the complete cron directory in the active instance's data directory. For a +downgrade after changing a chat, stop those processes again and restore that +coherent pre-change cron backup. This also restores the old schedules and task +settings; later changes are not included. Chat messages are not moved or deleted. + ## Delivery and Reliability Automation delivery is workspace-local. Scheduled jobs and local trigger diff --git a/nanobot/cron/binding.py b/nanobot/cron/binding.py new file mode 100644 index 000000000..2871a2f75 --- /dev/null +++ b/nanobot/cron/binding.py @@ -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() diff --git a/nanobot/cron/service.py b/nanobot/cron/service.py index 73b0609e0..71d4a2420 100644 --- a/nanobot/cron/service.py +++ b/nanobot/cron/service.py @@ -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() diff --git a/nanobot/cron/types.py b/nanobot/cron/types.py index 789e7a72b..bfb7226e5 100644 --- a/nanobot/cron/types.py +++ b/nanobot/cron/types.py @@ -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"), ) diff --git a/nanobot/webui/automation_chats.py b/nanobot/webui/automation_chats.py new file mode 100644 index 000000000..876673577 --- /dev/null +++ b/nanobot/webui/automation_chats.py @@ -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] diff --git a/nanobot/webui/automation_results.py b/nanobot/webui/automation_results.py index 4e7dab0cf..051d25385 100644 --- a/nanobot/webui/automation_results.py +++ b/nanobot/webui/automation_results.py @@ -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 diff --git a/nanobot/webui/client_contract.py b/nanobot/webui/client_contract.py index c6766b4c8..14b915a91 100644 --- a/nanobot/webui/client_contract.py +++ b/nanobot/webui/client_contract.py @@ -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, + ], } diff --git a/nanobot/webui/session_automations.py b/nanobot/webui/session_automations.py index b4a8d13f9..3fe508284 100644 --- a/nanobot/webui/session_automations.py +++ b/nanobot/webui/session_automations.py @@ -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 diff --git a/nanobot/webui/workspaces.py b/nanobot/webui/workspaces.py index 27902d13c..4b2df31b4 100644 --- a/nanobot/webui/workspaces.py +++ b/nanobot/webui/workspaces.py @@ -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( diff --git a/nanobot/webui/ws_http.py b/nanobot/webui/ws_http.py index 987a69b90..d7f024c4e 100644 --- a/nanobot/webui/ws_http.py +++ b/nanobot/webui/ws_http.py @@ -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: diff --git a/tests/webui/test_automation_chat_binding.py b/tests/webui/test_automation_chat_binding.py new file mode 100644 index 000000000..2a298fb63 --- /dev/null +++ b/tests/webui/test_automation_chat_binding.py @@ -0,0 +1,274 @@ +"""Move a complete scheduled turn through the real authenticated gateway.""" + +import asyncio +import json +import socket +import uuid +from dataclasses import asdict +from unittest.mock import MagicMock + +import httpx +import pytest +import websockets + +from nanobot.agent.loop import AgentLoop +from nanobot.bus.queue import MessageBus +from nanobot.channels.websocket.runtime import WebSocketChannel, WebSocketConfig +from nanobot.cron.binding import CronBinding, binding_revision +from nanobot.cron.bound_runner import run_bound_cron_job +from nanobot.cron.service import CronService +from nanobot.cron.types import CronRunRecord, CronSchedule +from nanobot.providers.base import GenerationSettings, LLMResponse +from nanobot.session.manager import SessionManager +from nanobot.webui.automation_chats import automation_chats +from nanobot.webui.automation_results import cron_run_response +from nanobot.webui.gateway_services import build_gateway_services +from nanobot.webui.workspaces import WebUIWorkspaceController + + +@pytest.fixture(autouse=True) +def isolate(tmp_path, monkeypatch): + monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path / "data") + monkeypatch.setattr("nanobot.config.loader._current_config_path", tmp_path / "config.json") + monkeypatch.setattr("nanobot.webui.workspaces.get_webui_dir", lambda: tmp_path / "webui") + + +def seed(tmp_path): + sessions = SessionManager(tmp_path / "workspace") + for key, title, route in [ + ("websocket:source", "Daily report", None), + ("telegram:-100:topic:42", "Product team", { + "channel": "telegram", "chat_id": "-100", + "metadata": {"message_thread_id": 42, "sender_id": "must-not-copy"}, + }), + ]: + session = sessions.get_or_create(key) + session.metadata["title"] = title + if route: + session.metadata["_compaction_route"] = route + session.add_message("user", title) + sessions.save(session) + cron = CronService(tmp_path / "cron" / "jobs.json") + job = cron.add_job( + "Daily report", CronSchedule(kind="every", every_ms=86400000), "Summarize", + session_key="websocket:source", origin_channel="websocket", origin_chat_id="source", + ) + return sessions, cron, job + + +def target_binding(): + return CronBinding("telegram:-100:topic:42", "telegram", "-100", {"message_thread_id": 42}) + + +@pytest.mark.asyncio +async def test_durable_move_stale_edit_failed_save_and_old_action(tmp_path, monkeypatch): + _, cron, job = seed(tmp_path) + await cron.start() + try: + old = cron.get_job(job.id) + revision = binding_revision(old) + before = cron.store_path.read_bytes() + write = cron._atomic_write + def fail(*args): + raise OSError("disk full") + monkeypatch.setattr(cron, "_atomic_write", fail) + with pytest.raises(OSError, match="disk full"): + cron.change_binding(job.id, revision=revision, binding=target_binding(), message="New") + assert cron.store_path.read_bytes() == before + assert cron.get_job(job.id) == old + monkeypatch.setattr(cron, "_atomic_write", write) + moved = cron.change_binding(job.id, revision=revision, binding=target_binding(), message="New") + assert moved.state == old.state + assert moved.enabled == old.enabled + assert moved.schedule == old.schedule + assert CronService(cron.store_path).get_job(job.id) == moved + with pytest.raises(ValueError, match="changed"): + cron.change_binding(job.id, revision=revision, binding=target_binding(), message="Stale") + # A CLI process can have read the old job before the WebUI commits. + cron._append_action("update", asdict(old)) + assert cron.get_job(job.id) == moved + # A directory-sync failure after replace must not report a false rollback. + def committed_then_failed(path, content): + write(path, content) + raise OSError("directory sync failed") + monkeypatch.setattr(cron, "_atomic_write", committed_then_failed) + moved = cron.change_binding(job.id, revision=binding_revision(moved), + binding=target_binding(), message="Committed") + assert cron.get_job(job.id).payload.message == moved.payload.message == "Committed" + finally: + cron.stop() + + +@pytest.mark.asyncio +async def test_running_job_cannot_move(tmp_path): + _, cron, job = seed(tmp_path) + entered, release = asyncio.Event(), asyncio.Event() + async def execute(_job): + entered.set() + await release.wait() + cron.on_job = execute + await cron.start() + task = asyncio.create_task(cron.run_job(job.id)) + try: + await asyncio.wait_for(entered.wait(), 3) + with pytest.raises(ValueError, match="busy"): + cron.change_binding(job.id, revision=binding_revision(job), + binding=target_binding(), message="New") + assert cron.get_job(job.id).payload.session_key == "websocket:source" + finally: + release.set() + await task + cron.stop() + + +@pytest.mark.asyncio +async def test_legacy_run_identity_is_captured_before_the_first_move(tmp_path): + _, cron, job = seed(tmp_path) + await cron.start() + try: + cron.get_job(job.id).state.run_history.append(CronRunRecord(run_at_ms=123, status="ok")) + cron._save_store() + moved = cron.change_binding(job.id, revision=binding_revision(cron.get_job(job.id)), + binding=target_binding(), message="Reviewed") + assert moved.state.run_history[0].session_key == "websocket:source" + assert CronService(cron.store_path).get_job(job.id).state.run_history == moved.state.run_history + finally: + cron.stop() + + +def test_target_identity_scope_and_channel_lifecycle(tmp_path): + sessions, _, job = seed(tmp_path) + (tmp_path / "other").mkdir() + workspaces = WebUIWorkspaceController(session_manager=sessions, + default_workspace=tmp_path / "workspace", default_restrict_to_workspace=False) + for key, metadata in [ + ("websocket:other-project", {"workspace_scope": {"project_path": str(tmp_path / "other"), "access_mode": "full"}}), + ("websocket:restricted", {"workspace_scope": {"project_path": str(tmp_path / "workspace"), "access_mode": "restricted"}}), + ("telegram:old-ambiguous", {}), + ("unified:default", {"_compaction_route": {"channel": "telegram", "chat_id": "-100"}}), + ]: + session = sessions.get_or_create(key) + session.metadata.update(metadata) + sessions.save(session) + chats = automation_chats(job, sessions, workspaces, {"telegram": {"running": True}}) + assert {chat.binding.session_key for chat in chats} == {"websocket:source", "telegram:-100:topic:42"} + target = next(chat for chat in chats if chat.title == "Product team") + assert target.binding == target_binding() + assert set(target.public_payload()) == {"id", "title", "channel"} + assert "-100" not in json.dumps(target.public_payload()) + assert len(automation_chats(job, sessions, workspaces, {})) == 1 + job.payload.session_key = "telegram:-100:topic:42" + job.payload.origin_channel = "telegram" + job.payload.origin_chat_id = "-100" + offline = automation_chats(job, sessions, workspaces, {}) + current = next(chat for chat in offline if chat.title == "Product team") + assert current.public_payload()["unavailable"] is True + # Only identical display names need a visible disambiguator. + session = sessions.get_or_create("websocket:source") + session.metadata["title"] = "Product team" + sessions.save(session) + duplicates = automation_chats(job, sessions, workspaces, {}) + assert len({chat.title for chat in duplicates}) == 2 + assert all(" · @" in chat.title for chat in duplicates) + + +async def mutate(ws, values, job_id): + request_id = str(uuid.uuid4()) + await ws.send(json.dumps({"type": "webui_request", "request_id": request_id, + "action": "automation.change_chat", "payload": {"id": job_id, "values": values}})) + async with asyncio.timeout(5): + while True: + response = json.loads(await ws.recv()) + if response.get("request_id") == request_id and response.get("event") == "webui_response": + return response + + +@pytest.mark.asyncio +async def test_real_gateway_move_run_reload_and_previous_result(tmp_path): + sessions, cron, job = seed(tmp_path) + provider = MagicMock() + provider.get_default_model.return_value = "test-model" + provider.generation = GenerationSettings(max_tokens=100) + provider.can_resume_conversation_state.return_value = False + provider.estimate_prompt_tokens.return_value = (100, "test") + requests = [] + async def reply(**kwargs): + requests.append(kwargs["messages"]) + return LLMResponse(content="Synthetic result") + provider.chat_stream_with_retry = reply + bus = MessageBus() + agent = AgentLoop(bus=bus, provider=provider, workspace=tmp_path / "workspace", + model="test-model", session_manager=sessions) + agent.tools.get_definitions = MagicMock(return_value=[]) + async def execute(job): + return await run_bound_cron_job(job, agent=agent, cron=cron) + cron.on_job = execute + await cron.start() + with socket.socket() as sock: + sock.bind(("127.0.0.1", 0)) + port = sock.getsockname()[1] + cfg = WebSocketConfig.model_validate({"enabled": True, "host": "127.0.0.1", "port": port, + "path": "/ws", "allowFrom": ["*"], "websocketRequiresToken": True}) + gateway = build_gateway_services(config=cfg, bus=bus, session_manager=sessions, + static_dist_path=None, workspace_path=tmp_path / "workspace", default_restrict_to_workspace=False, + runtime_model_name=None, runtime_surface="browser", runtime_capabilities_overrides=None, + cron_service=cron, channel_runtime_status=lambda: {"telegram": {"running": True}}) + channel = WebSocketChannel(cfg, bus, gateway=gateway) + server = asyncio.create_task(channel.start()) + client = None + try: + assert await cron.run_job(job.id) + old = cron.get_job(job.id) + old_run = old.state.run_history[-1] + token = gateway.tokens.issue_token(60, audience="webui") + async with asyncio.timeout(5): + while client is None: + try: + client = await websockets.connect(f"ws://127.0.0.1:{port}/ws?token={token}") + except OSError: + await asyncio.sleep(.01) + assert json.loads(await client.recv())["event"] == "ready" + api_token = gateway.tokens.issue_api_token(60) + async with httpx.AsyncClient(trust_env=False) as http: + url = f"http://127.0.0.1:{port}/api/webui/automations/chats?id={job.id}" + assert (await http.get(url)).status_code == 401 + result = await http.get(url, headers={"Authorization": f"Bearer {api_token}"}) + assert result.status_code == 200 + data = result.json() + target = next(chat for chat in data["chats"] if chat["channel"] == "telegram") + direct = await http.get( + f"http://127.0.0.1:{port}/api/webui/automations/change-chat?id={job.id}", + headers={"Authorization": f"Bearer {api_token}"}, + ) + assert direct.status_code == 405 + values = {"target_id": target["id"], "revision": data["revision"], "message": "Summarize this chat"} + assert not (await mutate(client, {**values, "chat_id": "forged"}, job.id))["ok"] + assert not (await mutate(client, {**values, "revision": "stale"}, job.id))["ok"] + assert not (await mutate(client, {**values, "target_id": "forged"}, job.id))["ok"] + changed = await mutate(client, values, job.id) + assert changed["ok"], changed + moved = CronService(cron.store_path).get_job(job.id) + assert moved.payload.origin_metadata == {"message_thread_id": 42} + assert moved.state.next_run_at_ms == old.state.next_run_at_ms + assert cron_run_response(cron.store_path.parent / "runs", moved, old_run) == "Synthetic result" + assert not (await mutate(client, values, job.id))["ok"] + assert await cron.run_job(job.id) + assert "Product team" in json.dumps(requests[-1]) + assert "Daily report" not in json.dumps(requests[-1]) + outgoing = [] + while bus.outbound_size: + outgoing.append(await bus.consume_outbound()) + delivered = [msg for msg in outgoing if msg.content == "Synthetic result" and msg.channel == "telegram"] + assert len(delivered) == 1 + assert delivered[0].chat_id == "-100" + assert delivered[0].metadata["message_thread_id"] == 42 + moved = CronService(cron.store_path).get_job(job.id) + for run in moved.state.run_history: + assert cron_run_response(cron.store_path.parent / "runs", moved, run) == "Synthetic result" + finally: + if client is not None: + await client.close() + await channel.stop() + await asyncio.wait_for(server, 5) + cron.stop() + await agent.aclose() diff --git a/webui/proposals/automation-chat/BindingControls.tsx b/webui/proposals/automation-chat/BindingControls.tsx deleted file mode 100644 index f472efeaf..000000000 --- a/webui/proposals/automation-chat/BindingControls.tsx +++ /dev/null @@ -1,173 +0,0 @@ -import { createContext, useContext, useEffect, useRef, useState, type ReactNode } from 'react'; -import { ChevronDown, MoreHorizontal, Users } from 'lucide-react'; -import { ChannelLogo } from '@/components/settings/channels/ChannelIdentity'; -import { Button } from '@/components/ui/button'; -import { DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog'; -import { Select, SelectTrigger, SelectValue, SelectContent, SelectItem } from '@/components/ui/select'; -import { Textarea } from '@/components/ui/textarea'; -import { Disclosure } from '@/components/ui/disclosure'; -import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'; -import type { NanobotFeatureInfo, SessionAutomationJob } from '@/lib/types'; - -export const targets = { - weixin: { name: '我的私聊', platform: '微信', channel: 'weixin', group: false }, - feishu: { name: '产品讨论群', platform: '飞书', channel: 'feishu', group: true }, - telegram: { name: '工作群 / 日报', platform: 'Telegram', channel: 'telegram', group: true }, - webui: { name: '天气助手', platform: '网页聊天', channel: 'websocket', group: false }, -}; -export type Target = keyof typeof targets; -export const legacy = '\n\n投递方式:调用 message 发送到微信。\nchannel="weixin"\nchat_id="demo-person"\ncontent=整理好的天气推送文本'; -export const PreviewContext = createContext<{ - mode: string; scenario: string; - save: (job: SessionAutomationJob, target: Target, message: string) => Promise; -} | null>(null); -const BindingContext = createContext<{ - saved: Target; notice: string; locked: boolean; - select: (target: Target) => void; -} | null>(null); - -export function ConversationIdentity({ target }: { target: Target }) { - const item = targets[target]; - const feature: NanobotFeatureInfo = { - name: item.channel, display_name: item.platform, type: 'channel', - enabled: true, installed: true, ready: true, status: 'ready', - install_supported: false, requires_restart: false, - }; - return - - {target === 'webui' ? - : } - - - {item.name}{item.platform} - - ; -} - -function ChatPicker({ value, disabled, onChange, detail = false }: { - value: Target; disabled: boolean; onChange: (target: Target) => void; detail?: boolean; -}) { - return ; -} - -// One original dialog owns the complete interaction. The page never unmounts. -export function BindingDialogFrame({ job, children }: { job: SessionAutomationJob; children: ReactNode }) { - const preview = useContext(PreviewContext)!; - const saved = (Object.keys(targets) as Target[]).find(key => targets[key].channel === job.origin?.channel) ?? 'webui'; - const [draft, setDraft] = useState(saved); - const [reviewing, setReviewing] = useState(false); - const [message, setMessage] = useState(job.payload.message); - const [saving, setSaving] = useState(false); - const [error, setError] = useState(''); - const [notice, setNotice] = useState(''); - const heading = useRef(null); - const returning = useRef(false); - const locked = Boolean(job.state.pending || preview.scenario === 'oldhost'); - useEffect(() => { - if (reviewing) heading.current?.focus(); - else if (returning.current) { - document.querySelector('[data-binding-select]')?.focus(); - returning.current = false; - } - }, [reviewing]); - const back = () => { returning.current = true; setReviewing(false); }; - const save = async () => { - if (draft === saved || !message.trim() || saving || locked) return; - setSaving(true); setError(''); - try { - await preview.save(job, draft, message); - setNotice('已更换,下次执行生效。'); back(); - } catch { setError('任务已被修改,未保存。原聊天未变,草稿已保留。'); } - finally { setSaving(false); } - }; - if (preview.mode === 'current') return children; - return { - if (target === saved || locked) return; - setDraft(target); setNotice(''); setError(''); setReviewing(true); - }, - }}> - {!reviewing ? children : <> - - 更换聊天 - -
-
- { setDraft(target); setError(''); }} /> -

原聊天:{targets[saved].name} · {targets[saved].platform}

-

后续任务会使用新聊天的记录,结果也默认发到这里。

-
-
-