diff --git a/docs/automations.md b/docs/automations.md index e3155ade8..3cd0df39d 100644 --- a/docs/automations.md +++ b/docs/automations.md @@ -60,6 +60,14 @@ Scheduled automations normally deliver the result back to the session where they were created. Use them for work that should run on a predictable schedule and report each run. +Write what the task should do, such as "Remind me to drink water". nanobot sends +the final reply to the task's saved chat. You do not need to put a channel, chat +ID, or a `message` tool call in the instructions for that reply. + +For separate sends, specify the recipients in the instructions. The agent can +still use `message` to send to other chats, send to several recipients, or attach +files. Existing tasks that explicitly request this tool remain supported. + For background checks that should stay quiet unless there is something useful to report, use heartbeat instead of a user-created scheduled automation. @@ -134,18 +142,22 @@ message. Copy the `nanobot trigger ...` command from the WebUI and replace ### Change the Chat for a Scheduled Task -Open a scheduled task in **Automations**. **Task chat** shows its saved chat, +Open a scheduled task in **Automations**. **Run and reply in** 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. +1. Select another chat from **Run and reply in**. +2. Review the task instructions. Remove recipients you no longer want, but keep + any intended separate sends. 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. +You can discuss each new result in that same chat. Background task results also +return there. If you delete that chat, nanobot asks you to confirm deletion of +its scheduled tasks as well. Cancelling the deletion keeps the chat and tasks. + 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 @@ -161,6 +173,8 @@ 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. +The confirmation screen lets you edit instructions such as "send to the original +chat" before you save. nanobot does not silently rewrite those instructions. ### Back Up Before Downgrading diff --git a/nanobot/agent/tools/cron.py b/nanobot/agent/tools/cron.py index f5566ae30..35c917d97 100644 --- a/nanobot/agent/tools/cron.py +++ b/nanobot/agent/tools/cron.py @@ -28,7 +28,10 @@ _CRON_PARAMETERS = tool_parameters_schema( ), message=StringSchema( "REQUIRED when action='add'. Instruction for the agent to execute when the job triggers " - "(e.g., 'Send a reminder to WeChat: xxx' or 'Check system status and report'). " + "(e.g., 'Remind me to drink water' or 'Check system status and report'). " + "The final reply goes to the task's saved chat automatically. " + "Do not copy the current channel/chat ID or require a message tool call for that reply. " + "Include other recipients only when the user requests separate sends. " "Not used for action='list' or action='remove'." ), every_seconds=IntegerSchema( diff --git a/nanobot/agent/tools/message.py b/nanobot/agent/tools/message.py index 82a5245c5..def57434f 100644 --- a/nanobot/agent/tools/message.py +++ b/nanobot/agent/tools/message.py @@ -120,10 +120,10 @@ class MessageTool(Tool): def description(self) -> str: return ( "Proactively send a message to a user/channel, optionally with file attachments. " - "Use this for reminders, cross-channel delivery, or explicit proactive sends. " - "Do not use this for the normal reply in the current chat: answer naturally instead. " - "If channel/chat_id would target the current runtime conversation, do not call this tool " - "unless the user explicitly asked you to proactively send an existing file attachment. " + "Use this for separate sends requested by the user or task, including sends to multiple chats. " + "For a normal reply, including a scheduled reminder or report, answer naturally instead: " + "nanobot delivers the final reply to the current chat. " + "Follow explicit task instructions that require this tool or name other recipients. " "When generate_image creates images in the current chat, use the message tool " "with the artifact paths in the media parameter to deliver the images to the user. " "For proactive attachment delivery, use the 'media' parameter with file paths. " diff --git a/nanobot/skills/cron/SKILL.md b/nanobot/skills/cron/SKILL.md index c4e6f4fc5..996dcdb09 100644 --- a/nanobot/skills/cron/SKILL.md +++ b/nanobot/skills/cron/SKILL.md @@ -5,14 +5,18 @@ description: Schedule reminders and recurring tasks. # Cron -Use the `cron` tool to schedule reminders or recurring tasks that should report back to the originating chat/session when they run. +Use the `cron` tool to schedule reminders or recurring tasks. New tasks run in the current chat. nanobot sends the agent's final reply to that chat. The user can change the task's chat in WebUI. + +Write what to do in `message`. For a normal reminder or report, do not copy the current channel, chat ID, or instructions to call the `message` tool into the task. For example, use "Remind me to drink water", not "Call message to send to this chat". + +If the user asks to send to other chats, preserve those recipients in the task instructions. Use the `message` tool for those sends and for file attachments. Existing tasks that explicitly request a `message` call still use it; changing the task's chat does not change explicit recipients in its instructions. Do not use `cron` for periodic background checks that should stay quiet when there is nothing useful to report. For those, update `HEARTBEAT.md`; the protected heartbeat job runs those checks and only delivers results that pass the notification gate. -## Three Modes +## Task Types -1. **Reminder** - message is sent directly to user -2. **Task** - message is a task description, agent executes and sends result +1. **Reminder** - the agent replies with the reminder when the task runs +2. **Task** - the agent follows the instructions and replies with the result 3. **One-time** - runs once at a specific time, then auto-deletes ## Examples diff --git a/nanobot/templates/agent/cron_reminder.md b/nanobot/templates/agent/cron_reminder.md index 64f94f21b..e039f3fa2 100644 --- a/nanobot/templates/agent/cron_reminder.md +++ b/nanobot/templates/agent/cron_reminder.md @@ -1,6 +1,8 @@ The scheduled time has arrived. Execute this scheduled cron job now and report the result to the user in the same session. Rules: +- Return the result as a normal reply. nanobot delivers it to this task's saved chat. +- Use the message tool only for file attachments or sends explicitly required by the task. Keep any explicit recipients in the task instructions. - Speak directly to the user in their language. - Do not narrate internal progress. - Do not include user IDs. diff --git a/nanobot/webui/automation_chats.py b/nanobot/webui/automation_chats.py index 876673577..88f9df913 100644 --- a/nanobot/webui/automation_chats.py +++ b/nanobot/webui/automation_chats.py @@ -12,6 +12,7 @@ from nanobot.session.manager import ( _metadata_title, # pyright: ignore[reportPrivateUsage] ) from nanobot.session.session_handles import SessionHandleResolver +from nanobot.utils.helpers import truncate_text from nanobot.webui.session_identity import is_webui_session_key from nanobot.webui.workspaces import WebUIWorkspaceController @@ -48,6 +49,7 @@ def automation_chats( job.payload.origin_metadata, ) result: list[AutomationChat] = [] + previews = {row["key"]: row.get("preview", "") for row in sessions.list_sessions()} for handle in SessionHandleResolver(sessions).list_all(): key = handle.session_key data = sessions.read_session_metadata(key) @@ -73,7 +75,10 @@ def automation_chats( if source.metadata() != target.metadata(): continue result.append(AutomationChat( - id=handle.id, title=_metadata_title(metadata) or f"@{handle.name}", + id=handle.id, + title=(_metadata_title(metadata) + or truncate_text(" ".join(previews.get(key, "").split()), 60) + or f"@{handle.name}"), binding=CronBinding(key, channel, chat_id, route_metadata), handle=handle.name, available=available, diff --git a/tests/cron/test_cron_reply_contract.py b/tests/cron/test_cron_reply_contract.py new file mode 100644 index 000000000..7bf38d73d --- /dev/null +++ b/tests/cron/test_cron_reply_contract.py @@ -0,0 +1,133 @@ +"""Scheduled replies and explicit sends share the normal agent delivery path.""" + +import json +from unittest.mock import MagicMock + +import pytest + +from nanobot.agent.loop import AgentLoop +from nanobot.agent.tools.context import current_request_context +from nanobot.bus.queue import MessageBus +from nanobot.config.schema import Config +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.session_turns import CRON_TRIGGER_META +from nanobot.cron.types import CronSchedule +from nanobot.providers.base import GenerationSettings, LLMResponse, ToolCallRequest +from nanobot.session.manager import SessionManager + + +@pytest.mark.asyncio +@pytest.mark.parametrize("delivery", ["reply", "legacy_message", "broadcast"]) +async def test_moved_cron_keeps_reply_send_and_prompt_prefix_contract(tmp_path, monkeypatch, delivery): + monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path / "data") + workspace = tmp_path / "workspace" + sessions = SessionManager(workspace) + bus = MessageBus() + cron = CronService(tmp_path / "cron" / "jobs.json") + attachment = workspace / "report.txt" + attachment.write_text("Report attachment", encoding="utf-8") + instructions = { + "reply": "Remind me to drink water", + "legacy_message": "Use message to send the reminder to the current chat", + "broadcast": "Use message to send the report to telegram:extra and feishu:team with report.txt", + } + job = cron.add_job( + "Reminder", CronSchedule(kind="every", every_ms=86400000), instructions[delivery], + session_key="telegram:old", origin_channel="telegram", origin_chat_id="old", + ) + 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 = [] + runs = set() + + async def reply(**kwargs): + ctx = current_request_context() + assert ctx is not None + trigger = ctx.metadata.get(CRON_TRIGGER_META) + # Serialize at the provider boundary, before the runner appends tool results. + requests.append(json.loads(json.dumps({ + "tools": kwargs["tools"], "messages": kwargs["messages"], + "run": trigger["run_id"] if trigger else None, + }))) + if trigger is None: + return LLMResponse(content="Ready") + run_id = trigger["run_id"] + if run_id not in runs: + runs.add(run_id) + if delivery == "legacy_message": + calls = [ToolCallRequest(id="reminder", name="message", arguments={ + "content": "Drink water", "channel": "telegram", "chat_id": "new", + })] + elif delivery == "broadcast": + calls = [ToolCallRequest(id=f"send-{index}", name="message", arguments={ + "content": "Extra report", "channel": channel, "chat_id": chat, + "media": [str(attachment)], + }) for index, (channel, chat) in enumerate([ + ("telegram", "extra"), ("feishu", "team"), + ])] + else: + calls = [] + if calls: + return LLMResponse(content=None, tool_calls=calls, finish_reason="tool_calls") + return LLMResponse(content="Drink water") + + provider.chat_stream_with_retry = reply + agent = AgentLoop(bus=bus, provider=provider, workspace=workspace, model="test-model", + session_manager=sessions, tools_config=Config().tools, cron_service=cron) + await cron.start() + try: + await agent.process_direct("Prepare for the reminder", session_key="telegram:new", + channel="telegram", chat_id="new") + moved = cron.change_binding(job.id, revision=binding_revision(job), + binding=CronBinding("telegram:new", "telegram", "new", {"message_thread_id": 42}), + message=job.payload.message) + assert moved.payload.message == instructions[delivery] + for _ in range(2): + while bus.outbound_size: + await bus.consume_outbound() + await run_bound_cron_job(moved, agent=agent, cron=cron) + outbound = [] + while bus.outbound_size: + message = await bus.consume_outbound() + if message.event is None and message.content: + outbound.append(message) + normal = [m for m in outbound if (m.channel, m.chat_id) == ("telegram", "new")] + # Normal backend replies and legacy same-chat sends each arrive once. + assert [m.content for m in normal] == ["Drink water"] + assert normal[0].metadata["message_thread_id"] == 42 + extra = [m for m in outbound if m not in normal] + assert [(m.channel, m.chat_id) for m in extra] == ( + [("telegram", "extra"), ("feishu", "team")] if delivery == "broadcast" else [] + ) + assert all(m.media == [str(attachment)] for m in extra) + assert all("message_thread_id" not in m.metadata for m in extra) + + # Ordinary turns, separate cron runs and tool continuations use the same + # system/tools prefix. Per-run instructions and runtime data stay at the end. + def stable(row): + return json.dumps([row["tools"], row["messages"][0]], ensure_ascii=False) + + assert all(stable(row) == stable(requests[0]) for row in requests) + assert len(runs) == 2 + for run_id in runs: + turn = [row for row in requests if row["run"] == run_id] + assert turn[0]["messages"][-1]["role"] == "user" + assert instructions[delivery] in turn[0]["messages"][-1]["content"] + if len(turn) > 1: + original = turn[0]["messages"] + assert turn[1]["messages"][:len(original)] == original + appended = turn[1]["messages"][len(original):] + assert appended[0]["role"] == "assistant" + assert appended[0]["tool_calls"] + assert all(row["role"] == "tool" for row in appended[1:]) + assert sessions.read_session_file("telegram:old") is None + history = sessions.read_session_file("telegram:new") + assert "Drink water" in json.dumps(history) + finally: + cron.stop() + await agent.aclose() diff --git a/tests/webui/test_automation_chat_binding.py b/tests/webui/test_automation_chat_binding.py index b1bf4f756..363659422 100644 --- a/tests/webui/test_automation_chat_binding.py +++ b/tests/webui/test_automation_chat_binding.py @@ -4,6 +4,7 @@ import asyncio import json import socket import uuid +from contextlib import suppress from dataclasses import asdict from unittest.mock import MagicMock @@ -12,6 +13,7 @@ import pytest import websockets from nanobot.agent.loop import AgentLoop +from nanobot.agent.tools.context import current_request_context from nanobot.bus.queue import MessageBus from nanobot.channels.websocket.runtime import WebSocketChannel, WebSocketConfig from nanobot.config.schema import Config @@ -19,7 +21,7 @@ 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.providers.base import GenerationSettings, LLMResponse, ToolCallRequest from nanobot.session.manager import SessionManager from nanobot.webui.automation_chats import automation_chats from nanobot.webui.automation_results import cron_run_response @@ -174,6 +176,24 @@ def test_target_identity_scope_and_channel_lifecycle(tmp_path): assert all(" · @" in chat.title for chat in duplicates) +def test_untitled_chat_uses_message_preview_until_renamed(tmp_path): + sessions, _, job = seed(tmp_path) + chat = sessions.get_or_create("websocket:reminder") + chat.add_message("user", "十分钟后提醒我喝水") + sessions.save(chat) + workspaces = WebUIWorkspaceController(session_manager=sessions, + default_workspace=tmp_path / "workspace", default_restrict_to_workspace=False) + chats = automation_chats(job, sessions, workspaces, {}) + choice = next(item for item in chats if item.binding.session_key == chat.key) + assert choice.public_payload()["title"] == "十分钟后提醒我喝水" + chat.metadata.update(title="My reminders", title_user_edited=True) + sessions.save(chat) + renamed = next(item for item in automation_chats(job, sessions, workspaces, {}) + if item.binding.session_key == chat.key) + assert renamed.id == choice.id + assert renamed.title == "My reminders" + + async def mutate(ws, values, job_id): request_id = str(uuid.uuid4()) await ws.send(json.dumps({"type": "webui_request", "request_id": request_id, @@ -186,8 +206,14 @@ async def mutate(ws, values, job_id): @pytest.mark.asyncio -async def test_real_gateway_move_run_reload_and_previous_result(tmp_path): +@pytest.mark.parametrize("target_channel", ["telegram", "websocket"]) +async def test_real_gateway_move_run_reload_and_previous_result(tmp_path, target_channel): sessions, cron, job = seed(tmp_path) + if target_channel == "websocket": + target_session = sessions.get_or_create("websocket:destination") + target_session.metadata["title"] = "Report inbox" + target_session.add_message("user", "Report inbox") + sessions.save(target_session) provider = MagicMock() provider.get_default_model.return_value = "test-model" provider.generation = GenerationSettings(max_tokens=100) @@ -248,7 +274,8 @@ async def test_real_gateway_move_run_reload_and_previous_result(tmp_path): 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") + target = next(chat for chat in data["chats"] + if chat["title"] == ("Product team" if target_channel == "telegram" else "Report inbox")) 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}"}, @@ -261,30 +288,70 @@ async def test_real_gateway_move_run_reload_and_previous_result(tmp_path): 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.payload.origin_metadata == ({"message_thread_id": 42} if target_channel == "telegram" else {}) 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 target["title"] 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"] + target_chat_id = "-100" if target_channel == "telegram" else "destination" + delivered = [msg for msg in outgoing if msg.content == "Synthetic result" and msg.chat_id == target_chat_id] assert len(delivered) == 1 - assert delivered[0].chat_id == "-100" - assert delivered[0].metadata["message_thread_id"] == 42 + assert delivered[0].channel == target_channel + if target_channel == "telegram": + 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" history = serialize_automation_jobs([moved], include_details=True)[0]["state"]["run_history"] - assert [run["webui_session_key"] for run in history] == ["websocket:source", None] + expected_history = ["websocket:source", None if target_channel == "telegram" else "websocket:destination"] + assert [run["webui_session_key"] for run in history] == expected_history + await agent.process_direct("Explain the report you just sent.", + session_key=moved.payload.session_key, channel=target_channel, chat_id=target_chat_id) + assert any(row.get("role") == "assistant" and row.get("content") == "Synthetic result" + for row in requests[-1]) + if target_channel == "websocket": + for msg in outgoing: + if msg.channel == "websocket": + await channel.send(msg) + async with httpx.AsyncClient(trust_env=False) as http: + opened = await http.get( + f"http://127.0.0.1:{port}/api/sessions/websocket%3Adestination/webui-thread", + headers={"Authorization": f"Bearer {api_token}"}, + ) + assert opened.status_code == 200 + assert "Synthetic result" in opened.text + async def delete(confirm=False): + request_id = str(uuid.uuid4()) + await client.send(json.dumps({"type": "webui_request", "request_id": request_id, + "action": "session.delete", "payload": { + "key": "websocket:destination", "delete_automations": confirm, + }})) + async with asyncio.timeout(5): + while True: + response = json.loads(await client.recv()) + if response.get("request_id") == request_id: + assert response["ok"], response + return response["result"] + blocked = await delete() + assert blocked["blocked_by_automations"] + assert blocked["automations"][0]["id"] == job.id + assert cron.get_job(job.id) is not None + assert (await delete(confirm=True))["deleted"] + assert cron.get_job(job.id) is None + assert sessions.read_session_file("websocket:destination") is None + assert sessions.read_session_file("websocket:source") is not None + assert not await cron.run_job(job.id) + return cron.change_binding(job.id, revision=binding_revision(moved), binding=CronBinding("websocket:source", "websocket", "source", {}), message="Back") # Moving back must not turn the external run's link into the current chat. history = serialize_automation_jobs([cron.get_job(job.id)], include_details=True)[0]["state"]["run_history"] - assert [run["webui_session_key"] for run in history] == ["websocket:source", None] + assert [run["webui_session_key"] for run in history] == expected_history finally: if client is not None: await client.close() @@ -292,3 +359,67 @@ async def test_real_gateway_move_run_reload_and_previous_result(tmp_path): await asyncio.wait_for(server, 5) cron.stop() await agent.aclose() + + +@pytest.mark.asyncio +async def test_late_subagent_result_stays_with_moved_task(tmp_path, monkeypatch): + # A background result can arrive after the normal 300-second terminal wait. + monkeypatch.setattr("nanobot.agent.loop._SUBAGENT_TERMINAL_WAIT_SECONDS", 0.02) + sessions, cron, job = seed(tmp_path) + release = asyncio.Event() + entered = asyncio.Event() + started = False + 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") + async def reply(**kwargs): + nonlocal started + ctx = current_request_context() + assert ctx is not None + if ctx.session_key.startswith("subagent:"): + entered.set() + await release.wait() + return LLMResponse(content="37 items completed") + assert ctx.session_key == "telegram:-100:topic:42" + if ctx.sender_id == "subagent": + return LLMResponse(content="Final report: 37 items completed") + if not started: + started = True + return LLMResponse(content=None, tool_calls=[ToolCallRequest( + id="background-report", name="subagent", arguments={ + "action": "create", "task": "Prepare the report", "wait": False, + }, + )], finish_reason="tool_calls") + return LLMResponse(content="Preparing the report") + provider.chat_stream_with_retry = reply + bus = MessageBus() + agent = AgentLoop(bus=bus, provider=provider, workspace=tmp_path / "workspace", + model="test-model", session_manager=sessions, tools_config=Config().tools) + consumer = asyncio.create_task(agent.run()) + await cron.start() + try: + moved = cron.change_binding(job.id, revision=binding_revision(job), + binding=target_binding(), message="Prepare the report") + await asyncio.wait_for(run_bound_cron_job(moved, agent=agent, cron=cron), 5) + await asyncio.wait_for(entered.wait(), 5) + release.set() + delivered = [] + async with asyncio.timeout(5): + while not any(msg.content.startswith("Final report:") for msg in delivered): + msg = await bus.consume_outbound() + if msg.event is None and msg.content: + delivered.append(msg) + assert [(msg.channel, msg.chat_id) for msg in delivered] == [("telegram", "-100")] * 2 + assert "Final report: 37 items completed" in json.dumps( + sessions.read_session_file("telegram:-100:topic:42")) + assert "37 items completed" not in json.dumps(sessions.read_session_file("websocket:source")) + finally: + release.set() + cron.stop() + agent.stop() + consumer.cancel() + with suppress(asyncio.CancelledError): + await consumer + await agent.aclose() diff --git a/webui/proposals/automation-chat/README.md b/webui/proposals/automation-chat/README.md index 18e9037e8..e1f27f7de 100644 --- a/webui/proposals/automation-chat/README.md +++ b/webui/proposals/automation-chat/README.md @@ -17,6 +17,11 @@ 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. +The detail panel has one control, **Run and reply in**. It does not offer a +separate result recipient. The confirmation shows the current and new chats, +explains that old messages stay where they are, and lets the user update task +instructions. The user must review instructions that name an old recipient. + ## Ownership and commit boundary - The gateway resolves existing session handles, titles, canonical reply routes, @@ -75,6 +80,17 @@ 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. +New reminders need only task instructions. The cron skill, tool descriptions, +and scheduled-turn prompt agree that nanobot sends the final reply to the saved +chat. Explicit separate sends and attachments still use `message`. Existing +instructions and recipients are not rewritten. The confirmation asks users to +check recipients, not remove intended broadcasts. + +These instructions are static. No per-run tool list, schema, or system prompt is +added. Updated tool descriptions can cause a cache miss after the upgrade. +Task-specific instructions remain in the current user turn. Moving to another +chat intentionally changes the history; cache reuse must not override that. + ## Verification The focused regression suite exercises the actual HTTP/WebSocket gateway, @@ -83,6 +99,18 @@ 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. +The regression suite also checks follow-up model input in the new chat, a +background result after the parent turn's wait timeout, and confirmed or +cancelled deletion of the new WebUI chat. These use the existing session owner; +no separate delivery context is added to the agent loop. + +The reply-contract test covers normal replies, legacy same-chat `message` calls +without duplicate replies, and multiple explicit recipients with attachments. +It compares serialized tools and system messages across ordinary turns, two +scheduled runs, and tool continuations. It also checks that continuation history +keeps structured tool calls and results. This is not a live provider cache-hit +measurement or proof that every model will follow the prompt. + 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 @@ -95,6 +123,6 @@ acceptance. Raw test logs and local fixture state are kept outside the repositor Both screenshots show the production app connected to that isolated gateway. -![Saved task chat with its channel logo](detail.png) +![Saved task chat with its channel logo](detail.jpg) -![Review a chat change before saving](review.png) +![Review a chat change before saving](review.jpg) diff --git a/webui/proposals/automation-chat/detail.jpg b/webui/proposals/automation-chat/detail.jpg new file mode 100644 index 000000000..ee83d6d85 Binary files /dev/null and b/webui/proposals/automation-chat/detail.jpg differ diff --git a/webui/proposals/automation-chat/detail.png b/webui/proposals/automation-chat/detail.png deleted file mode 100644 index 509eda14a..000000000 Binary files a/webui/proposals/automation-chat/detail.png and /dev/null differ diff --git a/webui/proposals/automation-chat/review.jpg b/webui/proposals/automation-chat/review.jpg new file mode 100644 index 000000000..6409ff622 Binary files /dev/null and b/webui/proposals/automation-chat/review.jpg differ diff --git a/webui/proposals/automation-chat/review.png b/webui/proposals/automation-chat/review.png deleted file mode 100644 index be160e107..000000000 Binary files a/webui/proposals/automation-chat/review.png and /dev/null differ diff --git a/webui/src/components/settings/system/AutomationChatBinding.tsx b/webui/src/components/settings/system/AutomationChatBinding.tsx index 4844c2bc2..fc3b012c4 100644 --- a/webui/src/components/settings/system/AutomationChatBinding.tsx +++ b/webui/src/components/settings/system/AutomationChatBinding.tsx @@ -39,14 +39,14 @@ export function AutomationChatBinding({ job, token, onSave, children }: { children: (picker: ReactNode) => ReactNode; }) { const { t } = useTranslation(); - const tx = (key: string) => t(`settings.automations.chat.${key}`); + const tx = (key: string, values?: Record) => t(`settings.automations.chat.${key}`, values); const [data, setData] = useState(null); const [loadError, setLoadError] = useState(false); const [reload, setReload] = useState(0); - const [draft, setDraft] = useState<{ target: AutomationChat; previousTitle: string; revision: string; message: string } | null>(null); + const [draft, setDraft] = useState<{ target: AutomationChat; previous: AutomationChat; revision: string; message: string } | null>(null); const [saving, setSaving] = useState(false); const [error, setError] = useState(""); - const [saved, setSaved] = useState(false); + const [saved, setSaved] = useState(null); const heading = useRef(null); const trigger = useRef(null); const returning = useRef(false); @@ -77,21 +77,21 @@ export function AutomationChatBinding({ job, token, onSave, children }: { disabled={pickerDisabled} onValueChange={id => { const target = data?.chats.find(chat => chat.id === id); if (!target || target.unavailable || id === current?.id) return; - setError(""); setSaved(false); + setError(""); setSaved(null); setDraft(previous => previous ? { ...previous, target } : { - target, previousTitle: current?.title || fallback.title, + target, previous: current ?? fallback, revision: job.chat_binding_revision!, message: job.payload.message, }); }}> 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"}`}> + 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"> {!current ? : null} {data?.chats.map(chat => )} + className="h-auto min-h-11 py-2 [&>span:first-child]:min-w-0 [&>span:first-child]:max-w-[calc(100vw-5rem)] [&>span:first-child]:w-full">)} ; const save = async () => { @@ -100,7 +100,7 @@ export function AutomationChatBinding({ job, token, onSave, children }: { try { await onSave(job, { target_id: draft.target.id, revision: draft.revision, message: draft.message }); setData(previous => previous ? { ...previous, current: draft.target } : previous); - setSaved(true); back(); setReload(value => value + 1); + setSaved(draft.target.title); back(); setReload(value => value + 1); } catch (cause) { const reasons: Record = { automation_chat_conflict: "conflict", automation_chat_busy: "schedulerBusy", @@ -109,33 +109,37 @@ export function AutomationChatBinding({ job, token, onSave, children }: { setError(tx(cause instanceof Error ? reasons[cause.message] ?? "failed" : "failed")); } finally { setSaving(false); } }; - if (!draft) return children(
-
- {tx("label")} - {picker(false)} -
+ if (!draft) return children(
+

{tx("label")}

+ {picker(false)}

- {job.state.pending ? tx("busy") : saved ? tx("saved") : tx("hint")} + {job.state.pending ? tx("busy") : saved ? tx("saved", { chat: saved }) : tx("hint")}

{loadError ? : null} {data && data.chats.length <= (current ? 1 : 0) ?

{tx("available")}

: null}
); return <> - {tx("change")} + {tx("change")}
+
+ {tx("previous")} + +
+

{tx("new")}

{picker(true)} -

{tx("previous")} {draft.previousTitle}

+
+

{tx("effect")}

+

{tx("history")}