fix(goal): make cancellation a user-only control (#6667)

This commit is contained in:
chengyongru authored and GitHub committed 2026-11-14 23:48:13 +08:00
1 parent c927808aff
commit 12a86eaa86
33 files changed
+641 -63

No files matched your search

+1
View File
@@ -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"),
)
@@ -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())
+2 -1
View File
@@ -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]*)?$"
)
@@ -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
+77 -4
View File
@@ -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)
+15 -23
View File
@@ -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 <task>`."
@@ -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})."
+5 -4
View File
@@ -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}")
+8 -1
View File
@@ -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 <task>` 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]