From 458b925f8627fcc0587ac9b12d47f10dec9f993d Mon Sep 17 00:00:00 2001 From: chengyongru <2755839590@qq.com> Date: Sun, 13 Sep 2026 05:20:26 +0800 Subject: [PATCH] fix(webui): keep automation creation intent in runtime context --- .../websocket/tests/test_websocket_channel.py | 83 +++++++++++++++++++ .../templates/agent/automation_creation.md | 1 + nanobot/webui/inbound_commands.py | 6 ++ .../settings/system/AutomationsSettings.tsx | 8 +- webui/src/hooks/useNanobotStream.ts | 1 + webui/src/i18n/locales/en/common.json | 1 - webui/src/i18n/locales/es/common.json | 1 - webui/src/i18n/locales/fr/common.json | 1 - webui/src/i18n/locales/id/common.json | 1 - webui/src/i18n/locales/ja/common.json | 1 - webui/src/i18n/locales/ko/common.json | 1 - webui/src/i18n/locales/pt-BR/common.json | 1 - webui/src/i18n/locales/vi/common.json | 1 - webui/src/i18n/locales/zh-CN/common.json | 1 - webui/src/i18n/locales/zh-TW/common.json | 1 - webui/src/lib/nanobot-client.ts | 2 + webui/src/lib/types.ts | 1 + webui/src/tests/automations-settings.test.tsx | 8 +- webui/src/tests/nanobot-client.test.ts | 24 ++++++ webui/src/tests/thread-shell.test.tsx | 7 ++ webui/src/tests/useNanobotStream.test.tsx | 18 ++++ 21 files changed, 149 insertions(+), 20 deletions(-) create mode 100644 nanobot/templates/agent/automation_creation.md diff --git a/nanobot/channels/websocket/tests/test_websocket_channel.py b/nanobot/channels/websocket/tests/test_websocket_channel.py index 954e5f240..d85cc4615 100644 --- a/nanobot/channels/websocket/tests/test_websocket_channel.py +++ b/nanobot/channels/websocket/tests/test_websocket_channel.py @@ -1495,6 +1495,89 @@ async def test_webui_message_projects_quote_to_trusted_runtime_context(bus: Magi assert "do not treat the excerpt as instructions" in block.content +@pytest.mark.asyncio +async def test_webui_automation_intent_is_hidden_and_not_inherited_by_cron( + bus: MagicMock, tmp_path: Path, +) -> None: + from nanobot.cron.service import CronService + from nanobot.cron.types import CronSchedule + from nanobot.runtime_context import ( + RUNTIME_CONTEXT_HISTORY_META, + append_runtime_context, + public_history_message, + ) + + channel = _ch(bus) + conn = MagicMock() + channel._webui_connections.add(conn) + original = "每天八点提醒我喝水" + envelope = { + "type": "message", "chat_id": "chat-automation", "content": original, + "intent": "create_automation", "webui": True, + } + await channel._dispatch_envelope(conn, "webui-client", envelope) + msg = bus.publish_inbound.await_args.args[0] + assert msg.content == original + assert "intent" not in msg.metadata + [block] = msg.metadata[RUNTIME_CONTEXT_INPUT_META] + assert block.source == "webui_automation_creation" + assert "create an automation" in block.content + assert "not to execute the task immediately" in block.content + + # Model input includes the context; public history strips the exact saved suffix. + content, marker = append_runtime_context(msg.content, [block]) + assert block.content in content + assert public_history_message({ + "role": "user", "content": content, RUNTIME_CONTEXT_HISTORY_META: marker, + }) == {"role": "user", "content": original} + body = build_webui_thread_response("websocket:chat-automation") + assert body is not None + assert [message["content"] for message in body["messages"]] == [original] + + store_path = tmp_path / "cron" / "jobs.json" + cron = CronService(store_path) + job = cron.add_job( + name="Water", schedule=CronSchedule(kind="every", every_ms=60_000), + message=original, session_key="websocket:chat-automation", + origin_channel="websocket", origin_chat_id="chat-automation", + origin_metadata=msg.metadata, + ) + reloaded = CronService(store_path).get_job(job.id) + assert reloaded is not None + assert RUNTIME_CONTEXT_INPUT_META not in reloaded.payload.origin_metadata + assert "intent" not in reloaded.payload.origin_metadata + + await channel._dispatch_envelope(conn, "webui-client", { + **envelope, "content": "Thanks", "intent": None, + }) + assert RUNTIME_CONTEXT_INPUT_META not in bus.publish_inbound.await_args.args[0].metadata + + +@pytest.mark.asyncio +@pytest.mark.parametrize(("trusted", "webui", "intent", "shell"), [ + (False, True, "create_automation", False), + (True, False, "create_automation", False), + (True, True, None, False), + (True, True, "delete_automation", False), + (True, True, {"instruction": "arbitrary prompt"}, False), + (True, True, "create_automation", True), +]) +async def test_webui_automation_context_requires_valid_trusted_intent( + bus: MagicMock, trusted: bool, webui: bool, intent: object, shell: bool, +) -> None: + channel = _ch(bus) + conn = MagicMock() + if trusted: + channel._webui_connections.add(conn) + await channel._dispatch_envelope(conn, "client", { + "type": "message", "chat_id": "chat-intent", + "content": "!echo hello" if shell else "hello", + "intent": intent, "webui": webui, "user_shell": shell, + }) + msg = bus.publish_inbound.await_args.args[0] + assert RUNTIME_CONTEXT_INPUT_META not in msg.metadata + + @pytest.mark.asyncio async def test_webui_message_scope_inherits_persisted_session_scope( bus: MagicMock, diff --git a/nanobot/templates/agent/automation_creation.md b/nanobot/templates/agent/automation_creation.md new file mode 100644 index 000000000..8b376dc05 --- /dev/null +++ b/nanobot/templates/agent/automation_creation.md @@ -0,0 +1 @@ +The user submitted this request from the Automations creation interface. Their intent is to create an automation for this request, not to execute the task immediately. diff --git a/nanobot/webui/inbound_commands.py b/nanobot/webui/inbound_commands.py index ae5541f37..145329e35 100644 --- a/nanobot/webui/inbound_commands.py +++ b/nanobot/webui/inbound_commands.py @@ -35,6 +35,7 @@ from nanobot.session.webui_turns import ( websocket_turn_wall_started_at, ) from nanobot.utils.helpers import safe_filename +from nanobot.utils.prompt_templates import render_template from nanobot.webui.cli_apps_api import normalize_cli_app_mentions from nanobot.webui.forking import handle_webui_fork_chat from nanobot.webui.gateway_services import GatewayServices @@ -656,6 +657,11 @@ class WebUICommandRouter: ) if trusted_webui: context_blocks: list[RuntimeContextBlock] = [] + if not is_user_shell and envelope.get("intent") == "create_automation": + context_blocks.append(RuntimeContextBlock( + source="webui_automation_creation", + content=render_template("agent/automation_creation.md", strip=True), + )) quote = webui_quote_runtime_context( {WEBUI_QUOTE_METADATA: envelope.get("quoted_context")} ) diff --git a/webui/src/components/settings/system/AutomationsSettings.tsx b/webui/src/components/settings/system/AutomationsSettings.tsx index a55f9e82f..e9f600750 100644 --- a/webui/src/components/settings/system/AutomationsSettings.tsx +++ b/webui/src/components/settings/system/AutomationsSettings.tsx @@ -176,13 +176,9 @@ export function AutomationsSettings({ images?: SendAttachment[], options?: SendOptions, ) => onStartChat?.( - tx( - "settings.automations.createRequest", - "Create an automation for this request:\n\n{{request}}", - { request: content.trim() }, - ), + content.trim(), images, - options, + { ...options, intent: "create_automation" }, activeModelPreset, ); const filterLabel = filter === "all" ? tx("settings.automations.filter", "Filter") : tx("settings.automations.filteredBy", "Filter: {{status}}", { diff --git a/webui/src/hooks/useNanobotStream.ts b/webui/src/hooks/useNanobotStream.ts index 37f3bc2d1..1372fed4f 100644 --- a/webui/src/hooks/useNanobotStream.ts +++ b/webui/src/hooks/useNanobotStream.ts @@ -176,6 +176,7 @@ export interface SendAttachment { } export interface SendOptions { + intent?: "create_automation"; cliApps?: OutboundCliAppMention[]; mcpPresets?: OutboundMcpPresetMention[]; sessionMentions?: SessionMention[]; diff --git a/webui/src/i18n/locales/en/common.json b/webui/src/i18n/locales/en/common.json index e97662068..313f3a51c 100644 --- a/webui/src/i18n/locales/en/common.json +++ b/webui/src/i18n/locales/en/common.json @@ -1101,7 +1101,6 @@ "create": "Create automation", "createPrompt": "What would you like nanobot to automate?", "createInput": "Describe an automation", - "createRequest": "Create an automation for this request:\n\n{{request}}", "errors": { "legacyMissingDestination": "This older automation is missing its delivery destination. Recreate it from the linked chat to continue." }, diff --git a/webui/src/i18n/locales/es/common.json b/webui/src/i18n/locales/es/common.json index d46ce9523..1a310e273 100644 --- a/webui/src/i18n/locales/es/common.json +++ b/webui/src/i18n/locales/es/common.json @@ -902,7 +902,6 @@ "create": "Crear automatización", "createPrompt": "¿Qué te gustaría automatizar con nanobot?", "createInput": "Describe una automatización", - "createRequest": "Crea una automatización para esta solicitud:\n\n{{request}}", "errors": { "legacyMissingDestination": "Esta automatización antigua no tiene un destino de entrega. Vuelve a crearla desde el chat vinculado para continuar." }, diff --git a/webui/src/i18n/locales/fr/common.json b/webui/src/i18n/locales/fr/common.json index f46452a2b..02c2834e9 100644 --- a/webui/src/i18n/locales/fr/common.json +++ b/webui/src/i18n/locales/fr/common.json @@ -901,7 +901,6 @@ "create": "Créer une automatisation", "createPrompt": "Que voulez-vous automatiser avec nanobot ?", "createInput": "Décrire une automatisation", - "createRequest": "Crée une automatisation pour cette demande :\n\n{{request}}", "errors": { "legacyMissingDestination": "Cette ancienne automatisation n’a plus de destination. Recréez-la depuis la discussion liée pour continuer." }, diff --git a/webui/src/i18n/locales/id/common.json b/webui/src/i18n/locales/id/common.json index 5f4348f3f..1f2d898da 100644 --- a/webui/src/i18n/locales/id/common.json +++ b/webui/src/i18n/locales/id/common.json @@ -901,7 +901,6 @@ "create": "Buat otomatisasi", "createPrompt": "Apa yang ingin kamu otomatisasi dengan nanobot?", "createInput": "Jelaskan otomatisasi", - "createRequest": "Buat otomatisasi untuk permintaan ini:\n\n{{request}}", "errors": { "legacyMissingDestination": "Otomatisasi lama ini tidak memiliki tujuan pengiriman. Buat ulang dari chat terkait untuk melanjutkan." }, diff --git a/webui/src/i18n/locales/ja/common.json b/webui/src/i18n/locales/ja/common.json index 269907c59..dc8e86f46 100644 --- a/webui/src/i18n/locales/ja/common.json +++ b/webui/src/i18n/locales/ja/common.json @@ -901,7 +901,6 @@ "create": "自動タスクを作成", "createPrompt": "nanobot に何を自動化してほしいですか?", "createInput": "自動タスクを説明", - "createRequest": "次の依頼に対する自動タスクを作成してください:\n\n{{request}}", "errors": { "legacyMissingDestination": "この旧形式の自動タスクには送信先がありません。続行するには、関連チャットから作り直してください。" }, diff --git a/webui/src/i18n/locales/ko/common.json b/webui/src/i18n/locales/ko/common.json index 26bbfc1f2..12c5c0e34 100644 --- a/webui/src/i18n/locales/ko/common.json +++ b/webui/src/i18n/locales/ko/common.json @@ -901,7 +901,6 @@ "create": "자동화 만들기", "createPrompt": "nanobot이 무엇을 자동으로 해주면 좋을까요?", "createInput": "자동화 설명", - "createRequest": "다음 요청에 맞는 자동화를 만들어 주세요:\n\n{{request}}", "errors": { "legacyMissingDestination": "이전 형식의 자동화에 전송 대상이 없습니다. 계속하려면 연결된 채팅에서 다시 만들어 주세요." }, diff --git a/webui/src/i18n/locales/pt-BR/common.json b/webui/src/i18n/locales/pt-BR/common.json index ea8ead8ce..9c759f155 100644 --- a/webui/src/i18n/locales/pt-BR/common.json +++ b/webui/src/i18n/locales/pt-BR/common.json @@ -915,7 +915,6 @@ "create": "Criar automação", "createPrompt": "O que você gostaria de automatizar com o nanobot?", "createInput": "Descreva uma automação", - "createRequest": "Crie uma automação para esta solicitação:\n\n{{request}}", "errors": { "legacyMissingDestination": "Esta automação antiga não tem um destino de entrega. Recrie-a na conversa vinculada para continuar." }, diff --git a/webui/src/i18n/locales/vi/common.json b/webui/src/i18n/locales/vi/common.json index 17252af08..334c08ce8 100644 --- a/webui/src/i18n/locales/vi/common.json +++ b/webui/src/i18n/locales/vi/common.json @@ -901,7 +901,6 @@ "create": "Tạo tự động hóa", "createPrompt": "Bạn muốn nanobot tự động làm gì?", "createInput": "Mô tả tác vụ tự động", - "createRequest": "Tạo một tác vụ tự động cho yêu cầu này:\n\n{{request}}", "errors": { "legacyMissingDestination": "Tác vụ tự động cũ này thiếu nơi nhận. Hãy tạo lại từ cuộc trò chuyện liên kết để tiếp tục." }, diff --git a/webui/src/i18n/locales/zh-CN/common.json b/webui/src/i18n/locales/zh-CN/common.json index 40a712f16..ae100f1d7 100644 --- a/webui/src/i18n/locales/zh-CN/common.json +++ b/webui/src/i18n/locales/zh-CN/common.json @@ -1101,7 +1101,6 @@ "create": "创建自动任务", "createPrompt": "想让 nanobot 自动帮你做什么?", "createInput": "描述一个自动任务", - "createRequest": "请为以下需求创建自动任务:\n\n{{request}}", "errors": { "legacyMissingDestination": "这个旧版自动任务缺少发送目标,无法继续运行。请从关联会话中重新创建该任务。" }, diff --git a/webui/src/i18n/locales/zh-TW/common.json b/webui/src/i18n/locales/zh-TW/common.json index fc1205192..0aa7560ff 100644 --- a/webui/src/i18n/locales/zh-TW/common.json +++ b/webui/src/i18n/locales/zh-TW/common.json @@ -901,7 +901,6 @@ "create": "建立自動任務", "createPrompt": "想讓 nanobot 自動幫你做什麼?", "createInput": "描述自動任務", - "createRequest": "請為以下需求建立自動任務:\n\n{{request}}", "errors": { "legacyMissingDestination": "這個舊版自動任務缺少傳送目標,無法繼續執行。請從關聯對話中重新建立該任務。" }, diff --git a/webui/src/lib/nanobot-client.ts b/webui/src/lib/nanobot-client.ts index bcaa0d350..c2cc6eaa1 100644 --- a/webui/src/lib/nanobot-client.ts +++ b/webui/src/lib/nanobot-client.ts @@ -976,6 +976,7 @@ export class NanobotClient { mcpPresets?: OutboundMcpPresetMention[]; sessionMentions?: SessionMention[]; quotedContext?: string; + intent?: "create_automation"; workspaceScope?: WorkspaceScopePayload | null; turnId?: string; /** False for side-channel or injected messages that do not own a lifecycle. */ @@ -995,6 +996,7 @@ export class NanobotClient { ? { session_mentions: options.sessionMentions } : {}), ...(options?.quotedContext?.trim() ? { quoted_context: options.quotedContext.trim() } : {}), + ...(options?.intent === "create_automation" ? { intent: options.intent } : {}), ...(options?.workspaceScope ? { workspace_scope: options.workspaceScope } : {}), ...(options?.turnId ? { turn_id: options.turnId } : {}), webui: true, diff --git a/webui/src/lib/types.ts b/webui/src/lib/types.ts index e79737d56..59fbe05d1 100644 --- a/webui/src/lib/types.ts +++ b/webui/src/lib/types.ts @@ -1602,6 +1602,7 @@ export type Outbound = mcp_presets?: OutboundMcpPresetMention[]; session_mentions?: SessionMention[]; quoted_context?: string; + intent?: "create_automation"; workspace_scope?: WorkspaceScopePayload; turn_id?: string; /** Marks messages sent by the embedded WebUI, without changing the diff --git a/webui/src/tests/automations-settings.test.tsx b/webui/src/tests/automations-settings.test.tsx index de265df20..76155b8c8 100644 --- a/webui/src/tests/automations-settings.test.tsx +++ b/webui/src/tests/automations-settings.test.tsx @@ -490,9 +490,9 @@ describe("Automation task list and detail sheet", () => { await user.click(screen.getByRole("button", { name: "Send message" })); expect(onStartChat).toHaveBeenCalledWith( - "Create an automation for this request:\n\nEvery weekday at 9, summarize my open pull requests", - undefined, + "Every weekday at 9, summarize my open pull requests", undefined, + { intent: "create_automation" }, "fast", ); await waitFor(() => expect(composer).toHaveValue("")); @@ -512,9 +512,9 @@ describe("Automation task list and detail sheet", () => { await user.type(composer, "Run a deep weekly review"); await user.click(screen.getByRole("button", { name: "Send message" })); expect(onStartChat).toHaveBeenCalledWith( - "Create an automation for this request:\n\nRun a deep weekly review", - undefined, + "Run a deep weekly review", undefined, + { intent: "create_automation" }, "deep", ); }); diff --git a/webui/src/tests/nanobot-client.test.ts b/webui/src/tests/nanobot-client.test.ts index b9f6852ea..e6b0f63e0 100644 --- a/webui/src/tests/nanobot-client.test.ts +++ b/webui/src/tests/nanobot-client.test.ts @@ -1974,6 +1974,30 @@ describe("NanobotClient", () => { }); }); + it("sends automation intent separately from the user's text", () => { + const client = new NanobotClient({ + url: "ws://test", + reconnect: false, + socketFactory: (url) => new FakeSocket(url) as unknown as WebSocket, + }); + client.connect(); + lastSocket().fakeOpen(); + + client.sendMessage("chat-x", "每天八点提醒我喝水", undefined, { + intent: "create_automation", + }); + expect(JSON.parse(lastSocket().sent.at(-1) as string)).toEqual({ + type: "message", + chat_id: "chat-x", + content: "每天八点提醒我喝水", + intent: "create_automation", + webui: true, + }); + + client.sendMessage("chat-x", "Thanks"); + expect(JSON.parse(lastSocket().sent.at(-1) as string)).not.toHaveProperty("intent"); + }); + it("includes CLI app attachments in outbound messages", () => { const client = new NanobotClient({ url: "ws://test", diff --git a/webui/src/tests/thread-shell.test.tsx b/webui/src/tests/thread-shell.test.tsx index ad0e57227..6fa53ca2c 100644 --- a/webui/src/tests/thread-shell.test.tsx +++ b/webui/src/tests/thread-shell.test.tsx @@ -1608,6 +1608,7 @@ describe("ThreadShell", () => { id: "automation-first-message", chatId: "chat-new", content: "Every weekday at 9, summarize open pull requests", + options: { intent: "create_automation" as const }, }; render( @@ -1633,6 +1634,12 @@ describe("ThreadShell", () => { expect(client.sendMessage).toHaveBeenCalledTimes(1); expect(consumed).toHaveBeenCalledOnce(); expect(consumed).toHaveBeenCalledWith(pendingFirstMessage.id); + expect(client.sendMessage).toHaveBeenCalledWith( + "chat-new", + pendingFirstMessage.content, + undefined, + expect.objectContaining({ intent: "create_automation" }), + ); }); it("keeps the first landing message when new chat history is still empty", async () => { diff --git a/webui/src/tests/useNanobotStream.test.tsx b/webui/src/tests/useNanobotStream.test.tsx index efc21ed2e..166650826 100644 --- a/webui/src/tests/useNanobotStream.test.tsx +++ b/webui/src/tests/useNanobotStream.test.tsx @@ -2711,6 +2711,24 @@ describe("useNanobotStream", () => { expect(outbound[3]).not.toHaveProperty("quotedContext"); }); + it("keeps automation intent out of the optimistic user message", () => { + const fake = fakeClient(); + const { result } = renderHook(() => useNanobotStream("chat-automation", EMPTY_MESSAGES), { + wrapper: wrap(fake.client), + }); + act(() => { + result.current.send("每天八点提醒我喝水", undefined, { intent: "create_automation" }); + }); + expect(result.current.messages[0].content).toBe("每天八点提醒我喝水"); + expect(result.current.messages[0]).not.toHaveProperty("intent"); + expect(fake.client.sendMessage).toHaveBeenCalledWith( + "chat-automation", + "每天八点提醒我喝水", + undefined, + expect.objectContaining({ intent: "create_automation", turnId: expect.any(String) }), + ); + }); + it("attaches assistant media_urls to complete messages", () => { const fake = fakeClient(); const { result } = renderHook(() => useNanobotStream("chat-m", EMPTY_MESSAGES), {