fix(goal): make cancellation a user-only control (#6667)
This commit is contained in:
1 parent
c927808aff
commit
12a86eaa86
33 files changed
+641
-63
No files matched your search
@@ -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 <task>` | 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 <name>` 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.
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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())
|
||||
|
||||
@@ -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
@@ -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
@@ -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})."
|
||||
@@ -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}")
|
||||
|
||||
@@ -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]
|
||||
@@ -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())
|
||||
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
@@ -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 <goal>" in build_help_text()
|
||||
assert "/cancel_goal" in build_help_text()
|
||||
@@ -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(<TooltipProvider>
|
||||
{parameters.get("case") === "session-transition"
|
||||
{parameters.get("case") === "session-transition" && parameters.has("narrow")
|
||||
? <iframe title="Narrow goal preview" src={widePreview.href} style={{ display: "block", margin: "0 auto", height: "100dvh", width: "100%", maxWidth: 390, border: 0 }} />
|
||||
: parameters.get("case") === "session-transition"
|
||||
? <SessionTransitionFixture />
|
||||
: parameters.get("case") === "continuity"
|
||||
? <ContinuityFixture />
|
||||
|
||||
@@ -9,22 +9,65 @@ import { ThreadMessageCache } from "@/lib/thread-message-cache";
|
||||
import { ClientProvider } from "@/providers/ClientProvider";
|
||||
import { createStreamClient } from "@/tests/stream-client";
|
||||
|
||||
const { client, receive } = createStreamClient();
|
||||
const goalSummary = new URLSearchParams(location.search).has("long-goal")
|
||||
? "完成会话切换和目标状态界面的优化,统一明暗主题下的布局、文字、图标与交互,验证桌面和窄屏体验后提交代码并更新发布说明"
|
||||
: "Keep the composer stable";
|
||||
for (const topic of ["goal", "together", "blocked"]) {
|
||||
receive({ event: "goal_state", chat_id: topic, goal_state: {
|
||||
active: topic !== "blocked", status: topic === "blocked" ? "blocked" : "active",
|
||||
ui_summary: goalSummary,
|
||||
objective: "Verify session navigation with real components.\n\n" + "- Preserve drafts, reading position and usable header controls.\n".repeat(6),
|
||||
...(topic === "blocked" ? { recap: "Waiting for a workspace permission decision." } : {}),
|
||||
} });
|
||||
export function installSessionTransitionPreviewApi() {
|
||||
const original = window.fetch.bind(window);
|
||||
window.fetch = async (input, init) => {
|
||||
const url = new URL(input instanceof Request ? input.url : String(input), location.href);
|
||||
if (url.origin !== location.origin || !url.pathname.startsWith("/api/")) return original(input, init);
|
||||
if (url.pathname === "/api/commands") return Response.json({ commands: [
|
||||
{ command: "/cancel_goal", title: "Cancel goal", description: "Cancel the goal", icon: "square", lifecycle: "side_channel", accepts_args: false },
|
||||
] });
|
||||
if (url.pathname.endsWith("/subagents")) return Response.json({ tasks: [] });
|
||||
if (url.pathname.endsWith("/webui-thread")) {
|
||||
const topic = decodeURIComponent(url.pathname.split("/")[3]).split(":")[1];
|
||||
return Response.json({ schemaVersion: 3, projection: "events", events: [
|
||||
{ event: "user_message", chat_id: topic, projection_id: `${topic}-prompt`, turn_id: "fixture-turn", starts_turn: true, text: `Question for ${topic}` },
|
||||
{ event: "message", chat_id: topic, projection_id: `${topic}-answer`, turn_id: "fixture-turn", text: `Answer for ${topic}\n\n` + "A long conversation stays at its reading position.\n\n".repeat(25) },
|
||||
] });
|
||||
}
|
||||
return Response.json({}, { status: 404 });
|
||||
};
|
||||
}
|
||||
|
||||
export function SessionTransitionFixture() {
|
||||
const [pendingCancel, setPendingCancel] = useState<{ chat_id: string; turn_id: string } | null>(null);
|
||||
const [{ client, receive, socket }] = useState(() => {
|
||||
const preview = createStreamClient((data) => {
|
||||
const frame = JSON.parse(data);
|
||||
if (frame.content === "/cancel_goal") setPendingCancel({ chat_id: frame.chat_id, turn_id: frame.turn_id });
|
||||
});
|
||||
for (const topic of ["goal", "together", "blocked"]) {
|
||||
preview.receive({ event: "goal_state", chat_id: topic, goal_state: {
|
||||
active: topic !== "blocked", status: topic === "blocked" ? "blocked" : "active",
|
||||
ui_summary: goalSummary,
|
||||
objective: "Verify session navigation with real components.\n\n" + "- Preserve drafts, reading position and usable header controls.\n".repeat(6),
|
||||
...(topic === "blocked" ? { recap: "Waiting for a workspace permission decision." } : {}),
|
||||
} });
|
||||
}
|
||||
if (new URLSearchParams(location.search).has("preview")) {
|
||||
const send = preview.client.sendSystemCommand.bind(preview.client);
|
||||
preview.client.sendSystemCommand = (chatId, command) => send(chatId, command, 600_000);
|
||||
}
|
||||
return preview;
|
||||
});
|
||||
const [online, setOnline] = useState(true);
|
||||
const cancelPreview = new URLSearchParams(location.search).has("cancel-goal");
|
||||
const finishCancel = (success: boolean) => {
|
||||
if (!pendingCancel) return;
|
||||
if (success) {
|
||||
if (client.getGoalState(pendingCancel.chat_id)?.active) {
|
||||
receive({ event: "turn_end", chat_id: pendingCancel.chat_id, turn_id: "live-turn" });
|
||||
}
|
||||
receive({ event: "goal_state", chat_id: pendingCancel.chat_id, goal_state: { active: false } });
|
||||
}
|
||||
receive({ event: "message", ...pendingCancel, text: success ? "Goal cancelled." : "Could not save goal cancellation." });
|
||||
setPendingCancel(null);
|
||||
};
|
||||
const workbench = new URLSearchParams(location.search).has("workbench");
|
||||
const [topic, setTopic] = useState(workbench ? "goal" : "plain");
|
||||
const [topic, setTopic] = useState(new URLSearchParams(location.search).get("topic") ?? (workbench ? "goal" : "plain"));
|
||||
const [cache] = useState(() => new ThreadMessageCache(() => false));
|
||||
const [drafts] = useState(() => new ComposerDraftStore());
|
||||
const dark = new URLSearchParams(location.search).has("dark");
|
||||
@@ -41,6 +84,15 @@ export function SessionTransitionFixture() {
|
||||
receive({ event: "goal_status", chat_id: topic, turn_id: "live-turn", status: "running", started_at: Date.now() / 1000 });
|
||||
receive({ event: "delta", chat_id: topic, turn_id: "live-turn", stream_id: "live", text: "Live reply continues" });
|
||||
}}>Stream reply</button>
|
||||
{cancelPreview ? <>
|
||||
<button disabled={!pendingCancel} onClick={() => finishCancel(true)}>Confirm cancellation</button>
|
||||
<button disabled={!pendingCancel} onClick={() => finishCancel(false)}>Fail cancellation</button>
|
||||
<button onClick={() => {
|
||||
if (online) client.close();
|
||||
else { client.connect(); socket.onopen?.(); }
|
||||
setOnline(!online);
|
||||
}}>{online ? "Disconnect" : "Reconnect"}</button>
|
||||
</> : null}
|
||||
</nav>
|
||||
{workbench ? <PaneWorkbench
|
||||
panes={["goal", "blocked"].map(key => ({ key, title: key }))} activePaneKey={topic} layout="columns"
|
||||
|
||||
@@ -67,6 +67,32 @@ test("blocked goal remains visible until cleared and survives session switching"
|
||||
await expect(page.locator(".goal-island")).toHaveCount(0);
|
||||
});
|
||||
|
||||
for (const { width, topic } of [{ width: 1440, topic: "goal" }, { width: 390, topic: "blocked" }]) {
|
||||
test(`goal cancellation is reachable at ${width}px`, async ({ page }) => {
|
||||
await page.setViewportSize({ width, height: 844 });
|
||||
await installPreview(page);
|
||||
await page.goto("/browser/fixture.html?case=session-transition&cancel-goal");
|
||||
await select(page, topic);
|
||||
await page.getByRole("textbox").fill("Keep this draft");
|
||||
await page.getByRole("button", { name: "Show full goal" }).click();
|
||||
const dialog = page.getByRole("dialog", { name: "Goal", exact: true });
|
||||
await dialog.evaluate(async el => { await Promise.all(el.getAnimations({ subtree: true }).map(animation => animation.finished)); });
|
||||
const cancel = dialog.getByRole("button", { name: "Cancel goal", exact: true });
|
||||
const panelBounds = await dialog.boundingBox();
|
||||
const buttonBounds = await cancel.boundingBox();
|
||||
expect(buttonBounds!.y).toBeGreaterThanOrEqual(panelBounds!.y);
|
||||
expect(buttonBounds!.y + buttonBounds!.height).toBeLessThanOrEqual(panelBounds!.y + panelBounds!.height);
|
||||
await cancel.focus();
|
||||
await page.keyboard.press("Enter");
|
||||
const confirm = page.getByRole("button", { name: "Confirm cancellation", exact: true });
|
||||
await expect(confirm).toBeEnabled();
|
||||
await confirm.click();
|
||||
await expect(page.locator(".goal-island")).toHaveCount(0);
|
||||
await expect(page.getByRole("textbox")).toHaveValue("Keep this draft");
|
||||
expect(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth)).toBe(false);
|
||||
});
|
||||
}
|
||||
|
||||
for (const viewport of [{ width: 390, height: 844 }, { width: 844, height: 390 }]) {
|
||||
test(`long goal summaries leave the objective readable at ${viewport.width}x${viewport.height}`, async ({ page }) => {
|
||||
await page.setViewportSize(viewport);
|
||||
|
||||
@@ -3,15 +3,22 @@ import { useLayoutEffect, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { MarkdownText, preloadMarkdownText } from "@/components/MarkdownText";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
|
||||
import { useOverlayEscapeFocus } from "@/hooks/useOverlayEscapeFocus";
|
||||
import type { GoalStateWsPayload } from "@/lib/types";
|
||||
|
||||
import "./goal-island.css";
|
||||
|
||||
export function GoalIsland({ goal }: { goal: GoalStateWsPayload }) {
|
||||
export function GoalIsland({ goal, cancelDisabled, onCancel }: {
|
||||
goal: GoalStateWsPayload;
|
||||
cancelDisabled: boolean;
|
||||
onCancel: () => Promise<void>;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [cancelling, setCancelling] = useState(false);
|
||||
const [cancelFailed, setCancelFailed] = useState(false);
|
||||
const [scrollBody, setScrollBody] = useState<HTMLDivElement | null>(null);
|
||||
const panelRef = useRef<HTMLDivElement>(null);
|
||||
const escapeFocus = useOverlayEscapeFocus();
|
||||
@@ -36,10 +43,30 @@ export function GoalIsland({ goal }: { goal: GoalStateWsPayload }) {
|
||||
const status = goal.status === "blocked" ? "blocked" : "active";
|
||||
const recap = goal.recap?.trim() ?? "";
|
||||
const collapsedLabel = status === "blocked" ? recap : label;
|
||||
const cancelButton = <Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="ml-auto h-7 shrink-0 px-2 text-caption text-muted-foreground"
|
||||
disabled={cancelDisabled || cancelling}
|
||||
aria-busy={cancelling}
|
||||
title={cancelDisabled ? t("thread.composer.cancelGoalOffline") : undefined}
|
||||
onClick={async () => {
|
||||
setCancelling(true);
|
||||
setCancelFailed(false);
|
||||
try {
|
||||
await onCancel();
|
||||
} catch {
|
||||
setCancelFailed(true);
|
||||
} finally {
|
||||
setCancelling(false);
|
||||
}
|
||||
}}
|
||||
>{t("thread.composer.cancelGoal")}</Button>;
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (!scrollBody) return;
|
||||
if (status === "blocked") scrollBody.scrollTop = 0;
|
||||
if (status === "blocked" || cancelFailed) scrollBody.scrollTop = 0;
|
||||
const measure = () => {
|
||||
scrollBody.toggleAttribute("data-overflow-top", scrollBody.scrollTop > 1);
|
||||
scrollBody.toggleAttribute("data-overflow-bottom", scrollBody.scrollHeight - scrollBody.clientHeight - scrollBody.scrollTop > 1);
|
||||
@@ -53,7 +80,7 @@ export function GoalIsland({ goal }: { goal: GoalStateWsPayload }) {
|
||||
observer.disconnect();
|
||||
scrollBody.removeEventListener("scroll", measure);
|
||||
};
|
||||
}, [scrollBody, status]);
|
||||
}, [scrollBody, status, cancelFailed]);
|
||||
|
||||
return (
|
||||
<div className="goal-island-position">
|
||||
@@ -87,13 +114,18 @@ export function GoalIsland({ goal }: { goal: GoalStateWsPayload }) {
|
||||
>
|
||||
<div className="goal-island-surface" aria-hidden />
|
||||
<div className="goal-island-panel-content">
|
||||
{status !== "blocked" && summary ? <div className="goal-island-summary markdown-content"><h2>{summary}</h2></div> : null}
|
||||
{status !== "blocked" ? <div className="goal-island-summary flex items-start gap-3">
|
||||
{summary ? <div className="markdown-content min-w-0 flex-1"><h2>{summary}</h2></div> : null}
|
||||
{cancelButton}
|
||||
</div> : null}
|
||||
<div ref={setScrollBody} className="goal-island-body">
|
||||
<div className="goal-island-document">
|
||||
{cancelFailed ? <p role="alert" className="mb-2 text-caption text-destructive">{t("thread.composer.cancelGoalFailed")}</p> : null}
|
||||
{status === "blocked" ? <div className="goal-island-blocked">
|
||||
<CircleAlert className="goal-island-status-icon" strokeWidth={2.5} aria-hidden="true" />
|
||||
<span className="sr-only">{t("thread.composer.goalBlocked")}</span>
|
||||
{recap ? <MarkdownText className="goal-island-reason">{recap}</MarkdownText> : null}
|
||||
{recap ? <MarkdownText className="goal-island-reason flex-1">{recap}</MarkdownText> : null}
|
||||
{cancelButton}
|
||||
</div> : null}
|
||||
{objective ? <MarkdownText className={status === "blocked" ? "mt-4" : undefined}>{objective}</MarkdownText> : null}
|
||||
{status !== "blocked" && recap ? <MarkdownText className="mt-4 text-muted-foreground">{recap}</MarkdownText> : null}
|
||||
|
||||
@@ -426,6 +426,18 @@ export function ThreadShell({
|
||||
[historyKey, sessions, titleOverrides],
|
||||
);
|
||||
const { client, getToken, ingressLimits, modelName, token, webuiCapabilities } = useClient();
|
||||
const [online, setOnline] = useState(client.status === "open");
|
||||
useEffect(() => client.onStatus((status) => setOnline(status === "open")), [client]);
|
||||
const cancelGoal = useCallback(async () => {
|
||||
if (!chatId || client.status !== "open") throw new Error(t("thread.composer.cancelGoalOffline"));
|
||||
await client.sendSystemCommand(chatId, "/cancel_goal").catch(() => {
|
||||
throw new Error(t("thread.composer.cancelGoalFailed"));
|
||||
});
|
||||
const remainingGoal = client.getGoalState(chatId);
|
||||
if (remainingGoal?.active || remainingGoal?.status === "blocked") {
|
||||
throw new Error(t("thread.composer.cancelGoalFailed"));
|
||||
}
|
||||
}, [chatId, client, t]);
|
||||
const favoriteWorkspaceProject = useCallback(
|
||||
async (path: string, pinned: boolean) => {
|
||||
const response = await client.requestMutation<{ favorite_projects: ProjectDirectory[] }>("workspace.favorite", { path, pinned });
|
||||
@@ -1060,6 +1072,9 @@ export function ThreadShell({
|
||||
|
||||
const handleThreadSend = useCallback(
|
||||
(content: string, images?: SendAttachment[], options?: SendOptions) => {
|
||||
if (content.trim() === "/cancel_goal" && options?.sideChannel) {
|
||||
return cancelGoal().then(() => true);
|
||||
}
|
||||
setRestoredFirstDraft((current) => current?.chatId === chatId ? { ...current, error: "" } : current);
|
||||
const submitted = send(content, images, withWorkspaceScope(options));
|
||||
if (
|
||||
@@ -1073,7 +1088,7 @@ export function ThreadShell({
|
||||
}
|
||||
return submitted?.delivery ? submitted.delivery.then(() => true) : submitted !== null;
|
||||
},
|
||||
[chatId, send, withWorkspaceScope],
|
||||
[cancelGoal, chatId, send, withWorkspaceScope],
|
||||
);
|
||||
|
||||
const loadTemporaryFilePreview = useCallback((path: string) =>
|
||||
@@ -1429,7 +1444,7 @@ export function ThreadShell({
|
||||
className={previewOpen ? "h-10" : undefined}
|
||||
title={title}
|
||||
goal={currentGoalState && (currentGoalState.active || currentGoalState.status === "blocked")
|
||||
? <GoalIsland key={historyKey} goal={currentGoalState} /> : undefined}
|
||||
? <GoalIsland key={historyKey} goal={currentGoalState} cancelDisabled={!online} onCancel={cancelGoal} /> : undefined}
|
||||
onToggleSidebar={onToggleSidebar}
|
||||
theme={theme}
|
||||
onToggleTheme={onToggleTheme}
|
||||
|
||||
@@ -93,11 +93,12 @@ function ComposerPreview() {
|
||||
function GoalPreview() {
|
||||
const { t } = useGalleryTranslation();
|
||||
const [status, setStatus] = useState<"active" | "blocked">("active");
|
||||
const [cancelled, setCancelled] = useState(false);
|
||||
return <div>
|
||||
<StatePicker label={t("previews.goal.state")} value={status} options={["active", "blocked"]} onChange={setStatus} />
|
||||
<StatePicker label={t("previews.goal.state")} value={status} options={["active", "blocked"]} onChange={(next) => { setStatus(next); setCancelled(false); }} />
|
||||
<div className="thread-header-container relative h-56 overflow-hidden rounded-control border bg-background">
|
||||
<GoalIsland goal={{ active: status === "active", status, ui_summary: t("previews.goal.summary"), objective: t("previews.goal.objective"),
|
||||
...(status === "blocked" ? { recap: t("previews.goal.recap") } : {}) }} />
|
||||
{!cancelled && <GoalIsland goal={{ active: status === "active", status, ui_summary: t("previews.goal.summary"), objective: t("previews.goal.objective"),
|
||||
...(status === "blocked" ? { recap: t("previews.goal.recap") } : {}) }} cancelDisabled={false} onCancel={async () => setCancelled(true)} />}
|
||||
</div>
|
||||
</div>;
|
||||
}
|
||||
|
||||
@@ -2120,6 +2120,9 @@
|
||||
"goalStateExpandAria": "Show full goal",
|
||||
"goalBlocked": "Blocked",
|
||||
"goalStateSheetTitle": "Goal",
|
||||
"cancelGoal": "Cancel goal",
|
||||
"cancelGoalFailed": "Could not cancel goal. Try again.",
|
||||
"cancelGoalOffline": "Reconnect to cancel the goal.",
|
||||
"send": "Send message",
|
||||
"stop": "Stop response",
|
||||
"quotedContext": "Quoted context",
|
||||
@@ -2262,6 +2265,10 @@
|
||||
"title": "Long-running goal",
|
||||
"description": "Have the assistant keep working toward this goal."
|
||||
},
|
||||
"cancel_goal": {
|
||||
"title": "Cancel goal",
|
||||
"description": "Cancel the active or blocked goal in this chat."
|
||||
},
|
||||
"trigger": {
|
||||
"title": "CLI trigger",
|
||||
"description": "Create a CLI trigger for this chat."
|
||||
|
||||
@@ -1938,6 +1938,9 @@
|
||||
"goalStateExpandAria": "Ver objetivo completo",
|
||||
"goalBlocked": "Bloqueado",
|
||||
"goalStateSheetTitle": "Objetivo",
|
||||
"cancelGoal": "Cancelar objetivo",
|
||||
"cancelGoalFailed": "No se pudo cancelar. Inténtalo de nuevo.",
|
||||
"cancelGoalOffline": "Vuelve a conectarte para cancelar el objetivo.",
|
||||
"send": "Enviar mensaje",
|
||||
"stop": "Detener respuesta",
|
||||
"quotedContext": "Contexto citado",
|
||||
@@ -2071,6 +2074,10 @@
|
||||
"title": "Objetivo a largo plazo",
|
||||
"description": "Haz que el asistente siga trabajando en este objetivo."
|
||||
},
|
||||
"cancel_goal": {
|
||||
"title": "Cancelar objetivo",
|
||||
"description": "Cancela el objetivo activo o bloqueado de este chat."
|
||||
},
|
||||
"trigger": {
|
||||
"title": "Activador CLI",
|
||||
"description": "Crea un activador CLI para este chat."
|
||||
|
||||
@@ -1938,6 +1938,9 @@
|
||||
"goalStateExpandAria": "Afficher l’objectif complet",
|
||||
"goalBlocked": "Bloqué",
|
||||
"goalStateSheetTitle": "Objectif",
|
||||
"cancelGoal": "Annuler l’objectif",
|
||||
"cancelGoalFailed": "Échec de l’annulation. Réessayez.",
|
||||
"cancelGoalOffline": "Reconnectez-vous pour annuler l’objectif.",
|
||||
"send": "Envoyer le message",
|
||||
"stop": "Arrêter la réponse",
|
||||
"quotedContext": "Contexte cité",
|
||||
@@ -2071,6 +2074,10 @@
|
||||
"title": "Objectif long terme",
|
||||
"description": "Demandez à l’assistant de poursuivre cet objectif."
|
||||
},
|
||||
"cancel_goal": {
|
||||
"title": "Annuler l’objectif",
|
||||
"description": "Annuler l’objectif actif ou bloqué de cette conversation."
|
||||
},
|
||||
"trigger": {
|
||||
"title": "Déclencheur CLI",
|
||||
"description": "Créez un déclencheur CLI pour cette discussion."
|
||||
|
||||
@@ -1938,6 +1938,9 @@
|
||||
"goalStateExpandAria": "Lihat tujuan lengkap",
|
||||
"goalBlocked": "Terhambat",
|
||||
"goalStateSheetTitle": "Tujuan",
|
||||
"cancelGoal": "Batalkan tujuan",
|
||||
"cancelGoalFailed": "Tujuan gagal dibatalkan. Coba lagi.",
|
||||
"cancelGoalOffline": "Hubungkan kembali untuk membatalkan tujuan.",
|
||||
"send": "Kirim pesan",
|
||||
"stop": "Hentikan respons",
|
||||
"quotedContext": "Konteks kutipan",
|
||||
@@ -2071,6 +2074,10 @@
|
||||
"title": "Tujuan jangka panjang",
|
||||
"description": "Minta asisten terus mengerjakan tujuan ini."
|
||||
},
|
||||
"cancel_goal": {
|
||||
"title": "Batalkan tujuan",
|
||||
"description": "Batalkan tujuan aktif atau terblokir di chat ini."
|
||||
},
|
||||
"trigger": {
|
||||
"title": "Pemicu CLI",
|
||||
"description": "Buat pemicu CLI untuk chat ini."
|
||||
|
||||
@@ -1938,6 +1938,9 @@
|
||||
"goalStateExpandAria": "目標の全文を表示",
|
||||
"goalBlocked": "進行不可",
|
||||
"goalStateSheetTitle": "目標",
|
||||
"cancelGoal": "目標を取り消す",
|
||||
"cancelGoalFailed": "取り消せませんでした。再試行してください。",
|
||||
"cancelGoalOffline": "再接続してから目標を取り消してください。",
|
||||
"send": "メッセージを送信",
|
||||
"stop": "応答を停止",
|
||||
"quotedContext": "引用したコンテキスト",
|
||||
@@ -2071,6 +2074,10 @@
|
||||
"title": "長期目標",
|
||||
"description": "アシスタントがこの目標に向けて作業を続けます。"
|
||||
},
|
||||
"cancel_goal": {
|
||||
"title": "目標を取り消す",
|
||||
"description": "このチャットの実行中またはブロック中の目標を取り消します。"
|
||||
},
|
||||
"trigger": {
|
||||
"title": "CLI トリガー",
|
||||
"description": "このチャット用の CLI トリガーを作成します。"
|
||||
|
||||
@@ -1938,6 +1938,9 @@
|
||||
"goalStateExpandAria": "전체 목표 보기",
|
||||
"goalBlocked": "진행 막힘",
|
||||
"goalStateSheetTitle": "목표",
|
||||
"cancelGoal": "목표 취소",
|
||||
"cancelGoalFailed": "목표를 취소하지 못했습니다. 다시 시도하세요.",
|
||||
"cancelGoalOffline": "다시 연결한 후 목표를 취소하세요.",
|
||||
"send": "메시지 보내기",
|
||||
"stop": "응답 중지",
|
||||
"quotedContext": "인용한 문맥",
|
||||
@@ -2071,6 +2074,10 @@
|
||||
"title": "장기 목표",
|
||||
"description": "어시스턴트가 이 목표를 향해 계속 작업하게 합니다."
|
||||
},
|
||||
"cancel_goal": {
|
||||
"title": "목표 취소",
|
||||
"description": "이 채팅에서 진행 중이거나 차단된 목표를 취소합니다."
|
||||
},
|
||||
"trigger": {
|
||||
"title": "CLI 트리거",
|
||||
"description": "이 채팅의 CLI 트리거를 만듭니다."
|
||||
|
||||
@@ -1940,6 +1940,9 @@
|
||||
"goalStateExpandAria": "Mostrar objetivo completo",
|
||||
"goalBlocked": "Bloqueado",
|
||||
"goalStateSheetTitle": "Objetivo",
|
||||
"cancelGoal": "Cancelar objetivo",
|
||||
"cancelGoalFailed": "Não foi possível cancelar. Tente novamente.",
|
||||
"cancelGoalOffline": "Reconecte-se para cancelar o objetivo.",
|
||||
"send": "Enviar mensagem",
|
||||
"stop": "Parar resposta",
|
||||
"quotedContext": "Contexto citado",
|
||||
@@ -2082,6 +2085,10 @@
|
||||
"title": "Objetivo de longa duração",
|
||||
"description": "Peça ao assistente para continuar trabalhando neste objetivo."
|
||||
},
|
||||
"cancel_goal": {
|
||||
"title": "Cancelar objetivo",
|
||||
"description": "Cancela o objetivo ativo ou bloqueado desta conversa."
|
||||
},
|
||||
"trigger": {
|
||||
"title": "Gatilho CLI",
|
||||
"description": "Crie um gatilho CLI para esta conversa."
|
||||
|
||||
@@ -1938,6 +1938,9 @@
|
||||
"goalStateExpandAria": "Xem đầy đủ mục tiêu",
|
||||
"goalBlocked": "Bị chặn",
|
||||
"goalStateSheetTitle": "Mục tiêu",
|
||||
"cancelGoal": "Hủy mục tiêu",
|
||||
"cancelGoalFailed": "Không thể hủy mục tiêu. Hãy thử lại.",
|
||||
"cancelGoalOffline": "Kết nối lại để hủy mục tiêu.",
|
||||
"send": "Gửi tin nhắn",
|
||||
"stop": "Dừng phản hồi",
|
||||
"quotedContext": "Ngữ cảnh được trích dẫn",
|
||||
@@ -2071,6 +2074,10 @@
|
||||
"title": "Mục tiêu dài hạn",
|
||||
"description": "Để trợ lý tiếp tục làm việc hướng đến mục tiêu này."
|
||||
},
|
||||
"cancel_goal": {
|
||||
"title": "Hủy mục tiêu",
|
||||
"description": "Hủy mục tiêu đang chạy hoặc bị chặn trong cuộc trò chuyện này."
|
||||
},
|
||||
"trigger": {
|
||||
"title": "Kích hoạt CLI",
|
||||
"description": "Tạo kích hoạt CLI cho trò chuyện này."
|
||||
|
||||
@@ -2120,6 +2120,9 @@
|
||||
"goalStateExpandAria": "查看完整目标",
|
||||
"goalBlocked": "已阻塞",
|
||||
"goalStateSheetTitle": "目标",
|
||||
"cancelGoal": "取消目标",
|
||||
"cancelGoalFailed": "取消失败,请重试。",
|
||||
"cancelGoalOffline": "请重新连接后取消目标。",
|
||||
"send": "发送消息",
|
||||
"stop": "停止响应",
|
||||
"quotedContext": "引用内容",
|
||||
@@ -2262,6 +2265,10 @@
|
||||
"title": "长期目标",
|
||||
"description": "让助手持续推进当前目标"
|
||||
},
|
||||
"cancel_goal": {
|
||||
"title": "取消目标",
|
||||
"description": "取消当前对话中执行或阻塞的目标"
|
||||
},
|
||||
"trigger": {
|
||||
"title": "CLI 触发器",
|
||||
"description": "创建绑定当前对话的 CLI 触发器"
|
||||
|
||||
@@ -1938,6 +1938,9 @@
|
||||
"goalStateExpandAria": "檢視完整目標",
|
||||
"goalBlocked": "已受阻",
|
||||
"goalStateSheetTitle": "目標",
|
||||
"cancelGoal": "取消目標",
|
||||
"cancelGoalFailed": "取消失敗,請重試。",
|
||||
"cancelGoalOffline": "請重新連線後取消目標。",
|
||||
"send": "送出訊息",
|
||||
"stop": "停止回覆",
|
||||
"quotedContext": "引用內容",
|
||||
@@ -2071,6 +2074,10 @@
|
||||
"title": "長期目標",
|
||||
"description": "讓助手持續推進當前目標"
|
||||
},
|
||||
"cancel_goal": {
|
||||
"title": "取消目標",
|
||||
"description": "取消目前對話中執行或受阻的目標"
|
||||
},
|
||||
"trigger": {
|
||||
"title": "CLI 觸發器",
|
||||
"description": "建立繫結當前對話的 CLI 觸發器"
|
||||
|
||||
@@ -11,7 +11,7 @@ const goal = { active: true, ui_summary: "Ship the release", objective: "Verify
|
||||
function Conversation({ blocked = false }: { blocked?: boolean }) {
|
||||
return <>
|
||||
<ThreadHeader title="Release planning" onToggleSidebar={vi.fn()} theme="light" onToggleTheme={vi.fn()}
|
||||
goal={<GoalIsland goal={{ ...goal, active: !blocked, status: blocked ? "blocked" : "active", ...(blocked ? { recap: "Waiting for approval." } : {}) }} />} />
|
||||
goal={<GoalIsland goal={{ ...goal, active: !blocked, status: blocked ? "blocked" : "active", ...(blocked ? { recap: "Waiting for approval." } : {}) }} cancelDisabled={false} onCancel={async () => {}} />} />
|
||||
<ThreadComposer onSend={vi.fn()} persistDraft={false} goalState={goal} />
|
||||
</>;
|
||||
}
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { NanobotClient } from "@/lib/nanobot-client";
|
||||
import type { InboundEvent } from "@/lib/types";
|
||||
|
||||
export function createStreamClient() {
|
||||
export function createStreamClient(onSend: (frame: string) => void = () => {}) {
|
||||
const socket = {
|
||||
readyState: 1,
|
||||
onopen: null as (() => void) | null,
|
||||
onmessage: null as ((event: MessageEvent) => void) | null,
|
||||
send() {},
|
||||
send: onSend,
|
||||
close() {},
|
||||
};
|
||||
const client = new NanobotClient({
|
||||
@@ -17,6 +17,7 @@ export function createStreamClient() {
|
||||
socket.onopen?.();
|
||||
return {
|
||||
client,
|
||||
socket,
|
||||
receive(event: InboundEvent) {
|
||||
socket.onmessage?.({ data: JSON.stringify(event) } as MessageEvent);
|
||||
},
|
||||
|
||||
@@ -5468,6 +5468,116 @@ describe("ThreadShell", () => {
|
||||
await waitFor(() => expect(scroller.scrollTop).toBe(1800));
|
||||
});
|
||||
|
||||
it.each(["active", "blocked"] as const)("cancels the %s goal through a system command and waits for goal_state", async (status) => {
|
||||
const client = makeClient();
|
||||
const chatId = `cancel-${status}`;
|
||||
let complete!: () => void;
|
||||
client.sendSystemCommand.mockImplementation(() => new Promise<void>((resolve) => { complete = resolve; }));
|
||||
render(wrap(client, <ThreadShell session={session(chatId)} title="Goal" onToggleSidebar={() => {}} />));
|
||||
await act(async () => {});
|
||||
act(() => {
|
||||
client._emitChat(chatId, { event: "goal_state", chat_id: chatId, goal_state: { active: status === "active", status, objective: "Ship the release" } });
|
||||
client._emitChat(chatId, { event: "goal_status", chat_id: chatId, turn_id: "running-turn", status: "running", started_at: 100 });
|
||||
client._emitChat(chatId, { event: "delta", chat_id: chatId, turn_id: "running-turn", stream_id: "live", text: "Still responding" });
|
||||
});
|
||||
await screen.findByText("Still responding");
|
||||
expect(screen.getByRole("button", { name: "Stop response" })).toBeVisible();
|
||||
const input = screen.getByRole("textbox", { name: "Message input" });
|
||||
fireEvent.change(input, { target: { value: "Keep my draft" } });
|
||||
fireEvent.click(await screen.findByRole("button", { name: "Show full goal" }));
|
||||
const button = screen.getByRole("button", { name: "Cancel goal" });
|
||||
fireEvent.click(button);
|
||||
expect(button).toBeDisabled();
|
||||
fireEvent.click(button);
|
||||
expect(client.sendSystemCommand).toHaveBeenCalledTimes(1);
|
||||
expect(client.sendSystemCommand).toHaveBeenCalledWith(chatId, "/cancel_goal");
|
||||
expect(screen.getByRole("dialog", { name: "Goal" })).toBeVisible();
|
||||
expect(input).toHaveValue("Keep my draft");
|
||||
expect(client.sendMessage).not.toHaveBeenCalled();
|
||||
expect(client.finishRunLocally).not.toHaveBeenCalled();
|
||||
expect(client.getRunState(chatId).active).toBe(true);
|
||||
act(() => {
|
||||
if (status === "active") client._emitChat(chatId, { event: "turn_end", chat_id: chatId, turn_id: "running-turn" });
|
||||
client._emitChat(chatId, { event: "goal_state", chat_id: chatId, goal_state: { active: false } });
|
||||
});
|
||||
await waitFor(() => expect(screen.queryByRole("button", { name: "Show full goal" })).not.toBeInTheDocument());
|
||||
await act(async () => complete());
|
||||
expect(input).toHaveValue("Keep my draft");
|
||||
expect(within(screen.getByTestId("thread-message-region")).queryByText("/cancel_goal")).not.toBeInTheDocument();
|
||||
fireEvent.change(input, { target: { value: "" } });
|
||||
if (status === "blocked") {
|
||||
act(() => client._emitChat(chatId, { event: "delta", chat_id: chatId, turn_id: "running-turn", stream_id: "live", text: " after goal cancellation" }));
|
||||
expect(await screen.findByText("Still responding after goal cancellation")).toBeVisible();
|
||||
expect(screen.getByRole("button", { name: "Stop response" })).toBeVisible();
|
||||
} else {
|
||||
expect(screen.queryByRole("button", { name: "Stop response" })).not.toBeInTheDocument();
|
||||
}
|
||||
});
|
||||
|
||||
it("disables offline goal cancellation and treats an unchanged goal after a control reply as a retryable failure", async () => {
|
||||
const client = makeClient();
|
||||
const chatId = "cancel-failure";
|
||||
render(wrap(client, <ThreadShell session={session(chatId)} title="Goal" onToggleSidebar={() => {}} />));
|
||||
await act(async () => {});
|
||||
act(() => {
|
||||
client._emitChat(chatId, { event: "goal_state", chat_id: chatId, goal_state: { active: false, status: "blocked", objective: "Ship the release" } });
|
||||
client._emitStatus("closed");
|
||||
});
|
||||
fireEvent.click(await screen.findByRole("button", { name: "Show full goal" }));
|
||||
const button = screen.getByRole("button", { name: "Cancel goal" });
|
||||
expect(button).toBeDisabled();
|
||||
fireEvent.click(button);
|
||||
expect(client.sendSystemCommand).not.toHaveBeenCalled();
|
||||
act(() => client._emitStatus("open"));
|
||||
fireEvent.click(button);
|
||||
expect(await screen.findByRole("alert")).toHaveTextContent("Could not cancel goal. Try again.");
|
||||
expect(button).toBeEnabled();
|
||||
expect(screen.getByRole("dialog", { name: "Goal" })).toBeVisible();
|
||||
client.sendSystemCommand.mockImplementationOnce(async () => {
|
||||
client._emitChat(chatId, { event: "goal_state", chat_id: chatId, goal_state: { active: false } });
|
||||
});
|
||||
fireEvent.click(button);
|
||||
await waitFor(() => expect(screen.queryByRole("button", { name: "Show full goal" })).not.toBeInTheDocument());
|
||||
expect(client.sendSystemCommand).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("sends /cancel_goal directly while streaming without a transcript entry, /stop, or offline replay", async () => {
|
||||
const client = makeClient();
|
||||
const chatId = "cancel-slash";
|
||||
vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => String(input).endsWith("/api/commands")
|
||||
? httpJson({ commands: [{ command: "/cancel_goal", title: "Cancel goal", description: "Cancel the goal", icon: "square", lifecycle: "side_channel", accepts_args: false }] })
|
||||
: new Response(null, { status: 404 })));
|
||||
render(wrap(client, <ThreadShell session={session(chatId)} title="Goal" onToggleSidebar={() => {}} />));
|
||||
await act(async () => {});
|
||||
act(() => {
|
||||
client._emitChat(chatId, { event: "goal_state", chat_id: chatId, goal_state: { active: false, status: "blocked", objective: "Ship the release" } });
|
||||
client._emitChat(chatId, { event: "goal_status", chat_id: chatId, turn_id: "unrelated", status: "running", started_at: 100 });
|
||||
client._emitChat(chatId, { event: "delta", chat_id: chatId, turn_id: "unrelated", stream_id: "live", text: "Unrelated reply" });
|
||||
client._emitStatus("closed");
|
||||
});
|
||||
const input = screen.getByRole("textbox", { name: "Message input" });
|
||||
fireEvent.change(input, { target: { value: "/cancel_goal" } });
|
||||
expect(await screen.findByRole("option", { name: /Cancel goal/ })).toBeVisible();
|
||||
fireEvent.keyDown(input, { key: "Escape" });
|
||||
fireEvent.keyDown(input, { key: "Enter" });
|
||||
expect(await screen.findByText("Reconnect to cancel the goal.")).toBeVisible();
|
||||
expect(client.sendSystemCommand).not.toHaveBeenCalled();
|
||||
expect(input).toHaveValue("/cancel_goal");
|
||||
act(() => client._emitStatus("open"));
|
||||
expect(client.sendSystemCommand).not.toHaveBeenCalled();
|
||||
client.sendSystemCommand.mockImplementationOnce(async () => {
|
||||
client._emitChat(chatId, { event: "goal_state", chat_id: chatId, goal_state: { active: false } });
|
||||
});
|
||||
fireEvent.keyDown(input, { key: "Enter" });
|
||||
await waitFor(() => expect(input).toHaveValue(""));
|
||||
expect(client.sendSystemCommand).toHaveBeenCalledTimes(1);
|
||||
expect(client.sendSystemCommand).toHaveBeenCalledWith(chatId, "/cancel_goal");
|
||||
expect(client.sendMessage).not.toHaveBeenCalled();
|
||||
expect(client.finishRunLocally).not.toHaveBeenCalled();
|
||||
expect(within(screen.getByTestId("thread-message-region")).queryByText("/cancel_goal")).not.toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: "Stop response" })).toBeVisible();
|
||||
});
|
||||
|
||||
it("opens slash commands on the blank welcome page", async () => {
|
||||
const client = makeClient();
|
||||
vi.stubGlobal(
|
||||
|
||||
Reference in new issue
Block a user