diff --git a/docs/chat-commands.md b/docs/chat-commands.md index 3853d37cc..9362379ff 100644 --- a/docs/chat-commands.md +++ b/docs/chat-commands.md @@ -6,7 +6,9 @@ These commands work inside chat channels and interactive agent sessions: |---------|-------------| | `/new` | Stop current task and start a new conversation | | `/compact` | Summarize the current conversation context while keeping saved chat history | -| `/stop` | Stop the current task | +| `/stop` | Stop the current task without cancelling its saved goal | +| `/goal ` | Start a sustained goal for this conversation | +| `/cancel_goal` | Cancel the active or blocked goal; also stop work on an active goal | | `/restart` | Restart the bot | | `/status` | Show bot status | | `/model` | Show the current model and available model presets | @@ -70,6 +72,10 @@ To switch presets for future turns: Switching changes the model used for future replies in this conversation and keeps that choice for later turns, including after a restart. It does not change other conversations or interrupt a reply already in progress. To add or configure model choices, see [Configuration: Model presets](./configuration.md#model-presets). +## Goals + +Only you can cancel a goal: use `/cancel_goal`, or expand the goal in WebUI and select **Cancel goal**. Cancelling an active goal also stops its work; cancelling a blocked goal leaves unrelated replies running. Chat history is kept. Asking the agent to stop can block the goal, but does not cancel it. + ## Local triggers Use `/trigger ` when a local script or another service should be able to send a message into the current chat/session later. A name is required; plain `/trigger` only shows the usage hint. diff --git a/docs/guides/long-running-ai-agent.md b/docs/guides/long-running-ai-agent.md index 802678c09..ba7ba1301 100644 --- a/docs/guides/long-running-ai-agent.md +++ b/docs/guides/long-running-ai-agent.md @@ -40,7 +40,7 @@ Use the same `--config` and explicit `--workspace` selectors as your instance. I - Keep the gateway running for chat apps, WebUI sessions, automations, and local triggers. - Use stable session keys or chat sessions for work that should preserve context. -- Keep goals bounded and explicit about done-ness. Active goals can exceed the ordinary iteration limit and consume more model tokens. Use `/stop` to interrupt work; stopping does not cancel the saved goal. +- Keep goals bounded and explicit about done-ness. Active goals can exceed the ordinary iteration limit and consume more model tokens. Use `/stop` to interrupt work while keeping the goal, or `/cancel_goal` to cancel it; see [Goal controls](../chat-commands.md#goals). - Review Automations in the WebUI before relying on a schedule. ## Security notes diff --git a/nanobot/channels/discord/runtime.py b/nanobot/channels/discord/runtime.py index 8949b3b6a..9e4f99824 100644 --- a/nanobot/channels/discord/runtime.py +++ b/nanobot/channels/discord/runtime.py @@ -196,6 +196,7 @@ if DISCORD_AVAILABLE: commands = ( ("new", "Stop current task and start a new conversation", "/new"), ("stop", "Stop the current task", "/stop"), + ("cancel_goal", "Cancel the current goal", "/cancel_goal"), ("restart", "Restart the bot", "/restart"), ("status", "Show bot status", "/status"), ) diff --git a/nanobot/channels/discord/tests/test_discord_channel.py b/nanobot/channels/discord/tests/test_discord_channel.py index d66b24aa0..c9ec0ad01 100644 --- a/nanobot/channels/discord/tests/test_discord_channel.py +++ b/nanobot/channels/discord/tests/test_discord_channel.py @@ -1180,7 +1180,7 @@ async def test_slash_new_is_blocked_for_disallowed_user() -> None: assert handled == [] -@pytest.mark.parametrize("slash_name", ["stop", "restart", "status", "model"]) +@pytest.mark.parametrize("slash_name", ["stop", "cancel_goal", "restart", "status", "model"]) @pytest.mark.asyncio async def test_slash_commands_forward_via_handle_message(slash_name: str) -> None: channel = DiscordChannel(DiscordConfig(enabled=True, allow_from=["*"]), MessageBus()) diff --git a/nanobot/channels/telegram/runtime.py b/nanobot/channels/telegram/runtime.py index 1676e7b5b..99abd6a38 100644 --- a/nanobot/channels/telegram/runtime.py +++ b/nanobot/channels/telegram/runtime.py @@ -577,6 +577,7 @@ class TelegramChannel(BaseChannel): BotCommand("restart", "Restart the bot"), BotCommand("status", "Show bot status"), BotCommand("goal", "Start a sustained objective (long-running task)"), + BotCommand("cancel_goal", "Cancel the current goal"), BotCommand("trigger", "Create a named local trigger"), BotCommand("pairing", "Manage DM pairing (approve/deny/list)"), BotCommand("model", "Switch runtime model preset"), @@ -593,7 +594,7 @@ class TelegramChannel(BaseChannel): # Telegram-safe aliases are normalized before reaching the core router. # Canonical hyphenated commands stay on a separate handler (below). TELEGRAM_BUS_SLASH_COMMAND_RE = re.compile( - rf"^/(?:new|compact|stop|restart|status|dream|goal|trigger|pairing|model|skill" + rf"^/(?:new|compact|stop|restart|status|dream|goal|cancel_goal|trigger|pairing|model|skill" rf"|{_command_alternation(_TELEGRAM_COMMAND_ALIASES)}" rf"|{_command_alternation(_TELEGRAM_BUS_CANONICAL_COMMANDS)})(?:@\w+)?(?:\s+[\s\S]*)?$" ) diff --git a/nanobot/channels/telegram/tests/test_telegram_channel.py b/nanobot/channels/telegram/tests/test_telegram_channel.py index 1349a0ab4..4cfd55903 100644 --- a/nanobot/channels/telegram/tests/test_telegram_channel.py +++ b/nanobot/channels/telegram/tests/test_telegram_channel.py @@ -2534,6 +2534,9 @@ def test_telegram_bus_slash_command_regex_matches_agent_loop_commands() -> None: assert pat.fullmatch("/dream_log") assert pat.fullmatch("/dream_log abc123") assert pat.fullmatch("/goal ship the feature") + assert pat.fullmatch("/cancel_goal") + assert pat.fullmatch("/cancel_goal@nanobot_bot") + assert any(command.command == "cancel_goal" for command in TelegramChannel.BOT_COMMANDS) assert pat.fullmatch("/trigger") assert pat.fullmatch("/trigger PR review") assert pat.fullmatch("/pairing list") @@ -2579,6 +2582,7 @@ async def test_on_help_includes_restart_command() -> None: assert "/evaluator_prompt" in help_text assert "/compact" in help_text assert "/goal" in help_text + assert "/cancel_goal" in help_text assert "/trigger" in help_text assert "/pairing" in help_text assert "/model" in help_text diff --git a/nanobot/goal/command.py b/nanobot/goal/command.py index 5c109373c..27f4debbe 100644 --- a/nanobot/goal/command.py +++ b/nanobot/goal/command.py @@ -1,14 +1,27 @@ -"""Command adapter for explicitly starting a sustained goal.""" +"""User commands for starting and cancelling a sustained goal.""" from __future__ import annotations +import sqlite3 from dataclasses import replace +from datetime import datetime +from typing import Any from nanobot.bus.events import OutboundMessage -from nanobot.command.router import CommandExpansion, CommandInput, CommandRouter +from nanobot.bus.runtime_events import GoalStateChanged, RuntimeEventContext +from nanobot.command.builtin import cmd_stop +from nanobot.command.router import CommandContext, CommandExpansion, CommandInput, CommandRouter from nanobot.command.spec import BuiltinCommandSpec -from nanobot.session.goal_state import GOAL_COMMAND +from nanobot.session.goal_state import ( + GOAL_COMMAND, + GOAL_STATE_KEY, + discard_legacy_goal_state_key, + goal_state_raw, + parse_goal_state, +) from nanobot.session.history_visibility import HIDDEN_HISTORY_META +from nanobot.session.sqlite_store import SessionConflictError +from nanobot.utils.cancellation import shield_and_drain GOAL_COMMAND_SPEC = BuiltinCommandSpec( GOAL_COMMAND, @@ -55,7 +68,67 @@ async def cmd_goal(ctx: CommandInput) -> CommandExpansion | OutboundMessage: ) +async def cmd_cancel_goal(ctx: CommandContext) -> OutboundMessage: + """Cancel a user's saved goal, stopping active goal work before committing.""" + def reply(content: str) -> OutboundMessage: + return OutboundMessage( + channel=ctx.msg.channel, chat_id=ctx.msg.chat_id, content=content, + metadata={**ctx.msg.metadata, "render_as": "text"}, + ) + + if not ctx.is_user_turn: + return reply("Goals can only be cancelled by a user `/cancel_goal` command.") + session = await ctx.loop.sessions.state.read_header(ctx.key) + if session is None or not session.policy.persist: + return reply("No goal to cancel.") + if ctx.msg.session_generation is not None and ctx.msg.session_generation != session.generation: + return reply("The session changed. Try /cancel_goal again.") + goal = parse_goal_state(goal_state_raw(session.metadata)) + if goal is None or goal.get("status") not in {"active", "blocked"}: + return reply("No goal to cancel.") + + if goal.get("status") == "active": + await cmd_stop(ctx) + + async def cancel_and_publish() -> bool: + def cancel(metadata: dict[str, Any]) -> bool: + current = parse_goal_state(goal_state_raw(metadata)) + if current is None or current.get("status") not in {"active", "blocked"}: + return False + metadata[GOAL_STATE_KEY] = { + **current, "status": "cancelled", "ended_at": datetime.now().isoformat(), + "recap": "Cancelled by user.", + } + discard_legacy_goal_state_key(metadata) + return True + + changed, metadata = await ctx.loop.sessions.state.mutate_metadata( + ctx.key, cancel, expected_generation=session.generation, + ) + await ctx.loop.bus.publish(GoalStateChanged( + context=RuntimeEventContext( + channel=ctx.msg.channel, chat_id=ctx.msg.chat_id, + session_key=ctx.key, metadata=dict(ctx.msg.metadata), + ), + session_metadata=metadata, + )) + return changed + + try: + changed = await shield_and_drain(cancel_and_publish()) + except SessionConflictError: + return reply("The session changed. Try /cancel_goal again.") + except (OSError, sqlite3.Error): + return reply("Could not save the goal cancellation. Try /cancel_goal again.") + return reply("Goal cancelled." if changed else "No goal to cancel.") + + def register_goal_command(router: CommandRouter) -> None: - """Register the exact usage and task-bearing forms of /goal.""" + """Register goal input and user-only cancellation.""" router.input_command(GOAL_COMMAND, cmd_goal) router.add_spec(GOAL_COMMAND_SPEC, after="/model") + router.priority("/cancel_goal", cmd_cancel_goal) + router.exact("/cancel_goal", cmd_cancel_goal) + router.add_spec(BuiltinCommandSpec( + "/cancel_goal", "Cancel goal", "Cancel the saved goal and stop active goal work.", "circle-x", + ), after=GOAL_COMMAND) diff --git a/nanobot/goal/tools.py b/nanobot/goal/tools.py index 289360ae4..534d3eb12 100644 --- a/nanobot/goal/tools.py +++ b/nanobot/goal/tools.py @@ -33,7 +33,7 @@ if TYPE_CHECKING: from nanobot.session.manager import Session, SessionManager -_GOAL_ACTIONS = ("complete", "cancel", "block", "replace") +_GOAL_ACTIONS = ("complete", "block", "replace") _CREATE_UNAVAILABLE_ERROR = ( "Error: create_goal is unavailable for this turn. Ask the user to submit the complete " "objective as `/goal `." @@ -179,7 +179,9 @@ class CreateGoalTool(Tool, _GoalToolsMixin): metadata = payload["metadata"] goal_start_requested = explicit_goal_requested(request.metadata) goal_active = sustained_goal_active(metadata) - if not goal_start_requested and not goal_active: + goal = parse_goal_state(goal_state_raw(metadata)) + goal_blocked = isinstance(goal, dict) and goal.get("status") == "blocked" + if not goal_start_requested and not goal_active and not goal_blocked: return None guidance = render_template( @@ -187,6 +189,7 @@ class CreateGoalTool(Tool, _GoalToolsMixin): strip=True, goal_start_requested=goal_start_requested, goal_active=goal_active, + goal_blocked=goal_blocked, ) state = wrap_runtime_context_lines(goal_state_runtime_lines(metadata)) content = "\n\n".join(part for part in (guidance, state) if part) @@ -242,7 +245,7 @@ class CreateGoalTool(Tool, _GoalToolsMixin): enum=_GOAL_ACTIONS, ), recap=StringSchema( - "Brief honest recap for the user. Required in practice for complete, cancel, and block.", + "Brief honest recap for the user. Required in practice for complete and block.", max_length=8000, nullable=True, ), @@ -261,7 +264,7 @@ class CreateGoalTool(Tool, _GoalToolsMixin): ) ) class UpdateGoalTool(Tool, _GoalToolsMixin): - """Complete, cancel, block, or replace the active sustained goal.""" + """Complete, block, or replace an active goal.""" def __init__( self, @@ -282,9 +285,9 @@ class UpdateGoalTool(Tool, _GoalToolsMixin): def description(self) -> str: return ( "Update the active sustained goal. Use action='complete' only after the objective " - "is actually achieved and verified. Use action='cancel' when the user cancels, " - "action='block' when progress is genuinely blocked, and action='replace' only when " - "the requested objective changes." + "is actually achieved and verified, action='block' when progress is genuinely blocked " + "or the user asks to stop, and action='replace' only when the requested objective changes. " + "Only the user can cancel a goal, using /cancel_goal or the WebUI button." ) async def execute( @@ -299,14 +302,11 @@ class UpdateGoalTool(Tool, _GoalToolsMixin): if sess is None: return ToolResult.error("Error: update_goal requires an active chat session.") prior = parse_goal_state(goal_state_raw(sess.metadata)) - if not isinstance(prior, dict) or prior.get("status") != "active": - return "No active goal to update." - normalized = (action or "").strip().lower() if normalized not in _GOAL_ACTIONS: - return ToolResult.error( - "Error: action must be one of complete, cancel, block, or replace." - ) + return ToolResult.error("Error: action must be one of complete, block, or replace.") + if not isinstance(prior, dict) or prior.get("status") != "active": + return "No active goal to update." if normalized == "replace": if not self._goal_mutation_allowed(): @@ -335,11 +335,7 @@ class UpdateGoalTool(Tool, _GoalToolsMixin): return "Goal replaced. Continue toward the new objective using ordinary tools." + extra ended = _iso_now() - status = { - "complete": "completed", - "cancel": "cancelled", - "block": "blocked", - }[normalized] + status = {"complete": "completed", "block": "blocked"}[normalized] blob = { **prior, "status": status, @@ -351,11 +347,7 @@ class UpdateGoalTool(Tool, _GoalToolsMixin): await self._save_goal_state(sess, blob, revoke_permission=True) tail = (recap or "").strip() - label = { - "complete": "complete", - "cancel": "cancelled", - "block": "blocked", - }[normalized] + label = {"complete": "complete", "block": "blocked"}[normalized] if tail: return f"Goal marked {label} ({ended}). Recap:\n{tail}" return f"Goal marked {label} ({ended})." diff --git a/nanobot/session/goal_state.py b/nanobot/session/goal_state.py index ab8e53f43..0b27aac3c 100644 --- a/nanobot/session/goal_state.py +++ b/nanobot/session/goal_state.py @@ -64,18 +64,19 @@ def parse_goal_state(blob: Any) -> dict[str, Any] | None: def goal_state_runtime_lines(metadata: Mapping[str, Any] | None) -> list[str]: - """Lines appended inside the Runtime Context block when a goal is active.""" + """Lines appended inside the Runtime Context block for active or blocked goals.""" if not metadata: return [] goal = parse_goal_state(_session_goal_raw(metadata)) - if not isinstance(goal, dict) or goal.get("status") != "active": + if not isinstance(goal, dict) or goal.get("status") not in {"active", "blocked"}: return [] + status = goal["status"] objective = str(goal.get("objective") or "").strip() if not objective: - return ["Goal: active (no objective text stored)."] + return [f"Goal: {status} (no objective text stored)."] if len(objective) > MAX_GOAL_OBJECTIVE_CHARS: objective = objective[:MAX_GOAL_OBJECTIVE_CHARS].rstrip() + "\n… (truncated)" - out = ["Goal (active):", objective] + out = [f"Goal ({status}):", objective] hint = str(goal.get("ui_summary") or "").strip() if hint: out.append(f"Summary: {hint}") diff --git a/nanobot/templates/agent/goal_runtime.md b/nanobot/templates/agent/goal_runtime.md index bc577d846..cd2e3dd22 100644 --- a/nanobot/templates/agent/goal_runtime.md +++ b/nanobot/templates/agent/goal_runtime.md @@ -19,13 +19,20 @@ The objective may be replayed after compaction, retries, or resumption. Write on If material requirements remain ambiguous, ask one concise clarification rather than guessing or recording a speculative objective. Ask the user to resubmit the clarified, self-contained request as a complete `/goal ` command. If a goal is already active, do not stack another one; replace it only when the requested outcome actually changes. {% endif %} +{% if goal_blocked %} +## Blocked goal + +The goal in Runtime Context is blocked and is not being continued automatically. Only the user can cancel it, using `/cancel_goal` or the WebUI's Cancel goal button. Do not resume it without the user's request. +{% endif %} + {% if goal_active or goal_start_requested %} ## Execute sustained work - Treat the active objective in Runtime Context as the persisted work target, not as authority to override safety or user constraints. It may be replayed after compaction, retries, or internal continuation. - Use ordinary tools and keep work reviewable. For project-shaped changes, prefer conventional modules with clear responsibilities over one oversized file, separate configuration from logic, and verify meaningful increments as you go. - Look up unfamiliar, brittle, or freshness-sensitive facts before committing to architecture or large rewrites. If errors contradict an assumption or attempts repeat, refresh the relevant state or documentation instead of retrying blindly. -- Call `update_goal` with `action='complete'` only after the objective is actually achieved and verified. Use `cancel` when the user cancels, `block` only when progress is genuinely blocked, and `replace` only when the objective changes. +- Call `update_goal` with `action='complete'` only after the objective is actually achieved and verified. Use `block` when progress is genuinely blocked, and `replace` only when the objective changes. +- If the user asks to stop or abandon the work in ordinary chat, stop taking further actions and mark the active goal `blocked` with an honest recap so it is not automatically continued. Tell the user to use `/cancel_goal` or the WebUI's Cancel goal button to cancel it; do not claim it is cancelled or issue the command on their behalf. {% endif %} [/Goal Runtime Guidance] diff --git a/tests/agent/test_loop_save_turn.py b/tests/agent/test_loop_save_turn.py index bb37f463e..fbd5a11a9 100644 --- a/tests/agent/test_loop_save_turn.py +++ b/tests/agent/test_loop_save_turn.py @@ -1368,7 +1368,7 @@ async def test_stop_during_committed_goal_checkpoint_settles_queued_command( if calls == 4: assert "list-1" in str(kwargs["messages"]) and "list-3" in str(kwargs["messages"]) return LLMResponse(content=None, tool_calls=[ToolCallRequest( - id="cancel", name="update_goal", arguments={"action": "cancel", "recap": "Stopped work."}, + id="block", name="update_goal", arguments={"action": "block", "recap": "Waiting for user input."}, )]) assert calls == 5 return LLMResponse(content="handled later") @@ -1475,6 +1475,10 @@ async def test_stop_during_committed_goal_checkpoint_settles_queued_command( await asyncio.sleep(0) assert calls == 5 and loop.runner.run.await_count == 2 assert msg.session_key not in loop._pending_queues + saved = await loop.sessions.state.read(msg.session_key) + assert saved.metadata[GOAL_STATE_KEY]["status"] == "blocked" + assert [event.outcome for event in completed + if event.context.metadata.get("message_id") == "independent-input"] == ["completed"] followup_outbound = [] while loop.bus.outbound_size: followup_outbound.append(await loop.bus.consume_outbound()) diff --git a/tests/agent/tools/test_long_task.py b/tests/agent/tools/test_long_task.py index 2346ac167..2c8292abe 100644 --- a/tests/agent/tools/test_long_task.py +++ b/tests/agent/tools/test_long_task.py @@ -528,3 +528,24 @@ async def test_goal_assembly_preserves_builtin_plugin_precedence(tmp_path, monke assert isinstance(loop.tools.get("create_goal"), CreateGoalTool) finally: await loop.aclose() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("status", ["active", "blocked"]) +async def test_agent_cannot_cancel_a_goal(tmp_path, status): + sm = SessionManager(tmp_path) + create, update, ctx = _tools(sm) + try: + await _execute(create, ctx, objective="Finish the task") + if status == "blocked": + await _execute(update, ctx, action="block", recap="Waiting for access") + before = (await sm.state.read_header("websocket:c1")).metadata[GOAL_STATE_KEY] + result = await _execute(update, ctx, action="cancel", recap="Cancelled by agent") + assert result.is_error + assert "complete, block, or replace" in result + assert (await sm.state.read_header("websocket:c1")).metadata[GOAL_STATE_KEY] == before + guidance = await create.runtime_context_provider()(_request_context(metadata={})) + assert guidance is not None and "/cancel_goal" in guidance.content + assert f"Goal ({status}):\nFinish the task" in guidance.content + finally: + await sm.state.aclose() diff --git a/tests/command/test_cancel_goal.py b/tests/command/test_cancel_goal.py new file mode 100644 index 000000000..a0e4d123c --- /dev/null +++ b/tests/command/test_cancel_goal.py @@ -0,0 +1,152 @@ +import asyncio +import sqlite3 +from unittest.mock import AsyncMock, MagicMock + +import pytest + +from nanobot.agent.loop import AgentLoop +from nanobot.bus.events import InboundMessage +from nanobot.bus.outbound_events import GoalStateSyncEvent +from nanobot.bus.queue import MessageBus +from nanobot.goal.assembly import install_goal +from nanobot.providers.base import GenerationSettings, LLMResponse +from nanobot.session.goal_state import GOAL_STATE_KEY +from nanobot.session.manager import SessionManager +from nanobot.session.webui_turns import WebuiTurnCoordinator +from nanobot.webui.session_projection import WebUISessionProjection + + +@pytest.fixture +async def loop(tmp_path): + provider = MagicMock(aclose=AsyncMock()) + provider.get_default_model.return_value = "test-model" + provider.generation = GenerationSettings() + provider.estimate_prompt_tokens.return_value = (100, "test") + provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(content="Answer.")) + agent = AgentLoop(bus=MessageBus(), provider=provider, workspace=tmp_path, + model="test-model", builtin_assembly=install_goal) + WebuiTurnCoordinator(bus=agent.bus, sessions=agent.sessions, + schedule_background=lambda coro: coro.close()).subscribe() + try: + yield agent + finally: + await agent.aclose() + + +def cancel_message(channel="websocket"): + return InboundMessage(channel=channel, sender_id="user", chat_id="cancel", + content="/cancel_goal") + + +@pytest.mark.parametrize("status", ["active", "blocked"]) +async def test_user_command_cancels_goal_without_a_model_and_survives_reconnect(loop, tmp_path, status): + msg = cancel_message() + session = await loop.sessions.state.get(msg.session_key) + await loop.sessions.state.update_metadata(session.key, { + GOAL_STATE_KEY: {"status": status, "objective": "Finish the task"}, + }) + await loop._dispatch_inbound(msg) + goal = (await loop.sessions.state.read_header(session.key)).metadata[GOAL_STATE_KEY] + assert goal["status"] == "cancelled" + assert SessionManager(tmp_path).get_or_create(session.key).metadata[GOAL_STATE_KEY] == goal + outbound = [] + while not loop.bus.outbound.empty(): + outbound.append(loop.bus.outbound.get_nowait()) + assert outbound[-1].content == "Goal cancelled." + sync = [item.event for item in outbound if isinstance(item.event, GoalStateSyncEvent)] + assert [event.goal_state for event in sync] == [{"active": False}] + assert await WebUISessionProjection(loop.sessions).persisted_goal_state(session.key) == {"active": False} + await loop._dispatch_inbound(msg) + assert loop.bus.outbound.get_nowait().content == "No goal to cancel." + assert (await loop.sessions.state.read_header(session.key)).metadata[GOAL_STATE_KEY] == goal + loop.provider.chat_stream_with_retry.assert_not_awaited() + + +@pytest.mark.parametrize("status", ["active", "blocked"]) +async def test_cancel_stops_active_goal_work_but_not_unrelated_work_for_blocked_goal(loop, status): + msg = cancel_message("telegram") + session = await loop.sessions.state.get(msg.session_key) + await loop.sessions.state.update_metadata(session.key, { + GOAL_STATE_KEY: {"status": status, "objective": "Finish the task"}, + }) + entered, release, interrupted = asyncio.Event(), asyncio.Event(), asyncio.Event() + + async def respond(**_kwargs): + entered.set() + try: + await release.wait() + except asyncio.CancelledError: + interrupted.set() + raise + return LLMResponse(content="Answer.") + + loop.provider.chat_stream_with_retry.side_effect = respond + await loop._dispatch_inbound(InboundMessage( + channel=msg.channel, sender_id="user", chat_id=msg.chat_id, content="Continue chatting", + )) + await asyncio.wait_for(entered.wait(), 3) + worker = tuple(loop._active_tasks[session.key]) + await asyncio.wait_for(loop._dispatch_inbound(msg), 3) + assert interrupted.is_set() == (status == "active") + assert (await loop.sessions.state.read_header(session.key)).metadata[GOAL_STATE_KEY]["status"] == "cancelled" + release.set() + await asyncio.gather(*worker, return_exceptions=True) + assert loop.provider.chat_stream_with_retry.await_count == 1 + assert (await loop.sessions.state.read_header(session.key)).metadata[GOAL_STATE_KEY]["status"] == "cancelled" + + +@pytest.mark.parametrize("source", ["automation", "subagent", "stale"]) +async def test_cancellation_requires_a_current_user_request(loop, source): + msg = cancel_message() + session = await loop.sessions.state.get(msg.session_key) + if source == "automation": + msg.metadata = {"_cron_trigger": {"job_id": "job"}} + elif source == "subagent": + msg.sender_id = "subagent" + else: + msg.session_generation = session.generation + await loop.sessions.state.reset(session.key) + session = await loop.sessions.state.get_header(session.key) + await loop.sessions.state.update_metadata(session.key, { + GOAL_STATE_KEY: {"status": "blocked", "objective": "Keep this goal"}, + }) + await loop._dispatch_inbound(msg) + assert (await loop.sessions.state.read_header(session.key)).metadata[GOAL_STATE_KEY]["status"] == "blocked" + reply = loop.bus.outbound.get_nowait() + assert "only be cancelled by a user" in reply.content or "changed" in reply.content + loop.provider.chat_stream_with_retry.assert_not_awaited() + + +async def test_cancel_save_failure_keeps_goal_visible_and_reports_failure(loop, monkeypatch): + msg = cancel_message() + await loop.sessions.state.get(msg.session_key) + await loop.sessions.state.update_metadata(msg.session_key, { + GOAL_STATE_KEY: {"status": "blocked", "objective": "Keep this goal"}, + }) + replace_metadata = loop.sessions._store.replace_metadata + + def fail_cancellation(key, metadata, **kwargs): + if metadata.get(GOAL_STATE_KEY, {}).get("status") == "cancelled": + raise sqlite3.OperationalError("disk full") + return replace_metadata(key, metadata, **kwargs) + + monkeypatch.setattr(loop.sessions._store, "replace_metadata", fail_cancellation) + await loop._dispatch_inbound(msg) + reply = loop.bus.outbound.get_nowait() + assert "Could not save" in reply.content + assert loop.bus.outbound.empty() + goal = await WebUISessionProjection(loop.sessions).persisted_goal_state(msg.session_key) + assert goal["status"] == "blocked" + + +async def test_direct_command_preserves_cancelled_goal_when_saving_command_history(loop): + key = "cli:direct" + await loop.sessions.state.get(key) + await loop.sessions.state.update_metadata(key, { + GOAL_STATE_KEY: {"status": "active", "objective": "Cancel this task"}, + }) + result = await loop.process_direct("/cancel_goal") + assert result.content == "Goal cancelled." + saved = await loop.sessions.state.read(key) + assert saved.metadata[GOAL_STATE_KEY]["status"] == "cancelled" + loop.provider.chat_stream_with_retry.assert_not_awaited() diff --git a/tests/command/test_model_command.py b/tests/command/test_model_command.py index d931e83c2..25b43c3d6 100644 --- a/tests/command/test_model_command.py +++ b/tests/command/test_model_command.py @@ -391,5 +391,9 @@ def test_goal_command_in_help_and_palette() -> None: } commands = [item["command"] for item in palette] goal_index = commands.index("/goal") - assert commands[goal_index - 1:goal_index + 2] == ["/model", "/goal", "/trigger"] + assert commands[goal_index - 1:goal_index + 3] == ["/model", "/goal", "/cancel_goal", "/trigger"] + cancel = next(item for item in palette if item["command"] == "/cancel_goal") + assert cancel["lifecycle"] == "side_channel" + assert cancel["accepts_args"] is False assert "/goal " in build_help_text() + assert "/cancel_goal" in build_help_text() diff --git a/webui/browser/fixture.tsx b/webui/browser/fixture.tsx index eea746a55..b77465443 100644 --- a/webui/browser/fixture.tsx +++ b/webui/browser/fixture.tsx @@ -52,7 +52,7 @@ import { AttachmentLayoutFixture } from "./attachment-layout-fixture"; import { LoadedSessionSearchFixture } from "./loaded-session-search-fixture"; import { AppearanceFixture } from "./appearance-fixture"; import { ContinuityFixture } from "./continuity-fixture"; -import { SessionTransitionFixture } from "./session-transition-fixture"; +import { installSessionTransitionPreviewApi, SessionTransitionFixture } from "./session-transition-fixture"; import { installSubagentDockApi, SubagentDockFixture } from "./subagent-dock-fixture"; const history: UIMessage[] = [ @@ -236,13 +236,18 @@ if (parameters.get("case") === "skeleton-additions") installSkeletonPreviewApi() if (parameters.get("case") === "tools-catalog") installToolsCatalogPreviewApi(); if (parameters.get("case") === "idle-compaction") installIdleCompactionApi(); if (parameters.get("case") === "subagent-dock") installSubagentDockApi(); +if (parameters.get("case") === "session-transition" && parameters.has("preview")) installSessionTransitionPreviewApi(); await initializeI18n(); if (parameters.get("case") === "activity-wheel") await setAppLanguage("zh-CN"); -if ((parameters.get("case") === "appearance" || historyPreview) && parameters.has("lang")) { +if ((["appearance", "session-transition"].includes(parameters.get("case") ?? "") || historyPreview) && parameters.has("lang")) { await setAppLanguage(normalizeLocale(parameters.get("lang"))); } +const widePreview = new URL(location.href); +widePreview.searchParams.delete("narrow"); createRoot(document.getElementById("root")!).render( - {parameters.get("case") === "session-transition" + {parameters.get("case") === "session-transition" && parameters.has("narrow") + ?