Your lightweight open-source personal agent.
Python agent-frameworkai-agentai-agentschatbotchatopsdiscord-botllm-agentsllmslocal-llmmcpmodel-context-protocolmulti-agentopenai-compatibleopenclawpersonal-ai-assistantpythonself-hostedtelegram-bot-ai-assistantwebuiworkflow-automation
fix(automations): clarify chat review and scheduling choices
Xubin Ren052ad09983e6
diff --git a/docs/automations.md b/docs/automations.mdindex d052385a1..b4f3a5734 100644--- a/docs/automations.md+++ b/docs/automations.md@@ -71,6 +71,17 @@ files. Existing tasks that explicitly request this tool remain supported.For background checks that should stay quiet unless there is something useful toreport, use heartbeat instead of a user-created scheduled automation.+Repetition alone does not select heartbeat. "Every day at 8am, remind me to+drink water" needs a cron schedule. "Keep an eye on open issues and tell me+when one needs attention" can use heartbeat if the check time is flexible.+Heartbeat does not guarantee a requested time or interval.++An upgrade does not overwrite your workspace's `AGENTS.md` or convert existing+heartbeat entries into cron jobs. The current scheduling rules are included in+the system prompt. If an old workspace rule directs all recurring tasks to+heartbeat, update that rule too. To correct an existing reminder, remove its old+heartbeat entry and create the cron task once. Check the task list to avoid duplicates.+## Local TriggersLocal triggers let a local script or external service send a message into a@@ -150,10 +161,15 @@ name show an `@handle` to help you tell them apart.To change the chat: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.+2. Review the task instructions, which are read-only by default. If they need+ changes, select **Edit instructions**. Remove recipients you no longer want,+ but keep intended separate sends. Members of the new chat can see future task messages and results.3. Select **Confirm change**. Wait for the saved confirmation.+If you edit the instructions, the button becomes **Save and change**. Both+changes are saved together; nothing is saved when you select **Edit instructions**.+To change the task name or schedule, use **Edit** in the task details instead.+Select **Cancel** before saving to return to the task without changes. After asuccessful save, select **Change back to** to review a return to the previouschat. You must confirm this change too. You can also select a previous chat fromdiff --git a/nanobot/skills/cron/SKILL.md b/nanobot/skills/cron/SKILL.mdindex 996dcdb09..849db89e1 100644--- a/nanobot/skills/cron/SKILL.md+++ b/nanobot/skills/cron/SKILL.md@@ -11,7 +11,7 @@ Write what to do in `message`. For a normal reminder or report, do not copy theIf 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.+Choose by timing and notification behavior, not repetition. A specified time or interval uses `cron`, even when it repeats: "every day at 8am, remind me to drink water" is a cron task. Use `HEARTBEAT.md` for background checks with flexible timing that should notify only on actionable changes. Heartbeat does not guarantee a requested time or interval; do not substitute it for an explicit schedule.## Task Typesdiff --git a/nanobot/templates/AGENTS.md b/nanobot/templates/AGENTS.mdindex b45305fb4..33ad702db 100644--- a/nanobot/templates/AGENTS.md+++ b/nanobot/templates/AGENTS.md@@ -8,8 +8,8 @@ Use this file for project-specific preferences, recurring workflow conventions,- Before scheduling reminders, check available skills and follow skill guidance first.- Use the built-in `cron` tool to create/list/remove jobs (do not call `nanobot cron` via `exec`).-- Get USER_ID and CHANNEL from the current session (e.g., `8281248569` and `telegram` from `telegram:8281248569`).-- Cron jobs run as scheduled turns in the origin chat/session and normally deliver the result back to that channel. Do not use cron for background checks that should stay silent when there is nothing useful to report; use `HEARTBEAT.md` instead.+- Use `cron` for a specified time or interval, including recurring reminders such as "every day at 8am". Repetition alone does not make a task a heartbeat task.+- The tool captures the current chat. Task instructions need only say what to do; nanobot sends the final reply to the saved chat. Include other recipients only when the user requests separate sends.**Do NOT just write reminders to MEMORY.md** — that won't trigger actual notifications.@@ -21,4 +21,4 @@ Use this file for project-specific preferences, recurring workflow conventions,- Use `edit_file` only for small exact replacements copied from the current `HEARTBEAT.md`.- Use `write_file` for first creation or intentional full-file rewrites.-When the user asks for a recurring/periodic heartbeat task, or for a periodic background check that should only notify on actionable changes, update `HEARTBEAT.md` instead of creating a one-time reminder. Use the built-in `cron` tool for explicit reminders, scheduled tasks that should report every run, or custom schedules that should not be part of the heartbeat task list.+Use `HEARTBEAT.md` for background checks with flexible timing that should notify only on actionable changes. Heartbeat does not guarantee a requested time or interval. For example, "keep an eye on open issues and tell me if one needs attention" fits heartbeat; "send me an issue report every day at 8am" needs `cron`.diff --git a/nanobot/templates/HEARTBEAT.md b/nanobot/templates/HEARTBEAT.mdindex 97af125c9..c176648ab 100644--- a/nanobot/templates/HEARTBEAT.md+++ b/nanobot/templates/HEARTBEAT.md@@ -3,7 +3,7 @@<!--This file is checked periodically by your nanobot agent. When nanobot gateway starts with gateway.heartbeat.enabled=true, it automatically registers a protected heartbeat cron job that reads this file.-Use this file for recurring background checks that should stay quiet unless there is something useful to report. Regular cron jobs are different: they normally deliver each run's result back to the chat/session where they were created.+Use this file for background checks with flexible timing that should stay quiet unless there is something useful to report. For a specified time or interval, including recurring reminders such as "every day at 8am", use the cron tool instead. Heartbeat does not guarantee that schedule. Regular cron jobs normally deliver each run's result back to their saved chat/session.If this file has no tasks (only headers and comments), the agent will skip it. Completed tasks should be deleted, not kept - heartbeat only reads "Active Tasks".-->diff --git a/nanobot/templates/agent/tool_contract.md b/nanobot/templates/agent/tool_contract.mdindex e34586745..536c58534 100644--- a/nanobot/templates/agent/tool_contract.md+++ b/nanobot/templates/agent/tool_contract.md@@ -3,3 +3,10 @@- Treat a clear user request as authorization to complete the task, including execution and verification.- Ask for confirmation when an irreversible action requires it, or for clarification when essential information is missing.- Wait for tool results before writing the final answer.++## Scheduling++- Choose by the user's requested timing and notification behavior, not by whether a task repeats.+- Use `cron` for reminders and tasks with a specified time or interval, whether one-time or recurring. "Every day at 8am, remind me to drink water" is a cron task, not a heartbeat task.+- Use `HEARTBEAT.md` for background checks with flexible timing that should notify only on actionable changes. Heartbeat does not guarantee a requested time or interval. Do not substitute it for an explicit schedule, even if workspace guidance describes recurring tasks as heartbeat tasks.+- Confirm a task only after its tool call or file update succeeds. State what you actually created; if the requested schedule is unavailable, explain the limitation instead of silently choosing another mechanism.diff --git a/tests/agent/test_context_prompt_cache.py b/tests/agent/test_context_prompt_cache.pyindex 37dc2df24..c582f03b4 100644--- a/tests/agent/test_context_prompt_cache.py+++ b/tests/agent/test_context_prompt_cache.py@@ -140,6 +140,40 @@ def test_execution_rules_reach_existing_workspace_soul(tmp_path) -> None:assert soul_path.read_text(encoding="utf-8") == legacy_soul[email protected]("legacy_workspace", [False, True])+def test_scheduling_contract_reaches_fresh_and_legacy_workspaces(tmp_path, legacy_workspace) -> None:+ """Default files can be skipped and old files must not hide the current contract."""+ from nanobot.utils.helpers import sync_workspace_templates++ workspace = _make_workspace(tmp_path)+ agents_path = workspace / "AGENTS.md"+ legacy_rule = (+ "When the user asks for a recurring/periodic task, update HEARTBEAT.md "+ "instead of creating a one-time cron reminder."+ )+ if legacy_workspace:+ agents_path.write_text(f"# Workspace rules\nReply in Chinese.\n{legacy_rule}\n", encoding="utf-8")+ sync_workspace_templates(workspace, silent=True)+ original = agents_path.read_bytes()+ builder = ContextBuilder(workspace)+ messages = builder.build_messages(history=[], current_message="每天早上8点提醒我喝水")+ system = messages[0]["content"]++ assert '"Every day at 8am, remind me to drink water" is a cron task, not a heartbeat task.' in system+ assert "Heartbeat does not guarantee a requested time or interval." in system+ assert "background checks with flexible timing" in system+ assert system.count("## Scheduling") == 1+ if legacy_workspace:+ assert "Reply in Chinese." in system+ assert system.index(legacy_rule) < system.index("## Scheduling")+ assert "even if workspace guidance describes recurring tasks as heartbeat tasks" in system+ else:+ assert "## AGENTS.md" not in system+ assert "每天早上8点提醒我喝水" in messages[-1]["content"]+ assert builder.build_messages(history=[], current_message="Check issues when convenient")[0] == messages[0]+ assert agents_path.read_bytes() == original++def test_default_soul_template_keeps_execution_policy_in_tool_contract() -> None:"""SOUL owns personality while the always-injected contract owns execution policy."""soul = (pkg_files("nanobot") / "templates" / "SOUL.md").read_text(encoding="utf-8")diff --git a/webui/proposals/automation-chat/README.md b/webui/proposals/automation-chat/README.mdindex 29b4e32cf..5ca4268d8 100644--- a/webui/proposals/automation-chat/README.md+++ b/webui/proposals/automation-chat/README.md@@ -19,8 +19,10 @@ is pending, so the PR remains a draft.The detail panel has one control, **Run and reply in**. It does not offer aseparate 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.+explains that old messages stay where they are, and shows read-only task+instructions. **Edit instructions** opens the text field only when needed, for+example to remove an old recipient. **Save and change** then saves both changes+together. Task name and schedule edits remain in the existing **Edit** dialog.Cancel leaves the task unchanged. After saving, **Change back to** opens the sameconfirmation for the previous chat; it does not silently undo a saved change.@@ -93,8 +95,15 @@ chat. Explicit separate sends and attachments still use `message`. Existinginstructions and recipients are not rewritten. The confirmation asks users tocheck recipients, not remove intended broadcasts.+Scheduling uses the requested time and notification behavior, not repetition.+The always-loaded tool contract distinguishes cron schedules from flexible,+quiet heartbeat checks. Updated workspace templates and the cron skill use the+same rule. Existing workspace files and heartbeat tasks are not rewritten;+the user guide explains how to correct an old rule or an existing task.+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.+added. Updated tool descriptions and static scheduling rules can cause a cache+miss after the upgrade.Task-specific instructions remain in the current user turn. Moving to anotherchat intentionally changes the history; cache reuse must not override that.diff --git a/webui/src/components/settings/system/AutomationChatBinding.tsx b/webui/src/components/settings/system/AutomationChatBinding.tsxindex d16d02469..47d3be7c2 100644--- a/webui/src/components/settings/system/AutomationChatBinding.tsx+++ b/webui/src/components/settings/system/AutomationChatBinding.tsx@@ -45,7 +45,7 @@ export function AutomationChatBinding({ job, token, chatNames, onSave, childrenconst [data, setData] = useState<AutomationChatsPayload | null>(null);const [loadError, setLoadError] = useState(false);const [reload, setReload] = useState(0);- const [draft, setDraft] = useState<{ target: AutomationChat; previous: AutomationChat; revision: string; message: string } | null>(null);+ const [draft, setDraft] = useState<{ target: AutomationChat; previous: AutomationChat; revision: string; message: string; editingMessage?: boolean } | null>(null);const [saving, setSaving] = useState(false);const [error, setError] = useState("");const [saved, setSaved] = useState<{ target: AutomationChat; previous: AutomationChat } | null>(null);@@ -159,16 +159,26 @@ export function AutomationChatBinding({ job, token, chatNames, onSave, children<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>+ <div className="space-y-2">+ <div className="flex items-center justify-between gap-3">+ <p className="text-[13px] font-medium">{tx("message")}</p>+ {!draft.editingMessage ? <Button variant="link" size="sm" disabled={saving}+ className="h-11 shrink-0 p-0 text-[12px] sm:h-9"+ onClick={() => setDraft({ ...draft, editingMessage: true })}>{tx("editInstructions")}</Button> : null}+ </div>+ {draft.editingMessage ? <>+ <Textarea autoFocus aria-label={tx("message")} 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" />+ <p className="text-[12px] leading-5 text-muted-foreground">{tx("editInstructionsHint")}</p>+ </> : <p className="whitespace-pre-wrap break-words text-[13px] leading-5 [overflow-wrap:anywhere]">{draft.message}</p>}+ </div><p className="text-[12px] leading-5 text-muted-foreground">{tx("review")}</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"><Button variant="ghost" size="sm" disabled={saving} className="h-11 font-normal text-muted-foreground sm:h-9" onClick={back}>{t("settings.automations.cancel")}</Button>- <Button size="sm" className="h-11 sm:h-9" disabled={locked || targetUnavailable || !draft.message.trim()} aria-busy={saving} onClick={() => void save()}>{tx(saving ? "saving" : "confirm")}</Button>+ <Button size="sm" className="h-11 sm:h-9" disabled={locked || targetUnavailable || !draft.message.trim()} aria-busy={saving} onClick={() => void save()}>{tx(saving ? "saving" : draft.editingMessage ? "saveAndChange" : "confirm")}</Button></DialogFooter></>;}diff --git a/webui/src/i18n/locales/en/common.json b/webui/src/i18n/locales/en/common.jsonindex 618dcc8e6..8eae96b28 100644--- a/webui/src/i18n/locales/en/common.json+++ b/webui/src/i18n/locales/en/common.json@@ -1396,6 +1396,9 @@"automations": {"chat": {"changeBack": "Change back to “{{chat}}”",+ "editInstructions": "Edit instructions",+ "editInstructionsHint": "These edits are saved with the chat change.",+ "saveAndChange": "Save and change","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.",diff --git a/webui/src/i18n/locales/es/common.json b/webui/src/i18n/locales/es/common.jsonindex fc6cbdc58..cb74fd51c 100644--- a/webui/src/i18n/locales/es/common.json+++ b/webui/src/i18n/locales/es/common.json@@ -1197,6 +1197,9 @@"automations": {"chat": {"changeBack": "Volver a «{{chat}}»",+ "editInstructions": "Editar instrucciones",+ "editInstructionsHint": "Los cambios se guardan junto con el cambio de chat.",+ "saveAndChange": "Guardar y cambiar","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.",diff --git a/webui/src/i18n/locales/fr/common.json b/webui/src/i18n/locales/fr/common.jsonindex ec5034c65..0a6be7762 100644--- a/webui/src/i18n/locales/fr/common.json+++ b/webui/src/i18n/locales/fr/common.json@@ -1196,6 +1196,9 @@"automations": {"chat": {"changeBack": "Revenir à « {{chat}} »",+ "editInstructions": "Modifier les instructions",+ "editInstructionsHint": "Ces modifications sont enregistrées avec le changement de conversation.",+ "saveAndChange": "Enregistrer et changer","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.",diff --git a/webui/src/i18n/locales/id/common.json b/webui/src/i18n/locales/id/common.jsonindex bd2d49fed..408ddd894 100644--- a/webui/src/i18n/locales/id/common.json+++ b/webui/src/i18n/locales/id/common.json@@ -1196,6 +1196,9 @@"automations": {"chat": {"changeBack": "Kembali ke “{{chat}}”",+ "editInstructions": "Ubah instruksi",+ "editInstructionsHint": "Perubahan ini disimpan bersama perubahan chat.",+ "saveAndChange": "Simpan dan ubah","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.",diff --git a/webui/src/i18n/locales/ja/common.json b/webui/src/i18n/locales/ja/common.jsonindex b51ffe749..e4e19edaf 100644--- a/webui/src/i18n/locales/ja/common.json+++ b/webui/src/i18n/locales/ja/common.json@@ -1196,6 +1196,9 @@"automations": {"chat": {"changeBack": "「{{chat}}」に戻す",+ "editInstructions": "指示を編集",+ "editInstructionsHint": "編集内容はチャットの変更と一緒に保存されます。",+ "saveAndChange": "保存して変更","conflict": "タスクが別の場所で変更されました。下書きは保持されています。タスクを開き直して最新の設定を確認してください。","unavailable": "このチャットは利用できないか、作業場所や権限が変わりました。別のチャットを選んでください。","schedulerBusy": "実行中または待機中のタスクがあります。完了後に再試行してください。",diff --git a/webui/src/i18n/locales/ko/common.json b/webui/src/i18n/locales/ko/common.jsonindex c63689a08..1a0767a78 100644--- a/webui/src/i18n/locales/ko/common.json+++ b/webui/src/i18n/locales/ko/common.json@@ -1196,6 +1196,9 @@"automations": {"chat": {"changeBack": "“{{chat}}”(으)로 되돌리기",+ "editInstructions": "지침 수정",+ "editInstructionsHint": "수정한 지침은 채팅 변경과 함께 저장됩니다.",+ "saveAndChange": "저장 후 변경","conflict": "다른 곳에서 작업이 변경되었습니다. 초안은 유지됩니다. 작업을 다시 열어 최신 설정을 확인하세요.","unavailable": "이 채팅을 사용할 수 없거나 작업 공간 또는 권한이 변경되었습니다. 다른 채팅을 선택하세요.","schedulerBusy": "실행 중이거나 대기 중인 작업이 있습니다. 완료 후 다시 시도하세요.",diff --git a/webui/src/i18n/locales/pt-BR/common.json b/webui/src/i18n/locales/pt-BR/common.jsonindex 799792d76..ab8d285df 100644--- a/webui/src/i18n/locales/pt-BR/common.json+++ b/webui/src/i18n/locales/pt-BR/common.json@@ -1210,6 +1210,9 @@"automations": {"chat": {"changeBack": "Voltar para “{{chat}}”",+ "editInstructions": "Editar instruções",+ "editInstructionsHint": "Estas alterações são salvas junto com a mudança de conversa.",+ "saveAndChange": "Salvar e mudar","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.",diff --git a/webui/src/i18n/locales/vi/common.json b/webui/src/i18n/locales/vi/common.jsonindex 84a1efa5f..87a00df71 100644--- a/webui/src/i18n/locales/vi/common.json+++ b/webui/src/i18n/locales/vi/common.json@@ -1196,6 +1196,9 @@"automations": {"chat": {"changeBack": "Chuyển lại về “{{chat}}”",+ "editInstructions": "Sửa hướng dẫn",+ "editInstructionsHint": "Các chỉnh sửa được lưu cùng với việc đổi cuộc trò chuyện.",+ "saveAndChange": "Lưu và đổi","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.",diff --git a/webui/src/i18n/locales/zh-CN/common.json b/webui/src/i18n/locales/zh-CN/common.jsonindex 6bcd0825c..97a5f43b5 100644--- a/webui/src/i18n/locales/zh-CN/common.json+++ b/webui/src/i18n/locales/zh-CN/common.json@@ -1396,6 +1396,9 @@"automations": {"chat": {"changeBack": "改回「{{chat}}」",+ "editInstructions": "修改说明",+ "editInstructionsHint": "说明会与聊天更换一起保存。",+ "saveAndChange": "保存并更换","conflict": "任务已在别处修改,草稿已保留。请重新打开任务,核对最新设置后再更换。","unavailable": "这个聊天已不可用,或工作目录、权限已改变。请选择其他聊天。","schedulerBusy": "有任务正在执行或排队。请等任务结束后再试。",diff --git a/webui/src/i18n/locales/zh-TW/common.json b/webui/src/i18n/locales/zh-TW/common.jsonindex 02b9fb7a6..d6c7981e4 100644--- a/webui/src/i18n/locales/zh-TW/common.json+++ b/webui/src/i18n/locales/zh-TW/common.json@@ -1196,6 +1196,9 @@"automations": {"chat": {"changeBack": "改回「{{chat}}」",+ "editInstructions": "修改說明",+ "editInstructionsHint": "說明會與聊天更換一起儲存。",+ "saveAndChange": "儲存並更換","conflict": "任務已在別處修改,草稿已保留。請重新開啟任務,確認最新設定後再更換。","unavailable": "這個聊天已無法使用,或工作目錄、權限已變更。請選擇其他聊天。","schedulerBusy": "有任務正在執行或排隊。請等任務結束後再試。",diff --git a/webui/src/tests/automation-chat-binding.test.tsx b/webui/src/tests/automation-chat-binding.test.tsxindex 48fb9fca1..975786b98 100644--- a/webui/src/tests/automation-chat-binding.test.tsx+++ b/webui/src/tests/automation-chat-binding.test.tsx@@ -36,9 +36,13 @@ it("keeps the original route until acknowledgement and saves the reviewed promptawait choose();expect(save).not.toHaveBeenCalled();expect(screen.getByRole("group", { name: "Now" })).toHaveTextContent("My planning");+ expect(screen.queryByRole("textbox", { name: "Task instructions" })).not.toBeInTheDocument();+ expect(screen.getByText(job.payload.message)).toBeInTheDocument();+ await user.click(screen.getByRole("button", { name: "Edit instructions" }));+ expect(screen.getByRole("textbox", { name: "Task instructions" })).toHaveFocus();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" }));+ await user.click(screen.getByRole("button", { name: "Save and change" }));expect(save).toHaveBeenCalledWith(job, { target_id: "target", revision: "rev-1", message: "New instructions" });expect(screen.getByRole("button", { name: "Changing…" })).toBeDisabled();expect(screen.queryByRole("status")).not.toBeInTheDocument();@@ -84,6 +88,11 @@ it("uses Chinese for the task menu and the change/cancel path", async () => {await user.click(await screen.findByRole("option", { name: /Product team/ }));expect(screen.getByRole("heading", { name: "更换聊天" })).toBeInTheDocument();expect(screen.getByRole("button", { name: "确认并更换" })).toBeInTheDocument();+ expect(screen.queryByRole("textbox", { name: "任务说明" })).not.toBeInTheDocument();+ await user.click(screen.getByRole("button", { name: "修改说明" }));+ expect(screen.getByRole("textbox", { name: "任务说明" })).toHaveFocus();+ expect(screen.getByText("说明会与聊天更换一起保存。")).toBeInTheDocument();+ expect(screen.getByRole("button", { name: "保存并更换" })).toBeInTheDocument();await user.click(screen.getByRole("button", { name: "取消" }));expect(screen.getByRole("heading", { name: "Daily report" })).toBeInTheDocument();expect(screen.getByRole("combobox", { name: "运行与回复" })).toHaveFocus();@@ -132,6 +141,7 @@ it("cancels a chat change without saving the edited instructions", async () => {const save = vi.fn();render(<AutomationDetailDialog {...props} job={job} onChangeChat={save} />);await choose();+ await user.click(screen.getByRole("button", { name: "Edit instructions" }));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" }));@@ -139,6 +149,8 @@ it("cancels a chat change without saving the edited instructions", async () => {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.queryByRole("textbox", { name: "Task instructions" })).not.toBeInTheDocument();+ await user.click(screen.getByRole("button", { name: "Edit instructions" }));expect(screen.getByRole("textbox", { name: "Task instructions" })).toHaveValue("Summarize the work.");});@@ -147,9 +159,10 @@ it("keeps a rejected draft and its original revision across polling", async () =const save = vi.fn().mockRejectedValue(new Error("automation_chat_conflict"));const { rerender } = render(<AutomationDetailDialog {...props} job={job} onChangeChat={save} />);await choose();+ await user.click(screen.getByRole("button", { name: "Edit instructions" }));await user.type(screen.getByRole("textbox", { name: "Task instructions" }), " Reviewed");rerender(<AutomationDetailDialog {...props} job={{ ...job, chat_binding_revision: "rev-2" }} onChangeChat={save} />);- await user.click(screen.getByRole("button", { name: "Confirm change" }));+ await user.click(screen.getByRole("button", { name: "Save and change" }));expect(save.mock.calls[0][1].revision).toBe("rev-1");expect(await screen.findByRole("alert")).toHaveTextContent("draft is kept");expect(screen.getByRole("textbox", { name: "Task instructions" })).toHaveValue("Summarize the work. Reviewed");@@ -172,6 +185,7 @@ it("keeps the reviewed chat identity when refreshed choices no longer contain itconst save = vi.fn();const { rerender } = render(<AutomationDetailDialog {...props} job={job} onChangeChat={save} />);await choose();+ await user.click(screen.getByRole("button", { name: "Edit instructions" }));await user.type(screen.getByRole("textbox", { name: "Task instructions" }), " Reviewed");vi.mocked(fetchAutomationChats).mockResolvedValue({revision: "rev-2", current: { ...source, title: "Renamed planning" }, chats: [source],@@ -181,7 +195,7 @@ it("keeps the reviewed chat identity when refreshed choices no longer contain itexpect(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(screen.getByRole("button", { name: "Save and change" })).toBeDisabled();expect(save).not.toHaveBeenCalled();await user.click(screen.getByRole("button", { name: "Cancel" }));expect(screen.getByRole("combobox", { name: "Run and reply in" })).toHaveTextContent("Renamed planning");