Skip to content

Your lightweight open-source personal agent.

fix(automations): unify chat replies and preserve explicit sends

Xubin Renab614478a022
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
+
+
[email protected]("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):
[email protected]("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()
+
+
+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<string, string>) => t(`settings.automations.chat.${key}`, values);
const [data, setData] = useState<AutomationChatsPayload | null>(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<string | null>(null);
const heading = useRef<HTMLHeadingElement>(null);
const trigger = useRef<HTMLButtonElement>(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,
});
}}>
<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"}`}>
+ 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">
<SelectValue><ChatIdentity chat={(review ? draft?.target : current) ?? 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>)}
+ 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"><ChatIdentity chat={chat} /></SelectItem>)}
</SelectContent>
</Select>;
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<string, string> = {
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(<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>
+ if (!draft) return children(<div className="space-y-2">
+ <p className="text-[13px] font-medium">{tx("label")}</p>
+ {picker(false)}
<p role={saved ? "status" : undefined} className="text-[12px] leading-5 text-muted-foreground">
- {job.state.pending ? tx("busy") : saved ? tx("saved") : tx("hint")}
+ {job.state.pending ? tx("busy") : saved ? tx("saved", { chat: 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>
+ <DialogTitle ref={heading} tabIndex={-1} className="break-words 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">
+ <div role="group" aria-label={tx("previous")} className="flex min-w-0 items-start gap-3 pb-1 text-muted-foreground">
+ <span className="shrink-0 text-[12px] leading-6">{tx("previous")}</span>
+ <ChatIdentity chat={draft.previous} />
+ </div>
+ <p className="text-[13px] font-medium">{tx("new")}</p>
{picker(true)}
- <p className="text-[12px] leading-5 text-muted-foreground">{tx("previous")} {draft.previousTitle}</p>
+ </div>
+ <div className="space-y-1">
<p className="text-[13px] leading-5">{tx("effect")}</p>
+ <p className="text-[12px] leading-5 text-muted-foreground">{tx("history")}</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 || targetUnavailable ? <p role="alert" className="text-[12px] leading-5 text-destructive">{error || tx("unavailable")}</p> : null}
</div>
<DialogFooter className="shrink-0 flex-row justify-end gap-2 px-6 pb-5 pt-3">
diff --git a/webui/src/i18n/locales/en/common.json b/webui/src/i18n/locales/en/common.json
index 577003d9b..d566c610c 100644
--- a/webui/src/i18n/locales/en/common.json
+++ b/webui/src/i18n/locales/en/common.json
@@ -1398,19 +1398,19 @@
"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",
+ "label": "Run and reply in",
+ "new": "Change to",
"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.",
+ "previous": "Now",
+ "hint": "The task runs in this chat and replies here by default.",
+ "effect": "From the next run, the task will use the new chat's messages and reply there.",
"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.",
+ "review": "Check any recipients in the instructions. Changing the chat does not change them. People in the new chat can see the task and its results.",
+ "history": "Old messages stay where they are. The schedule does not change.",
"busy": "Cannot change while this task is running or queued.",
- "saved": "Changed. Applies to future runs.",
+ "saved": "Changed to “{{chat}}”. Applies from the next run.",
"failed": "Could not confirm the change. Your draft is kept.",
"retry": "Retry loading chats",
"confirm": "Confirm change",
diff --git a/webui/src/i18n/locales/es/common.json b/webui/src/i18n/locales/es/common.json
index f0758a215..3e4009c6f 100644
--- a/webui/src/i18n/locales/es/common.json
+++ b/webui/src/i18n/locales/es/common.json
@@ -1199,19 +1199,19 @@
"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",
+ "label": "Ejecutar y responder en",
+ "new": "Cambiar a",
"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.",
+ "previous": "Actual",
+ "hint": "La tarea se ejecuta en este chat y responde aquí de forma predeterminada.",
+ "effect": "A partir de la próxima ejecución, la tarea usará los mensajes del nuevo chat y responderá allí.",
"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.",
+ "review": "Revisa los destinatarios de las instrucciones. Cambiar el chat no los modifica. Los miembros del nuevo chat pueden ver la tarea y sus resultados.",
+ "history": "Los mensajes anteriores no se trasladan. El horario no cambia.",
"busy": "No se puede cambiar mientras la tarea se ejecuta o espera en la cola.",
- "saved": "Cambiado. Se aplica a las próximas ejecuciones.",
+ "saved": "Se cambió a «{{chat}}». Se aplica desde la próxima ejecución.",
"failed": "No se pudo confirmar el cambio. Se conserva el borrador.",
"retry": "Volver a cargar chats",
"confirm": "Confirmar cambio",
diff --git a/webui/src/i18n/locales/fr/common.json b/webui/src/i18n/locales/fr/common.json
index 8fb4a5c6c..d3ea45363 100644
--- a/webui/src/i18n/locales/fr/common.json
+++ b/webui/src/i18n/locales/fr/common.json
@@ -1198,19 +1198,19 @@
"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",
+ "label": "Exécuter et répondre dans",
+ "new": "Remplacer par",
"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.",
+ "previous": "Actuel",
+ "hint": "La tâche s'exécute dans cette discussion et y répond par défaut.",
+ "effect": "Dès la prochaine exécution, la tâche utilisera les messages de la nouvelle discussion et y répondra.",
"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.",
+ "review": "Vérifiez les destinataires dans les instructions. Changer de discussion ne les modifie pas. Les membres de la nouvelle discussion peuvent voir la tâche et ses résultats.",
+ "history": "Les anciens messages restent à leur place. L'horaire ne change pas.",
"busy": "Modification impossible si la tâche est en cours ou en attente.",
- "saved": "Modifié. S’applique aux prochaines exécutions.",
+ "saved": "Discussion remplacée par « {{chat}} ». Applicable dès la prochaine exécution.",
"failed": "Impossible de confirmer la modification. Le brouillon est conservé.",
"retry": "Recharger les discussions",
"confirm": "Confirmer",
diff --git a/webui/src/i18n/locales/id/common.json b/webui/src/i18n/locales/id/common.json
index a49b60fec..58167ba77 100644
--- a/webui/src/i18n/locales/id/common.json
+++ b/webui/src/i18n/locales/id/common.json
@@ -1198,19 +1198,19 @@
"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",
+ "label": "Jalankan dan balas di",
+ "new": "Ganti ke",
"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.",
+ "previous": "Saat ini",
+ "hint": "Tugas berjalan di percakapan ini dan secara default membalas di sini.",
+ "effect": "Mulai eksekusi berikutnya, tugas akan menggunakan pesan dari percakapan baru dan membalas di sana.",
"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.",
+ "review": "Periksa penerima dalam instruksi. Mengganti percakapan tidak mengubah penerima tersebut. Anggota percakapan baru dapat melihat tugas dan hasilnya.",
+ "history": "Pesan lama tetap di tempatnya. Jadwal tidak berubah.",
"busy": "Tidak dapat diganti saat tugas berjalan atau mengantre.",
- "saved": "Diganti. Berlaku untuk pelaksanaan berikutnya.",
+ "saved": "Diubah ke “{{chat}}”. Berlaku mulai eksekusi berikutnya.",
"failed": "Perubahan belum dapat dikonfirmasi. Draf disimpan.",
"retry": "Muat ulang chat",
"confirm": "Konfirmasi perubahan",
diff --git a/webui/src/i18n/locales/ja/common.json b/webui/src/i18n/locales/ja/common.json
index 3a02576ce..775696ca8 100644
--- a/webui/src/i18n/locales/ja/common.json
+++ b/webui/src/i18n/locales/ja/common.json
@@ -1198,19 +1198,19 @@
"conflict": "タスクが別の場所で変更されました。下書きは保持されています。タスクを開き直して最新の設定を確認してください。",
"unavailable": "このチャットは利用できないか、作業場所や権限が変わりました。別のチャットを選んでください。",
"schedulerBusy": "実行中または待機中のタスクがあります。完了後に再試行してください。",
- "label": "タスクのチャット",
- "new": "新しいチャット",
+ "label": "実行・返信先",
+ "new": "変更先",
"current": "現在のチャット",
"web": "Webチャット",
"change": "チャットを変更",
- "previous": "変更前:",
- "hint": "このチャットの履歴を使い、通常はここに結果を送ります。",
- "effect": "今後の実行では新しいチャットの履歴を使い、通常はそこに結果を送ります。",
+ "previous": "現在",
+ "hint": "このチャットでタスクを実行し、既定ではここに結果を返信します。",
+ "effect": "次回から、新しいチャットの内容を参照してタスクを実行し、そこで返信します。",
"message": "タスクの指示",
- "review": "別のチャットへの送信指示が残っていないか確認してください。新しいチャットの参加者にタスクと結果が見える場合があります。",
- "history": "過去のメッセージは元のチャットに残ります。実行時刻は変わらず、今すぐ実行もしません。",
+ "review": "指示に含まれる宛先を確認してください。チャットを変更しても、その宛先は変わりません。新しいチャットのメンバーはタスクの内容と結果を見ることができます。",
+ "history": "以前のメッセージは移動しません。実行日時は変わりません。",
"busy": "実行中または待機中のタスクは変更できません。",
- "saved": "変更しました。次回から適用されます。",
+ "saved": "「{{chat}}」に変更しました。次回から適用されます。",
"failed": "変更を確認できませんでした。下書きは保存されています。",
"retry": "チャットを再読込",
"confirm": "変更を確定",
diff --git a/webui/src/i18n/locales/ko/common.json b/webui/src/i18n/locales/ko/common.json
index bf7161b6f..d4ce79e62 100644
--- a/webui/src/i18n/locales/ko/common.json
+++ b/webui/src/i18n/locales/ko/common.json
@@ -1198,19 +1198,19 @@
"conflict": "다른 곳에서 작업이 변경되었습니다. 초안은 유지됩니다. 작업을 다시 열어 최신 설정을 확인하세요.",
"unavailable": "이 채팅을 사용할 수 없거나 작업 공간 또는 권한이 변경되었습니다. 다른 채팅을 선택하세요.",
"schedulerBusy": "실행 중이거나 대기 중인 작업이 있습니다. 완료 후 다시 시도하세요.",
- "label": "작업 채팅",
- "new": "새 채팅",
+ "label": "실행 및 답장 위치",
+ "new": "변경할 채팅",
"current": "현재 채팅",
"web": "웹 채팅",
"change": "채팅 변경",
- "previous": "이전 채팅:",
- "hint": "이 채팅의 기록을 사용하며 결과도 기본적으로 여기로 보냅니다.",
- "effect": "다음 실행부터 새 채팅의 기록을 사용하며 결과도 기본적으로 그곳으로 보냅니다.",
+ "previous": "현재",
+ "hint": "이 채팅에서 작업을 실행하고 기본적으로 여기에 결과를 보냅니다.",
+ "effect": "다음 실행부터 새 채팅의 메시지를 참고하고 해당 채팅에 답장합니다.",
"message": "작업 지침",
- "review": "다른 채팅으로 보내라는 지침이 있는지 확인하세요. 새 채팅의 참여자가 작업 내용과 결과를 볼 수 있습니다.",
- "history": "이전 메시지는 원래 채팅에 남습니다. 일정은 유지되며 지금 실행하지 않습니다.",
+ "review": "지침에 지정된 수신자를 확인하세요. 채팅을 변경해도 해당 수신자는 바뀌지 않습니다. 새 채팅의 구성원은 작업 내용과 결과를 볼 수 있습니다.",
+ "history": "이전 메시지는 이동하지 않습니다. 일정은 변경되지 않습니다.",
"busy": "작업이 실행 중이거나 대기 중이면 변경할 수 없습니다.",
- "saved": "변경했습니다. 다음 실행부터 적용됩니다.",
+ "saved": "“{{chat}}”(으)로 변경했습니다. 다음 실행부터 적용됩니다.",
"failed": "변경을 확인하지 못했습니다. 초안은 유지됩니다.",
"retry": "채팅 다시 불러오기",
"confirm": "변경 확인",
diff --git a/webui/src/i18n/locales/pt-BR/common.json b/webui/src/i18n/locales/pt-BR/common.json
index 5baa2b761..41ffc3076 100644
--- a/webui/src/i18n/locales/pt-BR/common.json
+++ b/webui/src/i18n/locales/pt-BR/common.json
@@ -1212,19 +1212,19 @@
"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",
+ "label": "Executar e responder em",
+ "new": "Alterar para",
"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.",
+ "previous": "Atual",
+ "hint": "A tarefa é executada nesta conversa e responde aqui por padrão.",
+ "effect": "A partir da próxima execução, a tarefa usará as mensagens da nova conversa e responderá nela.",
"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.",
+ "review": "Confira os destinatários nas instruções. Mudar a conversa não altera esses destinatários. Os membros da nova conversa podem ver a tarefa e seus resultados.",
+ "history": "As mensagens anteriores ficam onde estão. O horário não muda.",
"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.",
+ "saved": "Alterado para “{{chat}}”. Válido a partir da próxima execução.",
"failed": "Não foi possível confirmar a alteração. O rascunho foi mantido.",
"retry": "Recarregar conversas",
"confirm": "Confirmar alteração",
diff --git a/webui/src/i18n/locales/vi/common.json b/webui/src/i18n/locales/vi/common.json
index 596c04be1..d2b3ff228 100644
--- a/webui/src/i18n/locales/vi/common.json
+++ b/webui/src/i18n/locales/vi/common.json
@@ -1198,19 +1198,19 @@
"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",
+ "label": "Chạy và trả lời trong",
+ "new": "Đổi sang",
"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 đó.",
+ "previous": "Hiện tại",
+ "hint": "Tác vụ chạy trong cuộc trò chuyện này và mặc định trả lời tại đây.",
+ "effect": "Từ lần chạy tiếp theo, tác vụ sẽ dùng tin nhắn trong cuộc trò chuyện mới và trả lời tại đó.",
"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.",
+ "review": "Kiểm tra người nhận trong chỉ dẫn. Đổi cuộc trò chuyện không thay đổi những người nhận này. Thành viên cuộc trò chuyện mới có thể xem tác vụ và kết quả.",
+ "history": "Tin nhắn cũ vẫn ở chỗ cũ. Lịch chạy không thay đổi.",
"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.",
+ "saved": "Đã đổi sang “{{chat}}”. Á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",
diff --git a/webui/src/i18n/locales/zh-CN/common.json b/webui/src/i18n/locales/zh-CN/common.json
index 5d6c50cf2..bd211da79 100644
--- a/webui/src/i18n/locales/zh-CN/common.json
+++ b/webui/src/i18n/locales/zh-CN/common.json
@@ -1398,19 +1398,19 @@
"conflict": "任务已在别处修改,草稿已保留。请重新打开任务,核对最新设置后再更换。",
"unavailable": "这个聊天已不可用,或工作目录、权限已改变。请选择其他聊天。",
"schedulerBusy": "有任务正在执行或排队。请等任务结束后再试。",
- "label": "任务所在聊天",
- "new": "新聊天",
+ "label": "运行与回复",
+ "new": "更换为",
"current": "当前聊天",
"web": "网页聊天",
"change": "更换聊天",
- "previous": "原聊天:",
- "hint": "使用这里的聊天记录,结果也默认发到这里。",
- "effect": "后续任务会使用新聊天的记录,结果也默认发到这里。",
+ "previous": "当前",
+ "hint": "任务在这个聊天中执行,结果默认发到这里。",
+ "effect": "从下次起,任务会参考新聊天的内容,并在该聊天回复。",
"message": "任务说明",
- "review": "请检查并移除发往其他聊天的旧指令。新聊天的成员可能看到任务内容和结果。",
- "history": "旧消息留在原聊天。执行时间不变,也不会立即运行。",
+ "review": "请检查说明中的收件人,更换聊天不会自动修改。新聊天的成员可见任务内容和结果。",
+ "history": "旧消息不会搬过去,执行时间不变。",
"busy": "任务正在执行或排队,暂时不能更换。",
- "saved": "已更换,下次执行生效。",
+ "saved": "已更换为「{{chat}}」,下次执行生效。",
"failed": "未能确认更换成功,草稿已保留。",
"retry": "重新加载聊天",
"confirm": "确认并更换",
diff --git a/webui/src/i18n/locales/zh-TW/common.json b/webui/src/i18n/locales/zh-TW/common.json
index 74154ff84..c5cb17631 100644
--- a/webui/src/i18n/locales/zh-TW/common.json
+++ b/webui/src/i18n/locales/zh-TW/common.json
@@ -1198,19 +1198,19 @@
"conflict": "任務已在別處修改,草稿已保留。請重新開啟任務,確認最新設定後再更換。",
"unavailable": "這個聊天已無法使用,或工作目錄、權限已變更。請選擇其他聊天。",
"schedulerBusy": "有任務正在執行或排隊。請等任務結束後再試。",
- "label": "任務所在聊天",
- "new": "新聊天",
+ "label": "執行與回覆",
+ "new": "更換為",
"current": "目前聊天",
"web": "網頁聊天",
"change": "更換聊天",
- "previous": "原聊天:",
- "hint": "使用這裡的聊天記錄,結果也預設傳到這裡。",
- "effect": "之後的任務會使用新聊天的記錄,結果也預設傳到那裡。",
+ "previous": "目前",
+ "hint": "任務在這個聊天中執行,結果預設傳送到這裡。",
+ "effect": "從下次起,任務會參考新聊天的內容,並在該聊天回覆。",
"message": "任務說明",
- "review": "請檢查並移除傳往其他聊天的舊指令。新聊天的成員可能看到任務內容和結果。",
- "history": "舊訊息留在原聊天。執行時間不變,也不會立即執行。",
+ "review": "請檢查說明中的收件人,更換聊天不會自動修改。新聊天的成員可見任務內容和結果。",
+ "history": "舊訊息不會移過去,執行時間不變。",
"busy": "任務正在執行或排隊,暫時無法更換。",
- "saved": "已更換,下次執行生效。",
+ "saved": "已更換為「{{chat}}」,下次執行生效。",
"failed": "無法確認更換成功,草稿已保留。",
"retry": "重新載入聊天",
"confirm": "確認並更換",
diff --git a/webui/src/tests/automation-chat-binding.test.tsx b/webui/src/tests/automation-chat-binding.test.tsx
index 8c63863b2..d0afb0002 100644
--- a/webui/src/tests/automation-chat-binding.test.tsx
+++ b/webui/src/tests/automation-chat-binding.test.tsx
@@ -20,7 +20,7 @@ beforeEach(() => { vi.mocked(fetchAutomationChats).mockResolvedValue(choices); }
afterEach(() => { cleanup(); vi.clearAllMocks(); });
async function choose() {
- const control = await screen.findByRole("combobox", { name: "Task chat" });
+ const control = await screen.findByRole("combobox", { name: "Run and reply in" });
await waitFor(() => expect(control).toBeEnabled());
fireEvent.keyDown(control, { key: "ArrowDown" });
fireEvent.click(await screen.findByRole("option", { name: /Product team/ }));
@@ -34,7 +34,7 @@ it("keeps the original route until acknowledgement and saves the reviewed prompt
const { rerender } = render(<AutomationDetailDialog {...props} job={job} onChangeChat={save} />);
await choose();
expect(save).not.toHaveBeenCalled();
- expect(screen.getByText(/Previous chat:/)).toHaveTextContent("My planning");
+ expect(screen.getByRole("group", { name: "Now" })).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" }));
@@ -47,14 +47,29 @@ it("keeps the original route until acknowledgement and saves the reviewed prompt
rerender(<AutomationDetailDialog {...props} job={{ ...job, chat_binding_revision: "rev-2" }} onChangeChat={save} />);
finish();
});
- expect(await screen.findByRole("status")).toHaveTextContent("Applies to future runs");
- expect(screen.getByRole("combobox", { name: "Task chat" })).toHaveTextContent("Product team");
- expect(screen.getByRole("combobox", { name: "Task chat" })).toBeDisabled();
+ expect(await screen.findByRole("status")).toHaveTextContent("Applies from the next run");
+ expect(screen.getByRole("combobox", { name: "Run and reply in" })).toHaveTextContent("Product team");
+ expect(screen.getByRole("combobox", { name: "Run and reply in" })).toBeDisabled();
await act(async () => refresh({ ...choices, current: target, revision: "rev-2" }));
- expect(screen.getByRole("combobox", { name: "Task chat" })).toHaveFocus();
+ expect(screen.getByRole("combobox", { name: "Run and reply in" })).toHaveFocus();
expect(props.onAction).not.toHaveBeenCalled();
});
+it("cancels a chat change without saving the edited instructions", async () => {
+ const user = userEvent.setup();
+ const save = vi.fn();
+ render(<AutomationDetailDialog {...props} job={job} onChangeChat={save} />);
+ await choose();
+ await user.clear(screen.getByRole("textbox", { name: "Task instructions" }));
+ await user.type(screen.getByRole("textbox", { name: "Task instructions" }), "Discard this draft");
+ await user.click(screen.getByRole("button", { name: "Cancel" }));
+ expect(save).not.toHaveBeenCalled();
+ expect(screen.getByRole("combobox", { name: "Run and reply in" })).toHaveTextContent("My planning");
+ expect(screen.getByRole("combobox", { name: "Run and reply in" })).toHaveFocus();
+ await choose();
+ expect(screen.getByRole("textbox", { name: "Task instructions" })).toHaveValue("Summarize the work.");
+});
+
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"));
@@ -67,7 +82,7 @@ it("keeps a rejected draft and its original revision across polling", async () =
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");
+ expect(screen.getByRole("combobox", { name: "Run and reply in" })).toHaveTextContent("My planning");
});
it("does not send the new request to an old host and locks a pending task", async () => {
@@ -76,7 +91,7 @@ it("does not send the new request to an old host and locks a pending task", asyn
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(await screen.findByRole("combobox", { name: "Run and reply in" })).toBeDisabled();
expect(save).not.toHaveBeenCalled();
});
@@ -91,13 +106,13 @@ it("keeps the reviewed chat identity when refreshed choices no longer contain it
});
rerender(<AutomationDetailDialog {...props} job={{ ...job, chat_binding_revision: "rev-2" }} onChangeChat={save} />);
expect(await screen.findByRole("alert")).toHaveTextContent("no longer available");
- expect(screen.getByRole("combobox", { name: "New chat" })).toHaveTextContent("Product team");
- expect(screen.getByText(/Previous chat:/)).toHaveTextContent("My planning");
+ expect(screen.getByRole("combobox", { name: "Change to" })).toHaveTextContent("Product team");
+ expect(screen.getByRole("group", { name: "Now" })).toHaveTextContent("My planning");
expect(screen.getByRole("textbox", { name: "Task instructions" })).toHaveValue("Summarize the work. Reviewed");
expect(screen.getByRole("button", { name: "Confirm change" })).toBeDisabled();
expect(save).not.toHaveBeenCalled();
await user.click(screen.getByRole("button", { name: "Cancel" }));
- expect(screen.getByRole("combobox", { name: "Task chat" })).toHaveTextContent("Renamed planning");
+ expect(screen.getByRole("combobox", { name: "Run and reply in" })).toHaveTextContent("Renamed planning");
});
it("keeps the current chat visible when discovery fails and permits a retry", async () => {
@@ -105,6 +120,6 @@ it("keeps the current chat visible when discovery fails and permits a retry", as
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());
+ await waitFor(() => expect(screen.getByRole("combobox", { name: "Run and reply in" })).toBeEnabled());
expect(fetchAutomationChats).toHaveBeenCalledTimes(2);
});