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

+44
View File
@@ -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
+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:
+274
View File
@@ -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()
@@ -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<void>;
} | 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 <span className="flex min-w-0 items-center gap-2.5 text-start">
<span aria-hidden className="relative h-6 w-6 shrink-0">
{target === 'webui' ? <img src="/brand/nanobot_mark.svg" alt="" className="h-6 w-6" />
: <span className="absolute left-0 top-0 origin-top-left scale-75"><ChannelLogo feature={feature} showBrandLogos /></span>}
</span>
<span className="flex min-w-0 flex-wrap items-baseline gap-x-2 text-[13px] leading-5">
<span className="min-w-0 break-words">{item.name}</span><span className="text-[12px] text-muted-foreground">{item.platform}</span>
</span>
</span>;
}
function ChatPicker({ value, disabled, onChange, detail = false }: {
value: Target; disabled: boolean; onChange: (target: Target) => void; detail?: boolean;
}) {
return <Select value={value} onValueChange={value => onChange(value as Target)} disabled={disabled}>
<SelectTrigger aria-label={detail ? '任务所在聊天' : '新聊天'} data-binding-select={detail || undefined}
className={`h-auto min-h-11 w-full py-2 [&>span:first-child]:min-w-0 [&>span:first-child]:flex-1 [&>span:first-child]:text-start ${detail ? 'border-transparent bg-transparent hover:bg-muted/50' : ''}`}>
<SelectValue><ConversationIdentity target={value} /></SelectValue>
</SelectTrigger>
<SelectContent>
{(Object.keys(targets) as Target[]).map(key => <SelectItem key={key} value={key} textValue={`${targets[key].name} ${targets[key].platform}`}
className="h-auto min-h-11 py-2 [&>span:last-child]:min-w-0 [&>span:last-child]:max-w-[calc(100vw-5rem)] [&>span:last-child]:w-full"><ConversationIdentity target={key} /></SelectItem>)}
<SelectItem value="offline" disabled className="h-auto min-h-11 text-[12px]">值班群 · 飞书(暂时无法连接)</SelectItem>
</SelectContent>
</Select>;
}
// 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<HTMLHeadingElement>(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<HTMLButtonElement>('[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 <BindingContext.Provider value={{ saved, notice, locked,
select: target => {
if (target === saved || locked) return;
setDraft(target); setNotice(''); setError(''); setReviewing(true);
},
}}>
{!reviewing ? children : <>
<DialogHeader className="shrink-0 px-6 pb-4 pr-12 pt-5 text-left">
<DialogTitle ref={heading} tabIndex={-1} className="text-lg font-medium leading-snug tracking-normal outline-none">更换聊天</DialogTitle>
</DialogHeader>
<div className="min-h-0 space-y-4 overflow-y-auto overscroll-contain px-6">
<div className="space-y-2">
<ChatPicker value={draft} disabled={saving || locked} onChange={target => { setDraft(target); setError(''); }} />
<p className="text-[12px] leading-5 text-muted-foreground">原聊天:{targets[saved].name} · {targets[saved].platform}</p>
<p className="text-[13px] leading-5">后续任务会使用新聊天的记录,结果也默认发到这里。</p>
</div>
<div className="space-y-2">
<label className="block space-y-2"><span className="text-[13px] font-medium">任务说明</span>
<Textarea aria-label="任务说明" rows={3} value={message} disabled={saving} onChange={event => { setMessage(event.target.value); setError(''); }} className="min-h-20 resize-y text-base leading-6 sm:text-[13px] sm:leading-5"/>
</label>
{message.includes(legacy.trim()) ? <div className="flex flex-wrap items-center gap-x-2 text-[12px] leading-5">
<span className="text-muted-foreground">说明仍要求发到微信。</span>
<Button variant="link" size="sm" className="h-auto min-h-11 px-0 py-1 text-[12px] sm:min-h-7" disabled={saving} onClick={() => setMessage(message.replace(legacy, ''))}>移除旧指令</Button>
</div> : null}
{targets[draft].group ? <p className="flex items-start gap-2 text-[12px] leading-5 text-muted-foreground"><Users className="mt-0.5 h-4 w-4 shrink-0" aria-hidden/>群成员可能看到任务内容和结果。</p> : null}
</div>
<Disclosure summary={<><ChevronDown className="h-3.5 w-3.5 shrink-0 transition-transform group-data-[state=open]/disclosure:rotate-180 motion-reduce:transition-none" aria-hidden/>记录和执行时间</>}
summaryClassName="flex min-h-9 items-center gap-1.5 rounded-control text-[12px] text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
contentClassName="pt-1 text-[12px] leading-5 text-muted-foreground">
旧聊天记录不会迁移。执行时间和启用状态不变,也不会立即运行。
</Disclosure>
{error ? <p role="alert" className="text-[12px] leading-5 text-destructive">{error}</p> : null}
</div>
<DialogFooter className="shrink-0 flex-row justify-end gap-2 px-6 pb-5 pt-3">
<Button variant="ghost" size="sm" disabled={saving} className="h-11 font-normal text-muted-foreground sm:h-9" onClick={back}>取消</Button>
<Button size="sm" className="h-11 min-w-24 sm:h-9" disabled={draft === saved || !message.trim() || saving || locked} aria-busy={saving} onClick={save}>{saving ? '正在更换…' : '确认并更换'}</Button>
</DialogFooter>
</>}
</BindingContext.Provider>;
}
export function BindingControls({ job, currentUi }: { job: SessionAutomationJob; currentUi: ReactNode }) {
const preview = useContext(PreviewContext);
const state = useContext(BindingContext);
if (!state || preview?.mode === 'current' || job.protected) return currentUi;
return <div>
<dl><div className="grid min-w-0 grid-cols-1 items-start gap-1 py-1 text-sm min-[420px]:grid-cols-[6rem_minmax(0,1fr)] min-[420px]:gap-4">
<dt className="text-[13px] text-muted-foreground min-[420px]:pt-3">任务所在聊天</dt>
<dd className="min-w-0">
<ChatPicker value={state.saved} disabled={state.locked} onChange={state.select} detail />
</dd>
</div></dl>
<p role={state.notice ? 'status' : undefined} className="mt-1 text-[12px] leading-5 text-muted-foreground">{state.locked ? (job.state.pending ? '执行或排队期间不能更换。' : '当前版本暂不支持更换。') : state.notice || '使用这里的聊天记录,结果也默认发到这里。'}</p>
</div>;
}
export function BindingDetailActions({ job, currentUi, busy, canToggle, canRun, localTrigger, originHref, onToggle, onRun, onEdit, onDelete }: {
job: SessionAutomationJob; currentUi: ReactNode; busy: boolean; canToggle: boolean; canRun: boolean;
localTrigger: boolean; originHref: string | null;
onToggle: () => void; onRun: () => void; onEdit: () => void; onDelete: () => void;
}) {
const preview = useContext(PreviewContext);
if (preview?.mode === 'current') return currentUi;
return <div className="flex shrink-0 items-center gap-2 border-t border-border/45 px-6 py-3">
{/* The detail dialog already owns the modal lock. */}
<DropdownMenu modal={false}>
<DropdownMenuTrigger asChild><Button size="icon" variant="ghost" disabled={busy} aria-label="更多操作" className="h-11 w-11 text-muted-foreground sm:h-9 sm:w-9"><MoreHorizontal className="h-4 w-4" aria-hidden /></Button></DropdownMenuTrigger>
<DropdownMenuContent side="top" align="start">
<DropdownMenuItem disabled={busy || !canToggle} onSelect={onToggle}>{job.enabled ? '停用任务' : '启用任务'}</DropdownMenuItem>
{originHref ? <DropdownMenuItem asChild><a href={originHref}>打开聊天</a></DropdownMenuItem> : null}
<DropdownMenuSeparator />
<DropdownMenuItem tone="destructive" disabled={busy} onSelect={onDelete}>删除任务</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
<div className="ml-auto flex gap-2">
<Button variant="ghost" size="sm" className="h-11 font-normal sm:h-9" disabled={busy} onClick={onEdit}>编辑</Button>
{!localTrigger ? <Button variant="secondary" size="sm" className="h-11 font-normal sm:h-9" disabled={busy || !canRun} onClick={onRun}>立即运行</Button> : null}
</div>
</div>;
}
+72 -165
View File
@@ -1,184 +1,91 @@
# Automation chat proposal
# Automation chat selection
Draft for design review. This is a runnable UI prototype, not a working change
to automation routing. It does not change the production build or gateway.
This draft now implements chat selection in the production WebUI and Python
gateway. The earlier in-memory preview and its build transform have been removed.
See [the user guide](../../../docs/automations.md#change-the-chat-for-a-scheduled-task)
for the interaction, limits, and downgrade warning.
## Problem
## Design decision
Automation details show the channel, such as “WeChat”, but not the specific
conversation. Users cannot check where a task runs and replies. Some put raw
`channel` and `chat_id` instructions in the task prompt to control delivery.
The display gap is confirmed in the source. A wrong-recipient incident has not
been reproduced from the reports.
The concerns in [#5513](https://github.com/HKUDS/nanobot/issues/5513#issuecomment-5488297111)
and [#5620](https://github.com/HKUDS/nanobot/pull/5620#issuecomment-5534384796)
still apply: running in chat A and forwarding the result to chat B separates
the reply from its history and can expose context from A.
The interface should answer two questions in plain language:
This implementation changes the whole binding for future runs: execution chat,
recorded turn, and default reply route. It does not add a delivery override or
copy old messages. It still changes the creation-chat rule. Maintainer agreement
is pending, so the PR remains a draft.
- Which chat does this task use?
- If I change it, what happens to the next run?
## Ownership and commit boundary
## Proposed interaction
- The gateway resolves existing session handles, titles, canonical reply routes,
channel availability, and effective workspace policy. The browser cannot submit
a raw session key, channel, recipient, or topic address.
- `GET /api/webui/automations/chats?id=...` uses the existing API authentication.
`automation.change_chat` uses the authenticated WebSocket mutation path. A
direct HTTP mutation is rejected. Its values are `target_id`, `revision`, and
the reviewed `message`.
- The gateway resolves the target again at save time. It rejects unknown,
offline, foreign-scope, and unsupported targets. Topic address metadata is
retained; sender identity and previous workspace policy are not copied.
- The cron owner compares the reviewed revision after merging pending CLI
actions. It rejects while a scheduled turn owns a live execution snapshot,
including one waiting in the agent queue. This first version conservatively
blocks changes while any scheduled turn is active.
- One atomic write saves the whole binding and reviewed prompt before the new
snapshot becomes live. A pre-commit write failure leaves the old state intact.
If directory sync fails after replacement, the owner reads back that exact
snapshot before reporting success. A binding version prevents an older CLI
action snapshot from restoring the previous route.
- Each run retains its session identity. Before the first supported move, older
run records are stamped with the known unchanged original binding. Audit result
checks still verify job, run, session, status, and file path.
Use the existing Automations page and detail dialog. Show a channel logo on the
left, then the chat name and platform. The Chinese label is “任务所在聊天”
(“Task chat”). Do not show an invented account label or an unexplained ID suffix.
Production must still distinguish real same-name chats or topics when needed.
No new execution path, agent-loop policy, dependencies, or separate CSS system
are added. The dialog uses the existing Select, Dialog, Button, Textarea, channel
logos, and DropdownMenu. The detail dialog owns the modal lock. Confirmation is
explicit and progress stays local to that action. The page remains visible.
1. Keep the saved chat selected by default. Do not infer it from the latest chat.
2. Selecting another chat opens a review step in the same dialog.
3. Keep the new chat editable in that step. Show the original chat below it.
Explain that future runs use the new chat's history and reply there by default.
4. Let the user review and edit the task prompt. Warn when the target is a group.
5. Use one explicit “确认并更换” (“Confirm and change”) action. Do not add a
second confirmation checkbox. Put history and schedule details in a disclosure.
6. Change the displayed saved chat only after the save succeeds. Keep the draft
after a conflict or when the user returns to the task details.
## Compatibility
Keep “Edit” and “Run now” visible in the detail footer. Put enable/disable,
delete, and the existing open-chat link in “More”. Keep the existing delete
confirmation. Reuse the shared Disclosure and DropdownMenu controls, as the
remote-connection screens do; do not add another style system. The menu is
non-modal because the detail dialog already owns the modal interaction lock.
The gateway advertises optional `webui.automation-chat.v1`; the core protocol
floor stays at 1. The optional `chat_binding_revision` job field exposes the
control only for supported jobs. A new client sends no new request to an old
host. An old client can keep using ordinary edits on a new host.
Changing a chat must not run the task, change its schedule, or enable a paused
task. Keep the page mounted during review and show save progress next to the
action. Do not replace the page with a spinner or report success before an
acknowledgement. This follows the interaction principle discussed in
[The perfect app has no loading states](https://floriankiem.com/writing/the-perfect-app-has-no-loading-states).
Storage paths and job IDs do not change. `bindingVersion` and per-run `sessionKey`
are additive fields with legacy defaults. The active instance still owns its
cron store and action log. **Downgrade after a move is not transparent**: follow
the backup/restore procedure in the user guide. Mixed-version cron writers after
a move are not supported. Rejected stale CLI updates are logged; retry the edit
from the current version after reading the latest task.
## Decision needed before implementation
Explicit message-tool instructions can still override the default destination.
Prompt review is required, not automatic rewriting. The selector does not create
new isolation for shared workspace memory or files and does not guarantee that a
remote platform will accept delivery.
The maintainer rejected an independent result-delivery target in
[#5513](https://github.com/HKUDS/nanobot/issues/5513#issuecomment-5488297111)
and repeated that concern on
[#5620](https://github.com/HKUDS/nanobot/pull/5620#issuecomment-5534384796).
Running in chat A and sending the result to chat B separates the reply from its
history and can expose context from A.
## Verification
This proposal does **not** add a delivery override. It proposes changing the
whole binding for future runs: execution chat, recorded result, and default
reply destination move together. This still changes the current rule that a
task stays in its creation chat. Maintainer approval is pending.
The focused regression suite exercises the actual HTTP/WebSocket gateway,
session manager, scheduler, agent queue, persistence, and audit reader. It
checks save/read-back, execution history and outbound topic routing, old results,
revision conflict, pre/post-replace errors, stale CLI actions, running jobs,
scope and route filtering, and old-host UI behavior.
Implement this in two stages:
- **A: Read-only identity.** Show the exact bound chat when the gateway can
resolve it. If it cannot, say that the chat is unknown. Keep all bindings and
execution behavior unchanged. This stage can ship independently.
- **B: Explicit chat change.** Add the selector only after agreement on the
binding change and after the gateway contract is implemented and verified.
If the decision is no, keep A and direct users to create the task in the
intended chat.
## Gateway contract required for stage B
The gateway owns identity, authorization, execution, and persistence. The client
must not assemble a route from a channel name or provide platform credentials.
A possible operation is `change_binding(job_id, target_ref, expected_revision,
reviewed_message)`; this is a proposal, not an existing API.
- Resolve the target in the same host, configuration, and workspace. A connected
channel does not prove that a recipient or topic is valid or authorized.
- Initially support ordinary scheduled agent jobs only. Keep system jobs,
local triggers, unified-session mode, temporary/deleted chats, and cross-host
moves read-only. Do not allow arbitrary recipient IDs or multiple recipients.
- Check job revision and running/queued state in the same serialized operation
that changes the binding. Do not check in HTTP and then write without a guard.
- Save the complete binding and reviewed prompt together. A failed write keeps
the old in-memory and persisted values. Task admission must observe either the
old binding or the new one, never part of each.
- Preserve enabled state, schedule, timezone, and scheduled occurrence. A save
must not create an extra run or lose work already admitted.
- Preserve the target used by each historical run. Never fill old history with
the current target. If the old target was not recorded, report it as unknown.
- Do not copy messages, summaries, transcripts, or files from the previous chat.
This does not create new isolation for shared workspace files or memory.
- Require prompt review: explicit `message` instructions can still send to a
different destination. The selector is not an outbound-message sandbox.
Never rewrite arbitrary prompts automatically.
Use existing session/channel ownership to resolve identities and routes. Keep
the atomic update in the cron owner, not the client. Do not introduce WebUI
policy in `agent/loop.py` or `agent/runner.py`.
At base `6b24ed80`, `nanobot/webui/session_automations.py::_origin_payload`
returns only channel and empty display text for non-WebSocket jobs. The detail
panel renders that channel label. `nanobot/agent/tools/cron.py` captures the
creation route; `nanobot/cron/bound_runner.py` and `session_delivery.py` consume
the binding. Legacy `channel`/`to` fields are not an API for changing the modern
session binding.
## Compatibility and acceptance gates
Stage A should add optional read fields. Stage B needs an optional capability;
older hosts must not receive the new mutation. Ordinary edits and existing jobs
must continue to work. Any new persisted revision/audit fields need explicit
restart and rollback rules before stage B can ship.
Required evidence before enabling real saves:
- A default run and a moved run use the correct chat history, recorded turn,
and reply route. A reply in the target chat can continue the task.
- Task admission versus save, two-tab updates, write failure, and restart do not
produce a partial binding, double delivery, or false success.
- Invalid, deleted, foreign, or unauthorized targets are rejected. Same-name
chats and topic/account routes remain distinguishable.
- Paused and scheduled jobs retain their state. Running or queued jobs reject
the change. A busy target chat retains normal queue behavior.
- Supported old/new client-host combinations, missing capability, reconnect,
and a late response after host switching preserve the correct host scope.
- Desktop and narrow mobile layouts, keyboard selection, cancellation, prompt
review, failed saves, and save/read-back are verified.
These are implementation gates, not claims about this prototype.
Browser checks use the normal production build served by an isolated real
gateway. Chat data, model replies, and channel status are synthetic. Saves are
persisted to a temporary cron store; model network calls and external channel
senders are not started. Checks cover restart/read-back, running a saved task,
concurrent-edit rejection with retained draft, deletion cancellation, and
desktop/320 px/390 px layouts. This is not physical-iOS or real-platform delivery
acceptance. Raw test logs and local fixture state are kept outside the repository.
## Screenshots
Synthetic data from this opt-in preview; neither screen changes a real task.
Both screenshots show the production app connected to that isolated gateway.
![Task details with the saved chat and channel logo](detail.jpg)
![Saved task chat with its channel logo](detail.png)
![Review the new chat and task prompt before confirmation](review.jpg)
## Run the prototype
Install the existing WebUI dependencies with the repository's usual setup.
From `webui/`:
```sh
node node_modules/typescript/bin/tsc --noEmit -p proposals/automation-chat/tsconfig.json
node node_modules/vite/bin/vite.js build --config proposals/automation-chat/vite.config.ts
node node_modules/vite/bin/vite.js preview --config proposals/automation-chat/vite.config.ts
```
Open `http://127.0.0.1:53822/`. For the weather details, open
`http://127.0.0.1:53822/?detail&theme=dark`.
Use the preview menu to compare current/proposed UI and simulate a slow save,
conflict, queued task, or old host. Refresh resets all changes.
The prototype imports the real Sidebar, Automations page, dialogs, channel
logos, UI controls, translations, CSS, and Tailwind configuration. An opt-in
Vite transform replaces the linked-chat and detail-action slots and wraps the
review frame in memory.
The build fails if those source anchors change. The transform is not used by
the product build and is not a proposed production extension point.
## Prototype limits
- All tasks, chat identities, and save responses are synthetic React state.
There is no API proxy, gateway connection, model call, task run, or message
delivery. Existing logo components may load remote brand images.
- The current fixtures have one selectable chat per platform. They do not prove
identity resolution, recipient permissions, or same-name disambiguation.
- The old-send-instruction button removes one exact fixture block on an explicit
click. It does not detect arbitrary routing instructions or sensitive text.
- The preview is Chinese-first. Production copy still needs all supported
locales, including verified accessibility labels.
- UI-only browser checks covered desktop, 320/390 px layouts, draft retention,
save acknowledgement, conflict, cancellation, keyboard flow, and the original
UI comparison. The narrow layouts have visible 44 px confirmation buttons and
16 px prompt input text. A delete-menu handoff exposed a stale pointer lock;
the non-modal menu fix was verified by cancelling deletion, closing details,
and opening another task. These checks do not prove real delivery,
persistence, or physical iOS behavior.
- No production runtime, wire schema, saved data, or package dependencies change
in this draft. This proposal is not merge-ready as a routing feature.
![Review a chat change before saving](review.png)
Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

@@ -1,12 +0,0 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>nanobot — Automation chat proposal</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/main.tsx"></script>
</body>
</html>
-115
View File
@@ -1,115 +0,0 @@
import { useEffect, useState } from 'react';
import { createRoot } from 'react-dom/client';
import { Menu, Moon, Sun, SlidersHorizontal } from 'lucide-react';
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import zhCN from '@/i18n/locales/zh-CN/common.json';
import { Sidebar } from '@/components/Sidebar';
import { AutomationsSettings, AutomationEditDialog, AutomationDeleteDialog } from '@/components/settings/system/AutomationsSettings';
import { Button } from '@/components/ui/button';
import { DialogLayoutContext } from '@/components/ui/dialog';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { Select, SelectTrigger, SelectValue, SelectContent, SelectItem } from '@/components/ui/select';
import { Sheet, SheetContent, SheetTitle } from '@/components/ui/sheet';
import { ClientProvider } from '@/providers/ClientProvider';
import { NanobotClient } from '@/lib/nanobot-client';
import type { ChatSummary, SessionAutomationJob } from '@/lib/types';
import { PreviewContext, targets, legacy, type Target } from './BindingControls';
import '@/globals.css';
const params = new URLSearchParams(location.search);
void i18n.use(initReactI18next).init({ lng: 'zh-CN', fallbackLng: 'zh-CN', resources: { 'zh-CN': { translation: zhCN, 'channel-weixin': { displayName: '微信' }, 'channel-feishu': { displayName: '飞书' }, 'channel-telegram': { displayName: 'Telegram' } } }, interpolation: { escapeValue: false }, initAsync: false });
// Required by the real sidebar. Never connect this client to a gateway.
const client = new NanobotClient({ url: 'ws://127.0.0.1:1/preview-disabled', reconnect: false });
const now = Date.now();
const tomorrow = new Date(); tomorrow.setDate(tomorrow.getDate() + 1); tomorrow.setHours(8, 0, 0, 0);
const weather: SessionAutomationJob = {
id: 'demo-weather-changde', name: '天气推送·常德', enabled: true,
schedule: { kind: 'cron', expr: '0 8 * * *', tz: 'Asia/Shanghai' },
payload: { message: '查询常德未来一小时天气,整理一条简短推送,重点写:\n- 天气现象、气温/体感、降水概率\n- 穿衣、带伞、防晒与出行建议\n\n口语化、简短,不照抄原始输出,不加多余分析。' + legacy },
state: { next_run_at_ms: tomorrow.getTime(), last_run_at_ms: tomorrow.getTime() - 86400000, last_status: 'ok', run_history: [1, 2, 3].map(day => ({ run_at_ms: tomorrow.getTime() - (day + 1) * 86400000, status: 'ok', duration_ms: 16000 })) },
origin: { channel: 'weixin', chat_id: 'demo-person', session_key: 'weixin:demo-person', title: '我的私聊' },
created_at_ms: now - 7 * 86400000,
};
const initialJobs: SessionAutomationJob[] = [weather,
{ ...weather, id: 'demo-daily', name: '产品进展日报', schedule: { kind: 'cron', expr: '0 18 * * 1-5', tz: 'Asia/Shanghai' }, payload: { message: '整理今日产品进展、待解决问题和明日安排,发一条简短日报。' }, origin: { channel: 'feishu', chat_id: 'demo-product', session_key: 'feishu:demo-product', title: '产品讨论群' }, state: { next_run_at_ms: tomorrow.getTime() + 36000000, last_status: 'ok' } },
{ ...weather, id: 'demo-weekly', name: '每周阅读回顾', enabled: false, schedule: { kind: 'cron', expr: '0 20 * * 0', tz: 'Asia/Shanghai' }, payload: { message: '回顾本周阅读笔记,挑选三条值得保留的观点。' }, origin: { channel: 'websocket', chat_id: 'demo-reading', session_key: 'websocket:demo-reading', title: '天气助手' }, state: {} },
];
const sessions: ChatSummary[] = [
['websocket:demo-weather', '天气助手', '整理天气推送'],
['websocket:demo-product', '产品计划', '本周开发进展'],
['websocket:demo-reading', '阅读笔记', '整理近期阅读'],
].map(([key, title, preview]) => ({ key, title, preview, channel: 'websocket', chatId: key.split(':')[1], createdAt: new Date(now - 86400000).toISOString(), updatedAt: new Date(now).toISOString() }));
function Preview() {
const [mode, setMode] = useState(params.get('mode') || 'proposal');
const [scenario, setScenario] = useState(params.get('scenario') || 'ready');
const [dark, setDark] = useState(params.has('theme') ? params.get('theme') === 'dark' : matchMedia('(prefers-color-scheme: dark)').matches);
const [jobs, setJobs] = useState(initialJobs);
const [filter, setFilter] = useState<'all' | 'active' | 'paused' | 'failed' | 'system'>('all');
const [sidebarOpen, setSidebarOpen] = useState(true);
const [mobileOpen, setMobileOpen] = useState(false);
const [anchor, setAnchor] = useState<HTMLDivElement | null>(null);
const [editJob, setEditJob] = useState<SessionAutomationJob | null>(null);
const [deleteJob, setDeleteJob] = useState<SessionAutomationJob | null>(null);
const [returnJob, setReturnJob] = useState<SessionAutomationJob | null>(params.has('detail') ? weather : null);
const [notice, setNotice] = useState('');
useEffect(() => { document.documentElement.classList.toggle('dark', dark); }, [dark]);
const demoOnly = () => { setMobileOpen(false); setNotice('此预览仅开放自动任务及关联会话流程,其他页面未接入。'); };
const payload = { jobs: jobs.map(job => ({ ...job, state: { ...job.state, pending: scenario === 'pending' } })) };
const save = async (job: SessionAutomationJob, target: Target, message: string) => {
// Latency exists only in the slow-ack demo, never as a decorative minimum.
if (scenario === 'slow') await new Promise(resolve => setTimeout(resolve, 2200));
if (scenario === 'conflict') throw new Error('Simulated revision conflict');
setJobs(current => current.map(item => item.id !== job.id ? item : { ...item,
payload: { ...item.payload, message },
origin: { channel: targets[target].channel, chat_id: `demo-${target}`, session_key: `${targets[target].channel}:demo-${target}`, title: targets[target].name },
}));
};
const sidebar = (mobile = false) => <Sidebar sessions={sessions} activeKey={null} loading={false} newChatActive={false} activeUtility="automations"
collapsed={!mobile && !sidebarOpen} containActionMenus={mobile} onCollapse={() => mobile ? setMobileOpen(false) : setSidebarOpen(false)} onExpand={() => setSidebarOpen(true)}
onNewChat={demoOnly} onSelect={demoOnly} onRequestDelete={demoOnly} onTogglePin={demoOnly} onRequestRename={demoOnly} onToggleArchive={demoOnly} onToggleGroup={demoOnly} onRequestRenameProject={demoOnly} onNewChatInProject={demoOnly}
onOpenSettings={demoOnly} onOpenApps={demoOnly} onOpenSkills={demoOnly} onOpenChannels={demoOnly} onOpenSearch={demoOnly} onToggleArchived={demoOnly}
onOpenAutomations={() => { setMobileOpen(false); setNotice(''); }}/>
return <ClientProvider client={client} token=""><PreviewContext.Provider value={{ mode, scenario, save }}>
<div className="flex h-dvh w-full flex-col overflow-hidden bg-background text-foreground">
<header className="flex h-11 shrink-0 items-center justify-between gap-2 border-b border-border/45 bg-sidebar px-4">
<div className="flex min-w-0 items-center gap-3 text-[12px]"><span className="shrink-0 font-medium">自动任务 · 交互预览</span><span className="hidden truncate text-muted-foreground sm:inline">合成数据 · 不运行任务,不投递消息</span></div>
<div className="flex shrink-0 gap-1">
<Popover><PopoverTrigger asChild><Button variant="ghost" size="sm" className="h-8 gap-1.5 text-[12px] font-normal"><SlidersHorizontal className="h-3.5 w-3.5" aria-hidden/><span>预览选项</span></Button></PopoverTrigger>
<PopoverContent align="end" className="w-64 space-y-4 text-[13px]">
<label className="block space-y-2"><span className="text-muted-foreground">界面</span><Select value={mode} onValueChange={setMode}><SelectTrigger aria-label="界面版本"><SelectValue/></SelectTrigger><SelectContent><SelectItem value="proposal">拟议改动</SelectItem><SelectItem value="current">当前代码</SelectItem></SelectContent></Select></label>
<label className="block space-y-2"><span className="text-muted-foreground">模拟状态</span><Select value={scenario} onValueChange={setScenario}><SelectTrigger aria-label="模拟状态"><SelectValue/></SelectTrigger><SelectContent>{[['ready','正常'],['slow','保存较慢'],['conflict','版本冲突'],['pending','任务已排队'],['oldhost','旧主机']].map(([value,label]) => <SelectItem key={value} value={value}>{label}</SelectItem>)}</SelectContent></Select></label>
<p className="text-[12px] leading-5 text-muted-foreground">仅模拟 UI。真实保存还需 gateway 接口与能力校验。</p>
</PopoverContent>
</Popover>
<Button variant="ghost" size="icon" className="h-8 w-8" aria-label={dark ? '切换浅色' : '切换深色'} onClick={() => setDark(!dark)}>{dark ? <Sun className="h-4 w-4"/> : <Moon className="h-4 w-4"/>}</Button>
</div>
</header>
<div className="relative flex min-h-0 flex-1 overflow-hidden">
<aside className="relative z-20 hidden h-full shrink-0 overflow-hidden lg:block" style={{ width: sidebarOpen ? 256 : 56 }}>{sidebar()}</aside>
<Sheet open={mobileOpen} onOpenChange={setMobileOpen}><SheetContent side="left" showCloseButton={false} aria-describedby={undefined} className="w-[280px] max-w-[85vw] p-0 lg:hidden"><SheetTitle className="sr-only">侧边栏</SheetTitle>{sidebar(true)}</SheetContent></Sheet>
<main className="relative flex min-w-0 flex-1 flex-col overflow-hidden bg-settings-canvas">
<div className="flex h-12 shrink-0 items-center gap-2 px-3 lg:hidden"><Button variant="ghost" size="icon" aria-label="打开侧边栏" onClick={() => setMobileOpen(true)}><Menu className="h-4 w-4"/></Button><span className="text-[13px]">nanobot</span></div>
<DialogLayoutContext.Provider value={anchor}>
<div className="min-w-0 flex-1 overflow-y-auto [scrollbar-gutter:stable]">
<div ref={setAnchor} data-settings-section="automations" data-main-navigation-expanded={sidebarOpen} className="settings-grid settings-feature-page settings-automations-grid mx-auto w-full py-6 sm:py-8 lg:py-12">
<AutomationsSettings payload={payload} loading={false} filter={filter} actionKey={null} error={null} onFilterChange={setFilter}
onStartChat={() => { setNotice('仅演示:创建请求未发送。输入草稿仍保留。'); return false; }} onManageModels={demoOnly}
onAction={(action, job) => { if (action === 'enable' || action === 'disable') setJobs(current => current.map(item => item.id === job.id ? { ...item, enabled: action === 'enable' } : item)); else setNotice('仅演示:没有运行任务或投递消息。'); }}
onRequestEdit={setEditJob} onRequestDelete={setDeleteJob} returnToDetailJob={returnJob} onReturnToDetailHandled={() => setReturnJob(null)}/>
{notice ? <p role="status" className="mt-4 text-[12px] leading-5 text-muted-foreground">{notice}</p> : null}
</div>
</div>
<AutomationEditDialog job={editJob} saving={false} onOpenChange={open => { if (!open) { setReturnJob(editJob); setEditJob(null); } }} onCancel={() => { setReturnJob(editJob); setEditJob(null); }} onSave={(job, values) => {
setJobs(current => current.map(item => item.id !== job.id ? item : { ...item, name: values.name ?? item.name, payload: { ...item.payload, message: values.message ?? item.payload.message }, schedule: { ...item.schedule, ...values.schedule } }));
setReturnJob(job); setEditJob(null);
}}/>
<AutomationDeleteDialog job={deleteJob} deleting={false} onOpenChange={open => { if (!open) { setReturnJob(deleteJob); setDeleteJob(null); } }} onConfirm={() => { setNotice('仅演示:任务没有删除。'); setReturnJob(deleteJob); setDeleteJob(null); }}/>
</DialogLayoutContext.Provider>
</main>
</div>
</div>
</PreviewContext.Provider></ClientProvider>;
}
createRoot(document.getElementById('root')!).render(<Preview/>);
Binary file not shown.

Before

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

@@ -1,5 +0,0 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": { "types": ["node", "vite/client"] },
"include": ["main.tsx", "BindingControls.tsx"]
}
@@ -1,78 +0,0 @@
import { defineConfig, normalizePath } from 'vite';
import react from '@vitejs/plugin-react';
import tailwindcss from 'tailwindcss';
import autoprefixer from 'autoprefixer';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import baseTailwind from '../../tailwind.config.js';
const root = path.dirname(fileURLToPath(import.meta.url));
const webui = path.resolve(root, '../..');
const repository = path.dirname(webui);
const realAutomations = normalizePath(path.join(webui, 'src/components/settings/system/AutomationsSettings.tsx'));
const linkedChat = ` <dl>
{!job.protected && job.origin?.channel && job.origin.channel !== "websocket" ? (
<AutomationDetail label={tx("settings.automations.labels.origin", "Linked chat")}>
{automationChannelLabel(job.origin.channel, t)}
</AutomationDetail>
) : null}
</dl>`;
const panelStart = ' <AutomationDetailPanel\n';
const panelEnd = ' onRequestDelete={onRequestDelete}\n />';
const actionsStart = ' {canManage ? (\n <div className="flex shrink-0 flex-wrap items-center gap-x-6 gap-y-2 border-t border-border/45 px-6 py-3">';
const actionsEnd = '\n ) : null}';
// These opt-in slots never edit product source or enter the production build.
export default defineConfig({
root,
publicDir: path.join(webui, 'public'),
cacheDir: path.join(root, '.vite'),
plugins: [{
name: 'automation-chat-proposal',
enforce: 'pre',
transform(source, id) {
if (normalizePath(id.split('?')[0]) !== realAutomations) return;
const code = source.replace(/\r\n/g, '\n');
for (const anchor of [linkedChat, panelStart, panelEnd, actionsStart]) {
if (code.split(anchor).length !== 2) {
throw new Error('Automation detail markup changed. Update the proposal seam.');
}
}
const from = code.indexOf(actionsStart);
const to = code.indexOf(actionsEnd, from);
if (to < 0) throw new Error('Automation detail actions changed. Update the proposal seam.');
const actions = code.slice(from, to + actionsEnd.length);
return {
code: `import { BindingControls, BindingDialogFrame, BindingDetailActions } from ${JSON.stringify(normalizePath(path.join(root, 'BindingControls.tsx')))};\n`
+ code.replace(linkedChat, ` <BindingControls job={job} currentUi={${linkedChat.trim()}} />`)
.replace(panelStart, ' <BindingDialogFrame key={job.id} job={job}><AutomationDetailPanel\n')
.replace(panelEnd, ' onRequestDelete={onRequestDelete}\n /></BindingDialogFrame>')
.replace(actions, ` {canManage ? <BindingDetailActions job={job} busy={busy} canToggle={canToggle} canRun={canRun} localTrigger={localTrigger} originHref={originHref}
onToggle={() => void onAction(job.enabled ? "disable" : "enable", job)} onRun={() => void onAction("run", job)}
onEdit={() => onRequestEdit(job)} onDelete={() => onRequestDelete(job)} currentUi={<>{${actions.trim().slice(1, -1)}}</>} /> : null}`),
map: null,
};
},
}, react()],
resolve: {
alias: { '@': path.join(webui, 'src') },
dedupe: ['react', 'react-dom', 'lucide-react', 'react-i18next', 'i18next'],
},
css: {
postcss: {
plugins: [tailwindcss({
...baseTailwind,
content: [
normalizePath(path.join(webui, 'src/**/*.{ts,tsx}')),
normalizePath(path.join(repository, 'nanobot/channels/*/webui/**/*.{ts,tsx}')),
normalizePath(path.join(webui, 'node_modules/streamdown/dist/*.js')),
normalizePath(path.join(root, '*.{tsx,html}')),
],
}), autoprefixer()],
},
},
// No API proxy. The proposal must not talk to an installed gateway.
server: { host: '127.0.0.1', port: 53822, strictPort: true, fs: { allow: [repository] } },
preview: { host: '127.0.0.1', port: 53822, strictPort: true },
build: { outDir: path.join(root, 'dist') },
});
@@ -121,6 +121,7 @@ export function SettingsPage({
handleApiServiceAction,
handleAutomationAction,
handleAutomationEdit,
handleAutomationChat,
handleCliAppAction,
handleDeleteModelConfiguration,
handleImportMcpConfig,
@@ -596,6 +597,7 @@ export function SettingsPage({
setAutomationPendingEdit(job);
}}
onRequestDelete={setAutomationPendingDelete}
onChangeChat={handleAutomationChat}
onManageModels={() => selectSection("models")}
returnToDetailJob={automationDetailReturn}
onReturnToDetailHandled={() => setAutomationDetailReturn(null)}
@@ -0,0 +1,138 @@
import { useEffect, useRef, useState, type ReactNode } from "react";
import { useTranslation } from "react-i18next";
import { ChannelLogo } from "@/components/settings/channels/ChannelIdentity";
import { channelUiOwner, channelUiPresentation } from "@/channel-plugins/registry";
import { channelTranslator } from "@/channel-plugins/i18n";
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 { fetchAutomationChats } from "@/lib/api";
import { readLocalPreferences } from "@/lib/local-preferences";
import type { AutomationChat, AutomationChatsPayload, AutomationChatUpdate, NanobotFeatureInfo, SessionAutomationJob } from "@/lib/types";
export type ChangeAutomationChat = (job: SessionAutomationJob, values: AutomationChatUpdate) => Promise<void>;
function ChatIdentity({ chat }: { chat: AutomationChat }) {
const { t } = useTranslation();
const owner = channelUiOwner(chat.channel);
const presentation = channelUiPresentation(chat.channel);
const platform = chat.channel === "websocket" ? t("settings.automations.chat.web")
: channelTranslator(t, owner)("displayName", presentation?.displayName ?? chat.channel);
const feature: NanobotFeatureInfo = {
name: chat.channel, display_name: platform, type: "channel", enabled: true,
installed: true, ready: true, status: "ready", install_supported: false, requires_restart: false,
};
return <span className="flex min-w-0 items-center gap-2.5 text-start">
<span aria-hidden className="relative h-6 w-6 shrink-0">
{chat.channel === "websocket" ? <img src="/brand/nanobot_mark.svg" alt="" className="h-6 w-6" />
: <span className="absolute left-0 top-0 origin-top-left scale-75"><ChannelLogo feature={feature} showBrandLogos={readLocalPreferences().brandLogos} /></span>}
</span>
<span className="flex min-w-0 flex-wrap items-baseline gap-x-2 text-[13px] leading-5">
<span className="min-w-0 break-words">{chat.title}</span><span className="text-[12px] text-muted-foreground">{platform}</span>
</span>
</span>;
}
export function AutomationChatBinding({ job, token, onSave, children }: {
job: SessionAutomationJob; token: string; onSave: ChangeAutomationChat;
children: (picker: ReactNode) => ReactNode;
}) {
const { t } = useTranslation();
const tx = (key: string) => t(`settings.automations.chat.${key}`);
const [data, setData] = useState<AutomationChatsPayload | null>(null);
const [loadError, setLoadError] = useState(false);
const [reload, setReload] = useState(0);
const [draft, setDraft] = useState<{ target: string; revision: string; message: string } | null>(null);
const [saving, setSaving] = useState(false);
const [error, setError] = useState("");
const [saved, setSaved] = useState(false);
const heading = useRef<HTMLHeadingElement>(null);
const trigger = useRef<HTMLButtonElement>(null);
const returning = useRef(false);
useEffect(() => {
const controller = new AbortController();
setLoadError(false);
void fetchAutomationChats(token, job.id, controller.signal).then(value => {
if (!controller.signal.aborted) setData(value);
}).catch(() => { if (!controller.signal.aborted) setLoadError(true); });
return () => controller.abort();
}, [token, job.id, job.chat_binding_revision, reload]);
const reviewing = draft !== null;
useEffect(() => {
if (reviewing) heading.current?.focus();
else if (returning.current) { trigger.current?.focus(); returning.current = false; }
}, [reviewing]);
const back = () => { returning.current = true; setDraft(null); };
const current = data?.current;
const fallback: AutomationChat = { id: "current", title: job.origin?.title || tx("current"), channel: job.origin?.channel || "websocket" };
const locked = saving || Boolean(job.state.pending);
const picker = (review: boolean) => <Select value={review ? draft?.target : current?.id ?? "current"}
disabled={locked || !data?.chats.length || loadError || (!review && data.revision !== job.chat_binding_revision)} onValueChange={target => {
if (target === current?.id) return;
setError(""); setSaved(false);
setDraft(previous => previous ? { ...previous, target } : {
target, revision: job.chat_binding_revision!, message: job.payload.message,
});
}}>
<SelectTrigger ref={review ? undefined : trigger} aria-label={tx(review ? "new" : "label")}
className={`h-auto min-h-11 w-full py-2 [&>span:first-child]:min-w-0 [&>span:first-child]:flex-1 [&>span:first-child]:text-start ${review ? "" : "border-transparent bg-transparent hover:bg-muted/50"}`}>
<SelectValue><ChatIdentity chat={data?.chats.find(chat => chat.id === (review ? draft?.target : current?.id)) ?? fallback} /></SelectValue>
</SelectTrigger>
<SelectContent>
{!current ? <SelectItem value="current" disabled><ChatIdentity chat={fallback} /></SelectItem> : null}
{data?.chats.map(chat => <SelectItem key={chat.id} value={chat.id} textValue={`${chat.title} ${chat.channel}`}
disabled={chat.unavailable || (review && chat.id === current?.id)}
className="h-auto min-h-11 py-2 [&>span:last-child]:min-w-0 [&>span:last-child]:max-w-[calc(100vw-5rem)] [&>span:last-child]:w-full"><ChatIdentity chat={chat} /></SelectItem>)}
</SelectContent>
</Select>;
const save = async () => {
if (!draft || locked || !draft.message.trim()) return;
setSaving(true); setError("");
try {
await onSave(job, { target_id: draft.target, revision: draft.revision, message: draft.message });
setData(previous => previous ? { ...previous, current: previous.chats.find(chat => chat.id === draft.target) ?? null } : previous);
setSaved(true); back(); setReload(value => value + 1);
} catch (cause) {
const reasons: Record<string, string> = {
automation_chat_conflict: "conflict", automation_chat_busy: "schedulerBusy",
automation_chat_unavailable: "unavailable",
};
setError(tx(cause instanceof Error ? reasons[cause.message] ?? "failed" : "failed"));
} finally { setSaving(false); }
};
if (!draft) return children(<div className="space-y-1">
<div className="grid min-w-0 grid-cols-1 items-start gap-1 py-1 min-[420px]:grid-cols-[6rem_minmax(0,1fr)] min-[420px]:gap-4">
<span className="text-[13px] text-muted-foreground min-[420px]:pt-3">{tx("label")}</span>
{picker(false)}
</div>
<p role={saved ? "status" : undefined} className="text-[12px] leading-5 text-muted-foreground">
{job.state.pending ? tx("busy") : saved ? tx("saved") : tx("hint")}
</p>
{loadError ? <Button variant="link" size="sm" onClick={() => setReload(value => value + 1)}>{tx("retry")}</Button> : null}
{data && data.chats.length <= (current ? 1 : 0) ? <p className="text-[12px] leading-5 text-muted-foreground">{tx("available")}</p> : null}
</div>);
return <>
<DialogHeader className="shrink-0 px-6 pb-4 pr-12 pt-5 text-left">
<DialogTitle ref={heading} tabIndex={-1} className="text-lg font-medium leading-snug tracking-normal outline-none">{tx("change")}</DialogTitle>
</DialogHeader>
<div className="min-h-0 space-y-4 overflow-y-auto overscroll-contain px-6">
<div className="space-y-2">
{picker(true)}
<p className="text-[12px] leading-5 text-muted-foreground">{tx("previous")} {current?.title || fallback.title}</p>
<p className="text-[13px] leading-5">{tx("effect")}</p>
</div>
<label className="block space-y-2"><span className="text-[13px] font-medium">{tx("message")}</span>
<Textarea rows={3} value={draft.message} disabled={saving} onChange={event => setDraft({ ...draft, message: event.target.value })}
className="min-h-20 resize-y text-base leading-6 sm:text-[13px] sm:leading-5" />
</label>
<p className="text-[12px] leading-5 text-muted-foreground">{tx("review")}</p>
<p className="text-[12px] leading-5 text-muted-foreground">{tx("history")}</p>
{error ? <p role="alert" className="text-[12px] leading-5 text-destructive">{error}</p> : null}
</div>
<DialogFooter className="shrink-0 flex-row justify-end gap-2 px-6 pb-5 pt-3">
<Button variant="ghost" size="sm" disabled={saving} className="h-11 font-normal text-muted-foreground sm:h-9" onClick={back}>{t("settings.automations.cancel")}</Button>
<Button size="sm" className="h-11 sm:h-9" disabled={locked || !draft.message.trim()} aria-busy={saving} onClick={() => void save()}>{tx(saving ? "saving" : "confirm")}</Button>
</DialogFooter>
</>;
}
@@ -8,12 +8,14 @@ import {
Clipboard,
ListFilter,
Loader2,
MoreHorizontal,
} from "lucide-react";
import { useTranslation } from "react-i18next";
import { channelTranslator } from "@/channel-plugins/i18n";
import { channelUiOwner, channelUiPresentation } from "@/channel-plugins/registry";
import { AutomationCalendar } from "@/components/settings/system/AutomationCalendar";
import { AutomationChatBinding, type ChangeAutomationChat } from "@/components/settings/system/AutomationChatBinding";
import { AutomationRunAtPicker, parseAutomationRunAt } from "@/components/settings/system/AutomationRunAtPicker";
import {
modelPresetOptionsFromSettings,
@@ -23,7 +25,7 @@ import { ThreadComposer } from "@/components/thread/ThreadComposer";
import { Button } from "@/components/ui/button";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
import { DropdownMenu, DropdownMenuContent, DropdownMenuRadioGroup, DropdownMenuRadioItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuRadioGroup, DropdownMenuRadioItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { ExpandableText } from "@/components/ui/expandable-text";
import {
Dialog,
@@ -62,6 +64,7 @@ export function AutomationsSettings({
onFilterChange, onAction,
onRequestEdit, onRequestDelete, onStartChat, onManageModels,
returnToDetailJob = null, onReturnToDetailHandled,
onChangeChat,
}: {
token?: string;
payload: AutomationsPayload | null;
@@ -84,6 +87,7 @@ export function AutomationsSettings({
onManageModels?: () => void;
returnToDetailJob?: SessionAutomationJob | null;
onReturnToDetailHandled?: () => void;
onChangeChat?: ChangeAutomationChat;
}) {
const { t, i18n } = useTranslation();
const tx = (key: string, fallback: string, values?: Record<string, unknown>) =>
@@ -362,6 +366,8 @@ export function AutomationsSettings({
</div>
<AutomationDetailDialog
token={token}
onChangeChat={onChangeChat}
job={selectedJob}
open={detailOpen}
locale={locale}
@@ -388,6 +394,8 @@ export function AutomationsSettings({
}
export function AutomationDetailDialog({
token = "",
onChangeChat,
job,
open,
locale,
@@ -399,6 +407,8 @@ export function AutomationDetailDialog({
onRequestDelete,
onCloseAutoFocus,
}: {
token?: string;
onChangeChat?: ChangeAutomationChat;
job: SessionAutomationJob | null;
open: boolean;
locale: string;
@@ -410,6 +420,11 @@ export function AutomationDetailDialog({
onRequestDelete: (job: SessionAutomationJob) => void;
onCloseAutoFocus?: (event: Event) => void;
}) {
const panel = (chatPicker?: ReactNode) => job ? <AutomationDetailPanel
key={job.id} job={job} locale={locale} actionKey={actionKey} error={error}
onAction={onAction} onRequestEdit={onRequestEdit} onRequestDelete={onRequestDelete}
chatPicker={chatPicker}
/> : null;
return (
<Dialog open={open} onOpenChange={onOpenChange}>
{job ? (
@@ -422,16 +437,9 @@ export function AutomationDetailDialog({
)}
onCloseAutoFocus={onCloseAutoFocus}
>
<AutomationDetailPanel
key={job.id}
job={job}
locale={locale}
actionKey={actionKey}
error={error}
onAction={onAction}
onRequestEdit={onRequestEdit}
onRequestDelete={onRequestDelete}
/>
{job.chat_binding_revision && onChangeChat ? (
<AutomationChatBinding key={job.id} job={job} token={token} onSave={onChangeChat}>{panel}</AutomationChatBinding>
) : panel()}
</DialogContent>
) : null}
</Dialog>
@@ -441,7 +449,9 @@ export function AutomationDetailDialog({
function AutomationDetailPanel({
job, locale, actionKey, error, onAction, onRequestEdit, onRequestDelete,
chatPicker,
}: {
chatPicker?: ReactNode;
job: SessionAutomationJob;
locale: string;
actionKey: string | null;
@@ -552,44 +562,28 @@ function AutomationDetailPanel({
</section> : null}
{job.state.last_error ? <AutomationError message={job.state.last_error} /> : null}
{error ? <AutomationError message={error} /> : null}
<dl>
{chatPicker ?? <dl>
{!job.protected && job.origin?.channel && job.origin.channel !== "websocket" ? (
<AutomationDetail label={tx("settings.automations.labels.origin", "Linked chat")}>
{automationChannelLabel(job.origin.channel, t)}
</AutomationDetail>
) : null}
</dl>
</dl>}
</div>
{canManage ? (
<div className="flex shrink-0 flex-wrap items-center gap-x-6 gap-y-2 border-t border-border/45 px-6 py-3">
<div className="flex max-w-full flex-wrap gap-2">
<Button variant="ghost" size="sm" className="font-normal text-muted-foreground" disabled={busy || !canToggle}
onClick={() => void onAction(job.enabled ? "disable" : "enable", job)}>
{actionKey === `enable:${job.id}` || actionKey === `disable:${job.id}`
? <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" aria-hidden /> : null}
{job.enabled ? tx("settings.automations.pause", "Disable") : tx("settings.automations.resume", "Enable")}
</Button>
{!localTrigger ? (
<Button variant="ghost" size="sm" className="font-normal text-muted-foreground" disabled={!canRun || busy} onClick={() => void onAction("run", job)}>
{actionKey === `run:${job.id}` ? <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" aria-hidden /> : null}
{tx("settings.automations.runNow", "Run now")}
</Button>
) : null}
<Button
variant="ghost"
size="sm"
className="font-normal text-muted-foreground hover:bg-destructive/10 hover:text-destructive focus-visible:text-destructive"
disabled={busy}
onClick={() => onRequestDelete(job)}
>
{tx("settings.automations.delete", "Delete")}
</Button>
</div>
<div className="ms-auto flex max-w-full flex-wrap justify-end gap-2">
<Button variant="ghost" size="sm" className="font-normal text-muted-foreground" disabled={busy} onClick={() => onRequestEdit(job)}>
{tx("settings.automations.edit", "Edit")}
</Button>
{originHref ? <Button asChild variant="ghost" size="sm" className="font-normal text-muted-foreground"><a href={originHref}>{tx("settings.automations.emptyAction", "Open a chat")}</a></Button> : null}
<div className="flex shrink-0 items-center gap-2 border-t border-border/45 px-6 py-3">
<DropdownMenu modal={false}>
<DropdownMenuTrigger asChild><Button size="icon" variant="ghost" disabled={busy} aria-label={tx("settings.automations.moreActions", "More actions")} className="h-11 w-11 text-muted-foreground sm:h-9 sm:w-9"><MoreHorizontal className="h-4 w-4" aria-hidden /></Button></DropdownMenuTrigger>
<DropdownMenuContent side="top" align="start">
<DropdownMenuItem disabled={busy || !canToggle} onSelect={() => void onAction(job.enabled ? "disable" : "enable", job)}>{job.enabled ? tx("settings.automations.pause", "Disable") : tx("settings.automations.resume", "Enable")}</DropdownMenuItem>
{originHref ? <DropdownMenuItem asChild><a href={originHref}>{tx("settings.automations.emptyAction", "Open a chat")}</a></DropdownMenuItem> : null}
<DropdownMenuSeparator />
<DropdownMenuItem tone="destructive" disabled={busy} onSelect={() => onRequestDelete(job)}>{tx("settings.automations.delete", "Delete")}</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
<div className="ml-auto flex gap-2">
<Button variant="ghost" size="sm" className="h-11 font-normal sm:h-9" disabled={busy} onClick={() => onRequestEdit(job)}>{tx("settings.automations.edit", "Edit")}</Button>
{!localTrigger ? <Button variant="secondary" size="sm" className="h-11 font-normal sm:h-9" disabled={busy || !canRun} onClick={() => void onAction("run", job)}>{tx("settings.automations.runNow", "Run now")}</Button> : null}
</div>
</div>
) : null}
@@ -11,6 +11,7 @@ import { DEFAULT_CUSTOM_MCP_FORM } from "@/components/settings/system/AppsSettin
import type { SystemSettingsState } from "@/components/settings/system/useSystemSettingsState";
import {
cancelMcpOAuth,
changeAutomationChat,
completeMcpOAuth,
disableNanobotFeature,
enableNanobotFeature,
@@ -34,6 +35,7 @@ import { notifyMcpPresetsChanged } from "@/lib/mcp-preset-events";
import type { NanobotClient } from "@/lib/nanobot-client";
import type {
AutomationUpdatePayload,
AutomationChatUpdate,
McpOAuthFlowPayload,
McpPresetsPayload,
NanobotFeatureInfo,
@@ -298,6 +300,12 @@ export function createSystemSettingsActions({
}
};
const handleAutomationChat = async (job: SessionAutomationJob, values: AutomationChatUpdate) => {
// The dialog owns the draft and error. Publish only the server acknowledgement.
const payload = await changeAutomationChat(client, job.id, values);
setAutomations(payload);
};
const closeMcpOAuthPopup = () => {
const popup = mcpOAuthPopupRef.current;
mcpOAuthPopupRef.current = null;
@@ -668,6 +676,7 @@ export function createSystemSettingsActions({
handleApiServiceAction,
handleAutomationAction,
handleAutomationEdit,
handleAutomationChat,
handleCliAppAction,
handleImportMcpConfig,
handleMcpOAuthCancel,
@@ -476,6 +476,7 @@ export function useSettingsController({
handleApiServiceAction,
handleAutomationAction,
handleAutomationEdit,
handleAutomationChat,
handleCliAppAction,
handleImportMcpConfig,
handleMcpOAuthCancel,
@@ -526,6 +527,7 @@ export function useSettingsController({
handleApiServiceAction,
handleAutomationAction,
handleAutomationEdit,
handleAutomationChat,
handleCliAppAction,
handleDeleteModelConfiguration,
handleImportMcpConfig,
+23
View File
@@ -1394,6 +1394,29 @@
"notEnabled": "Not enabled"
},
"automations": {
"chat": {
"conflict": "The task changed elsewhere. Your draft is kept. Reopen the task to review the latest settings.",
"unavailable": "This chat is no longer available with the same workspace and access mode. Select another chat.",
"schedulerBusy": "A task is running or queued. Wait for it to finish, then try again.",
"label": "Task chat",
"new": "New chat",
"current": "Current chat",
"web": "Web chat",
"change": "Change chat",
"previous": "Previous chat:",
"hint": "Uses this chat’s history. Results return here by default.",
"effect": "Future runs will use the new chat’s history and send results there by default.",
"message": "Task instructions",
"review": "Check for instructions that send to another chat. People in the new chat may see the task and its results.",
"history": "Old messages stay in the old chat. The schedule stays the same. This does not run the task.",
"busy": "Cannot change while this task is running or queued.",
"saved": "Changed. Applies to future runs.",
"failed": "Could not confirm the change. Your draft is kept.",
"retry": "Retry loading chats",
"confirm": "Confirm change",
"saving": "Changing…",
"available": "To add a chat, send nanobot a message there first. Only connected chats with the same workspace and access mode are listed."
},
"taskInfo": "Task information",
"runDetails": {
"loading": "Loading response…",
+23
View File
@@ -1195,6 +1195,29 @@
"notEnabled": "No activado"
},
"automations": {
"chat": {
"conflict": "La tarea cambió en otro lugar. Se conserva el borrador. Abre la tarea de nuevo para revisar los ajustes.",
"unavailable": "Este chat ya no está disponible con el mismo espacio de trabajo y modo de acceso. Elige otro chat.",
"schedulerBusy": "Hay una tarea en ejecución o en cola. Espera a que termine e inténtalo de nuevo.",
"label": "Chat de la tarea",
"new": "Nuevo chat",
"current": "Chat actual",
"web": "Chat web",
"change": "Cambiar chat",
"previous": "Chat anterior:",
"hint": "Usa el historial de este chat. Los resultados se envían aquí por defecto.",
"effect": "Las próximas ejecuciones usarán el historial del nuevo chat y enviarán allí los resultados por defecto.",
"message": "Instrucciones de la tarea",
"review": "Revisa las instrucciones que envíen a otro chat. Los miembros del nuevo chat pueden ver la tarea y sus resultados.",
"history": "Los mensajes anteriores permanecen en el chat original. El horario no cambia. La tarea no se ejecuta ahora.",
"busy": "No se puede cambiar mientras la tarea se ejecuta o espera en la cola.",
"saved": "Cambiado. Se aplica a las próximas ejecuciones.",
"failed": "No se pudo confirmar el cambio. Se conserva el borrador.",
"retry": "Volver a cargar chats",
"confirm": "Confirmar cambio",
"saving": "Cambiando…",
"available": "Primero envía un mensaje a nanobot en el chat de destino. Solo se muestran chats conectados con el mismo espacio de trabajo y modo de acceso."
},
"taskInfo": "Información de la tarea",
"runDetails": {
"loading": "Cargando respuesta…",
+23
View File
@@ -1194,6 +1194,29 @@
"notEnabled": "Non activé"
},
"automations": {
"chat": {
"conflict": "La tâche a été modifiée ailleurs. Le brouillon est conservé. Rouvrez la tâche pour vérifier ses paramètres.",
"unavailable": "Cette discussion n’est plus disponible avec le même espace de travail et mode d’accès. Choisissez-en une autre.",
"schedulerBusy": "Une tâche est en cours ou en attente. Attendez la fin, puis réessayez.",
"label": "Discussion de la tâche",
"new": "Nouvelle discussion",
"current": "Discussion actuelle",
"web": "Discussion web",
"change": "Changer de discussion",
"previous": "Ancienne discussion :",
"hint": "Utilise l’historique de cette discussion et y envoie les résultats par défaut.",
"effect": "Les prochaines exécutions utiliseront l’historique de la nouvelle discussion et y enverront les résultats par défaut.",
"message": "Instructions de la tâche",
"review": "Vérifiez les instructions qui envoient vers une autre discussion. Les membres de la nouvelle discussion peuvent voir la tâche et ses résultats.",
"history": "Les anciens messages restent dans la discussion d’origine. L’horaire ne change pas. La tâche ne démarre pas maintenant.",
"busy": "Modification impossible si la tâche est en cours ou en attente.",
"saved": "Modifié. S’applique aux prochaines exécutions.",
"failed": "Impossible de confirmer la modification. Le brouillon est conservé.",
"retry": "Recharger les discussions",
"confirm": "Confirmer",
"saving": "Modification…",
"available": "Envoyez d’abord un message à nanobot dans la discussion cible. Seules les discussions connectées avec le même espace de travail et mode d’accès sont proposées."
},
"taskInfo": "Informations sur la tâche",
"runDetails": {
"loading": "Chargement de la réponse…",
+23
View File
@@ -1194,6 +1194,29 @@
"notEnabled": "Belum aktif"
},
"automations": {
"chat": {
"conflict": "Tugas diubah di tempat lain. Draf disimpan. Buka ulang tugas untuk memeriksa pengaturan terbaru.",
"unavailable": "Chat ini tidak tersedia lagi dengan ruang kerja dan mode akses yang sama. Pilih chat lain.",
"schedulerBusy": "Ada tugas berjalan atau mengantre. Tunggu hingga selesai, lalu coba lagi.",
"label": "Chat tugas",
"new": "Chat baru",
"current": "Chat saat ini",
"web": "Chat web",
"change": "Ganti chat",
"previous": "Chat sebelumnya:",
"hint": "Menggunakan riwayat chat ini. Hasil dikirim ke sini secara default.",
"effect": "Pelaksanaan berikutnya menggunakan riwayat chat baru dan mengirim hasil ke sana secara default.",
"message": "Instruksi tugas",
"review": "Periksa instruksi yang mengirim ke chat lain. Anggota chat baru mungkin dapat melihat tugas dan hasilnya.",
"history": "Pesan lama tetap di chat asal. Jadwal tidak berubah. Tugas tidak dijalankan sekarang.",
"busy": "Tidak dapat diganti saat tugas berjalan atau mengantre.",
"saved": "Diganti. Berlaku untuk pelaksanaan berikutnya.",
"failed": "Perubahan belum dapat dikonfirmasi. Draf disimpan.",
"retry": "Muat ulang chat",
"confirm": "Konfirmasi perubahan",
"saving": "Mengganti…",
"available": "Kirim pesan ke nanobot di chat tujuan terlebih dahulu. Hanya chat terhubung dengan ruang kerja dan mode akses yang sama yang ditampilkan."
},
"taskInfo": "Informasi tugas",
"runDetails": {
"loading": "Memuat respons…",
+23
View File
@@ -1194,6 +1194,29 @@
"notEnabled": "無効"
},
"automations": {
"chat": {
"conflict": "タスクが別の場所で変更されました。下書きは保持されています。タスクを開き直して最新の設定を確認してください。",
"unavailable": "このチャットは利用できないか、作業場所や権限が変わりました。別のチャットを選んでください。",
"schedulerBusy": "実行中または待機中のタスクがあります。完了後に再試行してください。",
"label": "タスクのチャット",
"new": "新しいチャット",
"current": "現在のチャット",
"web": "Webチャット",
"change": "チャットを変更",
"previous": "変更前:",
"hint": "このチャットの履歴を使い、通常はここに結果を送ります。",
"effect": "今後の実行では新しいチャットの履歴を使い、通常はそこに結果を送ります。",
"message": "タスクの指示",
"review": "別のチャットへの送信指示が残っていないか確認してください。新しいチャットの参加者にタスクと結果が見える場合があります。",
"history": "過去のメッセージは元のチャットに残ります。実行時刻は変わらず、今すぐ実行もしません。",
"busy": "実行中または待機中のタスクは変更できません。",
"saved": "変更しました。次回から適用されます。",
"failed": "変更を確認できませんでした。下書きは保存されています。",
"retry": "チャットを再読込",
"confirm": "変更を確定",
"saving": "変更中…",
"available": "先に対象のチャットで nanobot にメッセージを送ってください。同じ作業場所と権限で接続中のチャットのみ表示されます。"
},
"taskInfo": "タスク情報",
"runDetails": {
"loading": "応答を読み込み中…",
+23
View File
@@ -1194,6 +1194,29 @@
"notEnabled": "비활성화됨"
},
"automations": {
"chat": {
"conflict": "다른 곳에서 작업이 변경되었습니다. 초안은 유지됩니다. 작업을 다시 열어 최신 설정을 확인하세요.",
"unavailable": "이 채팅을 사용할 수 없거나 작업 공간 또는 권한이 변경되었습니다. 다른 채팅을 선택하세요.",
"schedulerBusy": "실행 중이거나 대기 중인 작업이 있습니다. 완료 후 다시 시도하세요.",
"label": "작업 채팅",
"new": "새 채팅",
"current": "현재 채팅",
"web": "웹 채팅",
"change": "채팅 변경",
"previous": "이전 채팅:",
"hint": "이 채팅의 기록을 사용하며 결과도 기본적으로 여기로 보냅니다.",
"effect": "다음 실행부터 새 채팅의 기록을 사용하며 결과도 기본적으로 그곳으로 보냅니다.",
"message": "작업 지침",
"review": "다른 채팅으로 보내라는 지침이 있는지 확인하세요. 새 채팅의 참여자가 작업 내용과 결과를 볼 수 있습니다.",
"history": "이전 메시지는 원래 채팅에 남습니다. 일정은 유지되며 지금 실행하지 않습니다.",
"busy": "작업이 실행 중이거나 대기 중이면 변경할 수 없습니다.",
"saved": "변경했습니다. 다음 실행부터 적용됩니다.",
"failed": "변경을 확인하지 못했습니다. 초안은 유지됩니다.",
"retry": "채팅 다시 불러오기",
"confirm": "변경 확인",
"saving": "변경 중…",
"available": "먼저 대상 채팅에서 nanobot에 메시지를 보내세요. 같은 작업 공간과 접근 권한을 가진 연결된 채팅만 표시됩니다."
},
"taskInfo": "작업 정보",
"runDetails": {
"loading": "응답을 불러오는 중…",
+23
View File
@@ -1208,6 +1208,29 @@
"notEnabled": "Não habilitado"
},
"automations": {
"chat": {
"conflict": "A tarefa foi alterada em outro lugar. O rascunho foi mantido. Abra a tarefa novamente para conferir os ajustes.",
"unavailable": "Esta conversa não está mais disponível com o mesmo espaço de trabalho e modo de acesso. Escolha outra conversa.",
"schedulerBusy": "Há uma tarefa em execução ou na fila. Aguarde a conclusão e tente novamente.",
"label": "Conversa da tarefa",
"new": "Nova conversa",
"current": "Conversa atual",
"web": "Conversa web",
"change": "Mudar conversa",
"previous": "Conversa anterior:",
"hint": "Usa o histórico desta conversa. Os resultados são enviados aqui por padrão.",
"effect": "As próximas execuções usarão o histórico da nova conversa e enviarão os resultados para lá por padrão.",
"message": "Instruções da tarefa",
"review": "Confira instruções que enviam para outra conversa. Os membros da nova conversa podem ver a tarefa e seus resultados.",
"history": "As mensagens antigas ficam na conversa original. O horário não muda. A tarefa não será executada agora.",
"busy": "Não é possível mudar enquanto a tarefa está em execução ou na fila.",
"saved": "Alterado. Vale para as próximas execuções.",
"failed": "Não foi possível confirmar a alteração. O rascunho foi mantido.",
"retry": "Recarregar conversas",
"confirm": "Confirmar alteração",
"saving": "Alterando…",
"available": "Primeiro envie uma mensagem ao nanobot na conversa de destino. Só são listadas conversas conectadas com o mesmo espaço de trabalho e modo de acesso."
},
"taskInfo": "Informações da tarefa",
"runDetails": {
"loading": "Carregando resposta…",
+23
View File
@@ -1194,6 +1194,29 @@
"notEnabled": "Chưa bật"
},
"automations": {
"chat": {
"conflict": "Tác vụ đã được đổi ở nơi khác. Bản nháp được giữ lại. Mở lại tác vụ để kiểm tra cài đặt mới nhất.",
"unavailable": "Cuộc trò chuyện này không còn khả dụng với cùng không gian làm việc và quyền truy cập. Hãy chọn cuộc trò chuyện khác.",
"schedulerBusy": "Có tác vụ đang chạy hoặc chờ. Hãy đợi hoàn tất rồi thử lại.",
"label": "Cuộc trò chuyện của tác vụ",
"new": "Cuộc trò chuyện mới",
"current": "Cuộc trò chuyện hiện tại",
"web": "Trò chuyện web",
"change": "Đổi cuộc trò chuyện",
"previous": "Cuộc trò chuyện cũ:",
"hint": "Dùng lịch sử trò chuyện này. Mặc định kết quả được gửi về đây.",
"effect": "Các lần chạy sau sẽ dùng lịch sử trò chuyện mới và mặc định gửi kết quả đến đó.",
"message": "Hướng dẫn tác vụ",
"review": "Kiểm tra hướng dẫn gửi đến cuộc trò chuyện khác. Thành viên trong cuộc trò chuyện mới có thể thấy tác vụ và kết quả.",
"history": "Tin nhắn cũ vẫn ở cuộc trò chuyện cũ. Lịch chạy không đổi. Tác vụ không chạy ngay.",
"busy": "Không thể đổi khi tác vụ đang chạy hoặc chờ trong hàng đợi.",
"saved": "Đã đổi. Áp dụng từ lần chạy tiếp theo.",
"failed": "Chưa thể xác nhận thay đổi. Bản nháp được giữ lại.",
"retry": "Tải lại cuộc trò chuyện",
"confirm": "Xác nhận thay đổi",
"saving": "Đang đổi…",
"available": "Trước tiên hãy gửi tin nhắn cho nanobot trong cuộc trò chuyện đích. Chỉ hiển thị cuộc trò chuyện đã kết nối, có cùng không gian làm việc và chế độ truy cập."
},
"taskInfo": "Thông tin tác vụ",
"runDetails": {
"loading": "Đang tải phản hồi…",
+23
View File
@@ -1394,6 +1394,29 @@
"notEnabled": "未启用"
},
"automations": {
"chat": {
"conflict": "任务已在别处修改,草稿已保留。请重新打开任务,核对最新设置后再更换。",
"unavailable": "这个聊天已不可用,或工作目录、权限已改变。请选择其他聊天。",
"schedulerBusy": "有任务正在执行或排队。请等任务结束后再试。",
"label": "任务所在聊天",
"new": "新聊天",
"current": "当前聊天",
"web": "网页聊天",
"change": "更换聊天",
"previous": "原聊天:",
"hint": "使用这里的聊天记录,结果也默认发到这里。",
"effect": "后续任务会使用新聊天的记录,结果也默认发到这里。",
"message": "任务说明",
"review": "请检查并移除发往其他聊天的旧指令。新聊天的成员可能看到任务内容和结果。",
"history": "旧消息留在原聊天。执行时间不变,也不会立即运行。",
"busy": "任务正在执行或排队,暂时不能更换。",
"saved": "已更换,下次执行生效。",
"failed": "未能确认更换成功,草稿已保留。",
"retry": "重新加载聊天",
"confirm": "确认并更换",
"saving": "正在更换…",
"available": "先在目标聊天给 nanobot 发一条消息。这里只列出已连接、工作目录和权限相同的聊天。"
},
"taskInfo": "任务信息",
"runDetails": {
"loading": "正在加载回复…",
+23
View File
@@ -1194,6 +1194,29 @@
"notEnabled": "未啟用"
},
"automations": {
"chat": {
"conflict": "任務已在別處修改,草稿已保留。請重新開啟任務,確認最新設定後再更換。",
"unavailable": "這個聊天已無法使用,或工作目錄、權限已變更。請選擇其他聊天。",
"schedulerBusy": "有任務正在執行或排隊。請等任務結束後再試。",
"label": "任務所在聊天",
"new": "新聊天",
"current": "目前聊天",
"web": "網頁聊天",
"change": "更換聊天",
"previous": "原聊天:",
"hint": "使用這裡的聊天記錄,結果也預設傳到這裡。",
"effect": "之後的任務會使用新聊天的記錄,結果也預設傳到那裡。",
"message": "任務說明",
"review": "請檢查並移除傳往其他聊天的舊指令。新聊天的成員可能看到任務內容和結果。",
"history": "舊訊息留在原聊天。執行時間不變,也不會立即執行。",
"busy": "任務正在執行或排隊,暫時無法更換。",
"saved": "已更換,下次執行生效。",
"failed": "無法確認更換成功,草稿已保留。",
"retry": "重新載入聊天",
"confirm": "確認並更換",
"saving": "正在更換…",
"available": "先在目標聊天傳一則訊息給 nanobot。這裡只列出已連線、工作目錄和權限相同的聊天。"
},
"taskInfo": "任務資訊",
"runDetails": {
"loading": "正在載入回覆…",
+10
View File
@@ -1,5 +1,7 @@
import type {
ApiServicePayload,
AutomationChatsPayload,
AutomationChatUpdate,
AutomationsPayload,
AutomationUpdatePayload,
ChannelConfigurePayload,
@@ -521,6 +523,14 @@ export async function fetchAutomations(
);
}
export async function fetchAutomationChats(token: string, id: string, signal?: AbortSignal): Promise<AutomationChatsPayload> {
return request(`/api/webui/automations/chats?id=${encodeURIComponent(id)}`, token, { signal }, API_READ_TIMEOUT_MS);
}
export async function changeAutomationChat(transport: WebUIMutationTransport, id: string, values: AutomationChatUpdate): Promise<AutomationsPayload> {
return mutation(transport, "automation.change_chat", { id, values });
}
export async function fetchAutomationRunResult(
token: string,
id: string,
+8
View File
@@ -220,6 +220,7 @@ interface UISessionMessage {
}
export interface SessionAutomationJob {
chat_binding_revision?: string;
id: string;
name: string;
enabled: boolean;
@@ -268,6 +269,13 @@ export interface SessionAutomationJob {
export interface SessionAutomationsPayload { jobs: SessionAutomationJob[]; }
export interface AutomationsPayload { jobs: SessionAutomationJob[]; }
export interface AutomationChat { id: string; title: string; channel: string; unavailable?: boolean; }
export interface AutomationChatsPayload {
revision: string;
current: AutomationChat | null;
chats: AutomationChat[];
}
export interface AutomationChatUpdate { target_id: string; revision: string; message: string; }
export interface AutomationUpdatePayload {
name?: string;
message?: string;
+16
View File
@@ -1,6 +1,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
changeAutomationChat,
cancelMcpOAuth,
configureChannel,
completeMcpOAuth,
@@ -13,6 +14,7 @@ import {
fetchFilePreview,
fetchFilePreviewAvailability,
fetchAutomations,
fetchAutomationChats,
fetchAutomationRunResult,
fetchApiService,
fetchCliApps,
@@ -377,6 +379,20 @@ describe("webui API helpers", () => {
);
});
it("reads chat choices over HTTP and commits the opaque choice over WebSocket", async () => {
const controller = new AbortController();
await fetchAutomationChats("tok", "task/id", controller.signal);
expect(fetch).toHaveBeenCalledWith(
"/api/webui/automations/chats?id=task%2Fid",
expect.objectContaining({ headers: { Authorization: "Bearer tok" }, signal: expect.any(AbortSignal) }),
);
vi.mocked(fetch).mockClear();
const values = { target_id: "opaque-id", revision: "reviewed-version", message: "Reviewed prompt" };
await changeAutomationChat(mutationTransport, "task/id", values);
expect(requestMutation).toHaveBeenCalledWith("automation.change_chat", { id: "task/id", values }, 20_000);
expect(fetch).not.toHaveBeenCalled();
});
it("validates channel settings with form values", async () => {
await validateChannel(
mutationTransport,
@@ -0,0 +1,81 @@
import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { AutomationDetailDialog } from "@/components/settings/system/AutomationsSettings";
import { fetchAutomationChats } from "@/lib/api";
import type { AutomationChatsPayload, SessionAutomationJob } from "@/lib/types";
vi.mock("@/lib/api", () => ({ fetchAutomationChats: vi.fn() }));
const source = { id: "source", title: "My planning", channel: "websocket" };
const target = { id: "target", title: "Product team", channel: "telegram" };
const choices: AutomationChatsPayload = { revision: "rev-1", current: source, chats: [source, target] };
const job: SessionAutomationJob = {
id: "daily", name: "Daily report", enabled: true, chat_binding_revision: "rev-1",
schedule: { kind: "every", every_ms: 86400000 }, state: {},
payload: { message: "Summarize the work." }, origin: { ...source, session_key: "websocket:source" },
};
const props = { open: true, locale: "en", actionKey: null, error: null,
onOpenChange: vi.fn(), onAction: vi.fn(), onRequestEdit: vi.fn(), onRequestDelete: vi.fn() };
beforeEach(() => { vi.mocked(fetchAutomationChats).mockResolvedValue(choices); });
afterEach(() => { cleanup(); vi.clearAllMocks(); });
async function choose() {
const control = await screen.findByRole("combobox", { name: "Task chat" });
await waitFor(() => expect(control).toBeEnabled());
fireEvent.keyDown(control, { key: "ArrowDown" });
fireEvent.click(await screen.findByRole("option", { name: /Product team/ }));
await screen.findByRole("heading", { name: "Change chat" });
}
it("keeps the original route until acknowledgement and saves the reviewed prompt", async () => {
let finish!: () => void;
const save = vi.fn(() => new Promise<void>(resolve => { finish = resolve; }));
const user = userEvent.setup();
render(<AutomationDetailDialog {...props} job={job} onChangeChat={save} />);
await choose();
expect(save).not.toHaveBeenCalled();
expect(screen.getByText(/Previous chat:/)).toHaveTextContent("My planning");
await user.clear(screen.getByRole("textbox", { name: "Task instructions" }));
await user.type(screen.getByRole("textbox", { name: "Task instructions" }), "New instructions");
await user.click(screen.getByRole("button", { name: "Confirm change" }));
expect(save).toHaveBeenCalledWith(job, { target_id: "target", revision: "rev-1", message: "New instructions" });
expect(screen.getByRole("button", { name: "Changing…" })).toBeDisabled();
expect(screen.queryByRole("status")).not.toBeInTheDocument();
await act(async () => finish());
expect(await screen.findByRole("status")).toHaveTextContent("Applies to future runs");
expect(props.onAction).not.toHaveBeenCalled();
});
it("keeps a rejected draft and its original revision across polling", async () => {
const user = userEvent.setup();
const save = vi.fn().mockRejectedValue(new Error("automation_chat_conflict"));
const { rerender } = render(<AutomationDetailDialog {...props} job={job} onChangeChat={save} />);
await choose();
await user.type(screen.getByRole("textbox", { name: "Task instructions" }), " Reviewed");
rerender(<AutomationDetailDialog {...props} job={{ ...job, chat_binding_revision: "rev-2" }} onChangeChat={save} />);
await user.click(screen.getByRole("button", { name: "Confirm change" }));
expect(save.mock.calls[0][1].revision).toBe("rev-1");
expect(await screen.findByRole("alert")).toHaveTextContent("draft is kept");
expect(screen.getByRole("textbox", { name: "Task instructions" })).toHaveValue("Summarize the work. Reviewed");
await user.click(screen.getByRole("button", { name: "Cancel" }));
expect(screen.getByRole("combobox", { name: "Task chat" })).toHaveTextContent("My planning");
});
it("does not send the new request to an old host and locks a pending task", async () => {
const save = vi.fn();
const { rerender } = render(<AutomationDetailDialog {...props} job={{ ...job, chat_binding_revision: undefined }} onChangeChat={save} />);
expect(fetchAutomationChats).not.toHaveBeenCalled();
expect(screen.queryByRole("combobox")).not.toBeInTheDocument();
rerender(<AutomationDetailDialog {...props} job={{ ...job, state: { pending: true } }} onChangeChat={save} />);
expect(await screen.findByRole("combobox", { name: "Task chat" })).toBeDisabled();
expect(save).not.toHaveBeenCalled();
});
it("keeps the current chat visible when discovery fails and permits a retry", async () => {
const user = userEvent.setup();
vi.mocked(fetchAutomationChats).mockRejectedValueOnce(new Error("offline"));
render(<AutomationDetailDialog {...props} job={job} onChangeChat={vi.fn()} />);
await user.click(await screen.findByRole("button", { name: "Retry loading chats" }));
await waitFor(() => expect(screen.getByRole("combobox", { name: "Task chat" })).toBeEnabled());
expect(fetchAutomationChats).toHaveBeenCalledTimes(2);
});
+32 -29
View File
@@ -54,6 +54,13 @@ function openFilters() {
return screen.getByRole("menu", { name: /^Filter/ });
}
function taskMenuItem(name: string) {
if (!screen.queryByRole("menu")) {
fireEvent.pointerDown(screen.getByRole("button", { name: i18n.t("settings.automations.moreActions") }), { button: 0, ctrlKey: false });
}
return screen.getByRole("menuitem", { name, exact: true });
}
function selectFilter(name: string) {
const menu = openFilters();
fireEvent.click(within(menu).getByRole("menuitemradio", { name }));
@@ -255,7 +262,7 @@ describe("Automation task list and detail sheet", () => {
const dialog = screen.getByRole("dialog", { name: "PR watch" });
expect(dialog).not.toHaveAttribute("aria-describedby");
expect(within(dialog).queryByText("Instructions")).not.toBeInTheDocument();
expect(within(dialog).getByRole("link", { name: "Open a chat" })).toHaveAttribute(
expect(taskMenuItem("Open a chat")).toHaveAttribute(
"href", "#/chat/websocket%3Ademo",
);
expect(within(dialog).getByRole("button", { name: "Task information" })).toHaveAttribute("aria-expanded", "false");
@@ -424,7 +431,8 @@ describe("Automation task list and detail sheet", () => {
await user.click(within(screen.getByRole("dialog", { name: dayLabel })).getByRole("button", { name: /Crowded 4.*Planned/ }));
const detail = await screen.findByRole("dialog", { name: "Crowded 4" });
expect(screen.queryByRole("dialog", { name: dayLabel })).not.toBeInTheDocument();
expect(within(detail).getByRole("link", { name: "Open a chat" })).toBeVisible();
expect(taskMenuItem("Open a chat")).toBeVisible();
await user.keyboard("{Escape}");
await user.click(within(detail).getByRole("button", { name: "Close" }));
await waitFor(() => expect(more).toHaveFocus());
});
@@ -626,14 +634,13 @@ describe("Automation task list and detail sheet", () => {
expect(details).toHaveAttribute("aria-expanded", "false");
if (!job.protected) {
expect(within(dialog).queryByRole("switch")).not.toBeInTheDocument();
const disable = within(dialog).getByRole("button", { name: "Disable" });
const taskActions = within(dialog).getByRole("button", { name: "Run now" }).parentElement;
expect(disable.parentElement).toBe(taskActions);
expect(within(dialog).getByRole("button", { name: "Delete" }).parentElement).toBe(taskActions);
const edit = within(dialog).getByRole("button", { name: "Edit" });
expect(edit.parentElement).not.toBe(taskActions);
expect(edit.parentElement).toHaveClass("ms-auto", "flex-wrap", "justify-end");
expect(within(dialog).getByRole("link", { name: "Open a chat" }).parentElement).toBe(edit.parentElement);
expect(edit.parentElement).toBe(taskActions);
expect(edit.parentElement).toHaveClass("ml-auto");
expect(taskMenuItem("Disable")).toBeVisible();
expect(taskMenuItem("Delete")).toBeVisible();
expect(taskMenuItem("Open a chat")).toHaveAttribute("href", "#/chat/websocket%3Ademo");
}
});
@@ -782,7 +789,7 @@ describe("Automation task list and detail sheet", () => {
rerender(<Harness payload={payload} onAction={action}
titleOverrides={{ "websocket:demo": "新会话名称" }} />);
expect(within(dialog).queryByText("新会话名称")).not.toBeInTheDocument();
await user.click(within(dialog).getByRole("button", { name: "Disable" }));
await user.click(taskMenuItem("Disable"));
expect(action).toHaveBeenCalledWith("disable", expect.objectContaining({
id: task.id, payload: task.payload,
origin: expect.objectContaining({ session_key: "websocket:demo" }),
@@ -792,19 +799,19 @@ describe("Automation task list and detail sheet", () => {
rerender(<Harness payload={payload} titleOverrides={{}} />);
await user.click(screen.getByRole("button", { name: /PR watch/ }));
expect(screen.queryByText("nanobot-development")).not.toBeInTheDocument();
expect(screen.getByRole("link", { name: "Open a chat" })).toHaveAttribute("href", "#/chat/websocket%3Ademo");
expect(taskMenuItem("Open a chat")).toHaveAttribute("href", "#/chat/websocket%3Ademo");
});
it("retains the inspected task across refreshes and closes if it is removed", () => {
const action = vi.fn();
const { rerender } = render(<Harness onAction={action} />);
fireEvent.click(screen.getByRole("button", { name: /PR watch/ }));
fireEvent.click(screen.getByRole("button", { name: "Disable" }));
fireEvent.click(taskMenuItem("Disable"));
expect(action).toHaveBeenCalledWith("disable", task);
rerender(<Harness payload={{ jobs: [{ ...task, enabled: false }] }} onAction={action} filter="active" />);
expect(screen.getByRole("dialog", { name: "PR watch" })).toBeVisible();
expect(screen.getByRole("button", { name: "Enable" })).toBeEnabled();
fireEvent.click(screen.getByRole("button", { name: "Enable" }));
expect(taskMenuItem("Enable")).not.toHaveAttribute("aria-disabled");
fireEvent.click(taskMenuItem("Enable"));
expect(action).toHaveBeenLastCalledWith("enable", { ...task, enabled: false });
rerender(<Harness payload={{ jobs: [] }} />);
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
@@ -819,12 +826,12 @@ describe("Automation task list and detail sheet", () => {
expect(screen.getByRole("button", { name: "筛选", exact: true })).toBeVisible();
fireEvent.click(screen.getByRole("button", { name: /PR watch/ }));
const dialog = screen.getByRole("dialog", { name: "PR watch" });
fireEvent.click(within(dialog).getByRole("button", { name: "停用", exact: true }));
fireEvent.click(taskMenuItem("停用"));
expect(action).toHaveBeenLastCalledWith("disable", task);
const disabledTask = { ...task, enabled: false };
rerender(<Harness payload={{ jobs: [disabledTask] }} onAction={action} />);
expect(within(dialog).getByRole("button", { name: "启用", exact: true })).toBeEnabled();
fireEvent.click(within(dialog).getByRole("button", { name: "启用", exact: true }));
expect(taskMenuItem("启用")).not.toHaveAttribute("aria-disabled");
fireEvent.click(taskMenuItem("启用"));
expect(action).toHaveBeenLastCalledWith("enable", disabledTask);
expect(dialog).not.toHaveTextContent("暂停");
expect(dialog).not.toHaveTextContent("恢复");
@@ -882,7 +889,7 @@ describe("Automation task list and detail sheet", () => {
await waitFor(() => expect(edit).toHaveBeenCalledWith(task));
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
await user.click(screen.getByRole("button", { name: /PR watch/ }));
await user.click(screen.getByRole("button", { name: "Delete" }));
await user.click(taskMenuItem("Delete"));
await waitFor(() => expect(remove).toHaveBeenCalledWith(task));
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
});
@@ -932,7 +939,7 @@ describe("Automation task list and detail sheet", () => {
await user.click(screen.getByRole("button", { name: /PR watch/ }));
const detail = screen.getByRole("dialog", { name: "PR watch" });
expect(document.body.style.pointerEvents).toBe("none");
await user.click(screen.getByRole("button", { name: "Delete" }));
await user.click(taskMenuItem("Delete"));
expect(detail).toHaveAttribute("data-state", "closed");
finishExit(detail);
const confirmation = await screen.findByRole("dialog", { name: "Delete automation" });
@@ -1005,10 +1012,9 @@ describe("Automation task list and detail sheet", () => {
await user.click(screen.getByRole("button", { name: "Run now" }));
expect(action).toHaveBeenCalledWith("run", task);
rerender(<Harness actionKey="run:private-job-id" />);
for (const name of ["Edit", "Run now", "Delete"]) {
for (const name of ["Edit", "Run now", "More actions"]) {
expect(screen.getByRole("button", { name })).toBeDisabled();
}
expect(screen.getByRole("button", { name: "Disable" })).toBeDisabled();
rerender(<Harness error="Unable to run task" />);
expect(within(screen.getByRole("dialog")).getByRole("alert")).toHaveTextContent("Unable to run task");
});
@@ -1018,18 +1024,15 @@ describe("Automation task list and detail sheet", () => {
const action = vi.fn();
const { rerender } = render(<Harness onAction={action} />);
await user.click(screen.getByRole("button", { name: /PR watch/ }));
const control = screen.getByRole("button", { name: "Disable" });
control.focus();
const control = taskMenuItem("Disable");
act(() => control.focus());
await user.keyboard(" ");
expect(action).toHaveBeenCalledWith("disable", task);
expect(control).toHaveTextContent("Disable");
rerender(<Harness onAction={action} actionKey={`disable:${task.id}`} />);
expect(control).toBeDisabled();
await user.click(control);
expect(screen.getByRole("button", { name: "More actions" })).toBeDisabled();
expect(action).toHaveBeenCalledTimes(1);
rerender(<Harness onAction={action} payload={{ jobs: [{ ...task, enabled: false }] }} />);
expect(control).toHaveTextContent("Enable");
expect(control).toBeEnabled();
expect(taskMenuItem("Enable")).not.toHaveAttribute("aria-disabled");
});
it("does not allow running a pending task or resuming an unlinked task", async () => {
@@ -1040,7 +1043,7 @@ describe("Automation task list and detail sheet", () => {
await user.click(screen.getByRole("button", { name: /PR watch/ }));
expect(screen.getByRole("button", { name: "Run now" })).toBeDisabled();
rerender(<Harness payload={{ jobs: [{ ...task, enabled: false, origin: null }] }} />);
expect(screen.getByRole("button", { name: "Enable" })).toBeDisabled();
expect(taskMenuItem("Enable")).toHaveAttribute("aria-disabled", "true");
expect(screen.queryByRole("link", { name: "Open a chat" })).not.toBeInTheDocument();
});
@@ -1055,7 +1058,7 @@ describe("Automation task list and detail sheet", () => {
expect(within(screen.getByRole("dialog")).getByText("nanobot trigger run trigger-1")).toBeVisible();
expect(screen.getByRole("button", { name: "Copy" })).toBeEnabled();
expect(screen.queryByRole("button", { name: "Run now" })).not.toBeInTheDocument();
expect(screen.getByRole("button", { name: "Delete" })).toBeVisible();
expect(taskMenuItem("Delete")).toBeVisible();
});
it("shows paused failures honestly and does not fabricate successful runs", () => {