Skip to content

Your lightweight open-source personal agent.

feat(subagent): add session-owned task messaging and cancellation (#5985)

chengyongru6ff96f2a8f10
diff --git a/docs/concepts.md b/docs/concepts.md
index 00dfef726..924a41a11 100644
--- a/docs/concepts.md
+++ b/docs/concepts.md
@@ -173,6 +173,37 @@ Tools are discovered automatically from built-in modules and plugin entry points
Security-sensitive controls live in [`configuration.md#security`](./configuration.md#security). For production or shared chat apps, also configure channel access controls such as `allowFrom`, pairing, or WebSocket tokens.
+## Subagents
+
+Nanobot can delegate parts of a request to subagents while remaining responsible
+for the final answer. In the conversation that started the work, you can ask it
+to check progress, send follow-up instructions, wait for results, or cancel a
+task. Cancelling one task leaves the others running. A delivered instruction
+means the subagent received it, not that it has acted on it yet.
+
+Background tasks return their results to the conversation that started them.
+Single-turn CLI and SDK calls wait for results when background delivery is
+unavailable. Tasks that reach their iteration limit are marked incomplete;
+cancelled, failed, and incomplete tasks retain available partial results.
+
+Use `/stop` to stop the current session and its subagents. Other sessions are
+unaffected. Some operations may take time to stop, and cancellation does not
+undo file changes or other actions already taken.
+
+Subagents belong to their original conversation. They do not appear as separate
+topics or in general conversation searches. Deleting the conversation stops its
+subagents and removes their saved history; forking it does not copy them.
+
+Saved task history and results remain available after a gateway restart.
+Unfinished tasks are marked interrupted, with saved partial results when
+available. Nanobot does not automatically resume them or resend completion
+notifications; ask it to start a new task to continue the work.
+
+See [Delegated work in the WebUI](./webui.md#delegated-work) for progress and
+task details. WebUI temporary chats do not support subagents. SDK calls with
+`ephemeral=True` wait for delegated results without saving the temporary
+conversation or its subagent history.
+
## Background Jobs
When `nanobot gateway` starts, it runs workspace-scoped automations and
diff --git a/docs/webui.md b/docs/webui.md
index ba4479ae0..4f4eb5f98 100644
--- a/docs/webui.md
+++ b/docs/webui.md
@@ -238,6 +238,28 @@ by the summary remain in your chat history but are no longer sent to the model
verbatim. Use `/compact` to compact the current topic's context manually.
See [Memory](./memory.md) for compaction and Dream consolidation.
+### Delegated work
+
+When nanobot delegates work to subagents, a work group appears under the request
+that started it. Progress continues to update after the main reply finishes.
+Completed tasks stay available for inspection, and refreshing or reopening the
+WebUI restores saved progress and results without restarting the work.
+
+Work groups follow the browser's **Activity details** preference: **Auto** opens
+running work and folds it when all tasks finish; **Expanded** keeps it open by
+default. You can also expand or fold a group manually to check individual
+outcomes, including failures and partial results.
+
+Select a task to open its read-only conversation on the right, or across the
+screen on mobile. Read its messages, tool activity, file edits, and results,
+including formatted Markdown. Closing the details leaves the task running; its
+stop button cancels only that task. Give follow-up instructions to nanobot in
+the main conversation.
+
+These controls appear when the connected host supports subagent tasks. See
+[Subagents](./concepts.md#subagents) for cancellation, saved history, and gateway
+restart behavior.
+
## Temporary Chats
Use a temporary chat for a conversation that should not be added to nanobot's
diff --git a/nanobot/agent/loop.py b/nanobot/agent/loop.py
index a11ed88dd..93dfb0a58 100644
--- a/nanobot/agent/loop.py
+++ b/nanobot/agent/loop.py
@@ -11,6 +11,7 @@ import time
import weakref
from collections.abc import Coroutine, Iterable, Mapping
from contextlib import AbstractContextManager, ExitStack, nullcontext, suppress
+from copy import deepcopy
from dataclasses import dataclass, field
from datetime import datetime
from enum import Enum, auto
@@ -76,7 +77,7 @@ from nanobot.session.automation_turns import automation_history_overrides
from nanobot.session.goal_state import goal_state_runtime_lines, sustained_goal_active
from nanobot.session.history_visibility import HIDDEN_HISTORY_META
from nanobot.session.keys import UNIFIED_SESSION_KEY, remember_last_channel
-from nanobot.session.manager import SESSION_CACHE_MAX_SIZE, Session, SessionManager
+from nanobot.session.manager import SESSION_CACHE_MAX_SIZE, Session, SessionManager, SessionPolicy
from nanobot.session.model_selection import (
SESSION_MODEL_PRESET_METADATA_KEY,
model_preset_from_metadata,
@@ -399,6 +400,7 @@ class AgentLoop:
max_iterations=self.max_iterations,
max_concurrent_subagents=max_concurrent_subagents,
consolidator=self.consolidator,
+ session_manager=self.sessions,
)
self._unified_session = unified_session
self._running = False
@@ -518,6 +520,10 @@ class AgentLoop:
"""Keep subagent runtime limits aligned with mutable loop settings."""
self.subagents.max_iterations = self.max_iterations
+ def set_runtime_max_iterations(self, value: int) -> None:
+ self.max_iterations = value
+ self._sync_subagent_runtime_limits()
+
def invalidate_runtime_config(self) -> None:
"""Invalidate runtime config for lazy refresh at the next admission."""
self.runtime_resolver.invalidate()
@@ -733,9 +739,11 @@ class AgentLoop:
metadata=dict(ctx.msg.metadata or {}),
attributes=dict(ctx.attributes),
sender_id=ctx.msg.sender_id,
- turn_id=ctx.turn_id,
+ turn_id=ctx.delivery.route.turn_id or ctx.turn_id,
workspace=scope.project_path,
log_content=ctx.session.policy.log_content and not ctx.ephemeral,
+ persist_session=ctx.session.policy.persist and not ctx.ephemeral,
+ can_receive_background_results=self._running,
)
async def _resolve_runtime_context_for_turn(
@@ -1001,7 +1009,7 @@ class AgentLoop:
ephemeral = ephemeral or (session is not None and not session.policy.persist)
async def _checkpoint(payload: dict[str, Any]) -> None:
- if session is None:
+ if session is None or ephemeral:
return
public_payload = dict(payload)
private_state = public_payload.pop("provider_state", None)
@@ -1166,6 +1174,7 @@ class AgentLoop:
chat_id="direct",
session_key=session.key if session is not None else None,
runtime=runtime,
+ can_receive_background_results=self._running,
)
active_session_key = session.key if session else request_ctx.session_key
consolidation_session_key = active_session_key or "agent:transient"
@@ -1192,6 +1201,10 @@ class AgentLoop:
request_ctx.log_content and not ephemeral
and (session is None or session.policy.log_content)
),
+ persist_session=(
+ request_ctx.persist_session and not ephemeral
+ and (session is None or session.policy.persist)
+ ),
)
effective_tools = tools if tools is not None else self.tools
file_state_token = bind_file_states(self._file_state_store.for_session(active_session_key))
@@ -1355,7 +1368,7 @@ class AgentLoop:
continue
if (
msg.require_existing_session
- and self.sessions.get_cached(effective_key) is None
+ and self.sessions.get_existing(effective_key) is None
):
continue
if msg.is_user_input:
@@ -1432,6 +1445,8 @@ class AgentLoop:
def _enqueue_session_message(self, msg: InboundMessage) -> None:
"""Admit session work without waiting for its execution or result."""
session_key = self._effective_session_key(msg)
+ if not self.subagents.accepts_result(msg, session_key):
+ return
if session_key != msg.session_key:
msg = dataclasses.replace(msg, session_key_override=session_key)
@@ -1735,6 +1750,7 @@ class AgentLoop:
delivery: TurnDelivery | None = None,
on_runtime_admitted: Callable[[LLMRuntime], Awaitable[None]] | None = None,
attributes: Mapping[str, Any] | None = None,
+ session: Session | None = None,
) -> OutboundMessage | None:
"""Process a single inbound message and return the response."""
kind = TurnKind.USER if msg.is_user_input else TurnKind.SYSTEM
@@ -1745,6 +1761,8 @@ class AgentLoop:
key = session_key or msg.session_key_override or f"{destination[0]}:{destination[1]}"
else:
key = session_key or msg.session_key
+ if not self.subagents.accepts_result(msg, key):
+ return None
if delivery is None:
delivery = self.turn_delivery_factory.create(msg, key)
elif delivery.session_key != key:
@@ -1752,7 +1770,7 @@ class AgentLoop:
t0 = time.time()
ctx = TurnContext(
msg=msg,
- session=None,
+ session=session,
session_key=key,
turn_id=f"{key}:{time.time_ns()}",
runtime=runtime,
@@ -1936,7 +1954,7 @@ class AgentLoop:
if ctx.session is None:
if msg.require_existing_session:
- ctx.session = self.sessions.get_cached(ctx.session_key)
+ ctx.session = self.sessions.get_existing(ctx.session_key)
if ctx.session is None:
raise RuntimeError("required session is not active")
else:
@@ -1955,7 +1973,7 @@ class AgentLoop:
if ctx.kind is TurnKind.SYSTEM:
logger.info("Processing system message from {}", msg.sender_id)
- elif session.policy.log_content:
+ elif session.policy.log_content and not ctx.ephemeral:
preview = msg.content[:80] + "..." if len(msg.content) > 80 else msg.content
logger.info("Processing message from {}:{}: {}", msg.channel, msg.sender_id, preview)
else:
@@ -2194,7 +2212,6 @@ class AgentLoop:
async def _persist_turn(self, ctx: TurnContext) -> None:
session = ctx.require_session()
- turn_continuation.prepare_save_boundary(ctx)
if (
ctx.kind is TurnKind.USER
@@ -2213,6 +2230,8 @@ class AgentLoop:
else ctx.turn_wall_started_at
)
ctx.turn_latency_ms = max(0, int((time.time() - latency_started_at) * 1000))
+ ctx.delivery.record_latency(ctx.turn_latency_ms)
+ turn_continuation.prepare_save_boundary(ctx)
if ctx.usage is not None and not ctx.ephemeral:
session.metadata["_last_usage"] = ctx.usage.to_dict()
self._save_turn(
@@ -2229,7 +2248,6 @@ class AgentLoop:
# The next request must rebuild from the portable checkpoint;
# the opaque continuation predates that transcript rewrite.
session.provider_state = None
- ctx.delivery.record_latency(ctx.turn_latency_ms)
self._clear_pending_user_turn(session)
self._clear_runtime_checkpoint(session)
self.sessions.save(session)
@@ -2515,8 +2533,13 @@ class AgentLoop:
runtime: LLMRuntime | None = None,
on_runtime_admitted: Callable[[LLMRuntime], Awaitable[None]] | None = None,
attributes: Mapping[str, Any] | None = None,
+ _session_policy: SessionPolicy | None = None,
) -> OutboundMessage | None:
- """Process an external message directly and return the outbound payload."""
+ """Process an external message directly and return the outbound payload.
+
+ ``ephemeral`` skips Memory journaling and extra hooks. SDK temporary
+ turns also supply a non-persistent policy for a detached session.
+ """
if channel == "system":
raise ValueError("channel 'system' is reserved for internal messages")
metadata: dict[str, Any] = {}
@@ -2537,6 +2560,16 @@ class AgentLoop:
"on_stream_end": on_stream_end,
"ephemeral": ephemeral,
}
+ if _session_policy is not None:
+ # Isolate per-run state before any early save or checkpoint;
+ # the cached conversation must survive a temporary SDK turn.
+ session = deepcopy(self.sessions.get_or_create(session_key))
+ session.policy = SessionPolicy(
+ persist=session.policy.persist and _session_policy.persist,
+ log_content=session.policy.log_content and _session_policy.log_content,
+ disabled_tools=session.policy.disabled_tools | _session_policy.disabled_tools,
+ )
+ kwargs["session"] = session
if _run_extra_hooks_for_ephemeral:
kwargs["run_extra_hooks_for_ephemeral"] = True
if hooks is not None:
diff --git a/nanobot/agent/runner.py b/nanobot/agent/runner.py
index fc81d08a1..41ef375e5 100644
--- a/nanobot/agent/runner.py
+++ b/nanobot/agent/runner.py
@@ -60,6 +60,14 @@ from nanobot.utils.runtime import (
is_blank_text,
)
+
+def _raise_if_cancelling() -> None:
+ """Do not resume model work when a dependency suppresses cancellation."""
+ task = asyncio.current_task()
+ if task is not None and task.cancelling():
+ raise asyncio.CancelledError
+
+
ContinuationCallback = Callable[[], str | None]
CheckpointCallback = Callable[[dict[str, Any]], Awaitable[None]]
InjectionCallback = Callable[[], Awaitable[Iterable[Any] | None]]
@@ -863,6 +871,7 @@ class AgentRunner:
malformed_retry: bool = False,
transcript: list[dict[str, Any]] | None,
) -> tuple[LLMResponse, LLMUsage]:
+ _raise_if_cancelling()
tool_definitions = spec.tools.get_definitions()
messages, provider_context = await self.context_governor.prepare_request(
request_state,
@@ -876,6 +885,7 @@ class AgentRunner:
messages,
tools=tool_definitions,
)
+ _raise_if_cancelling()
wants_streaming = hook.wants_streaming()
provider_context = replace(
provider_context or ProviderCallContext(),
@@ -993,6 +1003,7 @@ class AgentRunner:
request_started_at = time.perf_counter()
try:
response = await coro
+ _raise_if_cancelling()
except asyncio.CancelledError:
_pause_generation()
await _close_native_reasoning()
@@ -1214,6 +1225,7 @@ class AgentRunner:
request_state: ModelRequestState,
transcript: list[dict[str, Any]] | None = None,
) -> LLMResponse:
+ _raise_if_cancelling()
messages, provider_context = await self.context_governor.prepare_request(
request_state,
messages,
@@ -1225,6 +1237,7 @@ class AgentRunner:
messages,
tools=None,
)
+ _raise_if_cancelling()
response = await spec.runtime.provider.chat_stream_with_retry(
**kwargs,
provider_context=replace(
@@ -1232,11 +1245,13 @@ class AgentRunner:
response_preset=spec.runtime.model_preset or "",
),
)
+ _raise_if_cancelling()
await self.context_governor.summarize_provider_compaction(
request_state,
response,
current_request_boundary=(len(transcript) if transcript is not None else None),
)
+ _raise_if_cancelling()
request_state.provider_compaction_applied |= response.provider_compaction_applied
return response
diff --git a/nanobot/agent/session_activity.py b/nanobot/agent/session_activity.py
new file mode 100644
index 000000000..ab2f422ad
--- /dev/null
+++ b/nanobot/agent/session_activity.py
@@ -0,0 +1,72 @@
+"""Retain runner activity on Session messages without changing model input."""
+
+from __future__ import annotations
+
+from copy import deepcopy
+from typing import Any
+
+from nanobot.agent.hook import AgentHook, AgentHookContext
+from nanobot.bus.outbound_events import ProgressEvent
+from nanobot.events import AgentEvent
+
+
+class SessionActivity(AgentHook):
+ """Associate shared progress events with the response that produced them."""
+
+ def __init__(self) -> None:
+ super().__init__()
+ self._messages: list[dict[str, Any]] = []
+ self._iteration_start = 0
+ self._current: list[ProgressEvent] | None = None
+ self._pending: list[ProgressEvent] = []
+ self._responses: dict[int, list[ProgressEvent]] = {}
+
+ async def before_iteration(self, context: AgentHookContext) -> None:
+ self._messages = context.messages
+ self._iteration_start = len(context.messages)
+ self._current = None
+ self._pending = []
+
+ def _bind_response(self) -> None:
+ if self._current is None:
+ response = next((message for message in self._messages[self._iteration_start:]
+ if message.get("role") == "assistant"), None)
+ if response is not None:
+ self._current = self._responses.setdefault(id(response), [])
+ self._current.extend(self._pending)
+ self._pending = []
+
+ def remember(self, event: AgentEvent) -> bool:
+ """Keep structured tool/file activity, including its actual error phase."""
+ if not isinstance(event, ProgressEvent) or not (event.tool_events or event.file_edit_events):
+ return False
+ self._bind_response()
+ target = self._current if self._current is not None else self._pending
+ target.append(deepcopy(event))
+ return True
+
+ def transcript(self, messages: list[dict[str, Any]] | None = None) -> list[dict[str, Any]]:
+ """Add display fields only to detached copies, never provider messages."""
+ self._bind_response()
+ rows: list[dict[str, Any]] = []
+ for message in self._messages if messages is None else messages:
+ if message.get("role") == "system":
+ continue
+ row = deepcopy(message)
+ row.update(self._fields(self._responses.get(id(message), [])))
+ rows.append(row)
+ # Provider-hosted tools may emit activity before the response exists.
+ # An empty display row is omitted by Session.get_history() on replay.
+ if self._pending:
+ rows.append({"role": "assistant", "content": "", **self._fields(self._pending)})
+ return rows
+
+ @staticmethod
+ def _fields(events: list[ProgressEvent]) -> dict[str, Any]:
+ tools = list({tool["call_id"]: tool for event in events
+ for tool in event.tool_events or []}.values())
+ edits = list({(edit["call_id"], edit["path"]): edit for event in events
+ for edit in event.file_edit_events or []}.values())
+ return {key: deepcopy(value) for key, value in (
+ ("tool_events", tools), ("file_edit_events", edits),
+ ) if value}
diff --git a/nanobot/agent/subagent.py b/nanobot/agent/subagent.py
index e41fd166a..88f1da90f 100644
--- a/nanobot/agent/subagent.py
+++ b/nanobot/agent/subagent.py
@@ -7,17 +7,23 @@ import json
import time
import uuid
import warnings
-from collections.abc import Mapping
-from dataclasses import dataclass, field
+from collections.abc import Callable, Mapping
+from copy import deepcopy
+from dataclasses import dataclass, field, replace
from functools import partial
from pathlib import Path
-from typing import TYPE_CHECKING, Any, NotRequired, TypedDict, cast
+from typing import TYPE_CHECKING, Any, Literal, NotRequired, TypedDict, cast
from loguru import logger
from nanobot.agent.hook import AgentHook, AgentHookContext
+from nanobot.agent.hooks import create_file_edit_activity_hook
from nanobot.agent.runner import AgentRunner, AgentRunSpec
-from nanobot.agent.tools.base import ToolResult
+from nanobot.agent.session_activity import SessionActivity
+from nanobot.agent.subagent_sessions import SubagentSessions
+from nanobot.agent.subagent_status import SubagentState as SubagentState
+from nanobot.agent.subagent_status import SubagentStatus
+from nanobot.agent.tools.base import Tool, ToolResult
from nanobot.agent.tools.context import (
RequestContext,
ToolContext,
@@ -28,17 +34,21 @@ from nanobot.agent.tools.exec_session import ExecSessionManager
from nanobot.agent.tools.file_state import FileStates
from nanobot.agent.tools.loader import ToolLoader
from nanobot.agent.tools.registry import ToolRegistry
+from nanobot.agent.turn_hooks import AgentTurnHookSpec, build_agent_turn_hook
from nanobot.bus.events import InboundMessage
from nanobot.bus.queue import MessageBus
+from nanobot.bus.runtime_events import RuntimeEventContext, SubagentTaskChanged
from nanobot.config.schema import AgentDefaults, ToolsConfig
+from nanobot.events import AgentEvent, EventSink
from nanobot.llm_usage.context import LLMUsageSource, current_llm_usage_source
-from nanobot.providers.base import LLMProvider, LLMUsage
+from nanobot.providers.base import LLMProvider, ToolCallRequest
from nanobot.security.workspace_access import (
WorkspaceScope,
bind_workspace_scope,
reset_workspace_scope,
workspace_sandbox_status,
)
+from nanobot.session.manager import Session, SessionManager, SessionPolicy
from nanobot.utils.llm_runtime import LLMRuntime
from nanobot.utils.prompt_templates import render_template
@@ -53,38 +63,131 @@ class _SubagentOrigin(TypedDict):
llm_usage_source: NotRequired[LLMUsageSource]
-@dataclass(slots=True)
-class SubagentStatus:
- """Real-time status of a running subagent."""
+
+class SubagentControlError(ValueError):
+ """A task control request violates ownership or admission rules."""
+
+
+class SubagentMessageReceipt(TypedDict):
task_id: str
- label: str
- task_description: str
- started_at: float # time.monotonic()
- # queued | initializing | awaiting_tools | tools_completed | final_response | done | error
- phase: str = "initializing"
- iteration: int = 0
- tool_events: list[dict[str, str]] = field(default_factory=list)
- usage: LLMUsage | None = None
+ message_id: str
+ receipt: Literal["accepted"]
+ delivered: Literal[False]
+
+
+@dataclass(frozen=True, slots=True)
+class _SubagentOutcome:
+ """Execution outcome, independent of process cleanup errors."""
+
+ state: Literal["done", "incomplete", "error", "cancelled"]
+ result: str
stop_reason: str | None = None
error: str | None = None
+@dataclass(slots=True)
+class _SubagentTask:
+ """Own one execution, its inbox, and resources until cleanup succeeds."""
+
+ status: SubagentStatus
+ session: Session
+ runtime: LLMRuntime
+ origin: _SubagentOrigin
+ origin_message_id: str | None = None
+ workspace_scope: WorkspaceScope | None = None
+ announce: bool = True
+ begun: bool = False
+ suppress_notice: bool = False
+ inbox: list[tuple[str, str]] = field(default_factory=list)
+ outcome: _SubagentOutcome | None = None
+ exec_manager: ExecSessionManager = field(default_factory=ExecSessionManager)
+ cleanup_task: asyncio.Task[int] | None = None
+
+ def raise_if_stopping(self) -> None:
+ if self.outcome is not None:
+ raise asyncio.CancelledError
+
+ def decide(self, outcome: _SubagentOutcome) -> bool:
+ """Seal execution once, before cancellation or cleanup can yield."""
+ if self.outcome is not None:
+ return False
+ self.outcome = outcome
+ self.status.state = self.status.phase = "stopping"
+ return True
+
+ def finish(self, max_chars: int, cleanup_error: str | None = None) -> _SubagentOutcome:
+ execution_outcome = self.outcome
+ if execution_outcome is None:
+ raise RuntimeError("cannot finish a task before execution has an outcome")
+ outcome = execution_outcome
+ if cleanup_error is not None:
+ outcome = _SubagentOutcome("error", cleanup_error, "error", cleanup_error)
+ status = self.status
+ has_partial_result = outcome.state != "done" and bool(status.result)
+ if outcome.state != "done" and status.result:
+ outcome = replace(outcome, result=status.result)
+ status.state = status.phase = outcome.state
+ status.finished_at = time.monotonic()
+ status.completed_at = time.time()
+ status.result = outcome.result[:max_chars]
+ status.partial = has_partial_result
+ status.stop_reason = outcome.stop_reason
+ status.error = outcome.error[:max_chars] if outcome.error else None
+ status.task_description = status.task_description[:max_chars]
+ status.label = status.label[:256]
+ status.tool_events = []
+ for message_id, _ in self.inbox:
+ status.receipts[message_id] = "undelivered"
+ self.inbox.clear()
+ # Failed cleanup can retain this task after its public status is evicted.
+ self.outcome = replace(
+ execution_outcome,
+ result=execution_outcome.result[:max_chars],
+ error=execution_outcome.error[:max_chars] if execution_outcome.error else None,
+ )
+ return outcome
+
+ def snapshot(self) -> SubagentStatus:
+ return deepcopy(self.status)
+
+
class _SubagentHook(AgentHook):
- """Hook for subagent execution — logs tool calls and updates status."""
+ """Update task status at runner boundaries."""
- def __init__(self, task_id: str, status: SubagentStatus | None = None) -> None:
+ def __init__(self, status: SubagentStatus | None = None,
+ *, check_active: Callable[[], None] | None = None,
+ max_result_chars: int = 16000,
+ on_status: Callable[[SubagentStatus], None] | None = None) -> None:
super().__init__()
- self._task_id = task_id
self._status = status
+ self._check_active = check_active
+ self._max_result_chars = max_result_chars
+ self._on_status = on_status
+
+ def _remember_output(self, context: AgentHookContext) -> None:
+ if self._status is None or context.error or context.response is None:
+ return
+ content = context.response.content
+ if content and content.strip():
+ self._status.result = content[:self._max_result_chars]
+ self._status.partial = True
async def before_execute_tools(self, context: AgentHookContext) -> None:
- for tool_call in context.tool_calls:
- args_str = json.dumps(tool_call.arguments, ensure_ascii=False)
- logger.debug(
- "Subagent [{}] executing: {} with arguments: {}",
- self._task_id, tool_call.name, args_str,
- )
+ self._remember_output(context)
+ if self._status is not None:
+ self._status.tool_events = [
+ {"name": call.name, "status": "running"} for call in context.tool_calls
+ ]
+ if self._status is not None and self._on_status is not None:
+ self._on_status(self._status)
+
+ async def before_execute_tool(
+ self, context: AgentHookContext, tool_call: ToolCallRequest,
+ tool: Tool | None, params: dict[str, Any],
+ ) -> None:
+ if self._check_active is not None:
+ self._check_active()
async def after_iteration(self, context: AgentHookContext) -> None:
if self._status is None:
@@ -92,8 +195,11 @@ class _SubagentHook(AgentHook):
self._status.iteration = context.iteration
self._status.tool_events = list(context.tool_events)
self._status.usage = context.usage
+ self._remember_output(context)
if context.error:
self._status.error = str(context.error)
+ if self._on_status is not None:
+ self._on_status(self._status)
class SubagentManager:
@@ -113,6 +219,7 @@ class SubagentManager:
max_concurrent_subagents: int | None = None,
*,
consolidator: Consolidator,
+ session_manager: SessionManager | None = None,
):
if cast(object, consolidator) is None:
raise TypeError("SubagentManager requires a consolidator")
@@ -162,22 +269,179 @@ class SubagentManager:
self.runner = AgentRunner()
self._exec_session_manager = ExecSessionManager()
self._running_tasks: dict[str, asyncio.Task[str]] = {}
- self._task_statuses: dict[str, SubagentStatus] = {}
- self._session_tasks: dict[str, set[str]] = {} # session_key -> {task_id, ...}
+ self._tasks: dict[str, _SubagentTask] = {}
+ self._terminal_statuses: dict[str, SubagentStatus] = {}
+ self._closed = False
+ self._close_task: asyncio.Task[int] | None = None
+ self.sessions = SubagentSessions(session_manager) if session_manager is not None else None
+
+ MAX_ACTIVE = 128
+ MAX_TERMINAL = 128
+ MAX_INBOX = 16
+ MAX_MESSAGES = 128
+ MAX_MESSAGE_BYTES = 8192
+
+ CANCEL_WAIT_SECONDS = 5.0
+
+ def _save_status(
+ self, status: SubagentStatus, *, fsync: bool = False,
+ ) -> None:
+ status.revision += 1
+ if self.sessions is not None and not self.sessions.save(status, fsync=fsync):
+ return
+ self._publish_status(status)
+
+ def _publish_status(self, status: SubagentStatus) -> None:
+ origin = self._tasks[status.task_id].origin
+ self.bus.publish_nowait(SubagentTaskChanged(
+ context=RuntimeEventContext(
+ channel=origin["channel"], chat_id=origin["chat_id"], session_key=status.owner,
+ ),
+ task_id=status.task_id,
+ ))
+
+ def recover_interrupted(self) -> None:
+ """Recover observations only after the host has claimed execution ownership."""
+ if self.sessions is not None:
+ self.sessions.interrupt_pending()
+
+ def _start_cleanup(self, record: _SubagentTask, *, retry: bool = False) -> asyncio.Task[int]:
+ cleanup = record.cleanup_task
+ if retry and cleanup is not None and cleanup.done():
+ record.cleanup_task = None
+ if record.cleanup_task is None:
+ record.cleanup_task = asyncio.create_task(record.exec_manager.close_all())
+ record.cleanup_task.add_done_callback(partial(self._cleanup_done, record))
+ return record.cleanup_task
+
+ def _cleanup_done(self, record: _SubagentTask, task: asyncio.Task[int]) -> None:
+ if not task.cancelled() and task.exception() is None:
+ self._release_task(record)
+
+ def _release_task(self, record: _SubagentTask) -> None:
+ cleanup = record.cleanup_task
+ if (record.status.finished_at is not None
+ and record.status.task_id not in self._running_tasks
+ and cleanup is not None and cleanup.done()
+ and not cleanup.cancelled() and cleanup.exception() is None):
+ self._tasks.pop(record.status.task_id, None)
+
+ def _finish(self, record: _SubagentTask,
+ cleanup_error: str | None = None) -> _SubagentOutcome:
+ outcome = record.finish(self.max_tool_result_chars, cleanup_error)
+ self._save_status(record.status, fsync=True)
+ self._terminal_statuses[record.status.task_id] = record.snapshot()
+ while len(self._terminal_statuses) > self.MAX_TERMINAL:
+ del self._terminal_statuses[next(iter(self._terminal_statuses))]
+ return outcome
+
+ async def _drain_inbox(self, record: _SubagentTask) -> list[dict[str, str]]:
+ record.raise_if_stopping()
+ snapshot, record.inbox = record.inbox, []
+ for message_id, _ in snapshot:
+ record.status.receipts[message_id] = "delivered"
+ if snapshot:
+ self._save_status(record.status)
+ return [{"role": "user", "content": content} for _, content in snapshot]
+
+ def _owned_status(self, task_id: str, owner: str | None) -> SubagentStatus:
+ status = self._terminal_statuses.get(task_id)
+ record = self._tasks.get(task_id)
+ if status is None and record is not None and record.status.finished_at is None:
+ status = record.status
+ if self.sessions is not None and owner:
+ if not self.sessions.exists(owner) or not self.sessions.contains(task_id, owner):
+ raise SubagentControlError("task unavailable")
+ if status is None:
+ status = self.sessions.status(task_id, owner)
+ if not owner or status is None or status.owner != owner:
+ raise SubagentControlError("task unavailable")
+ return status
+
+ def check(self, task_id: str, owner: str | None) -> SubagentStatus:
+ """Return detached status for one task owned by the caller's session."""
+ return deepcopy(self._owned_status(task_id, owner))
+
+ def accepts_result(self, msg: InboundMessage, owner: str) -> bool:
+ """Reject a completion whose owning child was removed after publication."""
+ task_id = msg.metadata.get("subagent_task_id")
+ if msg.sender_id != "subagent" or not isinstance(task_id, str) or self.sessions is None:
+ return True
+ return self.sessions.contains(task_id, owner)
+
+ def read_session(self, task_id: str, owner: str) -> tuple[SubagentStatus, Session]:
+ """Return task status and detached history through the ownership boundary."""
+ status = self.check(task_id, owner)
+ child = self.sessions.snapshot(task_id, owner) if self.sessions is not None else None
+ if child is None:
+ raise SubagentControlError("task unavailable")
+ return status, child
+
+ def send(self, task_id: str, owner: str | None,
+ message: str | None) -> SubagentMessageReceipt:
+ """Accept a bounded follow-up only while execution is open."""
+ status = self._owned_status(task_id, owner)
+ if status.state not in {"queued", "running"}:
+ raise SubagentControlError("task is not accepting messages")
+ if not message or not message.strip() or len(message.encode("utf-8")) > self.MAX_MESSAGE_BYTES:
+ raise SubagentControlError("message must contain text and be at most 8192 UTF-8 bytes")
+ record = self._tasks[task_id]
+ if len(record.inbox) >= self.MAX_INBOX or len(status.receipts) >= self.MAX_MESSAGES:
+ raise SubagentControlError("task message capacity reached")
+ message_id = str(uuid.uuid4())
+ record.inbox.append((message_id, message))
+ status.receipts[message_id] = "accepted"
+ self._save_status(status)
+ return {"task_id": task_id, "message_id": message_id,
+ "receipt": "accepted", "delivered": False}
+
+ async def cancel(self, task_id: str, owner: str | None) -> SubagentStatus:
+ """Stop an owned task and return its detached state after the bounded wait."""
+ status = self._owned_status(task_id, owner)
+ record = self._tasks.get(task_id)
+ if record is not None and record.status.finished_at is None:
+ await self._cancel_task(record)
+ status = record.status
+ return deepcopy(status)
+
+ async def _cancel_task(self, record: _SubagentTask,
+ *, suppress_notice: bool = False) -> None:
+ record.suppress_notice |= suppress_notice
+ task_id = record.status.task_id
+ task = self._running_tasks.get(task_id)
+ if record.decide(_SubagentOutcome("cancelled", "Task cancelled.", "cancelled")):
+ self._save_status(record.status, fsync=True)
+ if task is not None and record.begun and not task.done():
+ task.cancel()
+ if record.status.finished_at is None:
+ self._start_cleanup(record)
+ if task is not None:
+ # wait_for waits for cancellation acknowledgement and can hang here.
+ # Keep resistant work tracked, with its slot held, until it really exits.
+ await asyncio.wait({task}, timeout=self.CANCEL_WAIT_SECONDS)
def runtime_statuses(self) -> Mapping[str, SubagentStatus]:
- """Return the observable statuses of all active tasks."""
- return self._task_statuses
+ """Return detached active and retained terminal data, never task resources."""
+ return {
+ **{tid: record.snapshot() for tid, record in self._tasks.items()
+ if record.status.finished_at is None},
+ **deepcopy(self._terminal_statuses),
+ }
- def statuses_for_session(self, session_key: str | None) -> Mapping[str, SubagentStatus]:
+ def statuses_for_session(
+ self, session_key: str | None, *, include_history: bool = True,
+ ) -> Mapping[str, SubagentStatus]:
"""Return only tasks owned by the given session, never a global fallback."""
- if not session_key:
+ if not session_key or (self.sessions is not None and not self.sessions.exists(session_key)):
return {}
- task_ids = self._session_tasks.get(session_key, set())
return {
- task_id: status
- for task_id, status in self._task_statuses.items()
- if task_id in task_ids
+ **(self.sessions.load(session_key) if include_history and self.sessions is not None else {}),
+ **{tid: record.snapshot() for tid, record in self._tasks.items()
+ if record.status.owner == session_key and record.status.finished_at is None
+ and (self.sessions is None or self.sessions.contains(tid, session_key))},
+ **{tid: deepcopy(status) for tid, status in self._terminal_statuses.items()
+ if status.owner == session_key
+ and (self.sessions is None or self.sessions.contains(tid, session_key))},
}
def set_provider(self, provider: LLMProvider, model: str) -> None:
@@ -228,6 +492,7 @@ class SubagentManager:
self,
workspace: Path | None = None,
tools_config: ToolsConfig | None = None,
+ exec_manager: ExecSessionManager | None = None,
) -> ToolRegistry:
"""Build an isolated subagent tool registry via ToolLoader."""
root = self.workspace if workspace is None else workspace
@@ -236,7 +501,7 @@ class SubagentManager:
ctx = ToolContext(
config=cfg,
workspace=str(root.resolve()),
- exec_session_manager=self._exec_session_manager,
+ exec_session_manager=exec_manager or self._exec_session_manager,
file_state_store=FileStates(),
workspace_sandbox=workspace_sandbox_status(
restrict_to_workspace=cfg.restrict_to_workspace,
@@ -246,71 +511,59 @@ class SubagentManager:
ToolLoader().load(ctx, registry, scope="subagent")
return registry
- async def spawn(
- self,
- task: str,
- label: str | None = None,
- origin_channel: str = "cli",
- origin_chat_id: str = "direct",
- session_key: str | None = None,
- origin_message_id: str | None = None,
- temperature: float | None = None,
- workspace_scope: WorkspaceScope | None = None,
- *,
- runtime: LLMRuntime | None = None,
- ) -> str:
- """Spawn a subagent to execute a task in the background."""
+ def _create_task(
+ self, task: str, label: str | None, origin_channel: str, origin_chat_id: str,
+ session_key: str | None, origin_message_id: str | None,
+ temperature: float | None, workspace_scope: WorkspaceScope | None,
+ runtime: LLMRuntime | None, *, announce: bool, origin_turn_id: str | None,
+ session_policy: SessionPolicy | None,
+ ) -> _SubagentTask:
if runtime is None:
runtime = self._compat_spawn_runtime()
if temperature is not None:
runtime = runtime.with_generation_overrides(temperature=temperature)
- task_id = str(uuid.uuid4())[:8]
- display_label = label or task[:30] + ("..." if len(task) > 30 else "")
- origin: _SubagentOrigin = {
- "channel": origin_channel,
- "chat_id": origin_chat_id,
- "session_key": session_key,
- "llm_usage_source": current_llm_usage_source(),
- }
-
+ # A failed cleanup owns admission even after its status has been evicted.
+ if self._closed or len(self._tasks) >= self.MAX_ACTIVE:
+ raise SubagentControlError("subagent manager is closed or at task capacity")
+ owner = session_key or f"{origin_channel}:{origin_chat_id}"
+ task_id = str(uuid.uuid4())
status = SubagentStatus(
task_id=task_id,
- label=display_label,
+ revision=1,
+ label=label or task[:30] + ("..." if len(task) > 30 else ""),
task_description=task,
started_at=time.monotonic(),
+ owner=owner,
+ origin_message_id=origin_message_id,
+ origin_turn_id=origin_turn_id,
)
- self._task_statuses[task_id] = status
-
- bg_task = asyncio.create_task(
- self._run_subagent(
- task_id,
- task,
- display_label,
- origin,
- status,
- runtime,
- origin_message_id,
- workspace_scope,
- )
+ if self.sessions is not None:
+ child = self.sessions.create(status, policy=session_policy)
+ else:
+ child = Session(key=SubagentSessions.key(task_id), policy=session_policy or SessionPolicy())
+ child.add_message("user", task)
+ record = _SubagentTask(
+ status=status,
+ session=child,
+ runtime=runtime,
+ origin={
+ "channel": origin_channel, "chat_id": origin_chat_id,
+ "session_key": owner, "llm_usage_source": current_llm_usage_source(),
+ },
+ origin_message_id=origin_message_id,
+ workspace_scope=workspace_scope,
+ announce=announce,
)
- self._running_tasks[task_id] = bg_task
- if session_key:
- self._session_tasks.setdefault(session_key, set()).add(task_id)
-
- def _cleanup(_: asyncio.Task[str]) -> None:
- self._running_tasks.pop(task_id, None)
- self._task_statuses.pop(task_id, None)
- if session_key and (ids := self._session_tasks.get(session_key)):
- ids.discard(task_id)
- if not ids:
- del self._session_tasks[session_key]
-
- bg_task.add_done_callback(_cleanup)
+ self._tasks[task_id] = record
+ self._publish_status(status)
+ execution = asyncio.create_task(self._run_subagent(record))
+ self._running_tasks[task_id] = execution
+ execution.add_done_callback(partial(self._task_done, record))
+ logger.info("Started subagent [{}]: {}", task_id,
+ record.status.label if child.policy.log_content else "[content hidden]")
+ return record
- logger.info("Spawned subagent [{}]: {}", task_id, display_label)
- return f"Subagent [{display_label}] started (id: {task_id}). I'll notify you when it completes."
-
- async def run_inline(
+ async def spawn(
self,
task: str,
label: str | None = None,
@@ -322,207 +575,247 @@ class SubagentManager:
workspace_scope: WorkspaceScope | None = None,
*,
runtime: LLMRuntime | None = None,
+ origin_turn_id: str | None = None,
+ session_policy: SessionPolicy | None = None,
) -> str:
- """Run a subagent synchronously and return its result to the caller."""
- if runtime is None:
- runtime = self._compat_spawn_runtime()
- if temperature is not None:
- runtime = runtime.with_generation_overrides(temperature=temperature)
- task_id = str(uuid.uuid4())[:8]
- display_label = label or task[:30] + ("..." if len(task) > 30 else "")
- origin: _SubagentOrigin = {
- "channel": origin_channel,
- "chat_id": origin_chat_id,
- "session_key": session_key,
- "llm_usage_source": current_llm_usage_source(),
- }
- status = SubagentStatus(
- task_id=task_id,
- label=display_label,
- task_description=task,
- started_at=time.monotonic(),
- )
- self._task_statuses[task_id] = status
- logger.info("Running inline subagent [{}]: {}", task_id, display_label)
- inline_task = asyncio.create_task(
- self._run_subagent(
- task_id,
- task,
- display_label,
- origin,
- status,
- runtime,
- origin_message_id,
- workspace_scope,
- announce=False,
- )
- )
- self._running_tasks[task_id] = inline_task
- if session_key:
- self._session_tasks.setdefault(session_key, set()).add(task_id)
+ """Start background work and route its terminal result to the parent."""
try:
- result = await inline_task
- if status.phase == "error" or status.stop_reason == "error":
- return ToolResult.error(result)
- return result
- finally:
- self._running_tasks.pop(task_id, None)
- self._task_statuses.pop(task_id, None)
- if session_key and (ids := self._session_tasks.get(session_key)):
- ids.discard(task_id)
- if not ids:
- del self._session_tasks[session_key]
-
- async def _run_subagent(
- self,
- task_id: str,
- task: str,
- label: str,
- origin: _SubagentOrigin,
- status: SubagentStatus,
- runtime: LLMRuntime,
- origin_message_id: str | None = None,
- workspace_scope: WorkspaceScope | None = None,
- *,
- announce: bool = True,
- ) -> str:
- """Wait for capacity, then execute one subagent task."""
- status.phase = "queued"
- async with self._run_slots:
- status.phase = "initializing"
- return await self._run_admitted_subagent(
- task_id,
- task,
- label,
- origin,
- status,
- runtime,
- origin_message_id,
- workspace_scope,
- announce=announce,
+ record = self._create_task(
+ task, label, origin_channel, origin_chat_id, session_key,
+ origin_message_id, temperature, workspace_scope, runtime, announce=True, origin_turn_id=origin_turn_id,
+ session_policy=session_policy,
)
+ except SubagentControlError as exc:
+ return ToolResult.error(f"Error: {exc}")
+ status = record.status
+ return f"Subagent [{status.label}] started (id: {status.task_id}). I'll notify you when it completes."
- async def _run_admitted_subagent(
+ async def run_inline(
self,
- task_id: str,
task: str,
- label: str,
- origin: _SubagentOrigin,
- status: SubagentStatus,
- runtime: LLMRuntime,
+ label: str | None = None,
+ origin_channel: str = "cli",
+ origin_chat_id: str = "direct",
+ session_key: str | None = None,
origin_message_id: str | None = None,
+ temperature: float | None = None,
workspace_scope: WorkspaceScope | None = None,
*,
- announce: bool = True,
+ runtime: LLMRuntime | None = None,
+ origin_turn_id: str | None = None,
+ session_policy: SessionPolicy | None = None,
) -> str:
- """Execute the subagent task and announce the result."""
- logger.info("Subagent [{}] starting task: {}", task_id, label)
+ """Wait for the same task lifecycle without a background notice."""
+ try:
+ record = self._create_task(
+ task, label, origin_channel, origin_chat_id, session_key,
+ origin_message_id, temperature, workspace_scope, runtime, announce=False, origin_turn_id=origin_turn_id,
+ session_policy=session_policy,
+ )
+ except SubagentControlError as exc:
+ return ToolResult.error(f"Error: {exc}")
+ execution = self._running_tasks[record.status.task_id]
+ try:
+ result = await asyncio.shield(execution)
+ except asyncio.CancelledError:
+ caller = asyncio.current_task()
+ if execution.cancelled() and caller is not None and not caller.cancelling():
+ partial_result = record.status.result if record.status.partial else None
+ return ToolResult.error(
+ "Task cancelled." + (f"\nPartial result:\n{partial_result}" if partial_result else "")
+ )
+ await self._cancel_task(record, suppress_notice=True)
+ raise
+ if record.status.state == "error":
+ error = record.status.error or result
+ return ToolResult.error(error + (f"\nPartial result:\n{result}" if error != result else ""))
+ if record.status.state == "incomplete":
+ return ToolResult.error(f"Task incomplete ({record.status.stop_reason}).\n{result}")
+ return result
+
+ def _task_done(self, record: _SubagentTask, task: asyncio.Task[str]) -> None:
+ self._running_tasks.pop(record.status.task_id, None)
+ error = None if task.cancelled() else task.exception()
+ if error is not None:
+ logger.error("Subagent [{}] failed: {}", record.status.task_id,
+ error if record.session.policy.log_content else type(error).__name__)
+ if record.status.finished_at is None:
+ # An externally cancelled execution still owns cleanup and a terminal result.
+ record.decide(
+ _SubagentOutcome("error", f"Error: {error}", "error", str(error))
+ if error is not None
+ else _SubagentOutcome("cancelled", "Task cancelled.", "cancelled")
+ )
+ self._start_cleanup(record)
+ self._finish(record)
+ self._release_task(record)
+
+ async def _run_subagent(self, record: _SubagentTask) -> str:
+ """Execute once, seal the outcome, then clean up and publish once."""
+ status = record.status
+ task_text, label = status.task_description, status.label
+ record.begun = True
+ try:
+ record.raise_if_stopping()
+ async with self._run_slots:
+ record.raise_if_stopping()
+ status.state = "running"
+ status.phase = "initializing"
+ self._save_status(status)
+ outcome = await self._run_admitted_subagent(record)
+ record.decide(outcome)
+ except asyncio.CancelledError:
+ record.decide(_SubagentOutcome("cancelled", "Task cancelled.", "cancelled"))
+ except Exception as exc:
+ logger.opt(exception=record.session.policy.log_content).error("Subagent [{}] failed", status.task_id)
+ record.decide(_SubagentOutcome("error", f"Error: {exc}", "error", str(exc)))
+ cleanup_error = None
+ try:
+ await asyncio.shield(self._start_cleanup(record))
+ except Exception as exc:
+ logger.opt(exception=record.session.policy.log_content).error(
+ "Subagent [{}] exec cleanup failed", status.task_id,
+ )
+ cleanup_error = f"Error cleaning up task processes: {exc}"
+ outcome = self._finish(record, cleanup_error)
+ if record.announce and not record.suppress_notice and not self._closed:
+ await self._announce_result(
+ status.task_id, label, task_text, outcome.result, record.origin,
+ "ok" if outcome.state == "done" else outcome.state, record.origin_message_id,
+ receipts=dict(status.receipts),
+ stop_reason=status.stop_reason, error=status.error, partial_result=status.partial,
+ )
+ if outcome.state == "cancelled":
+ raise asyncio.CancelledError
+ return outcome.result
+
+ async def _run_admitted_subagent(self, record: _SubagentTask) -> _SubagentOutcome:
+ """Execute the admitted task with task-owned shell resources."""
+ status, origin, runtime = record.status, record.origin, record.runtime
+ task_id, label = status.task_id, status.label
+ origin_message_id, workspace_scope = record.origin_message_id, record.workspace_scope
+ logger.info("Subagent [{}] starting task: {}", task_id,
+ label if record.session.policy.log_content else "[content hidden]")
async def _on_checkpoint(payload: dict[str, Any]) -> None:
- status.phase = payload.get("phase", status.phase)
- status.iteration = payload.get("iteration", status.iteration)
-
+ record.raise_if_stopping()
+ phase = payload.get("phase", status.phase)
+ iteration = payload.get("iteration", status.iteration)
+ if (phase, iteration) != (status.phase, status.iteration):
+ status.phase, status.iteration = phase, iteration
+ self._save_status(status)
+
+ root = workspace_scope.project_path if workspace_scope is not None else self.workspace
+ cfg = None
+ if workspace_scope is not None:
+ cfg = self._subagent_tools_config()
+ cfg.restrict_to_workspace = workspace_scope.restrict_to_workspace
+ # Construct from the agent workspace; the bound scope below supplies the project cwd.
+ tools = self._build_tools(tools_config=cfg, exec_manager=record.exec_manager)
+ system_prompt = self._build_subagent_prompt(workspace=root)
+ messages: list[dict[str, Any]] = [
+ {"role": "system", "content": system_prompt},
+ *record.session.get_history(),
+ ]
+ activity = SessionActivity()
+
+ def save_observation(status: SubagentStatus) -> None:
+ record.session.messages = activity.transcript()
+ self._save_status(status)
+
+ async def publish_activity(event: AgentEvent) -> None:
+ if activity.remember(event):
+ save_observation(status)
+
+ events = EventSink(publish_activity)
+ hook = build_agent_turn_hook(AgentTurnHookSpec(
+ events=events,
+ streaming=True,
+ channel=origin["channel"],
+ chat_id=origin["chat_id"],
+ message_id=origin_message_id,
+ session_key=record.session.key,
+ workspace=root,
+ registered_hook_factories=[create_file_edit_activity_hook],
+ turn_hooks=[activity, _SubagentHook(
+ status, check_active=record.raise_if_stopping,
+ max_result_chars=self.max_tool_result_chars,
+ on_status=save_observation,
+ )],
+ ephemeral=not record.session.policy.persist,
+ run_extra_hooks_for_ephemeral=True,
+ log_content=record.session.policy.log_content,
+ ))
+
+ request_token = bind_request_context(RequestContext(
+ channel=origin["channel"],
+ chat_id=origin["chat_id"],
+ message_id=origin_message_id,
+ session_key=record.session.key,
+ runtime=runtime,
+ log_content=record.session.policy.log_content,
+ persist_session=record.session.policy.persist,
+ ))
+ token = bind_workspace_scope(workspace_scope) if workspace_scope is not None else None
try:
- root = workspace_scope.project_path if workspace_scope is not None else self.workspace
- cfg = None
- if workspace_scope is not None:
- cfg = self._subagent_tools_config()
- cfg.restrict_to_workspace = workspace_scope.restrict_to_workspace
- # Construct from the agent workspace; the bound scope below supplies the project cwd.
- tools = self._build_tools(tools_config=cfg)
- system_prompt = self._build_subagent_prompt(workspace=root)
- messages: list[dict[str, Any]] = [
- {"role": "system", "content": system_prompt},
- {"role": "user", "content": task},
- ]
-
- sess_key = origin.get("session_key")
- request_token = bind_request_context(RequestContext(
- channel=origin["channel"],
- chat_id=origin["chat_id"],
- message_id=origin_message_id,
- session_key=sess_key,
+ tool_definitions = tools.get_definitions()
+ consolidate_history = partial(
+ self.consolidator.summarize_transcript,
runtime=runtime,
+ session_key=record.session.key,
+ tools=tool_definitions,
+ persist=False,
+ )
+ consolidate_provider_compaction = partial(
+ self.consolidator.summarize_provider_compaction,
+ runtime=runtime,
+ session_key=record.session.key,
+ tools=tool_definitions,
+ persist=False,
+ )
+ result = await self.runner.run(AgentRunSpec(
+ initial_messages=messages,
+ tools=tools,
+ runtime=runtime,
+ max_iterations=self.max_iterations,
+ max_tool_result_chars=self.max_tool_result_chars,
+ hook=hook,
+ max_iterations_message="Task stopped at its iteration limit before producing a final response.",
+ finalize_on_max_iterations=False,
+ error_message=None,
+ checkpoint_callback=_on_checkpoint,
+ injection_callback=partial(self._drain_inbox, record),
+ session_key=record.session.key,
+ workspace=root if record.session.policy.persist else None,
+ llm_usage_source=origin.get(
+ "llm_usage_source",
+ current_llm_usage_source(),
+ ),
+ consolidate_history=consolidate_history,
+ consolidate_provider_compaction=consolidate_provider_compaction,
+ events=events,
))
- token = bind_workspace_scope(workspace_scope) if workspace_scope is not None else None
- try:
- tool_definitions = tools.get_definitions()
- consolidate_history = partial(
- self.consolidator.summarize_transcript,
- runtime=runtime,
- session_key=f"subagent:{task_id}",
- tools=tool_definitions,
- persist=False,
- )
- consolidate_provider_compaction = partial(
- self.consolidator.summarize_provider_compaction,
- runtime=runtime,
- session_key=f"subagent:{task_id}",
- tools=tool_definitions,
- persist=False,
- )
- result = await self.runner.run(AgentRunSpec(
- initial_messages=messages,
- tools=tools,
- runtime=runtime,
- max_iterations=self.max_iterations,
- max_tool_result_chars=self.max_tool_result_chars,
- hook=_SubagentHook(task_id, status),
- max_iterations_message="Task completed but no final response was generated.",
- finalize_on_max_iterations=False,
- error_message=None,
- checkpoint_callback=_on_checkpoint,
- session_key=sess_key,
- workspace=root,
- llm_usage_source=origin.get(
- "llm_usage_source",
- current_llm_usage_source(),
- ),
- consolidate_history=consolidate_history,
- consolidate_provider_compaction=consolidate_provider_compaction,
- ))
- finally:
- if token is not None:
- reset_workspace_scope(token)
- reset_request_context(request_token)
- status.phase = "done"
- status.stop_reason = result.stop_reason
-
- if result.stop_reason == "error":
- final_result = result.error or "Error: subagent execution failed."
- final_status = "error"
- else:
- final_result = result.final_content or "Task completed but no final response was generated."
- final_status = "ok"
- logger.info("Subagent [{}] completed successfully", task_id)
- if announce:
- await self._announce_result(
- task_id,
- label,
- task,
- final_result,
- origin,
- final_status,
- origin_message_id,
- )
- return final_result
-
- except Exception as e:
- status.phase = "error"
- status.error = str(e)
- logger.exception("Subagent [{}] failed", task_id)
- final_result = f"Error: {e}"
- if announce:
- await self._announce_result(
- task_id,
- label,
- task,
- final_result,
- origin,
- "error",
- origin_message_id,
- )
- return final_result
+ finally:
+ if token is not None:
+ reset_workspace_scope(token)
+ reset_request_context(request_token)
+ status.usage = result.usage
+ if result.messages:
+ record.session.messages = activity.transcript(result.messages)
+ record.session.provider_state = result.provider_state
+ checkpoint = result.summary_checkpoint
+ if checkpoint is not None:
+ boundary = checkpoint.transcript_boundary
+ if 0 <= boundary <= len(result.messages):
+ insert_at = sum(message.get("role") != "system" for message in result.messages[:boundary])
+ record.session.commit_summary_checkpoint(checkpoint.summary, insert_at=insert_at)
+ if result.stop_reason in {"error", "empty_final_response"}:
+ final_result = result.error or "Error: subagent execution failed."
+ return _SubagentOutcome("error", final_result, result.stop_reason, result.error)
+ if result.stop_reason == "max_iterations":
+ return _SubagentOutcome("incomplete", result.final_content or "Iteration limit reached.", result.stop_reason)
+ final_result = result.final_content or "Task completed but no final response was generated."
+ return _SubagentOutcome("done", final_result, result.stop_reason, result.error)
async def _announce_result(
self,
@@ -533,9 +826,17 @@ class SubagentManager:
origin: _SubagentOrigin,
status: str,
origin_message_id: str | None = None,
+ *,
+ receipts: dict[str, str] | None = None,
+ stop_reason: str | None = None,
+ error: str | None = None,
+ partial_result: bool = False,
) -> None:
"""Announce the subagent result to the main agent via the message bus."""
- status_text = "completed successfully" if status == "ok" else "failed"
+ status_text = {
+ "ok": "completed successfully", "cancelled": "was cancelled",
+ "incomplete": "stopped before completing the task",
+ }.get(status, "failed")
announce_content = render_template(
"agent/subagent_announce.md",
@@ -543,6 +844,9 @@ class SubagentManager:
status_text=status_text,
task=task,
result=result,
+ stop_reason=stop_reason,
+ error=error,
+ partial_result=partial_result,
)
# Inject as system message to trigger main agent.
@@ -551,10 +855,20 @@ class SubagentManager:
# routed to the correct pending queue (mid-turn injection) instead of
# being dispatched as a competing independent task.
override = origin.get("session_key") or f"{origin['channel']}:{origin['chat_id']}"
+ if self.sessions is not None and (
+ not self.sessions.exists(override) or not self.sessions.contains(task_id, override)
+ ):
+ return
metadata: dict[str, Any] = {
"injected_event": "subagent_result",
"subagent_task_id": task_id,
+ "subagent_state": "done" if status == "ok" else status,
+ "subagent_stop_reason": stop_reason,
+ "subagent_partial": partial_result,
}
+ metadata["subagent_message_receipts"] = receipts or {}
+ if receipts:
+ announce_content += "\nMessage receipts: " + json.dumps(receipts)
if origin_message_id:
metadata["origin_message_id"] = origin_message_id
msg = InboundMessage(
@@ -563,6 +877,7 @@ class SubagentManager:
chat_id=f"{origin['channel']}:{origin['chat_id']}",
content=announce_content,
session_key_override=override,
+ require_existing_session=True,
metadata=metadata,
)
@@ -594,23 +909,35 @@ class SubagentManager:
async def cancel_by_session(self, session_key: str) -> int:
"""Cancel all subagents for the given session. Returns count cancelled."""
- tasks = [self._running_tasks[tid] for tid in self._session_tasks.get(session_key, [])
- if tid in self._running_tasks and not self._running_tasks[tid].done()]
- for t in tasks:
- t.cancel()
- if tasks:
- await asyncio.gather(*tasks, return_exceptions=True)
- await self._exec_session_manager.terminate_by_owner(session_key)
- return len(tasks)
+ records = [record for tid, record in self._tasks.items()
+ if record.status.owner == session_key
+ and tid in self._running_tasks and not self._running_tasks[tid].done()]
+ # Suppress every notice before cancellation can yield to a sibling.
+ for record in records:
+ record.suppress_notice = True
+ await asyncio.gather(*(self._cancel_task(record, suppress_notice=True) for record in records))
+ return len(records)
async def close(self) -> None:
- """Cancel running subagents and close their shared exec sessions."""
- tasks = [task for task in self._running_tasks.values() if not task.done()]
- for task in tasks:
- task.cancel()
- if tasks:
- await asyncio.gather(*tasks, return_exceptions=True)
- await self._exec_session_manager.close_all()
+ """Request cancellation and bounded cleanup, retaining unfinished work."""
+ self._closed = True
+ await asyncio.gather(*(self._cancel_task(self._tasks[tid], suppress_notice=True)
+ for tid in list(self._running_tasks)))
+ cleanups: set[asyncio.Task[int]] = set()
+ for record in list(self._tasks.values()):
+ cleanup = record.cleanup_task
+ retry = cleanup is not None and cleanup.done() and (
+ cleanup.cancelled() or cleanup.exception() is not None
+ )
+ cleanups.add(self._start_cleanup(record, retry=retry))
+ if self._close_task is None:
+ self._close_task = asyncio.create_task(self._exec_session_manager.close_all())
+ cleanups.add(self._close_task)
+ done, _ = await asyncio.wait(cleanups, timeout=self.CANCEL_WAIT_SECONDS)
+ for task in done:
+ task.result()
+ if self._tasks:
+ logger.warning("Subagent shutdown returned with tasks or cleanup still pending")
def get_running_count(self) -> int:
"""Return the number of currently running subagents."""
@@ -618,8 +945,7 @@ class SubagentManager:
def get_running_count_by_session(self, session_key: str) -> int:
"""Return the number of currently running subagents for a session."""
- tids = self._session_tasks.get(session_key, set())
return sum(
- 1 for tid in tids
- if tid in self._running_tasks and not self._running_tasks[tid].done()
+ 1 for tid, task in self._running_tasks.items()
+ if self._tasks[tid].status.owner == session_key and not task.done()
)
diff --git a/nanobot/agent/subagent_sessions.py b/nanobot/agent/subagent_sessions.py
new file mode 100644
index 000000000..eb81deae9
--- /dev/null
+++ b/nanobot/agent/subagent_sessions.py
@@ -0,0 +1,161 @@
+"""Private child sessions for subagent transcripts and task observations."""
+
+from __future__ import annotations
+
+import math
+import time
+from copy import deepcopy
+from typing import Any, cast
+
+from loguru import logger
+from pydantic import TypeAdapter, ValidationError
+
+from nanobot.agent.subagent_status import SubagentSessionError as SubagentSessionError
+from nanobot.agent.subagent_status import SubagentStatus
+from nanobot.session.manager import Session, SessionManager, SessionPolicy
+from nanobot.session.types import PARENT_SESSION_KEY, SESSION_TYPE_KEY, SessionType
+
+SUBAGENT = SessionType("subagent", needs_handle=False, public_history=False)
+TASK_METADATA_KEY = "subagent_task"
+_STATUS = TypeAdapter(SubagentStatus)
+_ACTIVE_STATES = {"queued", "running", "stopping"}
+
+
+class SubagentSessions:
+ """Use the common session store; keep task access owned by the parent."""
+
+ def __init__(self, sessions: SessionManager):
+ self.sessions = sessions
+ sessions.types.register(SUBAGENT)
+
+ @staticmethod
+ def key(task_id: str) -> str:
+ return f"subagent:{task_id}"
+
+ def exists(self, owner: str) -> bool:
+ return self.sessions.get_cached(owner) is not None or self.sessions.read_session_metadata(owner) is not None
+
+ def contains(self, task_id: str, owner: str) -> bool:
+ key = self.key(task_id)
+ child = self.sessions.get_cached(key)
+ metadata = child.metadata if child is not None else (self.sessions.read_session_metadata(key) or {}).get("metadata", {})
+ return metadata.get(SESSION_TYPE_KEY) == SUBAGENT.name and metadata.get(PARENT_SESSION_KEY) == owner
+
+ def snapshot(self, task_id: str, owner: str) -> Session | None:
+ """Read a detached child only while its parent still owns it."""
+ with self.sessions.locked_session_files():
+ if not self.exists(owner) or not self.contains(task_id, owner):
+ return None
+ child = self.sessions.get_cached(self.key(task_id))
+ return deepcopy(child) if child is not None else self.sessions.read_session_snapshot(self.key(task_id))
+
+ @staticmethod
+ def _payload(status: SubagentStatus) -> dict[str, Any]:
+ return {
+ **_STATUS.dump_python(status, mode="json", exclude={"started_at", "finished_at"}),
+ "elapsed_seconds": status.as_dict()["elapsed_seconds"],
+ }
+
+ def create(self, status: SubagentStatus, *, policy: SessionPolicy | None = None) -> Session:
+ with self.sessions.locked_session_files():
+ parent = self.sessions.get_existing(status.owner)
+ if parent is None:
+ parent = self.sessions.get_or_create(status.owner)
+ requested = policy or SessionPolicy()
+ effective = SessionPolicy(
+ persist=parent.policy.persist and requested.persist,
+ log_content=parent.policy.log_content and requested.log_content,
+ )
+ if effective.persist and self.sessions.read_session_metadata(parent.key) is None:
+ self.sessions.save(parent, fsync=True)
+ key = self.key(status.task_id)
+ child = (self.sessions.get_or_create(key) if effective.persist
+ else self.sessions.get_or_create_transient(key))
+ child.policy = effective
+ child.metadata.update({
+ SESSION_TYPE_KEY: SUBAGENT.name,
+ PARENT_SESSION_KEY: status.owner,
+ TASK_METADATA_KEY: self._payload(status),
+ })
+ child.add_message("user", status.task_description)
+ self.sessions.save(child, fsync=True)
+ return child
+
+ def save(self, status: SubagentStatus, *, fsync: bool = False) -> bool:
+ with self.sessions.locked_session_files():
+ if not self.exists(status.owner):
+ return False
+ child = self.sessions.get_existing(self.key(status.task_id))
+ if child is None or not self.contains(status.task_id, status.owner):
+ return False
+ child.metadata[TASK_METADATA_KEY] = self._payload(status)
+ # Only create() establishes identity. Progress and late completion
+ # cannot recreate a child removed with its parent.
+ self.sessions.save(child, fsync=fsync)
+ return True
+
+ def status(self, task_id: str, owner: str) -> SubagentStatus | None:
+ payload = self.sessions.read_session_metadata(self.key(task_id))
+ if payload is None:
+ return None
+ metadata = payload.get("metadata", {})
+ if metadata.get(SESSION_TYPE_KEY) != SUBAGENT.name or metadata.get(PARENT_SESSION_KEY) != owner:
+ return None
+ raw: object = metadata.get(TASK_METADATA_KEY)
+ if not isinstance(raw, dict):
+ raise SubagentSessionError("invalid task session metadata")
+ value = cast(dict[str, object], raw)
+ elapsed = value.get("elapsed_seconds")
+ if (not isinstance(elapsed, (int, float)) or isinstance(elapsed, bool)
+ or not math.isfinite(elapsed) or elapsed < 0):
+ raise SubagentSessionError("invalid task duration")
+ now = time.monotonic()
+ try:
+ status = _STATUS.validate_python({
+ **value, "started_at": now - elapsed,
+ "finished_at": now if value.get("completed_at") is not None else None,
+ })
+ except ValidationError as exc:
+ raise SubagentSessionError("invalid task session metadata") from exc
+ if status.owner != owner or status.task_id != task_id:
+ raise SubagentSessionError("invalid task ownership")
+ return status
+
+ def load(self, owner: str) -> dict[str, SubagentStatus]:
+ result: dict[str, SubagentStatus] = {}
+ for key in self.sessions.child_session_keys(owner):
+ task_id = key.removeprefix("subagent:")
+ if key != self.key(task_id):
+ continue
+ status = self.status(task_id, owner)
+ if status is not None:
+ result[task_id] = status
+ return result
+
+ def interrupt_pending(self) -> None:
+ """Seal abandoned work after the gateway acquires execution ownership."""
+ for row in self.sessions.list_sessions():
+ key = row["key"]
+ payload = self.sessions.read_session_metadata(key)
+ metadata = (payload or {}).get("metadata", {})
+ if metadata.get(SESSION_TYPE_KEY) != SUBAGENT.name:
+ continue
+ owner = metadata.get(PARENT_SESSION_KEY)
+ if not isinstance(owner, str):
+ continue
+ try:
+ status = self.status(key.removeprefix("subagent:"), owner)
+ if status is None or status.state not in _ACTIVE_STATES:
+ continue
+ status.state = status.phase = "interrupted"
+ status.revision += 1
+ status.stop_reason = "host_restarted"
+ status.finished_at = time.monotonic()
+ status.completed_at = time.time()
+ status.partial = bool(status.result)
+ status.tool_events = []
+ status.receipts = {key: "undelivered" if receipt == "accepted" else receipt
+ for key, receipt in status.receipts.items()}
+ self.save(status, fsync=True)
+ except (OSError, SubagentSessionError):
+ logger.exception("Could not recover subagent session {}", key)
diff --git a/nanobot/agent/subagent_status.py b/nanobot/agent/subagent_status.py
new file mode 100644
index 000000000..893fa28e3
--- /dev/null
+++ b/nanobot/agent/subagent_status.py
@@ -0,0 +1,68 @@
+"""Task observations shared by execution and private child sessions."""
+
+from __future__ import annotations
+
+import time
+from dataclasses import dataclass, field
+from typing import Literal
+
+from nanobot.providers.base import LLMUsage
+
+SubagentState = Literal["queued", "running", "stopping", "done", "incomplete", "error", "cancelled", "interrupted"]
+
+
+class SubagentSessionError(ValueError):
+ """A private task session could not be read safely."""
+
+
+@dataclass(slots=True)
+class SubagentStatus:
+ """Observable task data, detached from execution and process resources."""
+
+ task_id: str
+ label: str
+ task_description: str
+ started_at: float # time.monotonic()
+ finished_at: float | None = None
+ # Runner checkpoints refine phase without changing the control lifecycle state.
+ phase: str = "queued"
+ owner: str = ""
+ state: SubagentState = "queued"
+ receipts: dict[str, str] = field(default_factory=dict)
+ result: str | None = None
+ partial: bool = False
+ iteration: int = 0
+ tool_events: list[dict[str, str]] = field(default_factory=list)
+ usage: LLMUsage | None = None
+ stop_reason: str | None = None
+ error: str | None = None
+ origin_message_id: str | None = None
+ origin_turn_id: str | None = None
+ created_at: float = field(default_factory=time.time)
+ completed_at: float | None = None
+ revision: int = 0
+
+ def as_dict(self) -> dict[str, object]:
+ """Serialize task observations without exposing ownership or resources."""
+ end = self.finished_at if self.finished_at is not None else time.monotonic()
+ return {
+ "task_id": self.task_id,
+ "revision": self.revision,
+ "origin_message_id": self.origin_message_id,
+ "origin_turn_id": self.origin_turn_id,
+ "created_at": self.created_at,
+ "completed_at": self.completed_at,
+ "label": self.label,
+ "task_description": self.task_description,
+ "state": self.state,
+ "phase": self.phase,
+ "elapsed_seconds": round(max(0.0, end - self.started_at), 1),
+ "iteration": self.iteration,
+ "tool_events": [dict(event) for event in self.tool_events],
+ "usage": self.usage.to_dict() if self.usage is not None else None,
+ "receipts": dict(self.receipts),
+ "result": self.result,
+ "partial": self.partial,
+ "stop_reason": self.stop_reason,
+ "error": self.error,
+ }
diff --git a/nanobot/agent/tools/context.py b/nanobot/agent/tools/context.py
index 40288a6ca..61b921fab 100644
--- a/nanobot/agent/tools/context.py
+++ b/nanobot/agent/tools/context.py
@@ -41,6 +41,9 @@ class RequestContext:
workspace: Path | None = None
attributes: dict[str, Any] = field(default_factory=dict)
log_content: bool = True
+ # The host can consume completion messages after this request returns.
+ can_receive_background_results: bool = True
+ persist_session: bool = True
@runtime_checkable
diff --git a/nanobot/agent/tools/runtime_control.py b/nanobot/agent/tools/runtime_control.py
index b3550df9b..e031ba067 100644
--- a/nanobot/agent/tools/runtime_control.py
+++ b/nanobot/agent/tools/runtime_control.py
@@ -7,10 +7,7 @@ from dataclasses import dataclass
from pathlib import Path
from typing import TYPE_CHECKING, Protocol, TypeAlias, runtime_checkable
-from nanobot.agent.tools.context import current_request_session_key
-
if TYPE_CHECKING:
- from nanobot.agent.subagent import SubagentManager, SubagentStatus
from nanobot.agent.tools.shell import ExecToolConfig
from nanobot.agent.tools.web import WebToolsConfig
from nanobot.config.schema import ModelPresetConfig
@@ -33,7 +30,6 @@ RUNTIME_SNAPSHOT_KEYS = frozenset({
"tool_names",
"web_config",
"exec_config",
- "subagents",
})
RUNTIME_COMMAND_KEYS = frozenset({
@@ -62,7 +58,6 @@ class RuntimeSnapshot:
tool_names: list[str]
web_config: dict[str, object]
exec_config: dict[str, object]
- subagent_statuses: dict[str, dict[str, object]]
scratchpad: dict[str, JsonValue]
def as_mapping(self) -> Mapping[str, object]:
@@ -79,7 +74,6 @@ class RuntimeSnapshot:
"tool_names": self.tool_names,
"web_config": self.web_config,
"exec_config": self.exec_config,
- "subagents": {"_task_statuses": self.subagent_statuses},
}
assert values.keys() == RUNTIME_SNAPSHOT_KEYS
return values
@@ -121,7 +115,6 @@ class _RuntimeControlTarget(Protocol):
max_tool_result_chars: int
web_config: WebToolsConfig
exec_config: ExecToolConfig
- subagents: SubagentManager
@property
def model(self) -> str: ...
@@ -145,6 +138,8 @@ class _RuntimeControlTarget(Protocol):
def set_runtime_context_window(self, context_window_tokens: int) -> LLMRuntime: ...
+ def set_runtime_max_iterations(self, value: int) -> None: ...
+
def set_model_preset(self, name: str | None) -> LLMRuntime: ...
def set_session_model_preset(self, session_key: str, name: str) -> LLMRuntime: ...
@@ -176,7 +171,6 @@ class AgentRuntimeControl:
tool_names=list(target.tool_names),
web_config=_snapshot_web_config(target.web_config),
exec_config=_snapshot_exec_config(target.exec_config),
- subagent_statuses=_snapshot_subagent_statuses(target.subagents),
scratchpad=_snapshot_json_mapping(self.__scratchpad),
)
@@ -194,8 +188,7 @@ class AgentRuntimeControl:
return self.__target.set_model_preset(name)
def set_max_iterations(self, value: int) -> None:
- self.__target.max_iterations = value
- self.__target.subagents.max_iterations = value
+ self.__target.set_runtime_max_iterations(value)
def set_context_window_tokens(self, value: int) -> LLMRuntime:
return self.__target.set_runtime_context_window(value)
@@ -265,30 +258,6 @@ def _snapshot_exec_config(config: ExecToolConfig) -> dict[str, object]:
}
-def _snapshot_subagent_statuses(
- manager: SubagentManager,
-) -> dict[str, dict[str, object]]:
- return {
- task_id: _snapshot_subagent_status(status)
- for task_id, status in manager.statuses_for_session(current_request_session_key()).items()
- }
-
-
-def _snapshot_subagent_status(status: SubagentStatus) -> dict[str, object]:
- return {
- "task_id": status.task_id,
- "label": status.label,
- "task_description": status.task_description,
- "started_at": status.started_at,
- "phase": status.phase,
- "iteration": status.iteration,
- "tool_events": [dict(event) for event in status.tool_events],
- "usage": status.usage.to_dict() if status.usage is not None else None,
- "stop_reason": status.stop_reason,
- "error": status.error,
- }
-
-
def _snapshot_json_mapping(values: Mapping[str, JsonValue]) -> dict[str, JsonValue]:
return {key: _snapshot_json_value(value) for key, value in values.items()}
diff --git a/nanobot/agent/tools/self.py b/nanobot/agent/tools/self.py
index 63da627b5..d7723f4e8 100644
--- a/nanobot/agent/tools/self.py
+++ b/nanobot/agent/tools/self.py
@@ -5,7 +5,6 @@
from __future__ import annotations
-import time
from collections.abc import Mapping
from typing import TYPE_CHECKING, Any, TypeGuard, cast
@@ -23,7 +22,6 @@ from nanobot.agent.tools.runtime_control import (
from nanobot.config_base import Base
if TYPE_CHECKING:
- from nanobot.agent.subagent import SubagentStatus
from nanobot.agent.tools.context import ToolContext
@@ -33,21 +31,6 @@ class MyToolConfig(Base):
allow_set: bool = False
-def _is_subagent_status(value: object) -> TypeGuard[SubagentStatus]:
- from nanobot.agent.subagent import SubagentStatus
-
- return isinstance(value, SubagentStatus)
-
-
-def _is_subagent_status_snapshot(value: object) -> TypeGuard[Mapping[str, object]]:
- if not isinstance(value, Mapping):
- return False
- return all(
- field in value
- for field in ("task_id", "label", "task_description", "started_at", "phase")
- )
-
-
def _is_string_mapping(value: object) -> TypeGuard[Mapping[str, object]]:
if not isinstance(value, Mapping):
return False
@@ -83,7 +66,7 @@ class MyTool(Tool):
# Config management
"_runtime_vars",
# Subsystems
- "runner", "sessions", "consolidator",
+ "runner", "sessions", "consolidator", "subagents",
"dream", "auto_compact", "context", "commands",
# Sensitive runtime state (credentials, message routing, task tracking)
"_pending_queues",
@@ -94,7 +77,6 @@ class MyTool(Tool):
})
READ_ONLY = frozenset({
- "subagents", # observable but replacing it would break the system
"tool_names",
"exec_config", # inspect allowed (e.g. check sandbox), modify blocked
"web_config", # inspect allowed (e.g. check enable), modify blocked
@@ -247,89 +229,8 @@ class MyTool(Tool):
# Smart formatting
# ------------------------------------------------------------------
- @staticmethod
- def _format_status(
- st: "SubagentStatus | Mapping[str, object]",
- indent: str = " ",
- ) -> str:
- if isinstance(st, Mapping):
- started_at = st.get("started_at", time.monotonic())
- raw_events = st.get("tool_events", [])
- phase = st.get("phase", "unknown")
- iteration = st.get("iteration", 0)
- usage = st.get("usage", {})
- error = st.get("error")
- stop_reason = st.get("stop_reason")
- else:
- started_at = st.started_at
- raw_events = st.tool_events
- phase = st.phase
- iteration = st.iteration
- usage = st.usage
- error = st.error
- stop_reason = st.stop_reason
- elapsed = time.monotonic() - (
- float(started_at) if isinstance(started_at, (int, float)) else time.monotonic()
- )
- tool_events = cast(list[object], raw_events) if isinstance(raw_events, list) else []
- tool_summaries: list[str] = []
- for raw_event in tool_events[-5:]:
- if not isinstance(raw_event, Mapping):
- continue
- event = cast(Mapping[str, object], raw_event)
- tool_summaries.append(
- f"{event.get('name', '?')}({event.get('status', '?')})"
- )
- tool_summary = ", ".join(tool_summaries) or "none"
- lines = [
- f"{indent}phase: {phase}, iteration: {iteration}, elapsed: {elapsed:.1f}s",
- f"{indent}tools: {tool_summary}",
- f"{indent}usage: {usage or 'n/a'}",
- ]
- if error:
- lines.append(f"{indent}error: {error}")
- if stop_reason:
- lines.append(f"{indent}stop_reason: {stop_reason}")
- return "\n".join(lines)
-
@staticmethod
def _format_value(val: Any, key: str = "") -> str:
- if _is_subagent_status(val):
- header = f"Subagent [{val.task_id}] '{val.label}'"
- detail = MyTool._format_status(val, " ")
- return f"{header}\n task: {val.task_description}\n{detail}"
- if _is_subagent_status_snapshot(val):
- header = f"Subagent [{val['task_id']}] '{val['label']}'"
- detail = MyTool._format_status(val, " ")
- return f"{header}\n task: {val['task_description']}\n{detail}"
- if isinstance(val, Mapping):
- mapping = cast(Mapping[object, object], val)
- else:
- mapping = None
- if mapping and set(mapping) == {"_task_statuses"}:
- task_statuses = mapping["_task_statuses"]
- if isinstance(task_statuses, Mapping):
- return MyTool._format_value(task_statuses, key)
- if (
- mapping
- and (
- _is_subagent_status(next(iter(mapping.values())))
- or _is_subagent_status_snapshot(next(iter(mapping.values())))
- )
- ):
- prefix = f"{key}: " if key else ""
- lines = [f"{prefix}{len(mapping)} subagent(s):"]
- for tid, st in mapping.items():
- if _is_subagent_status(st):
- detail = MyTool._format_status(st, " ")
- label = st.label
- elif _is_subagent_status_snapshot(st):
- detail = MyTool._format_status(st, " ")
- label = st.get("label", "?")
- else:
- continue
- lines.append(f" [{tid}] '{label}'\n{detail}")
- return "\n".join(lines)
# Scalar types — repr is fine
if isinstance(val, (str, int, float, bool, type(None))):
r = repr(val)
@@ -393,10 +294,6 @@ class MyTool(Tool):
def _inspect(self, key: str | None) -> str:
if not key:
return self._inspect_all()
- if key == "subagents" or key.startswith("subagents."):
- request_ctx = current_request_context()
- if request_ctx is None or not request_ctx.session_key:
- return ToolResult.error("Error: current session context is unavailable")
if key == "request" or key.startswith("request."):
request_ctx = current_request_context()
if request_ctx is None:
@@ -451,7 +348,6 @@ class MyTool(Tool):
"max_tool_result_chars",
"web_config",
"exec_config",
- "subagents",
):
parts.append(self._format_value(values[k], k))
if snapshot.scratchpad:
diff --git a/nanobot/agent/tools/spawn.py b/nanobot/agent/tools/spawn.py
deleted file mode 100644
index 8d5581c6a..000000000
--- a/nanobot/agent/tools/spawn.py
+++ /dev/null
@@ -1,107 +0,0 @@
-"""Spawn tool for creating background subagents."""
-
-# pyright: reportIncompatibleMethodOverride=false
-
-from __future__ import annotations
-
-from typing import TYPE_CHECKING, Any
-
-from nanobot.agent.tools.base import Tool, ToolResult, tool_parameters
-from nanobot.agent.tools.context import current_request_context
-from nanobot.agent.tools.schema import (
- BooleanSchema,
- NumberSchema,
- StringSchema,
- tool_parameters_schema,
-)
-from nanobot.security.workspace_access import current_workspace_scope
-
-if TYPE_CHECKING:
- from nanobot.agent.subagent import SubagentManager
- from nanobot.agent.tools.context import ToolContext
-
-
-@tool_parameters(
- tool_parameters_schema(
- task=StringSchema("The task for the subagent to complete"),
- label=StringSchema("Optional short label for the task (for display)"),
- temperature=NumberSchema(
- description=(
- "Optional sampling temperature for the subagent "
- "(0.0 = deterministic, higher = more creative). "
- "Defaults to the provider's configured temperature."
- ),
- minimum=0.0,
- maximum=2.0,
- ),
- wait=BooleanSchema(
- description=(
- "Wait for the subagent and return its result directly. Use this for a "
- "blocking consultation that must inform the current turn. Defaults to "
- "false for background execution."
- ),
- default=False,
- ),
- required=["task"],
- )
-)
-class SpawnTool(Tool):
- """Tool to spawn a subagent for background task execution."""
-
- def __init__(self, manager: "SubagentManager"):
- self._manager = manager
-
- @classmethod
- def create(cls, ctx: ToolContext) -> Tool:
- manager = ctx.subagent_manager
- if manager is None:
- raise RuntimeError("SpawnTool requires an initialized subagent manager")
- return cls(manager=manager)
-
- @property
- def name(self) -> str:
- return "spawn"
-
- @property
- def description(self) -> str:
- return (
- "Spawn a subagent to handle a task in the background. "
- "Use this for complex or time-consuming tasks that can run independently. "
- "Set wait=true for a consultation whose result must inform the current turn. "
- "The subagent will complete the task and report back when done. "
- "For deliverables or existing projects, inspect the workspace first "
- "and use a dedicated subdirectory when helpful."
- )
-
- @property
- def concurrency_safe(self) -> bool:
- """Each call owns its task state; the manager serializes capacity admission."""
- return True
-
- async def execute(
- self,
- task: str,
- label: str | None = None,
- temperature: float | None = None,
- wait: bool = False,
- **kwargs: Any,
- ) -> str:
- """Spawn a subagent to execute the given task."""
- request_ctx = current_request_context()
- if request_ctx is None or request_ctx.runtime is None:
- return ToolResult.error("Error: spawn requires an active model runtime")
- origin_channel = request_ctx.channel
- origin_chat_id = request_ctx.chat_id
- session_key = request_ctx.session_key or f"{origin_channel}:{origin_chat_id}"
- method = self._manager.run_inline if wait else self._manager.spawn
- return await method(
- task=task,
- runtime=request_ctx.runtime,
- label=label,
- origin_channel=origin_channel,
- origin_chat_id=origin_chat_id,
- session_key=session_key,
- origin_message_id=request_ctx.message_id,
- temperature=temperature,
- workspace_scope=current_workspace_scope(),
- )
diff --git a/nanobot/agent/tools/subagent.py b/nanobot/agent/tools/subagent.py
new file mode 100644
index 000000000..6abbed832
--- /dev/null
+++ b/nanobot/agent/tools/subagent.py
@@ -0,0 +1,155 @@
+"""Tool for creating, messaging, cancelling, and inspecting session-owned tasks."""
+
+# pyright: reportIncompatibleMethodOverride=false
+
+from __future__ import annotations
+
+import json
+from typing import TYPE_CHECKING, Any
+
+from nanobot.agent.subagent import SubagentControlError
+from nanobot.agent.tools.base import Tool, ToolResult, tool_parameters
+from nanobot.agent.tools.context import current_request_context, current_request_session_key
+from nanobot.agent.tools.schema import (
+ BooleanSchema,
+ NumberSchema,
+ StringSchema,
+ tool_parameters_schema,
+)
+from nanobot.security.workspace_access import current_workspace_scope
+from nanobot.session.manager import SessionPolicy
+
+if TYPE_CHECKING:
+ from nanobot.agent.subagent import SubagentManager
+ from nanobot.agent.tools.context import ToolContext
+
+
+@tool_parameters(tool_parameters_schema(
+ action=StringSchema(
+ "create starts a task; send queues a message; cancel requests an idempotent stop; "
+ "check returns task status, receipts, and results.",
+ enum=("create", "send", "cancel", "check"),
+ ),
+ task=StringSchema("Required for create: the task for the subagent to complete.", min_length=1),
+ label=StringSchema("Optional short label for create (for display)."),
+ temperature=NumberSchema(
+ description="Optional sampling temperature for create. Defaults to the parent's model runtime.",
+ minimum=0.0,
+ maximum=2.0,
+ ),
+ wait=BooleanSchema(
+ description=(
+ "For create: wait for the result directly when it must inform the current turn. "
+ "Defaults to false for background execution with a completion notification. "
+ "Ephemeral requests and hosts without a background consumer always wait."
+ ),
+ default=False,
+ ),
+ task_id=StringSchema(
+ "Full task ID returned by create. Required for send/cancel; optional for check. "
+ "Omit for check to list the current session's active and recently finished tasks.",
+ min_length=1,
+ ),
+ message=StringSchema(
+ "Required for send: text, at most 8192 UTF-8 bytes. Accepted means queued, not delivered. "
+ "Delivery receipts mean injected into the task transcript, not that the task acted on the message.",
+ max_length=8192,
+ ),
+ required=["action"],
+))
+class SubagentTool(Tool):
+ """Manage the current session's private subagent tasks."""
+
+ def __init__(self, manager: SubagentManager):
+ self._manager = manager
+
+ @classmethod
+ def create(cls, ctx: ToolContext) -> Tool:
+ if ctx.subagent_manager is None:
+ raise RuntimeError("SubagentTool requires an initialized subagent manager")
+ return cls(ctx.subagent_manager)
+
+ @property
+ def name(self) -> str:
+ return "subagent"
+
+ @property
+ def description(self) -> str:
+ return (
+ "Create, message, cancel, or check your session's private subagent tasks. "
+ "Use create for independent work; set wait=true for a blocking consultation. "
+ "Use send for follow-up instructions, cancel to stop one task, and check to read "
+ "progress, message receipts, and results. Check without task_id lists active and recent tasks; "
+ "use a known task_id to read an older result. "
+ "Background results arrive automatically; do not repeatedly poll check while waiting. "
+ "A partial result or iteration limit does not mean the task completed. "
+ "For deliverables or existing projects, inspect the workspace first "
+ "and use a dedicated subdirectory when helpful."
+ )
+
+ @property
+ def concurrency_safe(self) -> bool:
+ return True
+
+ async def execute(
+ self, action: str, task_id: str | None = None, message: str | None = None,
+ task: str | None = None, label: str | None = None,
+ temperature: float | None = None, wait: bool = False, **kwargs: Any,
+ ) -> str:
+ if action == "create":
+ if not task or not task.strip():
+ return ToolResult.error("Error: create requires a non-empty task")
+ return await self._create_task(task, label, temperature, wait)
+ owner = current_request_session_key()
+ try:
+ if action == "check":
+ if not owner:
+ raise SubagentControlError("task unavailable")
+ if task_id is not None:
+ return json.dumps(self._manager.check(task_id, owner).as_dict(), ensure_ascii=False)
+ return json.dumps({
+ "tasks": [status.as_dict()
+ for status in self._manager.statuses_for_session(owner, include_history=False).values()],
+ }, ensure_ascii=False)
+ if action in {"send", "cancel"}:
+ if not task_id:
+ return ToolResult.error(f"Error: {action} requires task_id")
+ if action == "send":
+ return json.dumps(self._manager.send(task_id, owner, message))
+ status = await self._manager.cancel(task_id, owner)
+ return json.dumps(status.as_dict(), ensure_ascii=False)
+ return ToolResult.error("Error: unknown subagent action")
+ except SubagentControlError as exc:
+ return ToolResult.error(f"Error: {exc}")
+
+ async def _create_task(
+ self, task: str, label: str | None, temperature: float | None, wait: bool,
+ ) -> str:
+ request_ctx = current_request_context()
+ if request_ctx is None or request_ctx.runtime is None:
+ return ToolResult.error("Error: create requires an active model runtime")
+ origin_channel = request_ctx.channel
+ origin_chat_id = request_ctx.chat_id
+ session_key = request_ctx.session_key or (
+ f"{origin_channel}:{origin_chat_id}" if origin_channel and origin_chat_id else None
+ )
+ if not session_key:
+ return ToolResult.error("Error: create requires an active session identity")
+ inline = wait or not request_ctx.can_receive_background_results or not request_ctx.persist_session
+ method = self._manager.run_inline if inline else self._manager.spawn
+ return await method(
+ task=task,
+ runtime=request_ctx.runtime,
+ label=label,
+ origin_channel=origin_channel,
+ origin_chat_id=origin_chat_id,
+ session_key=session_key,
+ origin_message_id=request_ctx.message_id,
+ origin_turn_id=request_ctx.turn_id,
+ temperature=temperature,
+ workspace_scope=current_workspace_scope(),
+ session_policy=SessionPolicy(
+ persist=request_ctx.persist_session,
+ log_content=request_ctx.log_content,
+ ),
+ )
diff --git a/nanobot/agent/turn_delivery.py b/nanobot/agent/turn_delivery.py
index 328e98d97..e8d274140 100644
--- a/nanobot/agent/turn_delivery.py
+++ b/nanobot/agent/turn_delivery.py
@@ -47,6 +47,8 @@ class TurnRoute:
chat_id: str
metadata: dict[str, Any] = field(default_factory=dict)
publish_lifecycle: bool = False
+ # Public turn identity supplied by the owning channel adapter.
+ turn_id: str | None = None
TurnRoutePolicy = Callable[[InboundMessage, str, TurnRoute], TurnRoute]
diff --git a/nanobot/bus/queue.py b/nanobot/bus/queue.py
index 16b4b129f..eee2a1923 100644
--- a/nanobot/bus/queue.py
+++ b/nanobot/bus/queue.py
@@ -145,4 +145,6 @@ class MessageBus:
async def drain(self) -> None:
"""Finish scheduled dispatches after producers stop, before disconnecting."""
while self._pending:
- await asyncio.gather(*self._pending, return_exceptions=True)
+ pending = tuple(self._pending)
+ await asyncio.gather(*pending, return_exceptions=True)
+ self._pending.difference_update(pending)
diff --git a/nanobot/bus/runtime_events.py b/nanobot/bus/runtime_events.py
index 2d532240d..2cb9b1922 100644
--- a/nanobot/bus/runtime_events.py
+++ b/nanobot/bus/runtime_events.py
@@ -90,6 +90,14 @@ class GoalStateChanged(AgentEvent):
session_metadata: dict[str, Any] = field(default_factory=dict)
+@dataclass(frozen=True)
+class SubagentTaskChanged(AgentEvent):
+ """A parent-owned task observation changed."""
+
+ context: RuntimeEventContext
+ task_id: str
+
+
@dataclass(frozen=True)
class RuntimeModelChanged(AgentEvent):
"""The active runtime model/preset changed."""
diff --git a/nanobot/channels/manager.py b/nanobot/channels/manager.py
index dddb5a646..a5bb0b73f 100644
--- a/nanobot/channels/manager.py
+++ b/nanobot/channels/manager.py
@@ -41,6 +41,7 @@ from nanobot.utils.restart import (
)
if TYPE_CHECKING:
+ from nanobot.agent.subagent import SubagentManager
from nanobot.cron.service import CronService
from nanobot.session.manager import SessionManager
from nanobot.triggers.local_store import LocalTriggerStore
@@ -111,6 +112,8 @@ class ChannelManager:
webui_recovery_action: (
Callable[[str, dict[str, Any]], Awaitable[dict[str, Any]]] | None
) = None,
+ webui_subagent_manager: SubagentManager | None = None,
+ webui_discard_session: Callable[[str], Awaitable[None]] | None = None,
config_path: Path | None = None,
):
if config_path is None:
@@ -134,6 +137,8 @@ class ChannelManager:
self._webui_mcp_reload = webui_mcp_reload
self._webui_skill_state_action = webui_skill_state_action
self._webui_recovery_action = webui_recovery_action
+ self._webui_subagent_manager = webui_subagent_manager
+ self._webui_discard_session = webui_discard_session
self.channels: dict[str, BaseChannel] = {}
self._channel_owners: dict[str, str] = {}
self._channel_runtime_specs: dict[str, tuple[str, str]] = {}
@@ -211,6 +216,8 @@ class ChannelManager:
mcp_reload=self._webui_mcp_reload,
skill_state_action=self._webui_skill_state_action,
recovery_action=self._webui_recovery_action,
+ subagent_manager=self._webui_subagent_manager,
+ discard_session=self._webui_discard_session,
logger=logger,
)
kwargs["gateway"] = gateway
diff --git a/nanobot/cli/gateway_runtime.py b/nanobot/cli/gateway_runtime.py
index b5a298a63..83a5f1ba9 100644
--- a/nanobot/cli/gateway_runtime.py
+++ b/nanobot/cli/gateway_runtime.py
@@ -735,6 +735,8 @@ def _run_gateway(
webui_mcp_reload=mcp_provider.reload,
webui_skill_state_action=_webui_skill_state_action,
webui_recovery_action=recovery.handle_action,
+ webui_subagent_manager=agent.subagents,
+ webui_discard_session=agent.discard_session,
config_path=Path(config_path),
)
@@ -1035,6 +1037,7 @@ def _run_gateway(
gateway_runtime.foreground_instance(gateway_start_options),
webui_turn_coordinator.connected(),
):
+ agent.subagents.recover_interrupted()
if health_server_enabled:
gateway_runtime.publish_health_host(config.gateway.host)
asyncio.run(run())
diff --git a/nanobot/sdk/runtime.py b/nanobot/sdk/runtime.py
index 663905c72..adb9bbda1 100644
--- a/nanobot/sdk/runtime.py
+++ b/nanobot/sdk/runtime.py
@@ -5,6 +5,8 @@ from __future__ import annotations
from collections.abc import Mapping
from typing import Any
+from nanobot.session.manager import SessionPolicy
+
def ensure_single_model_selector(
*,
@@ -39,6 +41,7 @@ def build_process_direct_kwargs(
if ephemeral:
kwargs["ephemeral"] = True
kwargs["_run_extra_hooks_for_ephemeral"] = True
+ kwargs["_session_policy"] = SessionPolicy(persist=False, log_content=False)
if attributes is not None:
kwargs["attributes"] = dict(attributes)
if on_stream is not None:
diff --git a/nanobot/session/history.py b/nanobot/session/history.py
index 3a7f4b981..f24289e60 100644
--- a/nanobot/session/history.py
+++ b/nanobot/session/history.py
@@ -95,6 +95,13 @@ class SessionHistoryReader:
key = row.get("key")
if not isinstance(key, str) or key == exclude_session_key:
continue
+ payload = self._sessions.read_session_metadata(key)
+ if payload is None:
+ continue
+ raw_metadata = cast(object, payload.get("metadata"))
+ metadata = cast(dict[str, Any], raw_metadata) if isinstance(raw_metadata, dict) else {}
+ if not self._sessions.types.public_history(metadata):
+ continue
title = _text(row.get("title"))
folded = title.casefold()
rank = (
@@ -139,6 +146,8 @@ class SessionHistoryReader:
return None
raw_metadata = cast(object, payload.get("metadata"))
metadata = cast(dict[str, Any], raw_metadata) if isinstance(raw_metadata, dict) else {}
+ if not self._sessions.types.public_history(metadata):
+ return None
updated = payload.get("updated_at")
return {
"session_key": session_key,
diff --git a/nanobot/session/manager.py b/nanobot/session/manager.py
index 8def6f41d..d0a54323f 100644
--- a/nanobot/session/manager.py
+++ b/nanobot/session/manager.py
@@ -30,6 +30,7 @@ from nanobot.runtime_context import (
from nanobot.session.history_visibility import HIDDEN_HISTORY_META, is_hidden_history_message
from nanobot.session.model_selection import SESSION_MODEL_PRESET_METADATA_KEY
from nanobot.session.summary import SUMMARY_CONTINUATION_TEXT, is_summary_checkpoint
+from nanobot.session.types import PARENT_SESSION_KEY, SESSION_TYPE_KEY, SessionTypes
from nanobot.utils.helpers import (
atomic_write_lines,
content_with_media_breadcrumbs,
@@ -59,6 +60,8 @@ _RUNTIME_CHECKPOINT_KEY = "runtime_checkpoint"
_RUNTIME_CHECKPOINT_VERSION = 1
_RUNTIME_CHECKPOINT_SUFFIX = ".checkpoint.json"
_FORK_VOLATILE_METADATA_KEYS = {
+ PARENT_SESSION_KEY,
+ SESSION_TYPE_KEY,
"goal_state",
"pending_user_turn",
"pending_user_followups",
@@ -170,9 +173,9 @@ class SessionPolicy:
@dataclass
class Session:
- """A conversation session."""
+ """Message history, runtime state, and metadata for one agent session."""
- key: str # channel:chat_id
+ key: str # namespace:identity
messages: list[dict[str, Any]] = field(default_factory=list)
created_at: datetime = field(default_factory=datetime.now)
updated_at: datetime = field(default_factory=datetime.now)
@@ -1534,6 +1537,7 @@ class SessionManager:
self._overflow_cache: WeakValueDictionary[str, Session] = WeakValueDictionary()
self._max_cached_sessions = SESSION_CACHE_MAX_SIZE
self._delete_observer: Callable[[str], None] | None = None
+ self.types = SessionTypes()
def _remember(self, session: Session) -> None:
"""Keep recent sessions strongly cached without duplicating live objects."""
@@ -1631,6 +1635,32 @@ class SessionManager:
self._remember(session)
return session
+ def get_existing(self, key: str) -> Session | None:
+ """Load an existing session without creating a deleted conversation."""
+ session = self._cached(key) or self._load(key)
+ if session is not None:
+ self._remember(session)
+ return session
+
+ def child_session_keys(self, parent_key: str) -> list[str]:
+ """Find persisted and active children through their declared parent."""
+ return [key for key, parent in self._session_parents().items() if parent == parent_key]
+
+ def _session_parents(self) -> dict[str, str]:
+ keys = {row["key"] for row in self.list_sessions()}
+ cached = {**self._overflow_cache, **self._cache}
+ keys.update(cached)
+ parents: dict[str, str] = {}
+ for key in sorted(keys):
+ session = cached.get(key)
+ metadata = session.metadata if session is not None else (
+ (self.read_session_metadata(key) or {}).get("metadata", {})
+ )
+ parent = metadata.get(PARENT_SESSION_KEY)
+ if isinstance(parent, str):
+ parents[key] = parent
+ return parents
+
def get_or_create_transient(
self,
key: str,
@@ -1741,12 +1771,28 @@ class SessionManager:
self._overflow_cache.pop(key, None)
def delete_session(self, key: str) -> bool:
- """Delete a persisted session and invalidate its cache entry."""
- self.invalidate(key)
- deleted = self._store.delete(key)
- if self._delete_observer is not None:
- self._delete_observer(key)
- return deleted
+ """Delete a session and its descendants, invalidating their cache entries."""
+ # Collect descendants before deletion; the common file lock also keeps
+ # handle allocation and child-session saves outside this boundary.
+ with self.locked_session_files():
+ children: dict[str, list[str]] = {}
+ for child, parent in self._session_parents().items():
+ children.setdefault(parent, []).append(child)
+ pending = [key]
+ collected: set[str] = set()
+ while pending:
+ current = pending.pop()
+ if current in collected:
+ continue
+ collected.add(current)
+ pending.extend(children.get(current, ()))
+ deleted = False
+ for current in collected:
+ self.invalidate(current)
+ deleted = self._store.delete(current) or deleted
+ if self._delete_observer is not None:
+ self._delete_observer(current)
+ return deleted
def restore_sessions_to_workspace(self) -> SessionRestoreResult:
"""Restore session files to the pre-relocation path for an explicit rollback."""
diff --git a/nanobot/session/session_handles.py b/nanobot/session/session_handles.py
index ec563b4bb..9cc6f01d6 100644
--- a/nanobot/session/session_handles.py
+++ b/nanobot/session/session_handles.py
@@ -172,6 +172,8 @@ class SessionHandleResolver:
if isinstance(raw_metadata, dict)
else {}
)
+ if not self._sessions.types.needs_handle(metadata):
+ continue
raw_name = metadata.get(SESSION_HANDLE_METADATA_KEY)
try:
name = normalize_session_handle(raw_name) if isinstance(raw_name, str) else ""
diff --git a/nanobot/session/types.py b/nanobot/session/types.py
new file mode 100644
index 000000000..e5c79ce2d
--- /dev/null
+++ b/nanobot/session/types.py
@@ -0,0 +1,46 @@
+"""Session kinds declare their public identity and history access."""
+
+from __future__ import annotations
+
+from collections.abc import Mapping
+from dataclasses import dataclass
+
+SESSION_TYPE_KEY = "session_type"
+PARENT_SESSION_KEY = "parent_session_key"
+
+
+@dataclass(frozen=True, slots=True)
+class SessionType:
+ name: str
+ needs_handle: bool
+ public_history: bool
+
+
+CONVERSATION = SessionType("conversation", needs_handle=True, public_history=True)
+
+
+class SessionTypes:
+ """Consume declarations from session owners without importing those owners."""
+
+ def __init__(self) -> None:
+ self._types: dict[str, SessionType] = {CONVERSATION.name: CONVERSATION}
+
+ def register(self, session_type: SessionType) -> None:
+ previous = self._types.get(session_type.name)
+ if previous is not None and previous != session_type:
+ raise ValueError(f"session type already registered: {session_type.name}")
+ self._types[session_type.name] = session_type
+
+ def resolve(self, metadata: Mapping[str, object]) -> SessionType | None:
+ # Legacy sessions are ordinary conversations. Explicit unknown kinds
+ # remain private until their owner registers the access contract.
+ name = metadata.get(SESSION_TYPE_KEY, CONVERSATION.name)
+ return self._types.get(name) if isinstance(name, str) else None
+
+ def needs_handle(self, metadata: Mapping[str, object]) -> bool:
+ kind = self.resolve(metadata)
+ return kind is not None and kind.needs_handle
+
+ def public_history(self, metadata: Mapping[str, object]) -> bool:
+ kind = self.resolve(metadata)
+ return kind is not None and kind.public_history
diff --git a/nanobot/session/webui_turns.py b/nanobot/session/webui_turns.py
index c8d79293d..aeedb90fe 100644
--- a/nanobot/session/webui_turns.py
+++ b/nanobot/session/webui_turns.py
@@ -31,6 +31,7 @@ from nanobot.bus.runtime_events import (
RuntimeEventContext,
RuntimeModelChanged,
SessionTurnStarted,
+ SubagentTaskChanged,
TurnCompleted,
TurnRunStatusChanged,
TurnRuntimeAdmitted,
@@ -55,7 +56,7 @@ from nanobot.webui.metadata import (
WEBSOCKET_TURN_OWNER_METADATA_KEY,
WEBUI_TURN_METADATA_KEY,
)
-from nanobot.webui.session_identity import is_webui_session_key
+from nanobot.webui.session_identity import is_webui_session_key, webui_session_key
from nanobot.webui.star_prompt import update_star_prompt
from nanobot.webui.transcript import append_session_message_input
@@ -502,7 +503,7 @@ class WebuiTurnRoutePolicy:
else uuid4().hex
)
metadata[WEBSOCKET_TURN_OWNER_METADATA_KEY] = owner
- routed = replace(routed, metadata=metadata)
+ routed = replace(routed, metadata=metadata, turn_id=current_turn_id)
# Direct websocket turns publish their final idle transition from
# the original input message. Carry the same server-owned identity
# there, overwriting any untrusted client-supplied value.
@@ -578,6 +579,7 @@ class WebuiTurnCoordinator:
self._handle_goal_state_changed,
GoalStateChanged,
),
+ self.bus.subscribe(self._handle_subagent_task_changed, SubagentTaskChanged),
self.bus.subscribe(
self._handle_runtime_model_changed,
RuntimeModelChanged,
@@ -734,6 +736,12 @@ class WebuiTurnCoordinator:
),
)
+ async def _handle_subagent_task_changed(self, event: SubagentTaskChanged) -> None:
+ ctx = event.context
+ if not self._is_websocket_event(ctx) or ctx.session_key != webui_session_key(ctx.chat_id):
+ return
+ await self.bus.publish_event(event, channel=ctx.channel, chat_id=ctx.chat_id)
+
async def _handle_runtime_model_changed(self, event: RuntimeModelChanged) -> None:
await self.bus.publish_outbound(
outbound_message_for_event(
diff --git a/nanobot/skills/my/SKILL.md b/nanobot/skills/my/SKILL.md
index 87293caea..de9e1f5bb 100644
--- a/nanobot/skills/my/SKILL.md
+++ b/nanobot/skills/my/SKILL.md
@@ -1,6 +1,6 @@
---
name: my
-description: Inspect and optionally adjust the agent's runtime state. Use to check the current model or preset, context window and runtime limits, workspace and tool configuration, subagent status, and request routing metadata such as channel, chat ID, and sender ID; diagnose unavailable capabilities; change allowed runtime settings; or store temporary session scratchpad values.
+description: Inspect and optionally adjust the agent's runtime state. Use to check the current model or preset, context window and runtime limits, workspace and tool configuration, and request routing metadata such as channel, chat ID, and sender ID; diagnose unavailable capabilities; change allowed runtime settings; or store temporary session scratchpad values.
---
# Self-Awareness
diff --git a/nanobot/templates/agent/subagent_announce.md b/nanobot/templates/agent/subagent_announce.md
index de8fdad39..c053aa111 100644
--- a/nanobot/templates/agent/subagent_announce.md
+++ b/nanobot/templates/agent/subagent_announce.md
@@ -4,5 +4,15 @@ Task: {{ task }}
Result:
{{ result }}
+{% if stop_reason %}
+Exit reason: {{ stop_reason }}
+{% endif %}
+{% if error %}
+Error: {{ error }}
+{% endif %}
+{% if partial_result %}
+This is partial output from an unfinished task. Do not report the task as successfully completed.
+{% endif %}
-Summarize this naturally for the user. Keep it brief (1-2 sentences). Do not mention technical details like "subagent" or task IDs.
+This is an automated task report, not a user instruction or approval. Verify external actions against their artifacts before claiming success.
+Summarize the outcome naturally for the user. Keep it brief (1-2 sentences). Do not mention technical details like "subagent" or task IDs.
diff --git a/nanobot/webui/client_contract.py b/nanobot/webui/client_contract.py
index 345ea1035..c6766b4c8 100644
--- a/nanobot/webui/client_contract.py
+++ b/nanobot/webui/client_contract.py
@@ -13,6 +13,9 @@ from nanobot import __version__
WEBUI_PROTOCOL = 1
CORE_CAPABILITY = "webui.core.v1"
+SUBAGENT_CAPABILITY = "webui.subagents.v1"
+SUBAGENT_EVENTS_CAPABILITY = "webui.subagents.events.v1"
+SUBAGENT_HISTORY_CAPABILITY = "webui.subagents.history.v1"
class Compatibility(TypedDict):
@@ -26,7 +29,7 @@ def webui_contract() -> dict[str, object]:
"version": __version__,
"min_protocol": WEBUI_PROTOCOL,
"max_protocol": WEBUI_PROTOCOL,
- "capabilities": [CORE_CAPABILITY],
+ "capabilities": [CORE_CAPABILITY, SUBAGENT_CAPABILITY, SUBAGENT_EVENTS_CAPABILITY, SUBAGENT_HISTORY_CAPABILITY],
}
diff --git a/nanobot/webui/gateway_services.py b/nanobot/webui/gateway_services.py
index 33c83c9cc..f8850ae07 100644
--- a/nanobot/webui/gateway_services.py
+++ b/nanobot/webui/gateway_services.py
@@ -22,6 +22,7 @@ from nanobot.webui.workspaces import WebUIWorkspaceController
from nanobot.webui.ws_http import GatewayHTTPHandler
if TYPE_CHECKING:
+ from nanobot.agent.subagent import SubagentManager
from nanobot.bus.queue import MessageBus
from nanobot.channels.websocket.runtime import WebSocketConfig
from nanobot.cron.service import CronService
@@ -74,6 +75,8 @@ def build_gateway_services(
mcp_reload: Callable[[], Awaitable[dict[str, Any]]] | None = None,
skill_state_action: Callable[[set[str]], None] | None = None,
recovery_action: Callable[[str, dict[str, Any]], Awaitable[dict[str, Any]]] | None = None,
+ subagent_manager: SubagentManager | None = None,
+ discard_session: Callable[[str], Awaitable[None]] | None = None,
logger: Any = default_logger,
) -> GatewayServices:
settings = WebUISettingsServices.create(
@@ -112,7 +115,7 @@ def build_gateway_services(
workspaces=workspaces,
logger=logger,
)
- session_projection = WebUISessionProjection(session_manager, log=logger)
+ session_projection = WebUISessionProjection(session_manager, subagent_manager=subagent_manager, log=logger)
http = GatewayHTTPHandler(
config=config,
session_manager=session_manager,
@@ -138,6 +141,8 @@ def build_gateway_services(
mcp_reload=mcp_reload,
skill_state_action=skill_state_action,
recovery_action=recovery_action,
+ subagent_manager=subagent_manager,
+ discard_session=discard_session,
log=logger,
)
endpoint = WebUIGatewayEndpoint(config=config, http=http, tokens=tokens)
diff --git a/nanobot/webui/outbound_projection.py b/nanobot/webui/outbound_projection.py
index cd5a57631..0d53dcc8c 100644
--- a/nanobot/webui/outbound_projection.py
+++ b/nanobot/webui/outbound_projection.py
@@ -20,6 +20,7 @@ from nanobot.bus.outbound_events import (
TurnModelUpdatedEvent,
UserInputEvent,
)
+from nanobot.bus.runtime_events import SubagentTaskChanged
from nanobot.session.webui_turns import clear_websocket_turn_if_current
from nanobot.webui.metadata import (
WEBSOCKET_TURN_OWNER_METADATA_KEY,
@@ -157,6 +158,7 @@ class WebUIOutboundProjector:
SessionUpdatedEvent,
GoalStatusEvent,
GoalStateSyncEvent,
+ SubagentTaskChanged,
ContextCompactionEvent,
)
log = (
@@ -244,6 +246,16 @@ class WebUIOutboundProjector:
)
await self._transport.send_session_updated(msg.chat_id, scope=session_update_scope)
return
+ if isinstance(event, SubagentTaskChanged):
+ if conns:
+ task = self._session_projection.subagent_task(webui_session_key(msg.chat_id), event.task_id)
+ if task is not None:
+ await self._transport.send_payload(
+ msg.chat_id,
+ {"event": "subagent_task", "chat_id": msg.chat_id, "task": task},
+ persistence="transient",
+ )
+ return
if isinstance(event, SessionUpdatedEvent):
if conns:
await self._transport.send_session_updated(msg.chat_id, scope=event.scope)
diff --git a/nanobot/webui/outbound_wire.py b/nanobot/webui/outbound_wire.py
index 7b7bbe75f..c693decb3 100644
--- a/nanobot/webui/outbound_wire.py
+++ b/nanobot/webui/outbound_wire.py
@@ -103,8 +103,14 @@ class ContextCompactionWirePayload(_ChatWirePayload):
phase: Literal["started", "succeeded", "failed", "cancelled"]
+class SubagentTaskWirePayload(_ChatWirePayload):
+ event: Literal["subagent_task"]
+ task: dict[str, object]
+
+
WebUIWirePayload: TypeAlias = (
RetryStatusWirePayload | ContextCompactionWirePayload | RecoveryStateWirePayload | TurnEndWirePayload
+ | SubagentTaskWirePayload
)
WebUIWirePersistence: TypeAlias = Literal[
"transient",
diff --git a/nanobot/webui/remote_proxy.py b/nanobot/webui/remote_proxy.py
index 34c787463..79b27d6df 100644
--- a/nanobot/webui/remote_proxy.py
+++ b/nanobot/webui/remote_proxy.py
@@ -259,7 +259,8 @@ class RemoteProxy:
"limits", "model_name", "runtime_surface", "runtime_capabilities",
) if key in data}
result.update(token=token, api_token=api_token, expires_in=ttl,
- terminal={"protocolVersion": 1, "gatewayId": self._gateway_id},
+ terminal={"protocolVersion": 1, "gatewayId": self._gateway_id,
+ "webui": terminal["webui"]},
ws_path=self._ws_path, ws_url=f"ws://127.0.0.1:{self.port}{self._ws_path}")
result["host_compatibility"] = report
return web.json_response(result, headers={"Cache-Control": "no-store"})
diff --git a/nanobot/webui/session_access.py b/nanobot/webui/session_access.py
index b0e8b5c39..70efa87ab 100644
--- a/nanobot/webui/session_access.py
+++ b/nanobot/webui/session_access.py
@@ -46,7 +46,10 @@ class WebuiSessionAccess:
) -> dict[str, Any] | None:
if session_key == exclude_session_key:
return None
- return self._sessions.read_session_metadata(session_key)
+ payload = self._sessions.read_session_metadata(session_key)
+ if payload is None or not self._sessions.types.public_history(_session_metadata(payload)):
+ return None
+ return payload
def normalize_mentions(
self,
diff --git a/nanobot/webui/session_list_index.py b/nanobot/webui/session_list_index.py
index e59a3aef3..96cd517b3 100644
--- a/nanobot/webui/session_list_index.py
+++ b/nanobot/webui/session_list_index.py
@@ -75,6 +75,11 @@ def list_webui_sessions(session_manager: SessionManager) -> list[dict[str, Any]]
_public_row(session_manager.sessions_dir, get_webui_dir(), row)
for row in rows
]
+ sessions = [
+ row for row in sessions if session_manager.types.public_history(
+ (session_manager.read_session_metadata(row["key"]) or {}).get("metadata", {})
+ )
+ ]
return sorted(sessions, key=lambda row: row.get("updated_at", ""), reverse=True)
diff --git a/nanobot/webui/session_projection.py b/nanobot/webui/session_projection.py
index d132d4394..9605d6884 100644
--- a/nanobot/webui/session_projection.py
+++ b/nanobot/webui/session_projection.py
@@ -2,16 +2,20 @@
from __future__ import annotations
-from typing import Any, Protocol, cast
+from typing import TYPE_CHECKING, Any, Protocol, cast
from loguru import logger as default_logger
+from nanobot.agent.subagent import SubagentControlError
from nanobot.providers.base import LLMUsage
from nanobot.session.goal_state import goal_state_ws_blob
from nanobot.session.model_selection import model_preset_from_metadata
from nanobot.session.recovery import recovery_state_from_metadata
from nanobot.session.webui_turns import websocket_turn_id, websocket_turn_wall_started_at
+if TYPE_CHECKING:
+ from nanobot.agent.subagent import SubagentManager
+
class SessionMetadataReader(Protocol):
"""Narrow persisted-session dependency used by WebUI projections."""
@@ -20,17 +24,28 @@ class SessionMetadataReader(Protocol):
class WebUISessionProjection:
- """Project persisted session metadata into stable WebUI protocol fields."""
+ """Project session metadata and owned child observations for WebUI clients."""
def __init__(
self,
sessions: SessionMetadataReader | None,
*,
+ subagent_manager: SubagentManager | None = None,
log: Any = default_logger,
) -> None:
self._sessions = sessions
+ self._subagents = subagent_manager
self._log = log
+ def subagent_task(self, session_key: str, task_id: str) -> dict[str, object] | None:
+ """Read the current public snapshot only while the parent still owns it."""
+ if self._subagents is None:
+ return None
+ try:
+ return self._subagents.check(task_id, session_key).as_dict()
+ except SubagentControlError:
+ return None
+
def attach_fields(self, session_key: str) -> dict[str, Any]:
"""Return the session runtime facts sent with an attach handshake."""
if self._sessions is None:
diff --git a/nanobot/webui/temporary_chats.py b/nanobot/webui/temporary_chats.py
index 4d40d6a50..9762dd557 100644
--- a/nanobot/webui/temporary_chats.py
+++ b/nanobot/webui/temporary_chats.py
@@ -20,7 +20,7 @@ from nanobot.webui.workspaces import WebUIWorkspaceController
_TEMPORARY_CHAT_DISABLED_TOOLS = frozenset({
"create_goal",
"update_goal",
- "spawn",
+ "subagent",
"cron",
})
_TEMPORARY_CHAT_COMMANDS = frozenset({"/model", "/stop"})
diff --git a/nanobot/webui/transcript.py b/nanobot/webui/transcript.py
index c1f9754f6..a272d4291 100644
--- a/nanobot/webui/transcript.py
+++ b/nanobot/webui/transcript.py
@@ -13,6 +13,7 @@ import threading
import time
import uuid
from dataclasses import dataclass
+from datetime import datetime
from pathlib import Path
from typing import Any, Callable, Mapping, NamedTuple, Sequence, cast
from urllib.parse import unquote, urlparse
@@ -23,9 +24,10 @@ from nanobot.config.paths import get_webui_dir
from nanobot.runtime_context import public_history_message
from nanobot.session.automation_turns import is_automation_kind
from nanobot.session.history_visibility import is_hidden_history_message
-from nanobot.session.manager import SessionManager
+from nanobot.session.manager import Session, SessionManager
from nanobot.utils.helpers import atomic_write_lines
from nanobot.webui.metadata import WEBUI_MESSAGE_SOURCE_METADATA_KEY, WEBUI_TURN_METADATA_KEY
+from nanobot.webui.outbound_wire import project_tool_events
from nanobot.webui.session_identity import webui_chat_id, webui_session_key
WEBUI_TRANSCRIPT_SCHEMA_VERSION = 3
@@ -1374,36 +1376,8 @@ def write_session_messages_as_transcript(
messages: list[dict[str, Any]],
) -> None:
"""Write a minimal WebUI transcript from already-truncated session messages."""
- target_chat_id = _chat_id_from_session_key(target_key)
- rows: list[dict[str, Any]] = []
- for msg in messages:
- if is_hidden_history_message(msg):
- continue
- msg = public_history_message(msg)
- role = msg.get("role")
- content = msg.get("content")
- text = content if isinstance(content, str) else ""
- if role == "user":
- row: dict[str, Any] = {"event": "user", "chat_id": target_chat_id, "text": text}
- media = msg.get("media")
- if isinstance(media, list) and media:
- row["media_paths"] = [
- str(p) for p in cast(list[Any], media) if isinstance(p, str) and p
- ]
- for key in ("cli_apps", "mcp_presets", "session_mentions"):
- value = msg.get(key)
- if isinstance(value, list) and value:
- row[key] = json.loads(json.dumps(value, ensure_ascii=False))
- elif role == "assistant" and text.strip():
- row = {"event": "message", "chat_id": target_chat_id, "text": text}
- media = msg.get("media")
- if isinstance(media, list) and media:
- row["media"] = [
- str(p) for p in cast(list[Any], media) if isinstance(p, str) and p
- ]
- else:
- continue
- rows.append(row)
+ rows = [row for msg in messages
+ if (row := _session_user_event(target_key, msg) or _session_assistant_event(target_key, msg)) is not None]
_write_transcript_lines(target_key, rows)
@@ -2448,6 +2422,76 @@ def _client_projection_events(
return events, fork_boundary_event_index
+def build_session_thread_response(
+ session: Session,
+ *,
+ active: bool = False,
+ latency_ms: int | None = None,
+ augment_user_media: Callable[[list[str]], list[dict[str, Any]]] | None = None,
+ augment_assistant_media: Callable[[list[str]], list[dict[str, Any]]] | None = None,
+ augment_assistant_text: Callable[[str], str] | None = None,
+) -> dict[str, Any]:
+ """Project a Session snapshot without creating a second display transcript."""
+ rows: list[dict[str, Any]] = []
+ chat_id = session.key.split(":", 1)[-1]
+ turn_id = f"session:{session.key}:0"
+ created_at_ms = int(session.created_at.timestamp() * 1000)
+ for index, message in enumerate(session.messages):
+ if is_hidden_history_message(message):
+ continue
+ if message.get("role") == "user":
+ turn_id = f"session:{session.key}:{index}"
+ timestamp = message.get("timestamp")
+ if isinstance(timestamp, str):
+ try:
+ created_at_ms = int(datetime.fromisoformat(timestamp).timestamp() * 1000)
+ except ValueError:
+ pass
+ records: list[dict[str, Any]] = []
+ row = _session_user_event(session.key, message) or _session_assistant_event(session.key, message)
+ reasoning = message.get("reasoning_content")
+ if message.get("role") == "assistant" and isinstance(reasoning, str) and reasoning:
+ records.append({"event": "message", "text": reasoning, "kind": "reasoning"})
+ calls = message.get("tool_calls")
+ has_calls = isinstance(calls, list) and len(cast(list[object], calls)) > 0
+ if row is not None and has_calls:
+ row["kind"] = "progress"
+ records.append(row)
+ if message.get("role") == "assistant":
+ tools = project_tool_events(_normalize_tool_events(message.get("tool_events")))
+ if tools:
+ records.append({"event": "message", "kind": "tool_hint",
+ "text": "\n".join(tool_trace_lines_from_events(tools)),
+ "tool_events": tools})
+ edits = message.get("file_edit_events")
+ if isinstance(edits, list) and edits:
+ records.append({"event": "file_edit", "edits": edits})
+ if row is not None and not has_calls:
+ records.append(row)
+ for offset, record in enumerate(records):
+ record.update({
+ "chat_id": chat_id, "turn_id": turn_id,
+ "turn_phase": "user" if record["event"] == "user" else
+ "reasoning" if record.get("kind") == "reasoning" else
+ "activity" if record["event"] == "file_edit" or record.get("kind") in {"progress", "tool_hint"}
+ else "answer",
+ "created_at_ms": created_at_ms,
+ _WEBUI_REPLAY_IDENTITY_KEY: f"session:{session.key}:{index}:{offset}",
+ })
+ rows.append(record)
+ if not active and rows:
+ rows.append({"event": "turn_end", "chat_id": chat_id,
+ "turn_id": turn_id, "latency_ms": latency_ms,
+ _WEBUI_REPLAY_IDENTITY_KEY: f"session:{session.key}:end"})
+ events = [event for record in rows if (event := _client_projection_event(
+ record, augment_user_media=augment_user_media, augment_assistant_media=augment_assistant_media,
+ augment_assistant_text=augment_assistant_text,
+ )) is not None]
+ return {"schemaVersion": WEBUI_TRANSCRIPT_SCHEMA_VERSION, "sessionKey": session.key,
+ "projection": "events", "events": events,
+ "active_turn_id": turn_id if active else None}
+
+
def build_webui_thread_response(
session_key: str,
*,
diff --git a/nanobot/webui/ws_http.py b/nanobot/webui/ws_http.py
index b80d0879b..987a69b90 100644
--- a/nanobot/webui/ws_http.py
+++ b/nanobot/webui/ws_http.py
@@ -26,6 +26,8 @@ from websockets.datastructures import Headers
from websockets.http11 import Request as WsRequest
from websockets.http11 import Response
+from nanobot.agent.subagent import SubagentControlError
+from nanobot.agent.subagent_status import SubagentSessionError
from nanobot.command.builtin import builtin_command_palette
from nanobot.cron.session_turns import is_bound_cron_job
from nanobot.cron.types import CronJob, CronSchedule
@@ -131,6 +133,7 @@ from nanobot.webui.star_prompt import update_star_prompt
from nanobot.webui.thread_disk import delete_webui_thread
from nanobot.webui.transcript import (
TranscriptReplayStats,
+ build_session_thread_response,
build_webui_thread_response,
build_webui_trace_detail_response,
webui_transcript_revision,
@@ -193,6 +196,7 @@ _WEBUI_MUTATION_PATHS = {
"workspace.pick_folder": "/api/workspaces/pick-folder",
"recovery.continue": "/api/webui/recovery/continue",
"recovery.dismiss": "/api/webui/recovery/dismiss",
+ "subagent.cancel": "/api/webui/subagents/cancel",
"settings.agent.update": "/api/settings/update",
"settings.model_configuration.create": "/api/settings/model-configurations/create",
"settings.model_configuration.update": "/api/settings/model-configurations/update",
@@ -266,6 +270,7 @@ for _ext, _ctype in _MIME_FIXES.items():
if TYPE_CHECKING:
+ from nanobot.agent.subagent import SubagentManager
from nanobot.bus.queue import MessageBus
from nanobot.channels.websocket.runtime import WebSocketConfig
from nanobot.cron.service import CronService
@@ -375,6 +380,8 @@ class GatewayHTTPHandler:
recovery_action: (
Callable[[str, dict[str, Any]], Awaitable[dict[str, Any]]] | None
) = None,
+ subagent_manager: SubagentManager | None = None,
+ discard_session: Callable[[str], Awaitable[None]] | None = None,
log: Any = logger,
) -> None:
self.config = config
@@ -398,6 +405,8 @@ class GatewayHTTPHandler:
)
self.skill_state_action = skill_state_action
self.recovery_action = recovery_action
+ self.subagent_manager = subagent_manager
+ self.discard_session = discard_session
self._skill_install_lock = asyncio.Lock()
self._folder_picker_lock = asyncio.Lock()
self.cron_service = cron_service
@@ -550,6 +559,7 @@ class GatewayHTTPHandler:
"/api/webui/star-prompt/dismiss",
"/api/webui/sidebar-state/update",
"/api/workspaces/pick-folder",
+ "/api/webui/subagents/cancel",
}
@staticmethod
@@ -606,6 +616,9 @@ class GatewayHTTPHandler:
if response is not None:
return response
+ if got == "/api/webui/subagents/cancel":
+ return await self._handle_subagent_cancel(request)
+
# Session routes
response = await self._dispatch_session_routes(request, got)
if response is not None:
@@ -756,6 +769,7 @@ class GatewayHTTPHandler:
),
"runtime_surface": self._runtime_surface,
"runtime_capabilities": self._capabilities,
+ "terminal": terminal,
}
return _http_json_response(payload, extra_headers=_NO_STORE_HEADERS)
@@ -845,9 +859,17 @@ class GatewayHTTPHandler:
if m:
return self._handle_session_automations(request, m.group(1))
+ m = re.fullmatch(r"/api/sessions/([^/]+)/subagents/([^/]+)/webui-thread", got)
+ if m:
+ return await asyncio.to_thread(self._handle_subagent_thread_get, request, m.group(1), m.group(2))
+
+ m = re.fullmatch(r"/api/sessions/([^/]+)/subagents", got)
+ if m:
+ return self._handle_subagents_get(request, m.group(1))
+
m = re.match(r"^/api/sessions/([^/]+)/delete$", got)
if m:
- return self._handle_session_delete(request, m.group(1))
+ return await self._handle_session_delete(request, m.group(1))
return None
@@ -872,6 +894,75 @@ class GatewayHTTPHandler:
return _http_error(exc.status, str(exc))
return _http_json_response(result)
+ def _handle_subagents_get(self, request: WsRequest, key: str) -> Response:
+ if not self.check_api_token(request):
+ return _http_error(401, "Unauthorized")
+ session_key = _decode_api_key(key)
+ if session_key is None:
+ return _http_error(400, "invalid session key")
+ if not is_webui_session_key(session_key):
+ return _http_error(404, "session not found")
+ if self.subagent_manager is None:
+ return _http_error(503, "subagent manager unavailable")
+ try:
+ statuses = self.subagent_manager.statuses_for_session(session_key)
+ except (OSError, SubagentSessionError):
+ return _http_error(503, "task history unavailable")
+ return _http_json_response({
+ "tasks": [status.as_dict() for status in statuses.values()],
+ }, extra_headers=_NO_STORE_HEADERS)
+
+ async def _handle_subagent_cancel(self, request: WsRequest) -> Response:
+ if not getattr(request, _WEBUI_MUTATION_REQUEST_ATTR, False):
+ return _http_error(405, "Subagent cancellation requires an authenticated WebSocket")
+ if self.subagent_manager is None:
+ return _http_error(503, "subagent manager unavailable")
+ payload = _mutation_payload(request)
+ if payload is None:
+ return _http_error(400, "invalid subagent cancellation payload")
+ session_key, task_id = payload.get("session_key"), payload.get("task_id")
+ if not isinstance(session_key, str) or not is_webui_session_key(session_key):
+ return _http_error(400, "invalid session key")
+ if not isinstance(task_id, str) or not task_id.strip():
+ return _http_error(400, "missing task id")
+ try:
+ status = await self.subagent_manager.cancel(task_id, session_key)
+ except SubagentControlError:
+ return _http_error(404, "task unavailable")
+ except (OSError, SubagentSessionError):
+ return _http_error(503, "task history unavailable")
+ return _http_json_response(status.as_dict(), extra_headers=_NO_STORE_HEADERS)
+
+ def _handle_subagent_thread_get(self, request: WsRequest, key: str, task_id: str) -> Response:
+ if not self.check_api_token(request):
+ return _http_error(401, "Unauthorized")
+ session_key, decoded_task_id = _decode_api_key(key), _decode_api_key(task_id)
+ if session_key is None or decoded_task_id is None:
+ return _http_error(400, "invalid task key")
+ if not is_webui_session_key(session_key):
+ return _http_error(404, "task unavailable")
+ if self.subagent_manager is None:
+ return _http_error(503, "task history unavailable")
+ try:
+ status, child = self.subagent_manager.read_session(decoded_task_id, session_key)
+ except SubagentControlError:
+ return _http_error(404, "task unavailable")
+ except (OSError, SubagentSessionError):
+ return _http_error(503, "task history unavailable")
+ scope = self.workspaces.scope_for_session_key(session_key)
+ data = build_session_thread_response(
+ child,
+ active=status.state in {"queued", "running", "stopping"},
+ latency_ms=(int(max(0.0, status.finished_at - status.started_at) * 1000)
+ if status.finished_at is not None else None),
+ augment_user_media=self.media.augment_transcript_media,
+ augment_assistant_media=self.media.augment_transcript_media,
+ augment_assistant_text=lambda text: self.media.rewrite_local_markdown_images(
+ text, workspace_path=scope.project_path,
+ ),
+ )
+ return _http_json_response(data, extra_headers=_NO_STORE_HEADERS)
+
async def _handle_session_context_get(self, request: WsRequest, key: str) -> Response:
if not self.check_api_token(request):
return _http_error(401, "Unauthorized")
@@ -1214,7 +1305,7 @@ class GatewayHTTPHandler:
)
)
- def _handle_session_delete(self, request: WsRequest, key: str) -> Response:
+ async def _handle_session_delete(self, request: WsRequest, key: str) -> Response:
if not self.check_api_token(request):
return _http_error(401, "Unauthorized")
if self.session_manager is None:
@@ -1247,6 +1338,10 @@ class GatewayHTTPHandler:
elif self.cron_service is not None:
self.cron_service.remove_job(job.id)
draft_deleted = self.workspaces.discard_draft_scope(decoded_key)
+ if self.discard_session is not None:
+ await self.discard_session(decoded_key)
+ elif self.subagent_manager is not None:
+ await self.subagent_manager.cancel_by_session(decoded_key)
session_deleted = self.session_manager.delete_session(decoded_key)
transcript_deleted = delete_webui_thread(decoded_key)
return _http_json_response(
diff --git a/tests/agent/session_helpers.py b/tests/agent/session_helpers.py
index 21f034251..d0088ad97 100644
--- a/tests/agent/session_helpers.py
+++ b/tests/agent/session_helpers.py
@@ -1,11 +1,24 @@
"""Session-worker completion helpers for integration tests."""
import asyncio
+import time
from nanobot.agent.loop import AgentLoop
+from nanobot.agent.subagent_status import SubagentStatus
from nanobot.bus.events import InboundMessage
+def save_completed_subagent(loop: AgentLoop, task_id: str, owner: str) -> None:
+ """Persist the child that owns a synthetic completion notification."""
+ assert loop.subagents.sessions is not None
+ now = time.monotonic()
+ loop.subagents.sessions.create(SubagentStatus(
+ task_id=task_id, label=task_id, task_description="Background work",
+ owner=owner, started_at=now, finished_at=now, completed_at=time.time(),
+ state="done", phase="done",
+ ))
+
+
async def run_session(loop: AgentLoop, msg: InboundMessage) -> None:
"""Submit input and wait for its session worker to finish."""
loop._enqueue_session_message(msg)
diff --git a/tests/agent/test_loop_progress.py b/tests/agent/test_loop_progress.py
index ce7d0a5ac..a4cb48c77 100644
--- a/tests/agent/test_loop_progress.py
+++ b/tests/agent/test_loop_progress.py
@@ -6,7 +6,7 @@ from unittest.mock import AsyncMock, MagicMock
import pytest
-from agent.session_helpers import run_session
+from agent.session_helpers import run_session, save_completed_subagent
from nanobot.agent.context import TranscriptInput
from nanobot.agent.hooks import create_file_edit_activity_hook
from nanobot.agent.loop import AgentLoop
@@ -869,6 +869,7 @@ class TestToolEventProgress:
session.add_message("user", "Run this in the background")
session.metadata.update({"webui": True, "title": "Existing title"})
loop.sessions.save(session)
+ save_completed_subagent(loop, "sub-1", session_key)
dispatch = asyncio.create_task(run_session(loop, InboundMessage(
channel="system",
sender_id="subagent",
diff --git a/tests/agent/test_loop_runner_integration.py b/tests/agent/test_loop_runner_integration.py
index 1112aebb2..b215c5805 100644
--- a/tests/agent/test_loop_runner_integration.py
+++ b/tests/agent/test_loop_runner_integration.py
@@ -2,7 +2,7 @@
from __future__ import annotations
-import time
+import asyncio
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
@@ -640,8 +640,8 @@ async def test_next_turn_after_llm_error_keeps_turn_boundary(tmp_path):
@pytest.mark.asyncio
-async def test_subagent_max_iterations_announces_existing_fallback(tmp_path, monkeypatch):
- from nanobot.agent.subagent import SubagentManager, SubagentStatus
+async def test_subagent_max_iterations_announces_partial_incomplete_result(tmp_path, monkeypatch):
+ from nanobot.agent.subagent import SubagentManager
from nanobot.bus.queue import MessageBus
bus = MessageBus()
@@ -658,24 +658,28 @@ async def test_subagent_max_iterations_announces_existing_fallback(tmp_path, mon
consolidator=MagicMock(),
max_iterations=2,
)
- mgr._announce_result = AsyncMock()
async def fake_execute(self, **kwargs):
return "tool result"
monkeypatch.setattr("nanobot.agent.tools.filesystem.ListDirTool.execute", fake_execute)
- status = SubagentStatus(task_id="sub-1", label="label", task_description="do task", started_at=time.monotonic())
- await mgr._run_subagent(
- "sub-1",
- "do task",
- "label",
- {"channel": "test", "chat_id": "c1"},
- status,
- LLMRuntime.capture(provider, "test-model", context_window_tokens=128_000),
+ await mgr.spawn(
+ task="do task",
+ label="label",
+ origin_channel="test",
+ origin_chat_id="c1",
+ runtime=LLMRuntime.capture(provider, "test-model", context_window_tokens=128_000),
)
-
- mgr._announce_result.assert_awaited_once()
- args = mgr._announce_result.await_args.args
- assert args[3] == "Task completed but no final response was generated."
- assert args[5] == "ok"
+ await asyncio.gather(*mgr._running_tasks.values(), return_exceptions=True)
+
+ status = next(iter(mgr.statuses_for_session("test:c1").values()))
+ assert status.state == "incomplete"
+ assert status.stop_reason == "max_iterations"
+ assert status.partial is True
+ assert status.result == "working"
+ notice = await asyncio.wait_for(bus.consume_inbound(), timeout=1)
+ assert notice.metadata["subagent_state"] == "incomplete"
+ assert notice.metadata["subagent_partial"] is True
+ assert "working" in notice.content
+ await mgr.close()
diff --git a/tests/agent/test_loop_save_turn.py b/tests/agent/test_loop_save_turn.py
index 7931fce78..316c69418 100644
--- a/tests/agent/test_loop_save_turn.py
+++ b/tests/agent/test_loop_save_turn.py
@@ -7,7 +7,7 @@ from unittest.mock import AsyncMock, MagicMock
import pytest
from loguru import logger
-from agent.session_helpers import run_session
+from agent.session_helpers import run_session, save_completed_subagent
from nanobot.agent.context import ContextBuilder, TranscriptInput
from nanobot.agent.loop import AgentLoop
from nanobot.agent.runner import AgentRunResult
@@ -1088,6 +1088,7 @@ async def test_subagent_followup_stages_provider_state_before_turn_runs(
session = loop.sessions.get_or_create("cli:subagent-crash")
session.provider_state = _provider_state()
loop.sessions.save(session)
+ save_completed_subagent(loop, "sub-1", session.key)
msg = InboundMessage(
channel="system",
@@ -1119,6 +1120,7 @@ async def test_subagent_followup_state_is_durable_before_prompt_assembly(
session = loop.sessions.get_or_create("cli:subagent-prompt-crash")
session.provider_state = _provider_state()
loop.sessions.save(session)
+ save_completed_subagent(loop, "sub-1", session.key)
msg = InboundMessage(
channel="system",
@@ -1152,6 +1154,7 @@ async def test_subagent_redelivery_does_not_duplicate_staged_provider_input(
session = loop.sessions.get_or_create("cli:subagent-redelivery")
session.provider_state = _provider_state()
loop.sessions.save(session)
+ save_completed_subagent(loop, "sub-1", session.key)
msg = InboundMessage(
channel="system",
sender_id="subagent",
@@ -1201,6 +1204,7 @@ async def test_subagent_followup_clears_state_before_compatibility_failure(
session = loop.sessions.get_or_create("cli:subagent-compat-crash")
session.provider_state = _provider_state()
loop.sessions.save(session)
+ save_completed_subagent(loop, "sub-1", session.key)
msg = InboundMessage(
channel="system",
@@ -1759,11 +1763,11 @@ async def test_process_direct_skip_user_persist_does_not_save_retry_user(
@pytest.mark.asyncio
-async def test_request_context_uses_effective_key_for_spawn_tool(tmp_path: Path) -> None:
+async def test_request_context_uses_effective_key_for_subagent_tool(tmp_path: Path) -> None:
loop = _make_full_loop(tmp_path)
- spawn_tool = loop.tools.get("spawn")
- assert spawn_tool is not None
- spawn_tool._manager.spawn = AsyncMock(return_value="started") # type: ignore[attr-defined]
+ subagent_tool = loop.tools.get("subagent")
+ assert subagent_tool is not None
+ subagent_tool._manager.spawn = AsyncMock(return_value="started") # type: ignore[attr-defined]
runtime = loop.llm_runtime()
with request_context(RequestContext(
@@ -1772,9 +1776,9 @@ async def test_request_context_uses_effective_key_for_spawn_tool(tmp_path: Path)
session_key="discord:parent-456:thread:thread-777",
runtime=runtime,
)):
- await spawn_tool.execute(task="inspect context")
+ await subagent_tool.execute(action="create", task="inspect context")
- call = spawn_tool._manager.spawn.await_args.kwargs # type: ignore[attr-defined]
+ call = subagent_tool._manager.spawn.await_args.kwargs # type: ignore[attr-defined]
assert call["origin_channel"] == "discord"
assert call["origin_chat_id"] == "thread-777"
assert call["session_key"] == "discord:parent-456:thread:thread-777"
@@ -1940,6 +1944,7 @@ async def test_system_subagent_followup_is_persisted_before_prompt_assembly(tmp_
session.add_message("user", "question")
session.add_message("assistant", "working")
loop.sessions.save(session)
+ save_completed_subagent(loop, "sub-1", session.key)
runtime = loop.llm_runtime()
seen: dict[str, object] = {}
@@ -2040,6 +2045,7 @@ async def test_turn_usage_is_persisted_with_the_saved_session(tmp_path: Path) ->
@pytest.mark.asyncio
async def test_system_subagent_followup_does_not_log_content(tmp_path: Path) -> None:
loop = _make_full_loop(tmp_path)
+ save_completed_subagent(loop, "sub-logs", "cli:logs")
async def fake_run_agent_loop(transcript_input, **_kwargs):
initial_messages = _assembled_messages(loop.context, transcript_input)
@@ -2076,6 +2082,7 @@ async def test_system_subagent_followup_does_not_log_content(tmp_path: Path) ->
@pytest.mark.asyncio
async def test_system_subagent_followup_uses_common_turn_lifecycle(tmp_path: Path) -> None:
loop = _make_full_loop(tmp_path)
+ save_completed_subagent(loop, "sub-1", "cli:test")
visited: list[str] = []
for name in (
@@ -2204,6 +2211,7 @@ async def test_multiple_subagent_followups_all_persist_as_standalone_history(tmp
loop._run_agent_loop = fake_run_agent_loop # type: ignore[method-assign]
for idx in range(3):
+ save_completed_subagent(loop, f"sub-{idx}", "cli:multi")
await loop._process_message(
InboundMessage(
channel="system",
@@ -2291,11 +2299,11 @@ def test_subagent_followup_skips_empty_content() -> None:
@pytest.mark.asyncio
-async def test_request_context_passes_thread_session_key_to_spawn(tmp_path: Path) -> None:
+async def test_request_context_passes_thread_session_key_to_subagent_create(tmp_path: Path) -> None:
loop = _make_full_loop(tmp_path)
- spawn_tool = loop.tools.get("spawn")
- assert spawn_tool is not None
- spawn_tool._manager.spawn = AsyncMock(return_value="started") # type: ignore[attr-defined]
+ subagent_tool = loop.tools.get("subagent")
+ assert subagent_tool is not None
+ subagent_tool._manager.spawn = AsyncMock(return_value="started") # type: ignore[attr-defined]
runtime = loop.llm_runtime()
with request_context(RequestContext(
@@ -2306,9 +2314,9 @@ async def test_request_context_passes_thread_session_key_to_spawn(tmp_path: Path
session_key="slack:C123:1700.42",
runtime=runtime,
)):
- await spawn_tool.execute(task="inspect thread")
+ await subagent_tool.execute(action="create", task="inspect thread")
- call = spawn_tool._manager.spawn.await_args.kwargs # type: ignore[attr-defined]
+ call = subagent_tool._manager.spawn.await_args.kwargs # type: ignore[attr-defined]
assert call["session_key"] == "slack:C123:1700.42"
assert call["origin_message_id"] == "msg-123"
assert call["runtime"] is runtime
@@ -2321,6 +2329,7 @@ async def test_system_subagent_followup_uses_thread_session_and_slack_metadata(t
thread_session = loop.sessions.get_or_create("slack:C123:1700.42")
thread_session.add_message("user", "thread question")
loop.sessions.save(thread_session)
+ save_completed_subagent(loop, "sub-1", thread_session.key)
seen: dict[str, object] = {}
diff --git a/tests/agent/test_loop_session_policy.py b/tests/agent/test_loop_session_policy.py
index ef6b61ca9..385c0d390 100644
--- a/tests/agent/test_loop_session_policy.py
+++ b/tests/agent/test_loop_session_policy.py
@@ -7,6 +7,8 @@ from loguru import logger
from agent.session_helpers import run_session
from nanobot.agent.context import TranscriptInput
from nanobot.agent.loop import AgentLoop
+from nanobot.agent.runner import AgentRunResult
+from nanobot.agent.subagent_sessions import SubagentSessions
from nanobot.agent.tools.context import current_request_context
from nanobot.agent.tools.registry import ToolRegistry
from nanobot.bus.events import (
@@ -19,6 +21,8 @@ from nanobot.providers.base import GenerationSettings, LLMResponse, ToolCallRequ
from nanobot.runtime_context import RuntimeContextBlock
from nanobot.session.keys import UNIFIED_SESSION_KEY
from nanobot.session.manager import SessionPolicy
+from nanobot.webui.temporary_chats import WebUITemporaryChats
+from nanobot.webui.workspaces import WebUIWorkspaceController
def _message(key: str, content: str) -> InboundMessage:
@@ -53,11 +57,14 @@ def _loop(tmp_path, responses: list[str], **kwargs) -> AgentLoop:
async def test_transient_session_keeps_history_without_persisting_or_durable_tools(tmp_path) -> None:
loop = _loop(tmp_path, ["first answer", "second answer"])
loop.context.memory.write_memory("private durable memory")
- key = "websocket:transient-test"
- loop.sessions.get_or_create_transient(
- key,
- disabled_tools={"create_goal", "update_goal", "spawn", "cron"},
+ temporary_chats = WebUITemporaryChats(
+ bus=loop.bus, session_manager=loop.sessions, logger=logger,
+ workspaces=WebUIWorkspaceController(
+ session_manager=loop.sessions, default_workspace=tmp_path,
+ default_restrict_to_workspace=True,
+ ),
)
+ key = f"websocket:{temporary_chats.create(object(), trusted_webui=True)}"
await loop._process_message(_message(key, "first question"))
await loop._process_message(_message(key, "second question"))
@@ -66,7 +73,7 @@ async def test_transient_session_keeps_history_without_persisting_or_durable_too
assert "private durable memory" not in str(calls[0].kwargs["messages"])
tool_names = {item["function"]["name"] for item in calls[0].kwargs["tools"]}
assert "read_session" in tool_names
- assert {"create_goal", "update_goal", "spawn", "cron"}.isdisjoint(tool_names)
+ assert {"create_goal", "update_goal", "subagent", "cron"}.isdisjoint(tool_names)
assert "first answer" in str(calls[1].kwargs["messages"])
session = loop.sessions.get_cached(key)
assert session is not None
@@ -77,6 +84,8 @@ async def test_transient_session_keeps_history_without_persisting_or_durable_too
"assistant",
]
assert loop.sessions.read_session_file(key) is None
+ temporary_chats.close()
+ await loop.aclose()
@pytest.mark.parametrize("selection", ["explicit_empty", "disable_all", "default"])
@@ -295,6 +304,47 @@ async def test_missing_required_session_cannot_fall_back_to_disk(tmp_path) -> No
assert loop.sessions.read_session_file(key) is None
+async def test_required_durable_session_survives_cache_eviction(tmp_path) -> None:
+ loop = _loop(tmp_path, ["received"])
+ key = "websocket:durable-parent"
+ session = loop.sessions.get_or_create(key)
+ session.add_message("user", "earlier question")
+ loop.sessions.save(session)
+ loop.sessions.invalidate(key)
+ try:
+ response = await loop._process_message(_message(key, "follow-up"))
+ assert response is not None and response.content == "received"
+ assert "earlier question" in str(loop.provider.chat_stream_with_retry.await_args.kwargs["messages"])
+ finally:
+ await loop.aclose()
+
+
+async def test_deleted_child_cannot_notify_a_recreated_parent(tmp_path) -> None:
+ loop = _loop(tmp_path, [])
+ key = "websocket:recreated-parent"
+ loop.subagents.runner.run = AsyncMock(return_value=AgentRunResult(messages=[], final_content="old result"))
+ try:
+ await loop.subagents.spawn("old task", session_key=key, runtime=loop.llm_runtime())
+ await asyncio.gather(*loop.subagents._running_tasks.values())
+ task_id, = loop.subagents.statuses_for_session(key)
+ notice = await asyncio.wait_for(loop.bus.consume_inbound(), timeout=2)
+ assert notice.require_existing_session
+ assert loop.sessions.delete_session(key)
+ assert loop.sessions.read_session_file(SubagentSessions.key(task_id)) is None
+ loop.sessions.save(loop.sessions.get_or_create(key))
+
+ assert loop.subagents.statuses_for_session(key) == {}
+ loop._enqueue_session_message(notice)
+ assert key not in loop._pending_queues
+ assert await loop._process_message(notice) is None
+ loop.provider.chat_stream_with_retry.assert_not_awaited()
+ assert loop.sessions.read_session_file(key)["messages"] == []
+ finally:
+ await loop.aclose()
+
+
@pytest.mark.asyncio
async def test_session_discard_control_cancels_active_turn(tmp_path, monkeypatch) -> None:
provider_started = asyncio.Event()
@@ -322,7 +372,7 @@ async def test_session_discard_control_cancels_active_turn(tmp_path, monkeypatch
previous_file_state = loop._file_state_store.for_session(key)
loop.sessions.get_or_create_transient(
key,
- disabled_tools={"create_goal", "update_goal", "spawn", "cron"},
+ disabled_tools={"create_goal", "update_goal", "subagent", "cron"},
)
run_task = asyncio.create_task(loop.run())
await loop.bus.publish_inbound(_message(key, "private"))
diff --git a/tests/agent/test_subagent.py b/tests/agent/test_subagent.py
index 9b36a959f..3b7309e0b 100644
--- a/tests/agent/test_subagent.py
+++ b/tests/agent/test_subagent.py
@@ -8,7 +8,7 @@ import pytest
from nanobot.agent.memory import Consolidator
from nanobot.agent.runner import AgentRunResult
-from nanobot.agent.subagent import SubagentManager, SubagentStatus
+from nanobot.agent.subagent import SubagentManager
from nanobot.agent.tools.filesystem import FileToolsConfig
from nanobot.bus.queue import MessageBus
from nanobot.config.schema import ToolsConfig
@@ -39,6 +39,10 @@ async def test_subagent_uses_tool_loader():
assert tools.has("write_file")
assert not tools.has("message")
assert not tools.has("spawn")
+ assert not tools.has("subagent")
+ assert not tools.has("send_session_message")
+ assert not tools.has("read_session")
+ assert not tools.has("my")
@pytest.mark.asyncio
@@ -152,22 +156,16 @@ async def test_subagent_keeps_project_runtime_scope_with_agent_owned_tools(tmp_p
return_value=AgentRunResult(final_content="ok", messages=[], stop_reason="completed")
)
manager._announce_result = AsyncMock()
- status = SubagentStatus(
- task_id="t1",
- label="label",
- task_description="task",
- started_at=0.0,
- )
- await manager._run_subagent(
- "t1",
- "task",
- "label",
- {"channel": "websocket", "chat_id": "direct"},
- status,
- _runtime(provider),
+ await manager.spawn(
+ task="task",
+ label="label",
+ origin_channel="websocket",
+ origin_chat_id="direct",
+ runtime=_runtime(provider),
workspace_scope=build_workspace_scope(project, "restricted"),
)
+ await asyncio.gather(*manager._running_tasks.values(), return_exceptions=True)
spec = manager.runner.run.call_args.args[0]
assert spec.workspace == project
diff --git a/tests/agent/test_subagent_control.py b/tests/agent/test_subagent_control.py
new file mode 100644
index 000000000..0a2b4ad26
--- /dev/null
+++ b/tests/agent/test_subagent_control.py
@@ -0,0 +1,894 @@
+"""Private task ownership, message receipts, cancellation, and shell lifetime."""
+
+import asyncio
+import json
+import os
+import re
+import shlex
+import subprocess
+import sys
+import uuid
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+from loguru import logger
+
+from nanobot.agent.memory import Consolidator
+from nanobot.agent.runner import AgentRunResult
+from nanobot.agent.subagent import SubagentManager
+from nanobot.agent.tools.base import Tool
+from nanobot.agent.tools.context import RequestContext, current_request_context, request_context
+from nanobot.agent.tools.registry import ToolRegistry, is_tool_error_result
+from nanobot.agent.tools.shell import ExecTool
+from nanobot.agent.tools.subagent import SubagentTool
+from nanobot.bus.events import InboundMessage
+from nanobot.bus.queue import MessageBus
+from nanobot.nanobot import Nanobot
+from nanobot.providers.base import GenerationSettings, LLMProvider, LLMResponse, ToolCallRequest
+from nanobot.session.webui_turns import WebuiTurnRoutePolicy
+from nanobot.utils.llm_runtime import LLMRuntime
+
+
+def setup(tmp_path, **kwargs):
+ manager = SubagentManager(
+ workspace=tmp_path, bus=MessageBus(), max_tool_result_chars=16000,
+ consolidator=MagicMock(spec=Consolidator), **kwargs,
+ )
+ provider = MagicMock(spec=LLMProvider)
+ provider.generation = GenerationSettings()
+ runtime = LLMRuntime.capture(provider, "test", context_window_tokens=128000)
+ ctx = RequestContext("websocket", "route", session_key="owner", runtime=runtime)
+ return manager, provider, ctx
+
+
+async def spawn(manager, ctx, text="task"):
+ with request_context(ctx):
+ result = await SubagentTool(manager).execute(action="create", task=text)
+ task_id = re.search(r"id: ([\w-]+)", result).group(1)
+ assert str(uuid.UUID(task_id)) == task_id
+ return task_id
+
+
+async def control(manager, ctx, task_id, action=None, message=None):
+ with request_context(ctx):
+ return await SubagentTool(manager).execute(action or "check", task_id, message)
+
+
+async def settled(manager):
+ await asyncio.gather(*list(manager._running_tasks.values()), return_exceptions=True)
+ await asyncio.sleep(0)
+
+
+async def test_direct_turn_waits_for_child_without_a_background_consumer(loop_factory):
+ loop = loop_factory()
+ loop.provider.provider_name = "test"
+ loop.provider.chat_stream_with_retry = AsyncMock(side_effect=[
+ LLMResponse(content=None, tool_calls=[ToolCallRequest(
+ id="delegate", name="subagent",
+ arguments={"action": "create", "task": "Inspect the configuration"},
+ )]),
+ LLMResponse(content="Verified child findings"),
+ LLMResponse(content="Parent conclusion from the child findings"),
+ ])
+ try:
+ response = await loop.process_direct("Delegate this inspection")
+ assert response.content == "Parent conclusion from the child findings"
+ parent_followup = loop.provider.chat_stream_with_retry.call_args_list[-1].kwargs["messages"]
+ assert any(m.get("role") == "tool" and m.get("content") == "Verified child findings"
+ for m in parent_followup)
+ assert loop.bus.inbound_size == 0
+ assert loop.subagents.get_running_count() == 0
+ assert next(iter(loop.subagents.statuses_for_session("cli:direct").values())).state == "done"
+ finally:
+ await loop.subagents.close()
+
+
[email protected]("existing_parent", [False, True])
[email protected]("streamed", [False, True])
+async def test_sdk_ephemeral_delegation_never_persists_on_later_flush(
+ loop_factory, existing_parent, streamed,
+):
+ loop = loop_factory()
+ bot = Nanobot(loop)
+ key = "sdk:ephemeral-delegation"
+ parent = loop.sessions.get_or_create(key)
+ if existing_parent:
+ parent.add_message("user", "Earlier durable question")
+ loop.sessions.save(parent)
+ before = {path.name: path.read_bytes() for path in loop.sessions.sessions_dir.glob("*.jsonl")}
+ secret = "private-delegation-marker"
+ source = loop.workspace / f"{secret}.txt"
+ source.write_text(secret * 1000, encoding="utf-8")
+ loop.max_tool_result_chars = 2048
+ responses = iter([
+ LLMResponse(content=None, tool_calls=[ToolCallRequest(
+ id="delegate", name="subagent", arguments={"action": "create", "task": secret},
+ )]),
+ LLMResponse(content=None, tool_calls=[ToolCallRequest(
+ id="inspect", name="read_file", arguments={"path": str(source)},
+ )]),
+ LLMResponse(content=f"Child findings: {secret}"),
+ LLMResponse(content=f"Parent conclusion: {secret}"),
+ ])
+ requests = []
+
+ async def respond(**kwargs):
+ requests.append(current_request_context())
+ return next(responses)
+
+ loop.provider.provider_name = "test"
+ loop.provider.chat_stream_with_retry = AsyncMock(side_effect=respond)
+ logs = []
+ sink = logger.add(lambda message: logs.append(message.record["message"]))
+ consumer = asyncio.create_task(loop.run())
+ try:
+ await asyncio.sleep(0)
+ assert loop._running
+ if streamed:
+ stream = await bot.run_streamed(secret, session_key=key, ephemeral=True)
+ result = await stream.wait()
+ else:
+ result = await bot.run(secret, session_key=key, ephemeral=True)
+ assert result.content == f"Parent conclusion: {secret}"
+ assert all(ctx is not None and not ctx.log_content and not ctx.persist_session for ctx in requests)
+ assert secret not in "\n".join(logs)
+ assert {path.name: path.read_bytes() for path in loop.sessions.sessions_dir.glob("*.jsonl")} == before
+ assert not list(loop.sessions.sessions_dir.glob("*.checkpoint.json"))
+ assert not (loop.workspace / ".nanobot" / "tool-results").exists()
+ assert loop.bus.inbound_size == 0
+
+ loop.provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(content="Durable answer"))
+ await bot.run("Durable follow-up", session_key=key)
+ bot.sessions.flush()
+ saved = "\n".join(path.read_text() for path in loop.sessions.sessions_dir.glob("*.jsonl"))
+ assert "Durable answer" in saved
+ assert ("Earlier durable question" in saved) is existing_parent
+ assert secret not in saved
+ assert len(list(loop.sessions.sessions_dir.glob("*.jsonl"))) == 1
+ finally:
+ loop.stop()
+ await asyncio.wait_for(consumer, timeout=2)
+ logger.remove(sink)
+ await bot.aclose()
+
+
+async def test_child_origin_uses_the_channel_turn_identity(loop_factory):
+ loop = loop_factory()
+ loop.provider.provider_name = "test"
+ loop.turn_delivery_factory.route_policy = WebuiTurnRoutePolicy(loop.sessions)
+ loop.provider.chat_stream_with_retry = AsyncMock(side_effect=[
+ LLMResponse(content=None, tool_calls=[ToolCallRequest(
+ id="delegate", name="subagent", arguments={"action": "create", "task": "Inspect config"},
+ )]),
+ LLMResponse(content="Child findings"),
+ LLMResponse(content="Parent conclusion"),
+ ])
+ message = InboundMessage("websocket", "user", "origin-check", "Delegate this inspection",
+ metadata={"webui_turn_id": "visible-parent-turn"})
+ try:
+ await loop._process_message(message)
+ status = next(iter(loop.subagents.statuses_for_session(message.session_key).values()))
+ assert status.origin_turn_id == "visible-parent-turn"
+ finally:
+ await loop.subagents.close()
+
+
+async def test_owner_canonical_fallback_and_absent_context(tmp_path):
+ manager, _, ctx = setup(tmp_path)
+ manager.runner.run = AsyncMock(return_value=AgentRunResult(messages=[], final_content="private"))
+ task_id = await spawn(manager, ctx)
+ receipt = manager.send(task_id, "owner", "follow-up")
+ snapshot = manager.statuses_for_session("owner")[task_id]
+ snapshot.state = "cancelled"
+ snapshot.owner = "other"
+ snapshot.receipts.clear()
+ current = manager.runtime_statuses()[task_id]
+ assert current.state == "queued"
+ assert current.owner == "owner"
+ assert current.receipts == {receipt["message_id"]: "accepted"}
+ await settled(manager)
+ terminal = await manager.cancel(task_id, "owner")
+ terminal.result = "tampered"
+ terminal.receipts.clear()
+ current = manager.statuses_for_session("owner")[task_id]
+ assert current.result == "private"
+ assert current.receipts == {receipt["message_id"]: "undelivered"}
+ denied = await SubagentTool(manager).execute("cancel", task_id)
+ assert is_tool_error_result(denied)
+ for stranger in [RequestContext("websocket", "route", session_key="other"),
+ RequestContext("websocket", "route"), RequestContext("", "")]:
+ for action in [None, "send", "cancel"]:
+ assert await control(manager, stranger, task_id, action, "secret") == denied
+ assert await control(manager, ctx, "missing") == denied
+ # Canonical identity, not the transport route, owns the task.
+ same_owner = RequestContext("cli", "different", session_key="owner")
+ assert json.loads(await control(manager, same_owner, task_id))["result"] == "private"
+ fallback = RequestContext("cli", "fallback", runtime=ctx.runtime)
+ fallback_id = await spawn(manager, fallback)
+ await settled(manager)
+ assert await control(manager, fallback, fallback_id, "cancel") == denied
+ explicit_owner = RequestContext("cli", "fallback", session_key="cli:fallback")
+ assert json.loads(await control(manager, explicit_owner, fallback_id))["state"] == "done"
+ assert manager.statuses_for_session(None) == {}
+ await manager.close()
+
+
+async def test_bounded_fifo_snapshot_and_terminal_receipts(tmp_path):
+ manager, _, ctx = setup(tmp_path)
+ entered, drain, drained, finish = (asyncio.Event() for _ in range(4))
+ snapshots = []
+
+ async def run(spec):
+ entered.set()
+ await drain.wait()
+ snapshots.append(await spec.injection_callback())
+ drained.set()
+ await finish.wait()
+ return AgentRunResult(messages=[], final_content="done")
+
+ manager.runner.run = run
+ task_id = await spawn(manager, ctx)
+ await entered.wait()
+ for invalid in ["", " ", "x" * 8193, "界" * 2731]:
+ assert is_tool_error_result(await control(manager, ctx, task_id, "send", invalid))
+ receipts = []
+ for i in range(manager.MAX_INBOX):
+ receipt = json.loads(await control(manager, ctx, task_id, "send", str(i)))
+ assert receipt["receipt"] == "accepted" and not receipt["delivered"]
+ receipts.append(receipt["message_id"])
+ assert is_tool_error_result(await control(manager, ctx, task_id, "send", "overflow"))
+ drain.set()
+ await drained.wait()
+ assert snapshots == [[{"role": "user", "content": str(i)} for i in range(manager.MAX_INBOX)]]
+ last = json.loads(await control(manager, ctx, task_id, "send", "late"))["message_id"]
+ finish.set()
+ await settled(manager)
+ status = json.loads(await control(manager, ctx, task_id))
+ assert status["state"] == "done"
+ assert status["receipts"] == {**dict.fromkeys(receipts, "delivered"), last: "undelivered"}
+ assert is_tool_error_result(await control(manager, ctx, task_id, "send", "no restart"))
+ notice = await manager.bus.consume_inbound()
+ assert notice.metadata["subagent_task_id"] == task_id
+ assert notice.metadata["subagent_message_receipts"] == status["receipts"]
+ assert last in notice.content
+ assert manager.bus.inbound_size == 0
+ await manager.close()
+
+
+async def test_lifetime_receipt_limit_rejects_without_silent_eviction(tmp_path):
+ manager, _, ctx = setup(tmp_path)
+ manager.MAX_MESSAGES = 2
+ entered = asyncio.Event()
+ specs = []
+
+ async def run(spec):
+ specs.append(spec)
+ entered.set()
+ await asyncio.Event().wait()
+
+ manager.runner.run = run
+ task_id = await spawn(manager, ctx)
+ await entered.wait()
+ for text in ["one", "two"]:
+ assert not is_tool_error_result(await control(manager, ctx, task_id, "send", text))
+ await specs[0].injection_callback()
+ assert is_tool_error_result(await control(manager, ctx, task_id, "send", "three"))
+ await control(manager, ctx, task_id, "cancel")
+ assert len(json.loads(await control(manager, ctx, task_id))["receipts"]) == 2
+ await manager.close()
+
+
[email protected]("begun", [False, True])
+async def test_queued_cancel_is_idempotent_and_never_admitted(tmp_path, begun):
+ manager, _, ctx = setup(tmp_path, max_concurrent_subagents=1)
+ entered = asyncio.Event()
+ calls = []
+
+ async def run(spec):
+ calls.append(spec.initial_messages[-1]["content"])
+ entered.set()
+ await asyncio.Event().wait()
+
+ manager.runner.run = run
+ await spawn(manager, ctx, "occupy")
+ await entered.wait()
+ queued = await spawn(manager, ctx, "queued")
+ accepted = json.loads(await control(manager, ctx, queued, "send", "pending"))
+ if begun:
+ await asyncio.sleep(0)
+ a, b = await asyncio.gather(control(manager, ctx, queued, "cancel"),
+ control(manager, ctx, queued, "cancel"))
+ assert json.loads(a) == json.loads(b)
+ assert json.loads(a)["state"] == "cancelled"
+ assert json.loads(a)["receipts"][accepted["message_id"]] == "undelivered"
+ assert calls == ["occupy"]
+ assert manager.bus.inbound_size == 1
+ await manager.close()
+ assert manager.bus.inbound_size == 1
+ with request_context(ctx):
+ assert is_tool_error_result(await SubagentTool(manager).execute(action="create", task="after close"))
+
+
+async def test_real_runner_injects_followup_without_durable_child_session(tmp_path):
+ manager, provider, ctx = setup(tmp_path)
+ entered, release = asyncio.Event(), asyncio.Event()
+ requests = []
+
+ async def chat(**kwargs):
+ requests.append([dict(m) for m in kwargs["messages"]])
+ if len(requests) == 1:
+ entered.set()
+ await release.wait()
+ return LLMResponse(content="answer")
+
+ provider.chat_stream_with_retry = AsyncMock(side_effect=chat)
+ task_id = await spawn(manager, ctx)
+ await entered.wait()
+ ids = [json.loads(await control(manager, ctx, task_id, "send", text))["message_id"]
+ for text in ["first update", "second update"]]
+ release.set()
+ await settled(manager)
+ assert len(requests) == 2
+ user_text = "\n".join(m["content"] for m in requests[-1] if m["role"] == "user")
+ assert user_text.index("first update") < user_text.index("second update")
+ assert json.loads(await control(manager, ctx, task_id))["receipts"] == dict.fromkeys(ids, "delivered")
+ assert not (tmp_path / "sessions").exists()
+ await manager.close()
+
+
+async def test_iteration_limit_returns_partial_findings_without_success_notice(tmp_path):
+ manager, provider, ctx = setup(tmp_path, max_iterations=1)
+ (tmp_path / "note.txt").write_text("evidence", encoding="utf-8")
+ provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(
+ content="Found the relevant file; verification is still pending.",
+ tool_calls=[ToolCallRequest("read", "read_file", {"path": "note.txt"})],
+ ))
+ task_id = await spawn(manager, ctx)
+ await settled(manager)
+ status = json.loads(await control(manager, ctx, task_id))
+ assert status["state"] == "incomplete"
+ assert status["stop_reason"] == "max_iterations"
+ assert status["partial"] is True
+ assert status["result"] == "Found the relevant file; verification is still pending."
+ notice = await manager.bus.consume_inbound()
+ assert "completed successfully" not in notice.content
+ assert notice.metadata["subagent_state"] == "incomplete"
+ assert notice.metadata["subagent_partial"] is True
+ assert notice.metadata["subagent_stop_reason"] == "max_iterations"
+ with request_context(ctx):
+ inline = await SubagentTool(manager).execute("create", task="verify", wait=True)
+ assert is_tool_error_result(inline)
+ assert "max_iterations" in inline
+ assert "verification is still pending" in inline
+ await manager.close()
+
+
[email protected]("inline", [False, True])
+async def test_cancel_preserves_completed_iteration_output_and_receipts(tmp_path, inline):
+ manager, provider, ctx = setup(tmp_path)
+ (tmp_path / "note.txt").write_text("evidence", encoding="utf-8")
+ entered = asyncio.Event()
+ calls = 0
+
+ async def chat(**kwargs):
+ nonlocal calls
+ calls += 1
+ if calls == 1:
+ return LLMResponse(content="Found a possible cause; not yet verified.", tool_calls=[
+ ToolCallRequest("read", "read_file", {"path": "note.txt"}),
+ ])
+ entered.set()
+ await asyncio.Event().wait()
+
+ provider.chat_stream_with_retry = AsyncMock(side_effect=chat)
+ if inline:
+ execution = asyncio.create_task(manager.run_inline(
+ task="task", session_key=ctx.session_key, runtime=ctx.runtime,
+ ))
+ else:
+ task_id = await spawn(manager, ctx)
+ await entered.wait()
+ if inline:
+ task_id = next(iter(manager.statuses_for_session(ctx.session_key)))
+ receipt = json.loads(await control(manager, ctx, task_id, "send", "please verify"))
+ status = json.loads(await control(manager, ctx, task_id, "cancel"))
+ assert status["state"] == "cancelled"
+ assert status["partial"] is True
+ assert status["result"] == "Found a possible cause; not yet verified."
+ assert status["receipts"][receipt["message_id"]] == "undelivered"
+ if inline:
+ result = await execution
+ assert is_tool_error_result(result)
+ assert result == f"Task cancelled.\nPartial result:\n{status['result']}"
+ assert manager.bus.inbound_size == 0
+ else:
+ notice = await manager.bus.consume_inbound()
+ assert status["result"] in notice.content
+ assert notice.metadata["subagent_state"] == "cancelled"
+ await manager.close()
+
+
+async def test_empty_final_response_is_a_failure(tmp_path):
+ manager, provider, ctx = setup(tmp_path)
+ provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(content=""))
+ task_id = await spawn(manager, ctx)
+ await settled(manager)
+ status = json.loads(await control(manager, ctx, task_id))
+ assert status["state"] == "error"
+ assert status["stop_reason"] == "empty_final_response"
+ assert status["error"]
+ notice = await manager.bus.consume_inbound()
+ assert "completed successfully" not in notice.content
+ assert notice.metadata["subagent_state"] == "error"
+ await manager.close()
+
+
+async def test_host_without_background_consumer_returns_the_child_result(tmp_path):
+ manager, _, ctx = setup(tmp_path)
+ ctx = RequestContext("cli", "oneshot", session_key="cli:oneshot", runtime=ctx.runtime,
+ can_receive_background_results=False)
+ manager.runner.run = AsyncMock(return_value=AgentRunResult(messages=[], final_content="verified"))
+ with request_context(ctx):
+ result = await SubagentTool(manager).execute("create", task="verify")
+ assert result == "verified"
+ assert manager.get_running_count() == 0
+ assert manager.bus.inbound_size == 0
+ await manager.close()
+
+
+async def test_provider_suppressed_cancellation_cannot_execute_returned_tools(tmp_path):
+ manager, provider, ctx = setup(tmp_path)
+ entered = asyncio.Event()
+
+ async def chat(**kwargs):
+ entered.set()
+ try:
+ await asyncio.Event().wait()
+ except asyncio.CancelledError:
+ return LLMResponse(content=None, tool_calls=[ToolCallRequest(
+ id="write", name="write_file", arguments={"path": "resurrected.txt", "content": "bad"},
+ )])
+
+ provider.chat_stream_with_retry = AsyncMock(side_effect=chat)
+ task_id = await spawn(manager, ctx)
+ await entered.wait()
+ assert json.loads(await control(manager, ctx, task_id, "cancel"))["state"] == "cancelled"
+ assert provider.chat_stream_with_retry.await_count == 1
+ assert not (tmp_path / "resurrected.txt").exists()
+ assert manager.bus.inbound_size == 1
+ await manager.close()
+
+
[email protected]("ending", ["done", "error", "cancel"])
+async def test_real_task_process_cleanup_preserves_sibling_parent_and_work_products(tmp_path, ending):
+ manager, _, ctx = setup(tmp_path)
+ script = tmp_path / "worker.py"
+ script.write_text("import sys\nprint('READY', flush=True)\nfor line in sys.stdin:\n print(line.strip(), flush=True)\n")
+ argv = [sys.executable, "-u", str(script)]
+ command = subprocess.list2cmdline(argv) if os.name == "nt" else shlex.join(argv)
+ kwargs = {"command": command, "yield_time_ms": 100, "timeout": 60}
+ if os.name == "nt":
+ kwargs["shell"] = "cmd"
+ events = {name: asyncio.Event() for name in ["one", "two"]}
+ releases = {name: asyncio.Event() for name in events}
+ exec_ids = {}
+ processes = {}
+
+ async def run(spec):
+ name = spec.initial_messages[-1]["content"]
+ written = await spec.tools.execute("write_file", {"path": f"{name}-output.txt", "content": name})
+ assert not is_tool_error_result(written), written
+ output = await spec.tools.execute("exec", kwargs)
+ assert not is_tool_error_result(output), output
+ exec_ids[name] = re.search(r"session_id: (\w+)", output).group(1)
+ exec_manager = spec.tools.get("exec")._session_manager
+ processes[name] = exec_manager._sessions[exec_ids[name]].process
+ events[name].set()
+ await releases[name].wait()
+ if name == "one" and ending == "error":
+ raise RuntimeError("task failed")
+ return AgentRunResult(messages=[], final_content="finished")
+
+ manager.runner.run = run
+ # The parent's exec manager must not be closed by task cancellation.
+ parent_exec = ExecTool(working_dir=str(tmp_path), session_manager=manager._exec_session_manager)
+ try:
+ with request_context(ctx):
+ output = await parent_exec.execute(**kwargs)
+ parent_id = re.search(r"session_id: (\w+)", output).group(1)
+ one = await spawn(manager, ctx, "one")
+ two = await spawn(manager, ctx, "two")
+ await asyncio.wait_for(asyncio.gather(*(event.wait() for event in events.values())), 15)
+ one_exec_manager = manager._tasks[one].exec_manager
+ if ending == "cancel":
+ await control(manager, ctx, one, "cancel")
+ else:
+ releases["one"].set()
+ await asyncio.gather(manager._running_tasks[one], return_exceptions=True)
+ expected = {"cancel": "cancelled", "error": "error", "done": "done"}[ending]
+ assert json.loads(await control(manager, ctx, one))["state"] == expected
+ assert await asyncio.wait_for(processes["one"].wait(), timeout=5) is not None
+ with pytest.raises(KeyError):
+ await one_exec_manager.write(
+ session_id=exec_ids["one"], chars=None, close_stdin=False, terminate=False,
+ yield_time_ms=0, max_output_chars=1000, owner_session_key=f"subagent:{one}",
+ )
+ for session_id, owner, exec_manager in [
+ (exec_ids["two"], f"subagent:{two}", manager._tasks[two].exec_manager),
+ (parent_id, "owner", manager._exec_session_manager),
+ ]:
+ poll = await exec_manager.write(
+ session_id=session_id, chars="SURVIVED\n", close_stdin=False, terminate=False,
+ yield_time_ms=1000, max_output_chars=1000, owner_session_key=owner,
+ )
+ assert not poll.done
+ assert "SURVIVED" in poll.output
+ assert script.exists()
+ assert await manager.cancel_by_session("owner") == 1
+ assert manager.bus.inbound_size == 1 # No cancelled sibling notice on parent stop.
+ parent_poll = await manager._exec_session_manager.write(
+ session_id=parent_id, chars="STILL ALIVE\n", close_stdin=False, terminate=False,
+ yield_time_ms=1000, max_output_chars=1000, owner_session_key="owner",
+ )
+ assert not parent_poll.done and "STILL ALIVE" in parent_poll.output
+ finally:
+ await manager.close()
+ assert script.exists()
+ assert (tmp_path / "one-output.txt").read_text() == "one"
+ assert (tmp_path / "two-output.txt").read_text() == "two"
+
+
+async def test_terminal_retention_and_active_capacity_are_bounded(tmp_path):
+ manager, _, ctx = setup(tmp_path)
+ manager.MAX_TERMINAL = 2
+ manager.MAX_ACTIVE = 1
+ entered, release = asyncio.Event(), asyncio.Event()
+
+ async def run(spec):
+ entered.set()
+ await release.wait()
+ return AgentRunResult(messages=[], final_content="done")
+
+ manager.runner.run = run
+ first = await spawn(manager, ctx)
+ await entered.wait()
+ with request_context(ctx):
+ assert is_tool_error_result(await SubagentTool(manager).execute(action="create", task="overflow"))
+ release.set()
+ await settled(manager)
+ for _ in range(3):
+ await spawn(manager, ctx)
+ await settled(manager)
+ assert len(manager.runtime_statuses()) == 2
+ assert len(manager.statuses_for_session("owner")) == 2
+ assert is_tool_error_result(await control(manager, ctx, first))
+ await manager.close()
+
+
[email protected]("shutdown", [False, True])
+async def test_completion_wins_cancel_race_and_rejects_late_messages(tmp_path, shutdown):
+ manager, _, ctx = setup(tmp_path)
+ manager.runner.run = AsyncMock(return_value=AgentRunResult(messages=[], final_content="finished"))
+ cleaning, release = asyncio.Event(), asyncio.Event()
+ task_id = await spawn(manager, ctx)
+ exec_manager = manager._tasks[task_id].exec_manager
+ cleanup = exec_manager.close_all
+
+ async def gated_cleanup():
+ cleaning.set()
+ await release.wait()
+ return await cleanup()
+
+ exec_manager.close_all = gated_cleanup
+ message_id = json.loads(await control(manager, ctx, task_id, "send", "too late"))["message_id"]
+ await cleaning.wait()
+ assert json.loads(await control(manager, ctx, task_id))["state"] == "stopping"
+ assert is_tool_error_result(await control(manager, ctx, task_id, "send", "rejected"))
+ cancellation = asyncio.create_task(manager.close() if shutdown else control(manager, ctx, task_id, "cancel"))
+ await asyncio.sleep(0)
+ release.set()
+ await cancellation
+ await settled(manager)
+ state = json.loads(await control(manager, ctx, task_id))
+ assert state["state"] == "done"
+ assert state["receipts"][message_id] == "undelivered"
+ assert state["result"] == "finished"
+ assert manager.bus.inbound_size == (0 if shutdown else 1)
+ await manager.close()
+
+
[email protected]("late_failure", [False, True])
+async def test_cancel_wins_over_late_execution_result(tmp_path, late_failure):
+ manager, _, ctx = setup(tmp_path)
+ entered, stopping, release = (asyncio.Event() for _ in range(3))
+
+ async def run(spec):
+ entered.set()
+ try:
+ await asyncio.Event().wait()
+ except asyncio.CancelledError:
+ stopping.set()
+ await release.wait()
+ if late_failure:
+ raise RuntimeError("late failure")
+ return AgentRunResult(messages=[], final_content="not success")
+
+ manager.runner.run = run
+ task_id = await spawn(manager, ctx)
+ await entered.wait()
+ message_id = json.loads(await control(manager, ctx, task_id, "send", "pending"))["message_id"]
+ cancelled = asyncio.create_task(control(manager, ctx, task_id, "cancel"))
+ await stopping.wait()
+ assert is_tool_error_result(await control(manager, ctx, task_id, "send", "late"))
+ release.set()
+ state = json.loads(await cancelled)
+ assert state["state"] == "cancelled"
+ assert state["receipts"][message_id] == "undelivered"
+ assert state["result"] == "Task cancelled."
+ assert json.loads(await control(manager, ctx, task_id, "cancel")) == state
+ assert manager.bus.inbound_size == 1
+ await manager.close()
+
+
+async def test_inline_caller_cancel_closes_child_without_notice(tmp_path):
+ manager, _, ctx = setup(tmp_path)
+ entered = asyncio.Event()
+
+ async def run(spec):
+ entered.set()
+ await asyncio.Event().wait()
+
+ manager.runner.run = run
+ with request_context(ctx):
+ inline = asyncio.create_task(SubagentTool(manager).execute(action="create", task="wait", wait=True))
+ await entered.wait()
+ inline.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await inline
+ assert [s.state for s in manager.statuses_for_session("owner").values()] == ["cancelled"]
+ assert manager.get_running_count() == 0
+ assert manager.bus.inbound_size == 0
+ await manager.close()
+
+
+async def test_cleanup_failure_survives_status_eviction_and_shutdown_retries(tmp_path):
+ manager, _, ctx = setup(tmp_path)
+ manager.MAX_TERMINAL = 1
+ manager.runner.run = AsyncMock(return_value=AgentRunResult(
+ messages=[], final_content="x" * (manager.max_tool_result_chars + 1),
+ ))
+ task_id = await spawn(manager, ctx)
+ exec_manager = manager._tasks[task_id].exec_manager
+ original_cleanup = exec_manager.close_all
+ exec_manager.close_all = AsyncMock(side_effect=RuntimeError("cleanup failed"))
+ message_id = json.loads(await control(manager, ctx, task_id, "send", "pending"))["message_id"]
+ await settled(manager)
+ state = json.loads(await control(manager, ctx, task_id))
+ assert state["state"] == "error"
+ assert "cleanup failed" in state["error"]
+ assert state["receipts"][message_id] == "undelivered"
+ assert json.loads(await control(manager, ctx, task_id, "cancel")) == state
+ exec_manager.close_all.assert_awaited_once()
+ assert manager.bus.inbound_size == 1
+ assert task_id in manager._tasks
+ assert len(manager._tasks[task_id].outcome.result) == manager.max_tool_result_chars
+ newer = await spawn(manager, ctx)
+ await settled(manager)
+ assert json.loads(await control(manager, ctx, newer))["state"] == "done"
+ assert is_tool_error_result(await control(manager, ctx, task_id, "cancel"))
+ manager.MAX_ACTIVE = 1
+ with request_context(ctx):
+ assert is_tool_error_result(await SubagentTool(manager).execute(action="create", task="over capacity"))
+ exec_manager.close_all = original_cleanup
+ await manager.close()
+ assert not manager._tasks
+ assert list(manager.runtime_statuses()) == [newer]
+
+
+async def test_tool_suppressed_cancellation_cannot_start_next_tool(tmp_path):
+ manager, provider, ctx = setup(tmp_path)
+ entered = asyncio.Event()
+ calls = []
+
+ class PauseTool(Tool):
+ name = "pause"
+ description = "Wait for a signal."
+ parameters = {"type": "object", "properties": {}}
+
+ async def execute(self, **kwargs):
+ calls.append("pause")
+ entered.set()
+ try:
+ await asyncio.Event().wait()
+ except asyncio.CancelledError:
+ return "suppressed"
+
+ registry = ToolRegistry()
+ registry.register(PauseTool())
+ manager._build_tools = lambda **kwargs: registry
+ provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(
+ content=None,
+ tool_calls=[ToolCallRequest(id=str(i), name="pause", arguments={}) for i in range(2)],
+ ))
+ task_id = await spawn(manager, ctx)
+ await entered.wait()
+ assert json.loads(await control(manager, ctx, task_id, "cancel"))["state"] == "cancelled"
+ assert calls == ["pause"]
+ assert provider.chat_stream_with_retry.await_count == 1
+ await manager.close()
+
+
+async def test_long_running_task_receipts_survive_newer_task_retention(tmp_path):
+ manager, _, ctx = setup(tmp_path)
+ manager.MAX_TERMINAL = 1
+ entered, release = asyncio.Event(), asyncio.Event()
+
+ async def run(spec):
+ if spec.initial_messages[-1]["content"] == "old":
+ entered.set()
+ await release.wait()
+ return AgentRunResult(messages=[], final_content="done")
+
+ manager.runner.run = run
+ old = await spawn(manager, ctx, "old")
+ await entered.wait()
+ message_id = json.loads(await control(manager, ctx, old, "send", "pending"))["message_id"]
+ newer = await spawn(manager, ctx, "new")
+ await manager._running_tasks[newer]
+ release.set()
+ await settled(manager)
+ assert is_tool_error_result(await control(manager, ctx, newer))
+ assert json.loads(await control(manager, ctx, old))["receipts"][message_id] == "undelivered"
+ await manager.bus.consume_inbound()
+ notice = await manager.bus.consume_inbound()
+ assert notice.metadata["subagent_task_id"] == old
+ assert notice.metadata["subagent_message_receipts"] == {message_id: "undelivered"}
+ await manager.close()
+
+
[email protected]("operation", ["cancel", "session", "close", "inline"])
+async def test_resistant_dependency_has_bounded_stop_and_no_late_result(tmp_path, operation):
+ manager, provider, ctx = setup(tmp_path, max_concurrent_subagents=1)
+ manager.CANCEL_WAIT_SECONDS = 0.02
+ entered, cancelled, release = (asyncio.Event() for _ in range(3))
+
+ async def chat(**kwargs):
+ entered.set()
+ try:
+ await asyncio.Event().wait()
+ except asyncio.CancelledError:
+ cancelled.set()
+ await release.wait()
+ return LLMResponse(content="must not publish", tool_calls=[ToolCallRequest(
+ id="late", name="write_file", arguments={"path": "late.txt", "content": "bad"},
+ )])
+
+ provider.chat_stream_with_retry = AsyncMock(side_effect=chat)
+ inline = None
+ if operation == "inline":
+ with request_context(ctx):
+ inline = asyncio.create_task(SubagentTool(manager).execute(action="create", task="wait", wait=True))
+ await entered.wait()
+ task_id = next(iter(manager.statuses_for_session("owner")))
+ else:
+ task_id = await spawn(manager, ctx)
+ await entered.wait()
+ record = manager._tasks[task_id]
+ status = record.status
+ try:
+ if operation == "cancel":
+ result = await asyncio.wait_for(control(manager, ctx, task_id, "cancel"), 1)
+ assert json.loads(result)["state"] == "stopping"
+ elif operation == "session":
+ assert await asyncio.wait_for(manager.cancel_by_session("owner"), 1) == 1
+ elif operation == "close":
+ await asyncio.wait_for(manager.close(), 1)
+ else:
+ inline.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await asyncio.wait_for(inline, 1)
+ assert cancelled.is_set()
+ assert status.state == "stopping"
+ assert manager.get_running_count() == 1
+ assert manager._run_slots.locked()
+ assert record.cleanup_task.done()
+ assert record.exec_manager._closed
+ assert is_tool_error_result(await control(manager, ctx, task_id, "send", "rejected"))
+ # Repeated cancel is bounded and must not interrupt the resistant coroutine.
+ assert json.loads(await control(manager, ctx, task_id, "cancel"))["state"] == "stopping"
+ assert manager.bus.inbound_size == 0
+ finally:
+ release.set()
+ await asyncio.wait_for(settled(manager), 2)
+ await manager.close()
+ assert status.state == "cancelled"
+ assert not (tmp_path / "late.txt").exists()
+ assert provider.chat_stream_with_retry.await_count == 1
+ assert manager.get_running_count() == 0
+ assert manager.bus.inbound_size == (1 if operation == "cancel" else 0)
+
+
+async def test_targeted_inline_cancel_does_not_cancel_waiting_parent(tmp_path):
+ manager, _, ctx = setup(tmp_path)
+ entered = asyncio.Event()
+
+ async def run(spec):
+ entered.set()
+ await asyncio.Event().wait()
+
+ manager.runner.run = run
+ with request_context(ctx):
+ parent = asyncio.create_task(SubagentTool(manager).execute(action="create", task="wait", wait=True))
+ await entered.wait()
+ task_id = next(iter(manager.statuses_for_session("owner")))
+ await control(manager, ctx, task_id, "cancel")
+ assert is_tool_error_result(await parent)
+ assert not parent.cancelled()
+ assert manager.bus.inbound_size == 0
+ await manager.close()
+
+
+async def test_cleanup_wait_is_bounded_and_repeated_cancel_does_not_interrupt_it(tmp_path):
+ manager, _, ctx = setup(tmp_path)
+ manager.CANCEL_WAIT_SECONDS = 0.02
+ manager.runner.run = AsyncMock(return_value=AgentRunResult(messages=[], final_content="done"))
+ cleaning, release = asyncio.Event(), asyncio.Event()
+ task_id = await spawn(manager, ctx)
+ record = manager._tasks[task_id]
+ status = record.status
+ original = record.exec_manager.close_all
+
+ async def cleanup():
+ cleaning.set()
+ await release.wait()
+ return await original()
+
+ record.exec_manager.close_all = cleanup
+ await cleaning.wait()
+ try:
+ assert json.loads(await asyncio.wait_for(control(manager, ctx, task_id, "cancel"), 1))["state"] == "stopping"
+ await asyncio.wait_for(manager.close(), 1)
+ assert status.state == "stopping"
+ assert manager.get_running_count() == 1
+ assert not record.cleanup_task.done()
+ finally:
+ release.set()
+ await asyncio.wait_for(settled(manager), 2)
+ assert status.state == "done"
+ assert manager.bus.inbound_size == 0
+
+
+def test_subagent_schema_exposes_task_actions(tmp_path):
+ manager, _, _ = setup(tmp_path)
+ properties = SubagentTool(manager).parameters["properties"]
+ assert properties["action"]["enum"] == ["create", "send", "cancel", "check"]
+ assert "owner" not in properties
+ tool = SubagentTool(manager)
+ assert tool.validate_params({"action": "create", "task": "review"}) == []
+ assert tool.validate_params({"action": "check"}) == []
+ assert tool.validate_params({"action": "send", "task_id": "task", "message": "update"}) == []
+ assert tool.validate_params({"action": "cancel", "task_id": "task"}) == []
diff --git a/tests/agent/test_subagent_lifecycle.py b/tests/agent/test_subagent_lifecycle.py
index 22d05eda5..c5776b5a2 100644
--- a/tests/agent/test_subagent_lifecycle.py
+++ b/tests/agent/test_subagent_lifecycle.py
@@ -70,8 +70,16 @@ async def _drain_subagent_tasks(sm: SubagentManager) -> None:
@pytest.mark.asyncio
async def test_close_cancels_tasks_before_closing_exec_sessions(tmp_path):
sm = _manager(tmp_path)
- task = asyncio.create_task(asyncio.Event().wait())
- sm._running_tasks["t1"] = task
+ entered = asyncio.Event()
+
+ async def run(spec):
+ entered.set()
+ await asyncio.Event().wait()
+
+ sm.runner.run = run
+ await sm.spawn("task", runtime=_runtime())
+ task = next(iter(sm._running_tasks.values()))
+ await entered.wait()
async def close_exec_sessions() -> int:
assert task.done()
@@ -96,7 +104,8 @@ class TestSubagentStatus:
task_id="abc", label="test", task_description="do stuff",
started_at=time.monotonic(),
)
- assert s.phase == "initializing"
+ assert s.phase == "queued"
+ assert s.state == "queued"
assert s.iteration == 0
assert s.tool_events == []
assert s.usage is None
@@ -214,14 +223,13 @@ class TestSpawn:
sm.runner.run = AsyncMock(return_value=AgentRunResult(
final_content="done", messages=[], stop_reason="completed",
))
- statuses = sm.runtime_statuses()
- assert not statuses
+ assert not sm.runtime_statuses()
await sm.spawn("my task", runtime=_runtime())
+ statuses = sm.runtime_statuses()
assert len(statuses) == 1
assert next(iter(statuses.values())).task_description == "my task"
await _drain_subagent_tasks(sm)
- # Status cleaned up after task completes
- assert not statuses
+ assert [s.state for s in sm.statuses_for_session("cli:direct").values()] == ["done"]
@pytest.mark.asyncio
async def test_registers_in_session_tasks(self, tmp_path):
@@ -233,15 +241,14 @@ class TestSpawn:
sm.runner.run = _slow_run
await sm.spawn("task", runtime=_runtime(), session_key="s1")
- assert "s1" in sm._session_tasks
- assert len(sm._session_tasks["s1"]) == 1
+ assert len(sm.statuses_for_session("s1")) == 1
block.set()
await _drain_subagent_tasks(sm)
- assert "s1" not in sm._session_tasks
+ assert [s.state for s in sm.statuses_for_session("s1").values()] == ["done"]
@pytest.mark.asyncio
- async def test_no_session_key_no_registration(self, tmp_path):
+ async def test_no_session_key_registers_channel_chat_owner(self, tmp_path):
sm = _manager(tmp_path)
block = asyncio.Event()
async def _slow_run(spec):
@@ -250,7 +257,7 @@ class TestSpawn:
sm.runner.run = _slow_run
await sm.spawn("task", runtime=_runtime())
- assert len(sm._session_tasks) == 0
+ assert len(sm.statuses_for_session("cli:direct")) == 1
block.set()
await _drain_subagent_tasks(sm)
@@ -266,7 +273,7 @@ class TestSpawn:
long_label_source = "A" * 50
await sm.spawn(long_label_source, runtime=_runtime(), session_key="s1")
- status = next(iter(sm._task_statuses.values()))
+ status = next(iter(sm.runtime_statuses().values()))
assert status.label == long_label_source[:30] + "..."
block.set()
@@ -284,14 +291,14 @@ class TestSpawn:
await sm.spawn(
"task", runtime=_runtime(), label="Custom Label", session_key="s1"
)
- status = next(iter(sm._task_statuses.values()))
+ status = next(iter(sm.runtime_statuses().values()))
assert status.label == "Custom Label"
block.set()
await _drain_subagent_tasks(sm)
@pytest.mark.asyncio
- async def test_cleanup_callback_removes_all_entries(self, tmp_path):
+ async def test_cleanup_callback_retains_terminal_status(self, tmp_path):
sm = _manager(tmp_path)
sm.runner.run = AsyncMock(return_value=AgentRunResult(
final_content="done", messages=[], stop_reason="completed",
@@ -299,8 +306,7 @@ class TestSpawn:
await sm.spawn("task", runtime=_runtime(), session_key="s1")
await _drain_subagent_tasks(sm)
assert len(sm._running_tasks) == 0
- assert len(sm._task_statuses) == 0
- assert len(sm._session_tasks) == 0
+ assert [s.state for s in sm.statuses_for_session("s1").values()] == ["done"]
@pytest.mark.asyncio
async def test_runtime_is_captured_before_background_task_starts(self, tmp_path):
@@ -351,12 +357,14 @@ class TestRunSubagent:
final_content="Task done!", messages=[], stop_reason="completed",
))
with patch.object(sm, "_announce_result", new_callable=AsyncMock) as mock_announce:
- await sm._run_subagent(
- "t1", "do task", "label",
- {"channel": "cli", "chat_id": "direct"},
- SubagentStatus(task_id="t1", label="label", task_description="do task", started_at=time.monotonic()),
- _runtime(),
+ await sm.spawn(
+ task="do task",
+ label="label",
+ origin_channel="cli",
+ origin_chat_id="direct",
+ runtime=_runtime(),
)
+ await asyncio.gather(*sm._running_tasks.values(), return_exceptions=True)
mock_announce.assert_called_once()
assert mock_announce.call_args.args[-2] == "ok"
@@ -364,12 +372,16 @@ class TestRunSubagent:
async def test_exception_run(self, tmp_path):
sm = _manager(tmp_path)
sm.runner.run = AsyncMock(side_effect=RuntimeError("LLM down"))
- status = SubagentStatus(task_id="t1", label="label", task_description="do task", started_at=time.monotonic())
with patch.object(sm, "_announce_result", new_callable=AsyncMock) as mock_announce:
- await sm._run_subagent(
- "t1", "do task", "label",
- {"channel": "cli", "chat_id": "direct"}, status, _runtime(),
+ await sm.spawn(
+ task="do task",
+ label="label",
+ origin_channel="cli",
+ origin_chat_id="direct",
+ runtime=_runtime(),
)
+ await asyncio.gather(*sm._running_tasks.values(), return_exceptions=True)
+ status = next(iter(sm.runtime_statuses().values()))
assert status.phase == "error"
assert "LLM down" in status.error
assert mock_announce.call_args.args[-2] == "error"
@@ -380,12 +392,16 @@ class TestRunSubagent:
sm.runner.run = AsyncMock(return_value=AgentRunResult(
final_content="ok", messages=[], stop_reason="completed",
))
- status = SubagentStatus(task_id="t1", label="label", task_description="do task", started_at=time.monotonic())
with patch.object(sm, "_announce_result", new_callable=AsyncMock):
- await sm._run_subagent(
- "t1", "do task", "label",
- {"channel": "cli", "chat_id": "direct"}, status, _runtime(),
+ await sm.spawn(
+ task="do task",
+ label="label",
+ origin_channel="cli",
+ origin_chat_id="direct",
+ runtime=_runtime(),
)
+ await asyncio.gather(*sm._running_tasks.values(), return_exceptions=True)
+ status = next(iter(sm.runtime_statuses().values()))
assert status.phase == "done"
assert status.stop_reason == "completed"
@@ -499,7 +515,7 @@ class TestCancelBySession:
runtime = _runtime()
await sm.spawn("task1", runtime=runtime, session_key="s1")
await sm.spawn("task2", runtime=runtime, session_key="s1")
- assert len(sm._session_tasks.get("s1", set())) == 2
+ assert len(sm.statuses_for_session("s1")) == 2
count = await sm.cancel_by_session("s1")
assert count == 2
@@ -539,7 +555,7 @@ class TestCancelBySession:
assert not queued_entered.is_set()
assert sm._running_tasks == {}
- assert sm._session_tasks == {}
+ assert [s.state for s in sm.statuses_for_session("s1").values()] == ["cancelled", "cancelled"]
@pytest.mark.asyncio
async def test_already_done_not_counted(self, tmp_path):
@@ -597,8 +613,8 @@ class TestRunningCounts:
class TestSubagentHook:
@pytest.mark.asyncio
- async def test_before_execute_tools_logs(self, tmp_path):
- hook = _SubagentHook("t1")
+ async def test_before_execute_tools_without_status_preserves_calls(self):
+ hook = _SubagentHook()
tool_call = MagicMock()
tool_call.name = "read_file"
tool_call.arguments = {"path": "/tmp/test"}
@@ -612,7 +628,7 @@ class TestSubagentHook:
status = SubagentStatus(
task_id="t1", label="test", task_description="do", started_at=time.monotonic(),
)
- hook = _SubagentHook("t1", status)
+ hook = _SubagentHook(status)
ctx = _make_hook_context(
iteration=3,
tool_events=[{"name": "read_file", "status": "ok", "detail": ""}],
@@ -625,7 +641,7 @@ class TestSubagentHook:
@pytest.mark.asyncio
async def test_after_iteration_no_status_noop(self):
- hook = _SubagentHook("t1", status=None)
+ hook = _SubagentHook()
ctx = _make_hook_context(iteration=5)
result = await hook.after_iteration(ctx)
assert result is None
@@ -636,7 +652,7 @@ class TestSubagentHook:
status = SubagentStatus(
task_id="t1", label="test", task_description="do", started_at=time.monotonic(),
)
- hook = _SubagentHook("t1", status)
+ hook = _SubagentHook(status)
ctx = _make_hook_context(error="something broke")
await hook.after_iteration(ctx)
assert status.error == "something broke"
diff --git a/tests/agent/test_task_cancel.py b/tests/agent/test_task_cancel.py
index b998066f8..24f26ab18 100644
--- a/tests/agent/test_task_cancel.py
+++ b/tests/agent/test_task_cancel.py
@@ -3,7 +3,6 @@
from __future__ import annotations
import asyncio
-import time
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch
@@ -455,7 +454,7 @@ class TestDispatch:
class TestSubagentCancellation:
@pytest.mark.asyncio
- async def test_cancel_by_session(self):
+ async def test_cancel_by_session(self, tmp_path):
from nanobot.agent.subagent import SubagentManager
from nanobot.bus.queue import MessageBus
@@ -468,18 +467,20 @@ class TestSubagentCancellation:
)
cancelled = asyncio.Event()
+ started = asyncio.Event()
+ mgr.workspace = tmp_path
- async def slow():
+ async def slow(spec):
+ started.set()
try:
await asyncio.sleep(60)
except asyncio.CancelledError:
cancelled.set()
raise
- task = asyncio.create_task(slow())
- await asyncio.sleep(0)
- mgr._running_tasks["sub-1"] = task
- mgr._session_tasks["test:c1"] = {"sub-1"}
+ mgr.runner.run = slow
+ await mgr.spawn("task", runtime=_runtime(MagicMock()), session_key="test:c1")
+ await started.wait()
count = await mgr.cancel_by_session("test:c1")
assert count == 1
@@ -500,7 +501,7 @@ class TestSubagentCancellation:
assert await mgr.cancel_by_session("nonexistent") == 0
@pytest.mark.asyncio
- async def test_cancel_by_session_terminates_exec_sessions(self):
+ async def test_cancel_by_session_does_not_terminate_parent_exec_sessions(self):
from nanobot.agent.subagent import SubagentManager
from nanobot.agent.tools.exec_session import ExecSessionManager
from nanobot.bus.queue import MessageBus
@@ -519,7 +520,7 @@ class TestSubagentCancellation:
await mgr.cancel_by_session("test:c1")
- mock_exec_mgr.terminate_by_owner.assert_awaited_once_with("test:c1")
+ mock_exec_mgr.terminate_by_owner.assert_not_awaited()
@pytest.mark.asyncio
async def test_subagent_preserves_reasoning_fields_in_tool_turn(self, monkeypatch, tmp_path):
@@ -559,16 +560,14 @@ class TestSubagentCancellation:
monkeypatch.setattr("nanobot.agent.tools.filesystem.ListDirTool.execute", fake_execute)
- from nanobot.agent.subagent import SubagentStatus
- status = SubagentStatus(task_id="sub-1", label="label", task_description="do task", started_at=time.monotonic())
- await mgr._run_subagent(
- "sub-1",
- "do task",
- "label",
- {"channel": "test", "chat_id": "c1"},
- status,
- _runtime(provider),
+ await mgr.spawn(
+ task="do task",
+ label="label",
+ origin_channel="test",
+ origin_chat_id="c1",
+ runtime=_runtime(provider),
)
+ await asyncio.gather(*mgr._running_tasks.values(), return_exceptions=True)
assistant_messages = [
msg for msg in captured_second_call
@@ -608,16 +607,14 @@ class TestSubagentCancellation:
mgr.runner.run = AsyncMock(side_effect=fake_run)
- from nanobot.agent.subagent import SubagentStatus
- status = SubagentStatus(task_id="sub-1", label="label", task_description="do task", started_at=time.monotonic())
- await mgr._run_subagent(
- "sub-1",
- "do task",
- "label",
- {"channel": "test", "chat_id": "c1"},
- status,
- _runtime(provider),
+ await mgr.spawn(
+ task="do task",
+ label="label",
+ origin_channel="test",
+ origin_chat_id="c1",
+ runtime=_runtime(provider),
)
+ await asyncio.gather(*mgr._running_tasks.values(), return_exceptions=True)
mgr.runner.run.assert_awaited_once()
mgr._announce_result.assert_awaited_once()
@@ -666,16 +663,14 @@ class TestSubagentCancellation:
monkeypatch.setattr("nanobot.agent.tools.filesystem.ListDirTool.execute", fake_execute)
- from nanobot.agent.subagent import SubagentStatus
- status = SubagentStatus(task_id="sub-1", label="label", task_description="do task", started_at=time.monotonic())
- await mgr._run_subagent(
- "sub-1",
- "do task",
- "label",
- {"channel": "test", "chat_id": "c1"},
- status,
- _runtime(provider),
+ await mgr.spawn(
+ task="do task",
+ label="label",
+ origin_channel="test",
+ origin_chat_id="c1",
+ runtime=_runtime(provider),
)
+ await asyncio.gather(*mgr._running_tasks.values(), return_exceptions=True)
mgr._announce_result.assert_awaited_once()
args = mgr._announce_result.await_args.args
@@ -686,7 +681,7 @@ class TestSubagentCancellation:
@pytest.mark.asyncio
async def test_cancel_by_session_cancels_running_subagent_tool(self, monkeypatch, tmp_path):
- from nanobot.agent.subagent import SubagentManager, SubagentStatus
+ from nanobot.agent.subagent import SubagentManager
from nanobot.bus.queue import MessageBus
from nanobot.providers.base import LLMResponse, ToolCallRequest
@@ -718,15 +713,8 @@ class TestSubagentCancellation:
monkeypatch.setattr("nanobot.agent.tools.filesystem.ListDirTool.execute", fake_execute)
- task = asyncio.create_task(
- mgr._run_subagent(
- "sub-1", "do task", "label", {"channel": "test", "chat_id": "c1"},
- SubagentStatus(task_id="sub-1", label="label", task_description="do task", started_at=time.monotonic()),
- _runtime(provider),
- )
- )
- mgr._running_tasks["sub-1"] = task
- mgr._session_tasks["test:c1"] = {"sub-1"}
+ await mgr.spawn("do task", label="label", runtime=_runtime(provider), session_key="test:c1")
+ task = next(iter(mgr._running_tasks.values()))
await asyncio.wait_for(started.wait(), timeout=1.0)
@@ -794,9 +782,8 @@ class TestSubagentAnnounceSessionKey:
assert msg.chat_id == "discord:333"
@pytest.mark.asyncio
- async def test_session_key_flows_through_run_subagent(self):
- """Verify session_key in origin propagates from _run_subagent to _announce_result."""
- from nanobot.agent.subagent import SubagentStatus
+ async def test_spawn_routes_result_to_parent_session(self):
+ """Background results return to the parent's canonical session."""
mgr, bus = self._make_mgr()
@@ -810,16 +797,15 @@ class TestSubagentAnnounceSessionKey:
mgr.runner.run = AsyncMock(side_effect=fake_run)
- status = SubagentStatus(
- task_id="sub-4", label="label", task_description="task",
- started_at=time.monotonic(),
- )
- await mgr._run_subagent(
- "sub-4", "task", "label",
- {"channel": "telegram", "chat_id": "444", "session_key": UNIFIED_SESSION_KEY},
- status,
- _runtime(),
+ await mgr.spawn(
+ task="task",
+ label="label",
+ origin_channel="telegram",
+ origin_chat_id="444",
+ runtime=_runtime(),
+ session_key=UNIFIED_SESSION_KEY,
)
+ await asyncio.gather(*mgr._running_tasks.values(), return_exceptions=True)
msg = await bus.consume_inbound()
assert msg.session_key_override == UNIFIED_SESSION_KEY
diff --git a/tests/agent/test_workspace_scope.py b/tests/agent/test_workspace_scope.py
index c18225ac8..d122ba7bc 100644
--- a/tests/agent/test_workspace_scope.py
+++ b/tests/agent/test_workspace_scope.py
@@ -16,7 +16,7 @@ from nanobot.agent.tools.image_generation import ImageGenerationError, ImageGene
from nanobot.agent.tools.message import MessageTool
from nanobot.agent.tools.search import GrepTool
from nanobot.agent.tools.shell import ExecTool
-from nanobot.agent.tools.spawn import SpawnTool
+from nanobot.agent.tools.subagent import SubagentTool
from nanobot.apps.cli.service import CliAppManager, CliAppsRuntimeConfig
from nanobot.config.schema import ImageGenerationToolConfig, ProviderConfig, ToolsConfig
from nanobot.security.workspace_access import (
@@ -532,7 +532,7 @@ async def test_cli_app_scope_controls_working_dir(
@pytest.mark.asyncio
-async def test_spawn_tool_forwards_current_workspace_scope(tmp_path: Path) -> None:
+async def test_subagent_tool_forwards_current_workspace_scope(tmp_path: Path) -> None:
project = tmp_path / "project"
project.mkdir()
scope = validate_workspace_scope_payload(
@@ -555,7 +555,7 @@ async def test_spawn_tool_forwards_current_workspace_scope(tmp_path: Path) -> No
return "spawned"
manager = Manager()
- tool = SpawnTool(manager) # type: ignore[arg-type]
+ tool = SubagentTool(manager) # type: ignore[arg-type]
token = bind_workspace_scope(scope)
try:
with request_context(RequestContext(
@@ -563,7 +563,7 @@ async def test_spawn_tool_forwards_current_workspace_scope(tmp_path: Path) -> No
chat_id="chat",
runtime=MagicMock(),
)):
- result = await tool.execute(task="inspect")
+ result = await tool.execute(action="create", task="inspect")
finally:
reset_workspace_scope(token)
diff --git a/tests/agent/tools/test_runtime_control.py b/tests/agent/tools/test_runtime_control.py
index 44304180e..bfb3be905 100644
--- a/tests/agent/tools/test_runtime_control.py
+++ b/tests/agent/tools/test_runtime_control.py
@@ -2,6 +2,8 @@
from __future__ import annotations
+import asyncio
+import json
from pathlib import Path
from unittest.mock import MagicMock
@@ -71,7 +73,6 @@ def test_runtime_snapshot_has_exact_allowlist_and_redacts_secrets(tmp_path: Path
"tool_names",
"web_config",
"exec_config",
- "subagents",
})
assert RUNTIME_SNAPSHOT_KEYS == expected_snapshot_keys
assert frozenset(values) == expected_snapshot_keys
@@ -247,64 +248,117 @@ def runtime() -> LLMRuntime:
return LLMRuntime(MagicMock(), "test", GenerationSettings(), 128_000)
[email protected]("key", [None, "subagents", "subagents._task_statuses"])
-async def test_my_subagent_snapshot_is_session_scoped(tmp_path, key, runtime):
[email protected]("params", [
+ {"action": "create"},
+ {"action": "create", "task": " "},
+ {"action": "send", "message": "update"},
+ {"action": "cancel"},
+])
+async def test_subagent_rejects_missing_action_inputs(tmp_path, runtime, params):
+ loop = _make_loop(tmp_path)
+ with request_context(RequestContext("test", "route", session_key="owner", runtime=runtime)):
+ result = await loop.tools.execute("subagent", params)
+ assert result.startswith("Error:")
+ assert loop.subagents.get_running_count() == 0
+
+
[email protected]("single_task", [False, True])
+async def test_subagent_check_is_session_scoped(tmp_path, single_task, runtime):
loop = _make_loop(tmp_path)
manager = loop.subagents
- # Spawn without yielding to the child runner: queued tasks must be scoped too.
+ # Queued tasks must be scoped before their runner starts.
await manager.spawn("ALPHA_PRIVATE_TASK", label="ALPHA_LABEL", session_key="owner:a", runtime=runtime)
await manager.spawn("BETA_PRIVATE_TASK", label="BETA_LABEL", session_key="owner:b", runtime=runtime)
try:
- tool = _my_tool(loop)
- with request_context(RequestContext("test", "same-chat", session_key="owner:a")):
- snapshot = tool._runtime_control.snapshot()
- assert len(snapshot.subagent_statuses) == 1
- assert "BETA" not in repr(snapshot.as_mapping())
- result = await tool.execute(action="check", key=key)
- assert "ALPHA_LABEL" in result
- assert "BETA" not in result
- with request_context(RequestContext("test", "same-chat", session_key="owner:b")):
- result = await tool.execute(action="check", key=key)
- assert "BETA_LABEL" in result
- assert "ALPHA" not in result
+ for owner, visible, hidden in [("owner:a", "ALPHA", "BETA"), ("owner:b", "BETA", "ALPHA")]:
+ with request_context(RequestContext("test", "same-chat", session_key=owner)):
+ params = {"action": "check"}
+ if single_task:
+ params["task_id"] = next(iter(manager.statuses_for_session(owner)))
+ result = await loop.tools.execute("subagent", params)
+ assert visible + "_LABEL" in result
+ assert visible + "_PRIVATE_TASK" in result
+ assert hidden not in result
+ assert "queued" in result
+ overview = await loop.tools.execute("my", {"action": "check"})
+ assert "ALPHA" not in overview and "BETA" not in overview
+ assert "not accessible" in await loop.tools.execute("my", {
+ "action": "check", "key": "subagents",
+ })
finally:
await manager.close()
[email protected]("field", ["", ".task_description", ".tool_events", ".usage"])
-async def test_my_rejects_other_sessions_task_paths(tmp_path, field, runtime):
+async def test_subagent_check_rejects_foreign_task(tmp_path, runtime):
loop = _make_loop(tmp_path)
manager = loop.subagents
await manager.spawn("PRIVATE_TASK", session_key="owner:a", runtime=runtime)
try:
task_id = next(iter(manager.statuses_for_session("owner:a")))
- tool = _my_tool(loop)
- with request_context(RequestContext("test", "same-chat", session_key="owner:a")):
- detail = await tool.execute(action="check", key=f"subagents._task_statuses.{task_id}")
- assert "PRIVATE_TASK" in detail
with request_context(RequestContext("test", "same-chat", session_key="owner:b")):
- result = await tool.execute(
- action="check", key=f"subagents._task_statuses.{task_id}{field}",
- )
- assert result.startswith("Error:")
- assert "PRIVATE_TASK" not in result
+ result = await loop.tools.execute("subagent", {"action": "check", "task_id": task_id})
+ unknown = await loop.tools.execute("subagent", {"action": "check", "task_id": "unknown"})
+ assert result == unknown
+ assert result.startswith("Error: task unavailable")
finally:
await manager.close()
@pytest.mark.parametrize("session_key", [None, ""])
-async def test_my_without_session_cannot_enumerate_tasks(tmp_path, session_key, runtime):
+async def test_subagent_check_without_session_cannot_enumerate_tasks(tmp_path, session_key, runtime):
loop = _make_loop(tmp_path)
manager = loop.subagents
await manager.spawn("PRIVATE_TASK", session_key="owner:a", runtime=runtime)
try:
- tool = _my_tool(loop)
- assert tool._runtime_control.snapshot().subagent_statuses == {}
- assert "PRIVATE_TASK" not in await tool.execute(action="check")
- assert "unavailable" in await tool.execute(action="check", key="subagents")
+ task_id = next(iter(manager.statuses_for_session("owner:a")))
+ assert "unavailable" in await loop.tools.execute("subagent", {"action": "check"})
with request_context(RequestContext("test", "same-chat", session_key=session_key)):
- assert tool._runtime_control.snapshot().subagent_statuses == {}
- assert "PRIVATE_TASK" not in await tool.execute(action="check")
- assert "unavailable" in await tool.execute(action="check", key="subagents._task_statuses")
+ assert "unavailable" in await loop.tools.execute("subagent", {"action": "check"})
+ assert "unavailable" in await loop.tools.execute("subagent", {
+ "action": "check", "task_id": task_id,
+ })
+ finally:
+ await manager.close()
+
+
+async def test_subagent_check_retained_results_and_receipts_are_scoped_and_detached(tmp_path, runtime):
+ from nanobot.agent.runner import AgentRunResult
+
+ loop = _make_loop(tmp_path)
+ manager = loop.subagents
+ entered, release = asyncio.Event(), asyncio.Event()
+
+ async def run(spec):
+ entered.set()
+ await release.wait()
+ return AgentRunResult(messages=[], final_content="PRIVATE_RESULT")
+
+ manager.runner.run = run
+ owner = RequestContext("test", "route", session_key="owner:a", runtime=runtime)
+ try:
+ with request_context(owner):
+ await loop.tools.execute("subagent", {"action": "create", "task": "private"})
+ await entered.wait()
+ task_id = next(iter(manager.statuses_for_session("owner:a")))
+ sent = json.loads(await loop.tools.execute("subagent", {
+ "action": "send", "task_id": task_id, "message": "pending",
+ }))
+ release.set()
+ await asyncio.gather(*manager._running_tasks.values())
+ params = {"action": "check", "task_id": task_id}
+ result = json.loads(await loop.tools.execute("subagent", params))
+ assert result["state"] == "done"
+ assert result["result"] == "PRIVATE_RESULT"
+ assert result["receipts"] == {sent["message_id"]: "undelivered"}
+ snapshot = manager.check(task_id, "owner:a")
+ snapshot.receipts.clear()
+ snapshot.result = "tampered"
+ assert json.loads(await loop.tools.execute("subagent", params)) == result
+ listed = json.loads(await loop.tools.execute("subagent", {"action": "check"}))
+ assert listed == {"tasks": [result]}
+ with request_context(RequestContext("test", "route", session_key="owner:b")):
+ assert "unavailable" in await loop.tools.execute("subagent", params)
+ assert json.loads(await loop.tools.execute("subagent", {"action": "check"})) == {"tasks": []}
finally:
+ release.set()
await manager.close()
diff --git a/tests/agent/tools/test_self_tool.py b/tests/agent/tools/test_self_tool.py
index 77ec3544a..a83f78f2a 100644
--- a/tests/agent/tools/test_self_tool.py
+++ b/tests/agent/tools/test_self_tool.py
@@ -40,6 +40,7 @@ def _make_mock_loop(**overrides):
loop._unified_session = False
loop._extra_hooks = []
loop.set_runtime_model.side_effect = lambda value: setattr(loop, "model", value)
+ loop.set_runtime_max_iterations.side_effect = lambda value: setattr(loop, "max_iterations", value)
loop.set_runtime_context_window.side_effect = lambda value: setattr(
loop,
"context_window_tokens",
@@ -59,12 +60,6 @@ def _make_mock_loop(**overrides):
# SubagentManager mock
loop.subagents = MagicMock()
- loop.subagents._running_tasks = {"abc123": MagicMock(done=MagicMock(return_value=False))}
- loop.subagents._task_statuses = {}
- loop.subagents.statuses_for_session.side_effect = (
- lambda key: loop.subagents._task_statuses if key == "test:owner" else {}
- )
- loop.subagents.get_running_count = MagicMock(return_value=1)
for k, v in overrides.items():
setattr(loop, k, v)
@@ -412,11 +407,11 @@ class TestModifyOpen:
@pytest.mark.asyncio
async def test_modify_subagents_blocked(self):
- """subagents is READ_ONLY — cannot be replaced."""
+ """Subagent control is outside the self-inspection capability."""
tool = _make_tool()
new_subagents = MagicMock()
result = await tool.execute(action="set", key="subagents", value=new_subagents)
- assert "read-only" in result
+ assert "protected" in result
@pytest.mark.asyncio
async def test_modify_runner_blocked(self):
@@ -584,78 +579,6 @@ class TestDeniedAttrs:
assert "protected" in result, f"{attr} should be blocked"
-# ---------------------------------------------------------------------------
-# SubagentStatus formatting
-# ---------------------------------------------------------------------------
-
-class TestSubagentStatusFormatting:
-
- def test_format_single_status(self):
- """_format_value should produce a rich multi-line display for a SubagentStatus."""
- from nanobot.agent.subagent import SubagentStatus
-
- status = SubagentStatus(
- task_id="abc12345",
- label="read logs and summarize",
- task_description="Read the log files and produce a summary",
- started_at=time.monotonic() - 12.4,
- phase="awaiting_tools",
- iteration=3,
- tool_events=[
- {"name": "read_file", "status": "ok", "detail": "read app.log"},
- {"name": "grep", "status": "ok", "detail": "searched ERROR"},
- {"name": "exec", "status": "error", "detail": "timeout"},
- ],
- usage=LLMUsage.reported(input_tokens=4500, output_tokens=1200),
- )
- result = MyTool._format_value(status)
- assert "abc12345" in result
- assert "read logs and summarize" in result
- assert "awaiting_tools" in result
- assert "iteration: 3" in result
- assert "read_file(ok)" in result
- assert "exec(error)" in result
- assert "4500" in result
-
- def test_format_status_dict(self):
- """_format_value should handle dict[str, SubagentStatus] with rich display."""
- from nanobot.agent.subagent import SubagentStatus
-
- statuses = {
- "abc12345": SubagentStatus(
- task_id="abc12345",
- label="task A",
- task_description="Do task A",
- started_at=time.monotonic() - 5.0,
- phase="awaiting_tools",
- iteration=1,
- ),
- }
- result = MyTool._format_value(statuses)
- assert "1 subagent(s)" in result
- assert "abc12345" in result
- assert "task A" in result
-
- def test_format_empty_status_dict(self):
- """Empty dict[str, SubagentStatus] should show 'no running subagents'."""
- result = MyTool._format_value({})
- assert "{}" in result
-
- def test_format_status_with_error(self):
- """Status with error should include the error message."""
- from nanobot.agent.subagent import SubagentStatus
-
- status = SubagentStatus(
- task_id="err00001",
- label="failing task",
- task_description="A task that fails",
- started_at=time.monotonic() - 1.0,
- phase="error",
- error="Connection refused",
- )
- result = MyTool._format_value(status)
- assert "error: Connection refused" in result
-
# ---------------------------------------------------------------------------
# _SubagentHook after_iteration updates status
# ---------------------------------------------------------------------------
@@ -674,7 +597,7 @@ class TestSubagentHookStatus:
task_description="test",
started_at=time.monotonic(),
)
- hook = _SubagentHook("test", status)
+ hook = _SubagentHook(status)
context = AgentHookContext(
iteration=5,
@@ -701,7 +624,7 @@ class TestSubagentHookStatus:
task_description="test",
started_at=time.monotonic(),
)
- hook = _SubagentHook("test", status)
+ hook = _SubagentHook(status)
context = AgentHookContext(
iteration=1,
@@ -718,7 +641,7 @@ class TestSubagentHookStatus:
from nanobot.agent.hook import AgentHookContext
from nanobot.agent.subagent import _SubagentHook
- hook = _SubagentHook("test")
+ hook = _SubagentHook()
context = AgentHookContext(iteration=1, messages=[])
result = await hook.after_iteration(context)
@@ -780,60 +703,6 @@ class TestCheckpointCallback:
assert status.iteration == 1
-# ---------------------------------------------------------------------------
-# check subagents._task_statuses via dot-path
-# Task status inspection requires the owning session context.
-# ---------------------------------------------------------------------------
-
-class TestInspectTaskStatuses:
-
- @pytest.mark.asyncio
- async def test_inspect_task_statuses_accessible(self):
- """subagents is READ_ONLY — check should show subagent statuses."""
- from nanobot.agent.subagent import SubagentStatus
-
- loop = _make_mock_loop()
- loop.subagents._task_statuses = {
- "abc12345": SubagentStatus(
- task_id="abc12345",
- label="read logs",
- task_description="Read the log files",
- started_at=time.monotonic() - 8.0,
- phase="awaiting_tools",
- iteration=2,
- tool_events=[{"name": "read_file", "status": "ok", "detail": "ok"}],
- usage=LLMUsage.reported(input_tokens=500, output_tokens=100),
- ),
- }
- tool = _make_tool(loop=loop)
- with request_context(RequestContext("test", "owner", session_key="test:owner")):
- result = await tool.execute(action="check", key="subagents._task_statuses")
- assert "abc12345" in result
- assert "read logs" in result
-
- @pytest.mark.asyncio
- async def test_inspect_single_subagent_status_accessible(self):
- """subagents._task_statuses.<id> should return individual SubagentStatus."""
- from nanobot.agent.subagent import SubagentStatus
-
- loop = _make_mock_loop()
- status = SubagentStatus(
- task_id="xyz",
- label="search code",
- task_description="Search the codebase",
- started_at=time.monotonic() - 3.0,
- phase="done",
- iteration=4,
- stop_reason="completed",
- )
- loop.subagents._task_statuses = {"xyz": status}
- tool = _make_tool(loop=loop)
- with request_context(RequestContext("test", "owner", session_key="test:owner")):
- result = await tool.execute(action="check", key="subagents._task_statuses.xyz")
- assert "search code" in result
- assert "completed" in result
-
-
# ---------------------------------------------------------------------------
# read-only mode (tools.my.allow_set=False)
# ---------------------------------------------------------------------------
diff --git a/tests/agent/tools/test_subagent_tools.py b/tests/agent/tools/test_subagent_tools.py
index 582b83fa1..26b129157 100644
--- a/tests/agent/tools/test_subagent_tools.py
+++ b/tests/agent/tools/test_subagent_tools.py
@@ -1,7 +1,6 @@
"""Tests for subagent tool registration and wiring."""
import asyncio
-import time
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch
@@ -9,7 +8,9 @@ import pytest
from nanobot.agent.context import TranscriptInput
from nanobot.agent.memory import Consolidator
+from nanobot.agent.runner import AgentRunResult
from nanobot.agent.tools.context import RequestContext
+from nanobot.agent.tools.registry import is_tool_error_result
from nanobot.config.schema import AgentDefaults
from nanobot.providers.base import GenerationSettings
from nanobot.utils.llm_runtime import LLMRuntime
@@ -35,7 +36,8 @@ async def test_run_inline_returns_result_without_announcement(tmp_path):
bus=MessageBus(),
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
)
- manager.runner.run = AsyncMock(return_value=SimpleNamespace(
+ manager.runner.run = AsyncMock(return_value=AgentRunResult(
+ messages=[],
stop_reason="done",
final_content="review result",
error=None,
@@ -52,8 +54,7 @@ async def test_run_inline_returns_result_without_announcement(tmp_path):
assert result == "review result"
manager._announce_result.assert_not_awaited()
assert manager._running_tasks == {}
- assert manager._task_statuses == {}
- assert manager._session_tasks == {}
+ assert [s.state for s in manager.statuses_for_session("test:c1").values()] == ["done"]
@pytest.mark.asyncio
@@ -69,7 +70,8 @@ async def test_run_inline_returns_structured_error(tmp_path):
bus=MessageBus(),
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
)
- manager.runner.run = AsyncMock(return_value=SimpleNamespace(
+ manager.runner.run = AsyncMock(return_value=AgentRunResult(
+ messages=[],
stop_reason="error",
final_content=None,
error="subagent failed",
@@ -85,13 +87,13 @@ async def test_run_inline_returns_structured_error(tmp_path):
assert result == "subagent failed"
assert is_tool_error_result(result)
assert manager._running_tasks == {}
- assert manager._session_tasks == {}
+ assert [s.state for s in manager.statuses_for_session("test:c1").values()] == ["error"]
@pytest.mark.asyncio
async def test_subagent_exec_tool_receives_allowed_env_keys(tmp_path):
"""allowed_env_keys from ExecToolConfig must be forwarded to the subagent's ExecTool."""
- from nanobot.agent.subagent import SubagentManager, SubagentStatus
+ from nanobot.agent.subagent import SubagentManager
from nanobot.agent.tools.shell import ExecToolConfig
from nanobot.bus.queue import MessageBus
from nanobot.config.schema import ToolsConfig
@@ -112,7 +114,8 @@ async def test_subagent_exec_tool_receives_allowed_env_keys(tmp_path):
exec_tool = spec.tools.get("exec")
assert exec_tool is not None
assert exec_tool.allowed_env_keys == ["GOPATH", "JAVA_HOME"]
- return SimpleNamespace(
+ return AgentRunResult(
+ messages=[],
stop_reason="done",
final_content="done",
error=None,
@@ -121,17 +124,14 @@ async def test_subagent_exec_tool_receives_allowed_env_keys(tmp_path):
mgr.runner.run = AsyncMock(side_effect=fake_run)
- status = SubagentStatus(
- task_id="sub-1", label="label", task_description="do task", started_at=time.monotonic()
- )
- await mgr._run_subagent(
- "sub-1",
- "do task",
- "label",
- {"channel": "test", "chat_id": "c1"},
- status,
- _runtime(provider),
+ await mgr.spawn(
+ task="do task",
+ label="label",
+ origin_channel="test",
+ origin_chat_id="c1",
+ runtime=_runtime(provider),
)
+ await asyncio.gather(*mgr._running_tasks.values(), return_exceptions=True)
mgr.runner.run.assert_awaited_once()
@@ -139,7 +139,7 @@ async def test_subagent_exec_tool_receives_allowed_env_keys(tmp_path):
@pytest.mark.asyncio
async def test_subagent_uses_configured_max_iterations(tmp_path):
"""Subagents should honor the configured tool-iteration limit."""
- from nanobot.agent.subagent import SubagentManager, SubagentStatus
+ from nanobot.agent.subagent import SubagentManager
from nanobot.bus.queue import MessageBus
bus = MessageBus()
@@ -156,7 +156,8 @@ async def test_subagent_uses_configured_max_iterations(tmp_path):
async def fake_run(spec):
assert spec.max_iterations == 37
- return SimpleNamespace(
+ return AgentRunResult(
+ messages=[],
stop_reason="done",
final_content="done",
error=None,
@@ -165,17 +166,14 @@ async def test_subagent_uses_configured_max_iterations(tmp_path):
mgr.runner.run = AsyncMock(side_effect=fake_run)
- status = SubagentStatus(
- task_id="sub-1", label="label", task_description="do task", started_at=time.monotonic()
- )
- await mgr._run_subagent(
- "sub-1",
- "do task",
- "label",
- {"channel": "test", "chat_id": "c1"},
- status,
- _runtime(provider),
+ await mgr.spawn(
+ task="do task",
+ label="label",
+ origin_channel="test",
+ origin_chat_id="c1",
+ runtime=_runtime(provider),
)
+ await asyncio.gather(*mgr._running_tasks.values(), return_exceptions=True)
mgr.runner.run.assert_awaited_once()
@@ -203,7 +201,8 @@ async def test_spawn_forwards_temperature_to_run_spec(tmp_path):
async def fake_run(spec):
seen["temperature"] = spec.runtime.generation.temperature
seen["runtime"] = spec.runtime
- return SimpleNamespace(
+ return AgentRunResult(
+ messages=[],
stop_reason="done", final_content="done", error=None, tool_events=[],
)
@@ -221,7 +220,7 @@ async def test_spawn_forwards_temperature_to_run_spec(tmp_path):
async def test_background_spawn_waits_for_concurrency_capacity(tmp_path):
"""Background tasks should be accepted and start when capacity becomes available."""
from nanobot.agent.subagent import SubagentManager
- from nanobot.agent.tools.spawn import SpawnTool
+ from nanobot.agent.tools.subagent import SubagentTool
from nanobot.bus.queue import MessageBus
bus = MessageBus()
@@ -249,7 +248,8 @@ async def test_background_spawn_waits_for_concurrency_capacity(tmp_path):
else:
second_entered.set()
await release_second.wait()
- return SimpleNamespace(
+ return AgentRunResult(
+ messages=[],
stop_reason="done",
final_content="done",
error=None,
@@ -260,23 +260,23 @@ async def test_background_spawn_waits_for_concurrency_capacity(tmp_path):
from nanobot.agent.tools.context import RequestContext, request_context
- tool = SpawnTool(mgr)
+ tool = SubagentTool(mgr)
with request_context(RequestContext(
channel="test",
chat_id="c1",
session_key="test:c1",
runtime=_runtime(provider),
)):
- first_result = await tool.execute(task="first task")
+ first_result = await tool.execute(action="create", task="first task")
assert "started" in first_result
await asyncio.wait_for(first_entered.wait(), timeout=1.0)
- second_result = await tool.execute(task="second task")
+ second_result = await tool.execute(action="create", task="second task")
assert "started" in second_result
tasks = list(mgr._running_tasks.values())
await asyncio.sleep(0)
assert not second_entered.is_set()
- phases = {status.task_description: status.phase for status in mgr._task_statuses.values()}
+ phases = {status.task_description: status.phase for status in mgr.runtime_statuses().values()}
assert phases == {"first task": "initializing", "second task": "queued"}
release_first.set()
@@ -288,9 +288,9 @@ async def test_background_spawn_waits_for_concurrency_capacity(tmp_path):
@pytest.mark.asyncio
-async def test_spawn_tool_waits_for_inline_result():
+async def test_subagent_tool_waits_for_inline_result():
from nanobot.agent.tools.context import RequestContext, request_context
- from nanobot.agent.tools.spawn import SpawnTool
+ from nanobot.agent.tools.subagent import SubagentTool
class Manager:
max_concurrent_subagents = 1
@@ -306,7 +306,7 @@ async def test_spawn_tool_waits_for_inline_result():
return await self.inline(**kwargs)
manager = Manager()
- tool = SpawnTool(manager)
+ tool = SubagentTool(manager)
runtime = _runtime(MagicMock())
with request_context(RequestContext(
channel="test",
@@ -314,7 +314,7 @@ async def test_spawn_tool_waits_for_inline_result():
session_key="test:c1",
runtime=runtime,
)):
- result = await tool.execute(task="review this", wait=True)
+ result = await tool.execute(action="create", task="review this", wait=True)
assert result == "review result"
manager.inline.assert_awaited_once()
@@ -325,7 +325,7 @@ async def test_spawn_tool_waits_for_inline_result():
async def test_inline_spawn_waits_for_concurrency_capacity(tmp_path):
from nanobot.agent.subagent import SubagentManager
from nanobot.agent.tools.context import RequestContext, request_context
- from nanobot.agent.tools.spawn import SpawnTool
+ from nanobot.agent.tools.subagent import SubagentTool
from nanobot.bus.queue import MessageBus
manager = SubagentManager(
@@ -348,7 +348,8 @@ async def test_inline_spawn_waits_for_concurrency_capacity(tmp_path):
else:
second_entered.set()
await release_second.wait()
- return SimpleNamespace(
+ return AgentRunResult(
+ messages=[],
stop_reason="done",
final_content="done",
error=None,
@@ -356,17 +357,17 @@ async def test_inline_spawn_waits_for_concurrency_capacity(tmp_path):
)
manager.runner.run = AsyncMock(side_effect=fake_run)
- tool = SpawnTool(manager)
+ tool = SubagentTool(manager)
with request_context(RequestContext(
channel="test",
chat_id="c1",
session_key="test:c1",
runtime=_runtime(MagicMock()),
)):
- first = asyncio.create_task(tool.execute(task="first", wait=True))
+ first = asyncio.create_task(tool.execute(action="create", task="first", wait=True))
await asyncio.wait_for(first_entered.wait(), timeout=1.0)
- second = asyncio.create_task(tool.execute(task="second", wait=True))
+ second = asyncio.create_task(tool.execute(action="create", task="second", wait=True))
await asyncio.sleep(0)
assert not second.done()
@@ -379,7 +380,7 @@ async def test_inline_spawn_waits_for_concurrency_capacity(tmp_path):
assert await second == "done"
assert manager.get_running_count() == 0
- assert manager._session_tasks == {}
+ assert [s.state for s in manager.statuses_for_session("test:c1").values()] == ["done", "done"]
@pytest.mark.asyncio
@@ -390,7 +391,7 @@ async def test_runner_executes_inline_spawn_batch_concurrently(tmp_path):
from nanobot.agent.tools.context import RequestContext, request_context
from nanobot.agent.tools.execution import execute_tool_calls
from nanobot.agent.tools.registry import ToolRegistry
- from nanobot.agent.tools.spawn import SpawnTool
+ from nanobot.agent.tools.subagent import SubagentTool
from nanobot.bus.queue import MessageBus
from nanobot.providers.base import ToolCallRequest
@@ -410,7 +411,8 @@ async def test_runner_executes_inline_spawn_batch_concurrently(tmp_path):
if len(entered) == 2:
both_entered.set()
await release.wait()
- return SimpleNamespace(
+ return AgentRunResult(
+ messages=[],
stop_reason="done",
final_content=spec.initial_messages[-1]["content"],
error=None,
@@ -419,18 +421,18 @@ async def test_runner_executes_inline_spawn_batch_concurrently(tmp_path):
manager.runner.run = AsyncMock(side_effect=fake_run)
tools = ToolRegistry()
- tools.register(SpawnTool(manager))
+ tools.register(SubagentTool(manager))
runtime = _runtime(MagicMock())
calls = [
ToolCallRequest(
- id="spawn-1",
- name="spawn",
- arguments={"task": "first", "wait": True},
+ id="create-1",
+ name="subagent",
+ arguments={"action": "create", "task": "first", "wait": True},
),
ToolCallRequest(
- id="spawn-2",
- name="spawn",
- arguments={"task": "second", "wait": True},
+ id="create-2",
+ name="subagent",
+ arguments={"action": "create", "task": "second", "wait": True},
),
]
@@ -485,11 +487,11 @@ async def test_cancel_by_session_cancels_inline_subagent(tmp_path):
await asyncio.wait_for(entered.wait(), timeout=1.0)
assert await manager.cancel_by_session("test:c1") == 1
- with pytest.raises(asyncio.CancelledError):
- await inline
+ result = await inline
+ assert is_tool_error_result(result)
+ assert result == "Task cancelled."
assert manager._running_tasks == {}
- assert manager._task_statuses == {}
- assert manager._session_tasks == {}
+ assert [s.state for s in manager.statuses_for_session("test:c1").values()] == ["cancelled"]
def test_subagent_default_max_concurrent_matches_agent_defaults(tmp_path):
@@ -567,13 +569,12 @@ async def test_agent_loop_syncs_updated_max_iterations_before_run(tmp_path):
async def fake_run(spec):
assert spec.max_iterations == 55
assert loop.subagents.max_iterations == 55
- return SimpleNamespace(
+ return AgentRunResult(
+ messages=[],
stop_reason="done",
final_content="done",
error=None,
tool_events=[],
- messages=[],
- usage=None,
had_injections=False,
tools_used=[],
)
@@ -609,13 +610,12 @@ async def test_drain_pending_no_block_when_no_subagents(tmp_path):
nonlocal injection_callback, terminal_injection_callback
injection_callback = spec.injection_callback
terminal_injection_callback = spec.terminal_injection_callback
- return SimpleNamespace(
+ return AgentRunResult(
+ messages=[],
stop_reason="done",
final_content="done",
error=None,
tool_events=[],
- messages=[],
- usage=None,
had_injections=False,
tools_used=[],
provider_state=None,
@@ -660,13 +660,12 @@ async def test_terminal_drain_timeout(tmp_path):
async def fake_runner_run(spec):
nonlocal terminal_injection_callback
terminal_injection_callback = spec.terminal_injection_callback
- return SimpleNamespace(
+ return AgentRunResult(
+ messages=[],
stop_reason="done",
final_content="done",
error=None,
tool_events=[],
- messages=[],
- usage=None,
had_injections=False,
tools_used=[],
provider_state=None,
@@ -674,13 +673,11 @@ async def test_terminal_drain_timeout(tmp_path):
loop.runner.run = AsyncMock(side_effect=fake_runner_run)
- # Register a "running" sub-agent that will never complete
- async def _hang_forever():
+ async def _hang_forever(spec):
await asyncio.Event().wait()
- hang_task = asyncio.create_task(_hang_forever())
- loop.subagents._session_tasks.setdefault(session.key, set()).add("sub-timeout-1")
- loop.subagents._running_tasks["sub-timeout-1"] = hang_task
+ loop.subagents.runner.run = _hang_forever
+ await loop.subagents.spawn("pending", runtime=loop.llm_runtime(), session_key=session.key)
runtime = loop.llm_runtime()
await loop._run_agent_loop(
@@ -707,12 +704,7 @@ async def test_terminal_drain_timeout(tmp_path):
results = await terminal_injection_callback()
assert results == []
- # Cleanup
- hang_task.cancel()
- try:
- await hang_task
- except asyncio.CancelledError:
- pass
+ await loop.subagents.close()
@pytest.mark.asyncio
@@ -736,13 +728,12 @@ async def test_terminal_drain_reuses_one_timeout_budget(tmp_path):
async def fake_runner_run(spec):
nonlocal terminal_injection_callback
terminal_injection_callback = spec.terminal_injection_callback
- return SimpleNamespace(
+ return AgentRunResult(
+ messages=[],
stop_reason="done",
final_content="done",
error=None,
tool_events=[],
- messages=[],
- usage=None,
had_injections=False,
tools_used=[],
provider_state=None,
@@ -750,12 +741,11 @@ async def test_terminal_drain_reuses_one_timeout_budget(tmp_path):
loop.runner.run = AsyncMock(side_effect=fake_runner_run)
- async def _hang_forever():
+ async def _hang_forever(spec):
await asyncio.Event().wait()
- hang_task = asyncio.create_task(_hang_forever())
- loop.subagents._session_tasks.setdefault(session.key, set()).add("sub-deadline-1")
- loop.subagents._running_tasks["sub-deadline-1"] = hang_task
+ loop.subagents.runner.run = _hang_forever
+ await loop.subagents.spawn("pending", runtime=loop.llm_runtime(), session_key=session.key)
await loop._run_agent_loop(
TranscriptInput(history=[{"role": "user", "content": "test"}], current_message=None),
@@ -788,6 +778,4 @@ async def test_terminal_drain_reuses_one_timeout_budget(tmp_path):
assert timeouts == [300.0, 200.0]
- hang_task.cancel()
- with pytest.raises(asyncio.CancelledError):
- await hang_task
+ await loop.subagents.close()
diff --git a/tests/bus/test_runtime_events.py b/tests/bus/test_runtime_events.py
index 436521196..885492325 100644
--- a/tests/bus/test_runtime_events.py
+++ b/tests/bus/test_runtime_events.py
@@ -110,6 +110,15 @@ async def test_scheduled_dispatch_is_owned_and_can_be_drained():
await bus.drain()
+async def test_drain_finishes_when_dispatch_completed_before_its_cleanup_callback():
+ bus = MessageBus()
+ task = bus.publish_nowait(RuntimeModelChanged("model", None))
+ await asyncio.sleep(0)
+ assert task is not None and task.done()
+ await bus.drain()
+ assert not bus._pending
+
+
@pytest.mark.asyncio
async def test_runtime_event_bus_filters_by_event_type() -> None:
bus = MessageBus()
diff --git a/tests/cli/test_commands.py b/tests/cli/test_commands.py
index ea051693b..6a09a9725 100644
--- a/tests/cli/test_commands.py
+++ b/tests/cli/test_commands.py
@@ -14,6 +14,7 @@ import pytest
from typer.testing import CliRunner
from nanobot.agent.memory import MemoryStore
+from nanobot.agent.subagent import SubagentManager
from nanobot.agent.tools.registry import ToolRegistry
from nanobot.agent.turn_delivery import TurnDeliveryFactory
from nanobot.bus.events import InboundMessage, OutboundMessage
@@ -84,6 +85,10 @@ class _GatewayAgentContractStub:
"""Minimal stable AgentLoop surface required by gateway assembly tests."""
tools = ToolRegistry()
+ subagents = MagicMock(spec=SubagentManager)
+
+ async def discard_session(self, _session_key: str) -> None:
+ pass
@staticmethod
def mcp_runtime_status() -> dict[str, str]:
@@ -3500,7 +3505,8 @@ def test_gateway_local_trigger_queue_submits_agent_turns(
enabled_channels: list[str] = []
def __init__(self, *_args, **_kwargs) -> None:
- return None
+ seen["webui_subagent_manager"] = _kwargs["webui_subagent_manager"]
+ seen["webui_discard_session"] = _kwargs["webui_discard_session"]
def get_channel(self, name: str) -> object | None:
return object() if name == "websocket" else None
@@ -3531,6 +3537,8 @@ def test_gateway_local_trigger_queue_submits_agent_turns(
agent = seen["agent"]
agent_kwargs = seen["agent_from_config_kwargs"]
kwargs = seen["local_trigger_queue_kwargs"]
+ assert seen["webui_subagent_manager"] is agent.subagents
+ assert seen["webui_discard_session"] == agent.discard_session
assert isinstance(agent_kwargs["provider"], UnconfiguredProvider) is bool(setup_error)
refreshed_snapshot = agent_kwargs["provider_snapshot_loader"]()
assert not isinstance(refreshed_snapshot.provider, UnconfiguredProvider)
diff --git a/tests/session/test_session_handles.py b/tests/session/test_session_handles.py
index e4d06d4b9..b579cfdfb 100644
--- a/tests/session/test_session_handles.py
+++ b/tests/session/test_session_handles.py
@@ -13,6 +13,7 @@ from nanobot.session.session_handles import (
_tier_size,
normalize_session_handle,
)
+from nanobot.session.types import SESSION_TYPE_KEY, SessionType
def _persist(manager: SessionManager, key: str) -> None:
@@ -183,3 +184,38 @@ def test_normalize_session_handle_accepts_optional_at_prefix() -> None:
normalize_session_handle("aa")
with pytest.raises(ValueError, match="invalid"):
normalize_session_handle("not-a-handle")
+
+
+def test_session_owner_registration_controls_handle_allocation(tmp_path: Path) -> None:
+ manager = SessionManager(tmp_path)
+ _persist(manager, "websocket:conversation")
+ for kind in ("review", "scratch"):
+ session = manager.get_or_create(f"internal:{kind}")
+ session.metadata[SESSION_TYPE_KEY] = kind
+ manager.save(session)
+ resolver = SessionHandleResolver(manager)
+ before = resolver.handle_for_session("websocket:conversation")
+ assert {handle.session_key for handle in resolver.list_all()} == {"websocket:conversation"}
+
+ manager.types.register(SessionType("review", needs_handle=True, public_history=True))
+ manager.types.register(SessionType("scratch", needs_handle=False, public_history=False))
+ assert resolver.handle_for_session("internal:review") is not None
+ assert resolver.handle_for_session("internal:scratch") is None
+ assert resolver.handle_for_session("websocket:conversation") == before
+
+
+def test_private_type_cannot_be_resolved_through_an_existing_handle(tmp_path: Path) -> None:
+ manager = SessionManager(tmp_path)
+ _persist(manager, "internal:private")
+ resolver = SessionHandleResolver(manager)
+ old_handle = resolver.handle_for_session("internal:private")
+ assert old_handle is not None
+ session = manager.get_or_create("internal:private")
+ session.metadata[SESSION_TYPE_KEY] = "private"
+ manager.save(session)
+ manager.types.register(SessionType("private", needs_handle=False, public_history=False))
+ assert resolver.resolve(old_handle.name) is None
+ assert resolver.handle_for_session(session.key) is None
+
+ reopened = SessionManager(tmp_path)
+ assert SessionHandleResolver(reopened).list_all() == []
diff --git a/tests/test_nanobot_facade.py b/tests/test_nanobot_facade.py
index 608a7ae3b..09ead451a 100644
--- a/tests/test_nanobot_facade.py
+++ b/tests/test_nanobot_facade.py
@@ -696,6 +696,7 @@ async def test_run_forwards_non_default_runtime_options(tmp_path):
media=["/tmp/image.png"],
ephemeral=True,
_run_extra_hooks_for_ephemeral=True,
+ _session_policy=ANY,
hooks=ANY,
)
diff --git a/tests/test_tool_contextvars.py b/tests/test_tool_contextvars.py
index 03e69f027..1da03bcaf 100644
--- a/tests/test_tool_contextvars.py
+++ b/tests/test_tool_contextvars.py
@@ -9,7 +9,7 @@ import pytest
from nanobot.agent.tools.context import RequestContext, request_context
from nanobot.agent.tools.cron import CronTool
from nanobot.agent.tools.message import MessageTool
-from nanobot.agent.tools.spawn import SpawnTool
+from nanobot.agent.tools.subagent import SubagentTool
from nanobot.cron.service import CronService
from nanobot.providers.base import GenerationSettings, LLMProvider
from nanobot.runtime_context import RUNTIME_CONTEXT_INPUT_META, RuntimeContextBlock
@@ -56,8 +56,8 @@ async def test_message_tool_keeps_task_local_context() -> None:
@pytest.mark.asyncio
-async def test_spawn_tool_keeps_task_local_context() -> None:
- seen: list[tuple[str, str, str]] = []
+async def test_subagent_tool_keeps_task_local_context() -> None:
+ seen: list[tuple[str, str, str, str | None, str | None]] = []
entered = asyncio.Event()
release = asyncio.Event()
@@ -77,40 +77,46 @@ async def test_spawn_tool_keeps_task_local_context() -> None:
origin_chat_id: str,
session_key: str,
origin_message_id: str | None = None,
+ origin_turn_id: str | None = None,
temperature: float | None = None,
workspace_scope=None,
+ session_policy=None,
) -> str:
- seen.append((origin_channel, origin_chat_id, session_key))
+ seen.append((origin_channel, origin_chat_id, session_key, origin_message_id, origin_turn_id))
return f"{origin_channel}:{origin_chat_id}:{task}"
- tool = SpawnTool(_Manager())
+ tool = SubagentTool(_Manager())
async def task_one() -> str:
with request_context(RequestContext(
channel="whatsapp",
chat_id="chat-a",
+ message_id="msg-a",
+ turn_id="turn-a",
runtime=_runtime("model-a"),
)):
entered.set()
await release.wait()
- return await tool.execute(task="one")
+ return await tool.execute(action="create", task="one")
async def task_two() -> str:
await entered.wait()
with request_context(RequestContext(
channel="telegram",
chat_id="chat-b",
+ message_id="msg-b",
+ turn_id="turn-b",
runtime=_runtime("model-b"),
)):
release.set()
- return await tool.execute(task="two")
+ return await tool.execute(action="create", task="two")
result_one, result_two = await asyncio.gather(task_one(), task_two())
assert result_one == "whatsapp:chat-a:one"
assert result_two == "telegram:chat-b:two"
- assert ("whatsapp", "chat-a", "whatsapp:chat-a") in seen
- assert ("telegram", "chat-b", "telegram:chat-b") in seen
+ assert ("whatsapp", "chat-a", "whatsapp:chat-a", "msg-a", "turn-a") in seen
+ assert ("telegram", "chat-b", "telegram:chat-b", "msg-b", "turn-b") in seen
@pytest.mark.asyncio
@@ -188,9 +194,9 @@ async def test_message_tool_default_values_without_request_context() -> None:
@pytest.mark.asyncio
-async def test_spawn_tool_basic_request_context_and_execute() -> None:
+async def test_subagent_tool_basic_request_context_and_execute() -> None:
"""A bound request context should provide the correct origin."""
- seen: list[tuple[str, str, str]] = []
+ seen: list[tuple[str, str, str, str | None, str | None]] = []
class _Manager:
max_concurrent_subagents = 1
@@ -208,25 +214,29 @@ async def test_spawn_tool_basic_request_context_and_execute() -> None:
origin_chat_id,
session_key,
origin_message_id=None,
+ origin_turn_id=None,
temperature=None,
workspace_scope=None,
+ session_policy=None,
):
- seen.append((origin_channel, origin_chat_id, session_key))
+ seen.append((origin_channel, origin_chat_id, session_key, origin_message_id, origin_turn_id))
return f"ok: {task}"
- tool = SpawnTool(_Manager())
+ tool = SubagentTool(_Manager())
with request_context(RequestContext(
channel="feishu",
chat_id="chat-abc",
+ message_id="msg-123",
+ turn_id="turn-123",
runtime=_runtime(),
)):
- result = await tool.execute(task="do something")
+ result = await tool.execute(action="create", task="do something")
assert result == "ok: do something"
- assert seen == [("feishu", "chat-abc", "feishu:chat-abc")]
+ assert seen == [("feishu", "chat-abc", "feishu:chat-abc", "msg-123", "turn-123")]
@pytest.mark.asyncio
-async def test_spawn_tool_rejects_missing_request_runtime() -> None:
+async def test_subagent_tool_rejects_missing_request_runtime() -> None:
"""Spawning cannot reconstruct a model runtime outside turn admission."""
seen: list[tuple[str, str, str]] = []
@@ -248,14 +258,15 @@ async def test_spawn_tool_rejects_missing_request_runtime() -> None:
origin_message_id=None,
temperature=None,
workspace_scope=None,
+ session_policy=None,
):
seen.append((origin_channel, origin_chat_id, session_key))
return "ok"
- tool = SpawnTool(_Manager())
+ tool = SubagentTool(_Manager())
- result = await tool.execute(task="test")
- assert result == "Error: spawn requires an active model runtime"
+ result = await tool.execute(action="create", task="test")
+ assert result == "Error: create requires an active model runtime"
assert result.is_error
assert seen == []
diff --git a/tests/tools/test_search_tools.py b/tests/tools/test_search_tools.py
index e4d249a95..ab2c3af42 100644
--- a/tests/tools/test_search_tools.py
+++ b/tests/tools/test_search_tools.py
@@ -6,7 +6,6 @@ import asyncio
import os
import re
import threading
-import time
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock
@@ -15,7 +14,7 @@ import pytest
from nanobot.agent.loop import AgentLoop
from nanobot.agent.memory import Consolidator
-from nanobot.agent.subagent import SubagentManager, SubagentStatus
+from nanobot.agent.subagent import SubagentManager
from nanobot.agent.tools.registry import is_tool_error_result
from nanobot.agent.tools.search import FindFilesTool, GrepTool
from nanobot.agent.tools.web import WebSearchTool
@@ -801,15 +800,14 @@ async def test_subagent_registers_search_backend(tmp_path: Path, monkeypatch, us
mgr.runner.run = fake_run
mgr._announce_result = AsyncMock()
- status = SubagentStatus(task_id="sub-1", label="label", task_description="search task", started_at=time.monotonic())
- await mgr._run_subagent(
- "sub-1",
- "search task",
- "label",
- {"channel": "cli", "chat_id": "direct"},
- status,
- LLMRuntime.capture(provider, "test-model", context_window_tokens=128_000),
+ await mgr.spawn(
+ task="search task",
+ label="label",
+ origin_channel="cli",
+ origin_chat_id="direct",
+ runtime=LLMRuntime.capture(provider, "test-model", context_window_tokens=128_000),
)
+ await asyncio.gather(*mgr._running_tasks.values(), return_exceptions=True)
assert ("rg" in captured["tool_names"]) == use_rg
assert ("find_files" in captured["tool_names"]) == (not use_rg)
diff --git a/tests/tools/test_tool_loader.py b/tests/tools/test_tool_loader.py
index afb0181b0..99de091fb 100644
--- a/tests/tools/test_tool_loader.py
+++ b/tests/tools/test_tool_loader.py
@@ -95,7 +95,7 @@ def test_discover_finds_concrete_tools():
assert "CliAppsTool" in class_names
assert "MessageTool" in class_names
assert "MyTool" in class_names
- assert "SpawnTool" in class_names
+ assert "SubagentTool" in class_names
assert "ExecSessionTool" in class_names
@@ -209,7 +209,7 @@ def test_fs_tool_create_respects_sandbox():
assert tool._allowed_dir == Path("/tmp/test")
-# --- Task 5: MessageTool, SpawnTool, CronTool ---
+# --- Message, subagent, and cron tool factories ---
async def test_message_tool_create():
@@ -221,13 +221,13 @@ async def test_message_tool_create():
assert isinstance(tool, MessageTool)
-def test_spawn_tool_create():
- from nanobot.agent.tools.spawn import SpawnTool
+def test_subagent_tool_create():
+ from nanobot.agent.tools.subagent import SubagentTool
mock_mgr = MagicMock()
mock_config = MagicMock()
ctx = ToolContext(config=mock_config, workspace="/tmp", subagent_manager=mock_mgr)
- tool = SpawnTool.create(ctx)
- assert isinstance(tool, SpawnTool)
+ tool = SubagentTool.create(ctx)
+ assert isinstance(tool, SubagentTool)
def test_cron_tool_enabled_without_service():
@@ -407,7 +407,7 @@ def test_mcp_wrappers_not_discoverable():
# --- Task 10: Integration test ---
-def test_loader_registers_same_tools_as_old_hardcoded():
+def test_loader_registers_builtin_tools():
"""Verify the loader produces the same tool set as the old _register_default_tools."""
from nanobot.agent.tools.loader import ToolLoader
from nanobot.agent.tools.registry import ToolRegistry
@@ -448,7 +448,7 @@ def test_loader_registers_same_tools_as_old_hardcoded():
"read_file", "write_file", "edit_file", "list_dir",
"exec", "exec_session", "list_exec_sessions",
"web_search", "web_fetch",
- "message", "spawn", "cron",
+ "message", "subagent", "cron",
"my",
}
actual = set(registered)
diff --git a/tests/webui/test_gateway_webui_smoke.py b/tests/webui/test_gateway_webui_smoke.py
index 481047593..b9aa4b77f 100644
--- a/tests/webui/test_gateway_webui_smoke.py
+++ b/tests/webui/test_gateway_webui_smoke.py
@@ -16,6 +16,8 @@ import httpx
import pytest
import websockets
+from nanobot.agent.subagent_sessions import SubagentSessions
+from nanobot.agent.subagent_status import SubagentStatus
from nanobot.config.loader import load_config
from nanobot.session.manager import SessionManager
from nanobot.session.recovery import PENDING_USER_TURN_KEY, RUNTIME_CHECKPOINT_KEY
@@ -280,6 +282,60 @@ async def test_gateway_webui_bootstrap_message_and_thread_hydration(tmp_path: Pa
_stop_gateway(process)
+async def test_gateway_recovers_private_children_and_deletes_them_with_parent(tmp_path: Path) -> None:
+ workspace = tmp_path / "workspace"
+ workspace.mkdir()
+ config_path, log_path = tmp_path / "config.json", tmp_path / "gateway.log"
+ ws_port, gateway_port = _free_port(), _free_port()
+ _write_smoke_config(config_path, workspace=workspace, ws_port=ws_port, gateway_port=gateway_port)
+ sessions = SessionManager(workspace, sessions_root=tmp_path / "sessions")
+ parent = sessions.get_or_create("websocket:subagent-smoke")
+ parent.add_message("user", "Inspect config")
+ sessions.save(parent)
+ children = SubagentSessions(sessions)
+ now = time.monotonic()
+ children.create(SubagentStatus(
+ task_id="finished", label="Finished", task_description="inspect", owner=parent.key,
+ started_at=now, finished_at=now, completed_at=time.time(), state="done", phase="done", result="Verified",
+ ))
+ children.create(SubagentStatus(
+ task_id="abandoned", label="Abandoned", task_description="inspect", owner=parent.key,
+ started_at=now, state="running", phase="thinking", result="Partial findings", partial=True,
+ receipts={"follow-up": "accepted"},
+ ))
+ process = _start_gateway(config_path, log_path)
+ base_url = f"http://127.0.0.1:{ws_port}"
+ try:
+ bootstrap = _wait_for_bootstrap(base_url, process, log_path)
+ api_token = bootstrap["api_token"]
+ path = f"{base_url}/api/sessions/{quote(parent.key, safe='')}/subagents"
+ first = _get_json(path, token=api_token)
+ tasks = {task["task_id"]: task for task in first["tasks"]}
+ assert tasks["finished"]["state"] == "done"
+ assert tasks["finished"]["result"] == "Verified"
+ assert tasks["abandoned"]["state"] == "interrupted"
+ assert tasks["abandoned"]["stop_reason"] == "host_restarted"
+ assert tasks["abandoned"]["result"] == "Partial findings"
+ assert tasks["abandoned"]["receipts"] == {"follow-up": "undelivered"}
+ assert _get_json(path, token=api_token) == first
+ sidebar = _get_json(f"{base_url}/api/sessions", token=api_token)
+ assert {row["key"] for row in sidebar["sessions"]} == {parent.key}
+ ws_url = bootstrap["ws_url"] + "?token=" + bootstrap["token"] + "&client_id=child-session-smoke"
+ async with websockets.connect(ws_url) as ws:
+ await _recv_until(ws, "ready")
+ await ws.send(json.dumps({
+ "type": "webui_request", "request_id": "delete-parent",
+ "action": "session.delete", "payload": {"key": parent.key},
+ }))
+ response = await _recv_until(ws, "webui_response")
+ assert response["ok"] is True, response
+ assert sessions.read_session_file(parent.key) is None
+ assert all(sessions.read_session_file(children.key(task_id)) is None for task_id in tasks)
+ finally:
+ _stop_gateway(process)
+
+
@pytest.mark.asyncio
async def test_desktop_terminal_identity_and_independent_client_lifetime(tmp_path: Path) -> None:
"""Two terminal clients exercise real authentication, framing and gateway lifetime."""
diff --git a/tests/webui/test_remote_proxy_bootstrap.py b/tests/webui/test_remote_proxy_bootstrap.py
new file mode 100644
index 000000000..7b680bc82
--- /dev/null
+++ b/tests/webui/test_remote_proxy_bootstrap.py
@@ -0,0 +1,57 @@
+"""An optional host capability survives the authenticated bootstrap proxy."""
+
+import json
+from unittest.mock import MagicMock
+
+import httpx
+import pytest
+from aiohttp.test_utils import make_mocked_request
+
+from nanobot.webui.remote_proxy import RemoteProxy
+from nanobot.webui.remote_ssh import Tunnel
+
+
[email protected]("capabilities", [
+ ["webui.core.v1"],
+ ["webui.core.v1", "webui.subagents.v1"],
+ ["webui.core.v1", "webui.subagents.v1", "webui.subagents.events.v1"],
+ ["webui.core.v1", "webui.subagents.v1", "webui.subagents.events.v1", "webui.subagents.history.v1"],
+])
+async def test_proxy_preserves_independently_declared_host_capabilities(monkeypatch, capabilities):
+ tunnel = MagicMock(spec=Tunnel)
+ tunnel.active = True
+ tunnel.port = 18791
+ proxy = RemoteProxy(tunnel, "private-upstream-secret", "gateway-test", "")
+ declaration = {
+ "version": "custom-host", "min_protocol": 1, "max_protocol": 1,
+ "capabilities": capabilities,
+ }
+
+ def upstream(request):
+ assert request.url.path == "/webui/bootstrap"
+ assert request.headers["X-Nanobot-Auth"] == "private-upstream-secret"
+ return httpx.Response(200, json={
+ "terminal": {"protocolVersion": 1, "gatewayId": "gateway-test", "webui": declaration},
+ "token": "upstream-ws-token", "api_token": "upstream-api-token",
+ "expires_in": 300, "ws_path": "/custom/ws",
+ })
+
+ client_type = httpx.AsyncClient
+ monkeypatch.setattr("nanobot.webui.remote_proxy.httpx.AsyncClient", lambda **kwargs: (
+ client_type(transport=httpx.MockTransport(upstream), **kwargs)
+ ))
+ request = make_mocked_request("GET", "/webui/bootstrap", headers={
+ "Host": "127.0.0.1:0", "X-Nanobot-Auth": proxy.secret,
+ })
+ try:
+ response = await proxy._handle(request)
+ assert response.status == 200
+ payload = json.loads(response.text)
+ assert payload["terminal"]["webui"] == declaration
+ assert payload["host_compatibility"]["status"] == "compatible"
+ assert payload["token"] != "upstream-ws-token"
+ assert payload["api_token"] != "upstream-api-token"
+ assert "private-upstream-secret" not in response.text
+ finally:
+ await proxy.close()
diff --git a/tests/webui/test_subagent_persistence.py b/tests/webui/test_subagent_persistence.py
new file mode 100644
index 000000000..b35b33eb5
--- /dev/null
+++ b/tests/webui/test_subagent_persistence.py
@@ -0,0 +1,731 @@
+"""A restarted host replays task observations without recovering execution."""
+
+import asyncio
+import json
+import subprocess
+import sys
+import textwrap
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, MagicMock
+from urllib.parse import quote
+
+import pytest
+from websockets.datastructures import Headers
+from websockets.http11 import Request
+
+from nanobot.agent.memory import Consolidator
+from nanobot.agent.runner import AgentRunResult
+from nanobot.agent.subagent import SubagentControlError, SubagentManager
+from nanobot.agent.subagent_sessions import SUBAGENT, TASK_METADATA_KEY, SubagentSessions
+from nanobot.agent.tools.context import RequestContext, current_request_context, request_context
+from nanobot.agent.tools.session_messages import ListSessionsTool, SendSessionMessageTool
+from nanobot.agent.tools.sessions import ReadSessionTool, SearchSessionsTool
+from nanobot.bus.queue import MessageBus
+from nanobot.bus.runtime_events import SubagentTaskChanged
+from nanobot.channels.websocket.runtime import WebSocketChannel, WebSocketConfig
+from nanobot.providers.base import (
+ GenerationSettings,
+ LLMProvider,
+ LLMResponse,
+ ProviderConversationState,
+ ToolCallRequest,
+)
+from nanobot.session.manager import SessionManager
+from nanobot.session.session_handles import SessionHandleResolver
+from nanobot.session.summary import SessionSummaryCheckpoint, is_summary_checkpoint
+from nanobot.session.types import PARENT_SESSION_KEY, SESSION_TYPE_KEY
+from nanobot.session.webui_turns import WebuiTurnCoordinator
+from nanobot.utils.llm_runtime import LLMRuntime
+from nanobot.webui.gateway_services import build_gateway_services
+
+
+def manager_with_storage(workspace, sessions_root):
+ sessions = SessionManager(workspace, sessions_root=sessions_root)
+ manager = SubagentManager(
+ workspace=workspace, bus=MessageBus(), max_tool_result_chars=16000,
+ consolidator=MagicMock(spec=Consolidator), session_manager=sessions,
+ )
+ provider = MagicMock(spec=LLMProvider)
+ provider.generation = GenerationSettings()
+ runtime = LLMRuntime.capture(provider, "test", context_window_tokens=128000)
+ return manager, sessions, runtime
+
+
+def gateway_for(manager, sessions, workspace):
+ gateway = build_gateway_services(
+ config=WebSocketConfig(), bus=manager.bus, session_manager=sessions,
+ static_dist_path=None, workspace_path=workspace, default_restrict_to_workspace=True,
+ config_path=workspace.parent / "config.json", runtime_model_name=None,
+ runtime_surface="gateway", runtime_capabilities_overrides=None, subagent_manager=manager,
+ )
+ token = gateway.tokens.issue_api_token(60)
+ return gateway, SimpleNamespace(remote_address=("127.0.0.1", 12345)), Headers({"Authorization": f"Bearer {token}"})
+
+
+async def test_child_thread_reads_real_session_through_parent_without_new_persistence(tmp_path):
+ workspace, root = tmp_path / "agent", tmp_path / "sessions"
+ workspace.mkdir()
+ (workspace / "config.txt").write_text("configured value", encoding="utf-8")
+ manager, sessions, runtime = manager_with_storage(workspace, root)
+ entered, release = asyncio.Event(), asyncio.Event()
+ final_text = ("## Findings\n\n" + "Verified configuration.\n" * 1000).rstrip()
+ calls = 0
+
+ async def respond(**_kwargs):
+ nonlocal calls
+ calls += 1
+ if calls == 1:
+ return LLMResponse(content="Inspecting configuration", tool_calls=[
+ ToolCallRequest("read-config", "read_file", {"path": "config.txt"}),
+ ])
+ entered.set()
+ await release.wait()
+ return LLMResponse(content=final_text)
+
+ runtime.provider.chat_stream_with_retry = AsyncMock(side_effect=respond)
+ gateway, connection, headers = gateway_for(manager, sessions, workspace)
+ try:
+ await manager.spawn("Inspect configuration", session_key="websocket:parent", runtime=runtime)
+ await asyncio.wait_for(entered.wait(), 5)
+ task_id, = manager.statuses_for_session("websocket:parent")
+ child_key = SubagentSessions.key(task_id)
+ path = f"/api/sessions/websocket%3Aparent/subagents/{task_id}/webui-thread"
+ files_before = set(root.rglob("*"))
+ denied = await gateway.http.dispatch(connection, Request(path, Headers()))
+ assert denied.status_code == 401
+ unknown = []
+ for candidate in (path.replace("parent", "other"), path.replace(task_id, "missing")):
+ response = await gateway.http.dispatch(connection, Request(candidate, headers))
+ assert response.status_code == 404
+ unknown.append(response.body)
+ assert unknown[0] == unknown[1]
+ direct = await gateway.http.dispatch(connection, Request(
+ f"/api/sessions/{quote(child_key, safe='')}/webui-thread", headers,
+ ))
+ assert direct.status_code == 404
+ response = await gateway.http.dispatch(connection, Request(path, headers))
+ assert response.status_code == 200
+ assert response.headers["Cache-Control"] == "no-store"
+ running = json.loads(response.body)
+ assert running["active_turn_id"]
+ assert [(event["event"], event.get("text")) for event in running["events"][:2]] == [
+ ("user_message", "Inspect configuration"), ("message", "Inspecting configuration"),
+ ]
+ tool = next(event for event in running["events"] if event.get("kind") == "tool_hint")
+ assert tool["tool_events"][0]["phase"] == "end"
+ assert "configured value" in tool["tool_events"][0]["result"]
+ assert set(root.rglob("*")) == files_before
+ release.set()
+ await asyncio.gather(*list(manager._running_tasks.values()))
+ assert len(manager.check(task_id, "websocket:parent").result) == 16000
+ await manager.close()
+ manager, sessions, _ = manager_with_storage(workspace, root)
+ gateway, connection, headers = gateway_for(manager, sessions, workspace)
+ response = await gateway.http.dispatch(connection, Request(path, headers))
+ completed = json.loads(response.body)
+ assert completed["active_turn_id"] is None
+ assert next(event["text"] for event in completed["events"] if event.get("turn_phase") == "answer") == final_text
+ assert [event["projection_id"] for event in completed["events"][:3]] == [
+ event["projection_id"] for event in running["events"]
+ ]
+ assert manager.get_running_count() == 0
+ deleted = await gateway.http.dispatch_webui_mutation(connection, "session.delete", {"key": "websocket:parent"})
+ assert deleted.status_code == 200
+ assert (await gateway.http.dispatch(connection, Request(path, headers))).status_code == 404
+ finally:
+ release.set()
+ await manager.close()
+
+
+async def test_new_unsaved_parent_has_an_empty_task_collection(tmp_path):
+ workspace = tmp_path / "agent"
+ manager, sessions, _ = manager_with_storage(workspace, tmp_path / "sessions")
+ gateway, connection, headers = gateway_for(manager, sessions, workspace)
+ key = "websocket:new-chat"
+ try:
+ response = await gateway.http.dispatch(
+ connection, Request(f"/api/sessions/{quote(key, safe='')}/subagents", headers),
+ )
+ assert response.status_code == 200
+ assert json.loads(response.body) == {"tasks": []}
+ assert response.headers["Cache-Control"] == "no-store"
+ assert sessions.read_session_metadata(key) is None
+ finally:
+ await manager.close()
+
+
+async def test_child_activity_replays_real_tool_errors_and_file_diffs(tmp_path):
+ workspace, root = tmp_path / "agent", tmp_path / "sessions"
+ workspace.mkdir()
+ (workspace / "example.txt").write_text("before\n", encoding="utf-8")
+ manager, sessions, runtime = manager_with_storage(workspace, root)
+ entered, release = asyncio.Event(), asyncio.Event()
+ responses = iter([
+ LLMResponse(content="Read the file", tool_calls=[
+ ToolCallRequest("read", "read_file", {"path": "example.txt"}),
+ ]),
+ LLMResponse(content="Edit the file", tool_calls=[
+ ToolCallRequest("edit", "edit_file", {
+ "path": "example.txt", "old_text": "before", "new_text": "after",
+ }),
+ ]),
+ LLMResponse(content="Check the missing file", tool_calls=[
+ ToolCallRequest("missing", "read_file", {"path": "missing.txt"}),
+ ]),
+ ])
+
+ async def respond(**kwargs):
+ for message in kwargs["messages"]:
+ assert not ({"tool_events", "file_edit_events"} & message.keys())
+ response = next(responses, None)
+ if response is not None:
+ return response
+ entered.set()
+ await release.wait()
+ return LLMResponse(content="Edited the file; the other file does not exist.")
+
+ runtime.provider.chat_stream_with_retry = AsyncMock(side_effect=respond)
+ gateway, connection, headers = gateway_for(manager, sessions, workspace)
+ try:
+ await manager.spawn("Edit and inspect files", session_key="websocket:parent", runtime=runtime)
+ await asyncio.wait_for(entered.wait(), 5)
+ task_id, = manager.statuses_for_session("websocket:parent")
+ path = f"/api/sessions/websocket%3Aparent/subagents/{task_id}/webui-thread"
+
+ async def assert_activity(gateway, connection, headers):
+ before = {file.name: file.read_bytes() for file in root.glob("*.jsonl")}
+ response = await gateway.http.dispatch(connection, Request(path, headers))
+ assert response.status_code == 200
+ thread = json.loads(response.body)
+ tools = [tool for event in thread["events"] for tool in event.get("tool_events", [])]
+ failure = next(tool for tool in tools if tool["call_id"] == "missing" and tool["phase"] == "error")
+ assert "File not found" in failure["error"]
+ edits = [edit for event in thread["events"] if event["event"] == "file_edit" for edit in event["edits"]]
+ completed = next(edit for edit in edits if edit["phase"] == "end")
+ assert completed["added"] == completed["deleted"] == 1
+ assert "+after" in completed["diff"]["text"]
+ assert "-before" in completed["diff"]["text"]
+ assert (workspace / "example.txt").read_text(encoding="utf-8") == "after\n"
+ assert {file.name: file.read_bytes() for file in root.glob("*.jsonl")} == before
+ return thread
+
+ assert (await assert_activity(gateway, connection, headers))["active_turn_id"]
+ release.set()
+ await asyncio.gather(*list(manager._running_tasks.values()))
+ await manager.close()
+ manager, sessions, _ = manager_with_storage(workspace, root)
+ gateway, connection, headers = gateway_for(manager, sessions, workspace)
+ assert (await assert_activity(gateway, connection, headers))["active_turn_id"] is None
+ assert manager.check(task_id, "websocket:parent").state == "done"
+ finally:
+ release.set()
+ await manager.close()
+
+
+async def test_provider_hosted_activity_is_visible_before_response_and_replays_in_order(tmp_path):
+ workspace, root = tmp_path / "agent", tmp_path / "sessions"
+ workspace.mkdir()
+ manager, sessions, runtime = manager_with_storage(workspace, root)
+ entered, release = asyncio.Event(), asyncio.Event()
+
+ async def respond(*, on_tool_call_delta, messages, **_kwargs):
+ assert all(not ({"tool_events", "file_edit_events"} & message.keys()) for message in messages)
+ activity = {
+ "kind": "hosted_tool", "call_id": "hosted-search", "name": "web_search",
+ "arguments": {"query": "nanobot"},
+ }
+ await on_tool_call_delta({**activity, "phase": "start"})
+ entered.set()
+ await release.wait()
+ await on_tool_call_delta({**activity, "phase": "end", "result": "Found documentation"})
+ return LLMResponse(content="## Findings\n\nFound documentation.")
+
+ runtime.provider.chat_stream_with_retry = AsyncMock(side_effect=respond)
+ gateway, connection, headers = gateway_for(manager, sessions, workspace)
+ try:
+ await manager.spawn("Search documentation", session_key="websocket:parent", runtime=runtime)
+ await asyncio.wait_for(entered.wait(), 5)
+ task_id, = manager.statuses_for_session("websocket:parent")
+ path = f"/api/sessions/websocket%3Aparent/subagents/{task_id}/webui-thread"
+ response = await gateway.http.dispatch(connection, Request(path, headers))
+ running = json.loads(response.body)
+ tool = next(event for event in running["events"] if event.get("kind") == "tool_hint")
+ assert tool["tool_events"][0]["phase"] == "start"
+ assert running["active_turn_id"]
+ _, child = manager.read_session(task_id, "websocket:parent")
+ assert child.get_history() == [{"role": "user", "content": "Search documentation"}]
+
+ release.set()
+ await asyncio.gather(*list(manager._running_tasks.values()))
+ await manager.close()
+ manager, sessions, _ = manager_with_storage(workspace, root)
+ gateway, connection, headers = gateway_for(manager, sessions, workspace)
+ response = await gateway.http.dispatch(connection, Request(path, headers))
+ completed = json.loads(response.body)
+ assert completed["active_turn_id"] is None
+ activity_index = next(i for i, event in enumerate(completed["events"]) if event.get("kind") == "tool_hint")
+ answer_index = next(i for i, event in enumerate(completed["events"]) if event.get("turn_phase") == "answer")
+ assert activity_index < answer_index
+ tool = completed["events"][activity_index]["tool_events"][0]
+ assert tool["phase"] == "end"
+ assert tool["result"] == "Found documentation"
+ _, child = manager.read_session(task_id, "websocket:parent")
+ assert all(not ({"tool_events", "file_edit_events"} & message.keys()) for message in child.get_history())
+ finally:
+ release.set()
+ await manager.close()
+
+
+async def test_task_changes_use_parent_chat_events_and_saved_child_observations(tmp_path):
+ manager, sessions, runtime = manager_with_storage(tmp_path / "agent", tmp_path / "sessions")
+ gateway, _, _ = gateway_for(manager, sessions, tmp_path / "agent")
+ channel = WebSocketChannel(WebSocketConfig(), manager.bus, gateway=gateway)
+ channel._safe_send_to = AsyncMock()
+ parent_connection, other_connection = MagicMock(), MagicMock()
+ channel._attach(parent_connection, "parent")
+ channel._attach(other_connection, "other")
+ coordinator = WebuiTurnCoordinator(manager.bus, sessions, schedule_background=MagicMock())
+ entered, release = asyncio.Queue(), asyncio.Event()
+
+ async def held(spec):
+ await spec.checkpoint_callback({"phase": "awaiting_model", "iteration": 1})
+ await entered.put(True)
+ await release.wait()
+ return AgentRunResult(messages=[], final_content="## Private findings\n\n- Verified")
+
+ async def deliver():
+ await manager.bus.drain()
+ while manager.bus.outbound_size:
+ message = await manager.bus.consume_outbound()
+ assert isinstance(message.event, SubagentTaskChanged)
+ await channel.send(message)
+ return [
+ (call.args[0], json.loads(call.args[1]))
+ for call in channel._safe_send_to.await_args_list
+ ]
+
+ manager.runner.run = held
+ try:
+ with coordinator.connected():
+ for chat in ("parent", "parent", "other"):
+ await manager.spawn(
+ "Investigate configuration", origin_channel="websocket", origin_chat_id=chat,
+ session_key=f"websocket:{chat}", origin_turn_id="finished-parent-turn", runtime=runtime,
+ )
+ await asyncio.wait_for(entered.get(), 2)
+ first, sibling = manager.statuses_for_session("websocket:parent")
+ foreign, = manager.statuses_for_session("websocket:other")
+ parent = sessions.get_existing("websocket:parent")
+ parent.add_message("assistant", "Parent reply already delivered")
+ sessions.save(parent)
+ original_messages = parent.messages.copy()
+ routed = await deliver()
+ assert {payload["task"]["task_id"] for conn, payload in routed if conn is parent_connection} == {first, sibling}
+ assert {payload["task"]["task_id"] for conn, payload in routed if conn is other_connection} == {foreign}
+ for _, payload in routed:
+ assert payload["event"] == "subagent_task"
+ assert "turn_id" not in payload
+ assert "owner" not in payload["task"]
+ assert payload["task"]["phase"] == "awaiting_model"
+ assert payload["task"]["revision"] > 1
+ previous_revision = manager.check(first, "websocket:parent").revision
+ channel._safe_send_to.reset_mock()
+ stopped = await manager.cancel(first, "websocket:parent")
+ routed = await deliver()
+ assert routed and all(conn is parent_connection for conn, _ in routed)
+ assert all(payload["task"]["state"] == "cancelled" for _, payload in routed)
+ assert stopped.revision > previous_revision
+ assert manager.check(sibling, "websocket:parent").state == "running"
+ channel._safe_send_to.reset_mock()
+ release.set()
+ await asyncio.gather(*list(manager._running_tasks.values()), return_exceptions=True)
+ routed = await deliver()
+ assert any(conn is parent_connection and payload["task"]["state"] == "done" for conn, payload in routed)
+ assert parent.messages == original_messages
+ saved = manager.sessions.status(sibling, "websocket:parent")
+ assert saved.revision == manager.check(sibling, "websocket:parent").revision
+ assert saved.result == "## Private findings\n\n- Verified"
+
+ channel._safe_send_to.reset_mock()
+ await manager.spawn(
+ "Queued before parent deletion", origin_channel="websocket", origin_chat_id="parent",
+ session_key="websocket:parent", runtime=runtime,
+ )
+ await manager.bus.drain()
+ assert manager.bus.outbound_size > 0
+ sessions.delete_session("websocket:parent")
+ assert await deliver() == []
+ finally:
+ await manager.close()
+ await manager.bus.drain()
+ await channel._cleanup_connection(parent_connection)
+ await channel._cleanup_connection(other_connection)
+
+
+async def test_abrupt_process_exit_preserves_terminal_records_and_interrupts_pending_work(tmp_path):
+ workspace, sessions_root = tmp_path / "agent", tmp_path / "sessions"
+ script = tmp_path / "host.py"
+ result_path = tmp_path / "ids.json"
+ script.write_text(textwrap.dedent('''
+ import asyncio, json, os, sys
+ from pathlib import Path
+ from unittest.mock import AsyncMock, MagicMock
+ from nanobot.agent.hook import AgentHookContext
+ from nanobot.agent.memory import Consolidator
+ from nanobot.agent.runner import AgentRunResult
+ from nanobot.agent.subagent import SubagentManager
+ from nanobot.bus.queue import MessageBus
+ from nanobot.providers.base import GenerationSettings, LLMProvider, LLMResponse, LLMUsage
+ from nanobot.session.manager import SessionManager
+ from nanobot.utils.llm_runtime import LLMRuntime
+
+ async def main():
+ workspace = Path(sys.argv[1])
+ sessions = SessionManager(workspace, sessions_root=Path(sys.argv[2]))
+ parent = sessions.get_or_create("websocket:parent")
+ parent.add_message("user", "Delegate the inspection", webui_turn_id="turn-1")
+ sessions.save(parent, fsync=True)
+ manager = SubagentManager(workspace=workspace, bus=MessageBus(), max_tool_result_chars=16000,
+ max_concurrent_subagents=1, consolidator=MagicMock(spec=Consolidator), session_manager=sessions)
+ provider = MagicMock(spec=LLMProvider)
+ provider.generation = GenerationSettings()
+ runtime = LLMRuntime.capture(provider, "test", context_window_tokens=128000)
+ manager.runner.run = AsyncMock(return_value=AgentRunResult(messages=[], final_content="Verified"))
+ await manager.run_inline("completed", session_key=parent.key, origin_turn_id="turn-1", runtime=runtime)
+ done, = manager.statuses_for_session(parent.key)
+ entered = asyncio.Event()
+ async def pending(spec):
+ await spec.hook.after_iteration(AgentHookContext(iteration=1, messages=[], response=LLMResponse(content="Partial findings"), usage=LLMUsage.reported(input_tokens=10, output_tokens=5)))
+ entered.set()
+ await asyncio.Event().wait()
+ manager.runner.run = pending
+ await manager.spawn("running", session_key=parent.key, origin_turn_id="turn-1", runtime=runtime)
+ await entered.wait()
+ await manager.spawn("queued", session_key=parent.key, origin_turn_id="turn-1", runtime=runtime)
+ statuses = manager.statuses_for_session(parent.key)
+ ids = {status.task_description: task_id for task_id, status in statuses.items()}
+ manager.send(ids["running"], parent.key, "Not yet delivered")
+ Path(sys.argv[3]).write_text(json.dumps(ids))
+ os._exit(0)
+ asyncio.run(main())
+ '''), encoding="utf-8")
+ subprocess.run([sys.executable, str(script), str(workspace), str(sessions_root), str(result_path)], check=True, timeout=15)
+ ids = json.loads(result_path.read_text())
+ manager, sessions, _ = manager_with_storage(workspace, sessions_root)
+ manager.runner.run = AsyncMock()
+ assert manager.check(ids["running"], "websocket:parent").state == "running"
+ manager.recover_interrupted()
+ gateway, connection, headers = gateway_for(manager, sessions, workspace)
+ path = f"/api/sessions/{quote('websocket:parent', safe='')}/subagents"
+ try:
+ first = await gateway.http.dispatch(connection, Request(path, headers))
+ assert first.status_code == 200
+ by_id = {task["task_id"]: task for task in json.loads(first.body)["tasks"]}
+ assert by_id[ids["completed"]]["state"] == "done"
+ assert by_id[ids["completed"]]["result"] == "Verified"
+ for name in ("running", "queued"):
+ assert by_id[ids[name]]["state"] == "interrupted"
+ assert by_id[ids[name]]["stop_reason"] == "host_restarted"
+ assert by_id[ids["running"]]["result"] == "Partial findings"
+ assert by_id[ids["running"]]["partial"] is True
+ assert by_id[ids["running"]]["usage"]["input_tokens"] == 10
+ assert list(by_id[ids["running"]]["receipts"].values()) == ["undelivered"]
+ assert by_id[ids["queued"]]["partial"] is False
+ assert all(task["origin_turn_id"] == "turn-1" for task in by_id.values())
+ assert all(task["created_at"] > 0 and task["completed_at"] > 0 for task in by_id.values())
+ assert manager.get_running_count() == 0
+ assert manager.bus.inbound_size == 0
+ manager.runner.run.assert_not_called()
+ second = await gateway.http.dispatch(connection, Request(path, headers))
+ assert second.body == first.body
+ persisted_parent = sessions.read_session_file("websocket:parent")
+ assert [row["content"] for row in persisted_parent["messages"]] == ["Delegate the inspection"]
+ assert {row["key"] for row in sessions.list_sessions()} == {
+ "websocket:parent", *(SubagentSessions.key(task_id) for task_id in ids.values()),
+ }
+ assert [handle.session_key for handle in SessionHandleResolver(sessions).list_all()] == ["websocket:parent"]
+ assert not list(sessions.sessions_dir.glob("*.subagents.json"))
+ with pytest.raises(SubagentControlError, match="task unavailable"):
+ manager.check(ids["completed"], "websocket:other")
+ third_manager, _, _ = manager_with_storage(workspace, sessions_root)
+ assert {key: value.as_dict() for key, value in third_manager.statuses_for_session("websocket:parent").items()} == by_id
+ await third_manager.close()
+ finally:
+ await manager.close()
+
+
+async def test_child_preserves_transcript_provider_state_and_summary_in_common_session(tmp_path):
+ manager, sessions, runtime = manager_with_storage(tmp_path / "agent", tmp_path / "sessions")
+ provider_state = ProviderConversationState(
+ kind="openai_responses", provider="openai:test", model="test", version=1,
+ payload={"response_id": "child-response"},
+ )
+
+ async def run(spec):
+ request = current_request_context()
+ assert request.session_key == spec.session_key
+ assert spec.session_key.startswith("subagent:")
+ assert spec.initial_messages[-1] == {"role": "user", "content": "Inspect the config"}
+ assert {"subagent", "send_session_message", "list_sessions"}.isdisjoint(
+ definition["function"]["name"] for definition in spec.tools.get_definitions()
+ )
+ return AgentRunResult(
+ messages=[*spec.initial_messages,
+ {"role": "assistant", "content": "Inspecting", "tool_calls": [
+ {"id": "read-1", "type": "function", "function": {"name": "read_file", "arguments": "{}"}},
+ ]},
+ {"role": "tool", "tool_call_id": "read-1", "content": "config contents"},
+ {"role": "assistant", "content": "Verified"}],
+ final_content="Verified", provider_state=provider_state,
+ summary_checkpoint=SessionSummaryCheckpoint("Configuration inspected", 4),
+ )
+
+ manager.runner.run = run
+ try:
+ await manager.run_inline("Inspect the config", session_key="websocket:parent", runtime=runtime)
+ task_id, = manager.statuses_for_session("websocket:parent")
+ reopened, restored, _ = manager_with_storage(tmp_path / "agent", tmp_path / "sessions")
+ child = restored.get_existing(SubagentSessions.key(task_id))
+ assert child.metadata[SESSION_TYPE_KEY] == SUBAGENT.name
+ assert child.metadata[PARENT_SESSION_KEY] == "websocket:parent"
+ assert [message["role"] for message in child.messages] == ["user", "assistant", "tool", "user", "assistant"]
+ assert is_summary_checkpoint(child.messages[3])
+ assert child.metadata["_last_summary"]["text"] == "Configuration inspected"
+ assert child.provider_state == provider_state
+ assert reopened.check(task_id, "websocket:parent").result == "Verified"
+ await reopened.close()
+ finally:
+ await manager.close()
+
+
+async def test_child_is_unavailable_to_public_session_tools(tmp_path):
+ manager, sessions, runtime = manager_with_storage(tmp_path / "agent", tmp_path / "sessions")
+ sessions.save(sessions.get_or_create("websocket:other"))
+ manager.runner.run = AsyncMock(return_value=AgentRunResult(messages=[], final_content="Private findings"))
+ try:
+ await manager.run_inline("Private investigation", session_key="websocket:parent", runtime=runtime)
+ task_id, = manager.statuses_for_session("websocket:parent")
+ child_key = SubagentSessions.key(task_id)
+ public_handle = SessionHandleResolver(sessions).handle_for_session("websocket:other")
+ sender = SendSessionMessageTool(sessions=sessions, bus=manager.bus)
+ with request_context(RequestContext(channel="websocket", chat_id="other", session_key="websocket:other")):
+ assert json.loads(await SearchSessionsTool(sessions).execute(query="Private investigation"))["results"] == []
+ assert "not found" in await ReadSessionTool(sessions).execute(session_key=child_key)
+ handles = json.loads(await ListSessionsTool(sessions).execute())
+ assert len(handles) == 1
+ assert "Error:" in await sender.execute(to=child_key, content="bypass parent", expect_reply=False)
+ with request_context(RequestContext(channel="websocket", chat_id="parent", session_key=child_key)):
+ assert "Error:" in await sender.execute(to=public_handle.name, content="bypass parent", expect_reply=False)
+ assert manager.bus.inbound_size == 0
+ assert manager.check(task_id, "websocket:parent").result == "Private findings"
+ finally:
+ await manager.close()
+
+
+async def test_constructing_another_reader_does_not_interrupt_running_work(tmp_path):
+ workspace, root = tmp_path / "agent", tmp_path / "sessions"
+ manager, sessions, runtime = manager_with_storage(workspace, root)
+ entered, release = asyncio.Event(), asyncio.Event()
+
+ async def held(_spec):
+ entered.set()
+ await release.wait()
+ return AgentRunResult(messages=[], final_content="Verified")
+
+ manager.runner.run = held
+ try:
+ await manager.spawn("inspect", session_key="websocket:parent", runtime=runtime)
+ await entered.wait()
+ task_id, = manager.statuses_for_session("websocket:parent")
+ receipt = manager.send(task_id, "websocket:parent", "Follow-up")
+ path = sessions._get_session_path(SubagentSessions.key(task_id))
+ before = path.read_bytes()
+ reader, _, _ = manager_with_storage(workspace, root)
+ observed = reader.check(task_id, "websocket:parent")
+ assert observed.state == "running"
+ assert observed.receipts[receipt["message_id"]] == "accepted"
+ assert path.read_bytes() == before
+ await reader.close()
+ assert path.read_bytes() == before
+ finally:
+ release.set()
+ await manager.close()
+
+
+async def test_webui_deletion_cancels_parent_work_and_removes_child_sessions(tmp_path):
+ manager, sessions, runtime = manager_with_storage(tmp_path / "agent", tmp_path / "sessions")
+ entered = asyncio.Event()
+
+ async def held(_spec):
+ entered.set()
+ await asyncio.Event().wait()
+
+ manager.runner.run = held
+ await manager.spawn("inspect", session_key="websocket:parent", runtime=runtime)
+ await entered.wait()
+ task_id, = manager.statuses_for_session("websocket:parent")
+ child_key = SubagentSessions.key(task_id)
+ gateway, connection, _ = gateway_for(manager, sessions, tmp_path / "agent")
+
+ async def discard(key):
+ assert sessions.read_session_file(key) is not None
+ await manager.cancel_by_session(key)
+
+ gateway.http.discard_session = AsyncMock(side_effect=discard)
+ try:
+ response = await gateway.http.dispatch_webui_mutation(
+ connection, "session.delete", {"key": "websocket:parent"},
+ )
+ assert response.status_code == 200
+ assert json.loads(response.body)["deleted"] is True
+ gateway.http.discard_session.assert_awaited_once_with("websocket:parent")
+ assert sessions.read_session_file("websocket:parent") is None
+ assert sessions.read_session_file(child_key) is None
+ assert manager.bus.inbound_size == 0
+ assert manager.get_running_count() == 0
+ finally:
+ await manager.close()
+
+
+async def test_history_outlives_the_runtime_cache_and_follows_parent_deletion(tmp_path):
+ manager, sessions, runtime = manager_with_storage(tmp_path / "agent", tmp_path / "sessions")
+ manager.MAX_TERMINAL = 1
+ manager.runner.run = AsyncMock(return_value=AgentRunResult(messages=[], final_content="Verified"))
+ try:
+ for name in ("first", "second"):
+ await manager.run_inline(name, session_key="websocket:parent", origin_turn_id="turn-1", runtime=runtime)
+ tasks = manager.statuses_for_session("websocket:parent")
+ assert len(tasks) == 2
+ assert len(manager.runtime_statuses()) == 1
+ assert len(manager.statuses_for_session("websocket:parent", include_history=False)) == 1
+ first = next(status for status in tasks.values() if status.task_description == "first")
+ assert manager.check(first.task_id, "websocket:parent").result == "Verified"
+ fork = sessions.fork_session_before_user_index("websocket:parent", "websocket:fork", 0)
+ assert TASK_METADATA_KEY not in fork.metadata
+ assert sessions.child_session_keys(fork.key) == []
+ child_paths = [sessions._get_session_path(SubagentSessions.key(task_id)) for task_id in tasks]
+ assert all(path.exists() for path in child_paths)
+ assert sessions.delete_session("websocket:parent")
+ assert not any(path.exists() for path in child_paths)
+ assert manager.statuses_for_session("websocket:parent") == {}
+ with pytest.raises(SubagentControlError):
+ manager.check(first.task_id, "websocket:parent")
+ manager.sessions.save(first)
+ assert sessions.read_session_file("websocket:parent") is None
+ assert not any(path.exists() for path in child_paths)
+ finally:
+ await manager.close()
+
+
+async def test_task_progress_does_not_rewrite_parent_history_or_invalidate_checkpoint(tmp_path):
+ manager, sessions, runtime = manager_with_storage(tmp_path / "agent", tmp_path / "sessions")
+ parent = sessions.get_or_create("websocket:parent")
+ parent.add_message("user", "Inspect config", webui_turn_id="turn-1")
+ sessions.save(parent)
+ path = sessions._get_session_path(parent.key)
+ before, stamp = path.read_bytes(), path.stat()
+ parent.metadata["runtime_checkpoint"] = {"phase": "tools_completed"}
+ parent.provider_state = ProviderConversationState(
+ kind="openai_responses", provider="openai:test", model="test", version=1,
+ payload={"response_id": "private-response"},
+ )
+ sessions.save_runtime_checkpoint(parent)
+ checkpoint_path = sessions._get_runtime_checkpoint_path(parent.key)
+ checkpoint = checkpoint_path.read_bytes()
+ manager.runner.run = AsyncMock(return_value=AgentRunResult(messages=[], final_content="Verified"))
+ try:
+ await manager.run_inline("check", session_key=parent.key, runtime=runtime)
+ assert path.read_bytes() == before
+ assert path.stat().st_ino == stamp.st_ino
+ assert path.stat().st_mtime_ns == stamp.st_mtime_ns
+ assert checkpoint_path.read_bytes() == checkpoint
+ restored = SessionManager(tmp_path / "agent", sessions_root=tmp_path / "sessions").get_or_create(parent.key)
+ assert restored.metadata["runtime_checkpoint"]["phase"] == "tools_completed"
+ assert restored.provider_state.payload == {"response_id": "private-response"}
+ assert len(manager.statuses_for_session(parent.key)) == 1
+ finally:
+ await manager.close()
+
+
+async def test_temporary_parent_never_persists_task_content(tmp_path):
+ manager, sessions, runtime = manager_with_storage(tmp_path / "agent", tmp_path / "sessions")
+ parent = sessions.get_or_create_transient("websocket:temporary")
+ async def run(_spec):
+ assert current_request_context().log_content is False
+ return AgentRunResult(messages=[], final_content="Private findings")
+
+ manager.runner.run = run
+ try:
+ await manager.run_inline("private task", session_key=parent.key, runtime=runtime)
+ assert len(manager.statuses_for_session(parent.key)) == 1
+ assert sessions.read_session_file(parent.key) is None
+ task_id, = manager.statuses_for_session(parent.key)
+ child = sessions.get_cached(SubagentSessions.key(task_id))
+ assert child is not None and not child.policy.persist
+ assert sessions.read_session_file(child.key) is None
+ reopened, _, _ = manager_with_storage(tmp_path / "agent", tmp_path / "sessions")
+ assert reopened.statuses_for_session(parent.key) == {}
+ await reopened.close()
+ finally:
+ await manager.close()
+
+
+async def test_child_sessions_use_common_restore_and_migration(tmp_path):
+ workspace, root = tmp_path / "agent", tmp_path / "sessions"
+ manager, sessions, runtime = manager_with_storage(workspace, root)
+ parent = sessions.get_or_create("websocket:parent")
+ parent.add_message("user", "Inspect config")
+ sessions.save(parent)
+ manager.runner.run = AsyncMock(return_value=AgentRunResult(messages=[], final_content="Verified"))
+ try:
+ await manager.run_inline("inspect", session_key=parent.key, runtime=runtime)
+ task_id, = manager.statuses_for_session(parent.key)
+ child_key = SubagentSessions.key(task_id)
+ paths = [sessions._get_session_path(key) for key in (parent.key, child_key)]
+ result = sessions.restore_sessions_to_workspace()
+ assert result.restored == 2 and result.conflicts == ()
+ for path in paths:
+ assert (workspace / "sessions" / path.name).read_bytes() == path.read_bytes()
+ path.unlink()
+ reopened, migrated, _ = manager_with_storage(workspace, root)
+ assert migrated.child_session_keys(parent.key) == [child_key]
+ assert reopened.check(task_id, parent.key).result == "Verified"
+ assert not list((workspace / "sessions").glob("*.jsonl"))
+ await reopened.close()
+ finally:
+ await manager.close()
+
+
+async def test_unreadable_task_history_is_not_an_empty_list(tmp_path):
+ manager, sessions, runtime = manager_with_storage(tmp_path / "agent", tmp_path / "sessions")
+ parent = sessions.get_or_create("websocket:parent")
+ sessions.save(parent)
+ manager.runner.run = AsyncMock(return_value=AgentRunResult(messages=[], final_content="Verified"))
+ await manager.run_inline("inspect", session_key=parent.key, runtime=runtime)
+ task_id, = manager.statuses_for_session(parent.key)
+ child = sessions.get_existing(SubagentSessions.key(task_id))
+ child.metadata[TASK_METADATA_KEY] = "damaged"
+ sessions.save(child)
+ gateway, connection, headers = gateway_for(manager, sessions, tmp_path / "agent")
+ try:
+ path = f"/api/sessions/{quote(parent.key, safe='')}/subagents"
+ response = await gateway.http.dispatch(connection, Request(path, headers))
+ assert response.status_code == 503
+ assert "task history unavailable" in response.body.decode()
+ finally:
+ await manager.close()
diff --git a/tests/webui/test_subagent_tasks.py b/tests/webui/test_subagent_tasks.py
new file mode 100644
index 000000000..d8b5c237a
--- /dev/null
+++ b/tests/webui/test_subagent_tasks.py
@@ -0,0 +1,94 @@
+"""The WebUI reads and cancels tasks through the session-owned lifecycle."""
+
+import asyncio
+import json
+from types import SimpleNamespace
+from unittest.mock import MagicMock
+from urllib.parse import quote
+
+import pytest
+from websockets.datastructures import Headers
+from websockets.http11 import Request
+
+from nanobot.agent.memory import Consolidator
+from nanobot.agent.subagent import SubagentManager
+from nanobot.bus.queue import MessageBus
+from nanobot.channels.websocket.runtime import WebSocketConfig
+from nanobot.providers.base import GenerationSettings, LLMProvider
+from nanobot.session.manager import SessionManager
+from nanobot.utils.llm_runtime import LLMRuntime
+from nanobot.webui.gateway_services import build_gateway_services
+
+
+async def test_webui_task_access_and_targeted_idempotent_cancel(tmp_path):
+ bus = MessageBus()
+ manager = SubagentManager(
+ workspace=tmp_path, bus=bus, max_tool_result_chars=16000,
+ consolidator=MagicMock(spec=Consolidator),
+ )
+ provider = MagicMock(spec=LLMProvider)
+ provider.generation = GenerationSettings()
+ runtime = LLMRuntime.capture(provider, "test", context_window_tokens=128000)
+ gateway = build_gateway_services(
+ config=WebSocketConfig(), bus=bus, session_manager=SessionManager(tmp_path),
+ static_dist_path=None, workspace_path=tmp_path, default_restrict_to_workspace=True,
+ config_path=tmp_path / "config.json", runtime_model_name=None,
+ runtime_surface="gateway", runtime_capabilities_overrides=None,
+ subagent_manager=manager,
+ )
+ connection = SimpleNamespace(remote_address=("127.0.0.1", 12345))
+ token = gateway.tokens.issue_api_token(60)
+ headers = Headers({"Authorization": f"Bearer {token}"})
+ entered = asyncio.Queue()
+
+ async def blocked(spec):
+ await entered.put(True)
+ await asyncio.Event().wait()
+
+ manager.runner.run = blocked
+ try:
+ for owner in ("websocket:a", "websocket:a", "websocket:b"):
+ await manager.spawn("work", session_key=owner, runtime=runtime)
+ await asyncio.wait_for(entered.get(), timeout=2)
+ first, sibling = manager.statuses_for_session("websocket:a")
+ foreign, = manager.statuses_for_session("websocket:b")
+ path = f"/api/sessions/{quote('websocket:a', safe='')}/subagents"
+ denied = await gateway.http.dispatch(connection, Request(path, Headers()))
+ assert denied.status_code == 401
+ response = await gateway.http.dispatch(connection, Request(path, headers))
+ assert response.status_code == 200
+ assert response.headers["Cache-Control"] == "no-store"
+ tasks = json.loads(response.body)["tasks"]
+ assert {task["task_id"] for task in tasks} == {first, sibling}
+ assert all(task["state"] == "running" and "owner" not in task for task in tasks)
+
+ http_stop = await gateway.http.dispatch(
+ connection, Request("/api/webui/subagents/cancel", headers),
+ )
+ assert http_stop.status_code == 405
+ errors = []
+ for task_id in (foreign, "missing"):
+ result = await gateway.http.dispatch_webui_mutation(
+ connection, "subagent.cancel", {"session_key": "websocket:a", "task_id": task_id},
+ )
+ assert result.status_code == 404
+ errors.append(result.body)
+ assert errors[0] == errors[1]
+ assert manager.check(foreign, "websocket:b").state == "running"
+
+ for _ in range(2):
+ result = await gateway.http.dispatch_webui_mutation(
+ connection, "subagent.cancel", {"session_key": "websocket:a", "task_id": first},
+ )
+ assert result.status_code == 200
+ assert json.loads(result.body)["state"] == "cancelled"
+ assert manager.check(sibling, "websocket:a").state == "running"
+ assert manager.check(foreign, "websocket:b").state == "running"
+ assert bus.inbound_size == 1
+ refreshed = await gateway.http.dispatch(connection, Request(path, headers))
+ assert {t["task_id"]: t["state"] for t in json.loads(refreshed.body)["tasks"]} == {
+ first: "cancelled", sibling: "running",
+ }
+ finally:
+ await manager.close()
diff --git a/webui/src/App.tsx b/webui/src/App.tsx
index 8f29e11ff..9cc58c3ae 100644
--- a/webui/src/App.tsx
+++ b/webui/src/App.tsx
@@ -116,8 +116,14 @@ type BootState =
modelName: string | null;
ingressLimits: BootstrapResponse["limits"] | null;
runtimeSurface: RuntimeSurface;
+ webuiCapabilities: string[];
};
+function bootstrapCapabilities(boot: BootstrapResponse): string[] {
+ const capabilities = boot.terminal?.webui?.capabilities;
+ return Array.isArray(capabilities) ? capabilities.filter((entry) => typeof entry === "string") : [];
+}
+
const SIDEBAR_STORAGE_KEY = "nanobot-webui.sidebar";
const SESSION_UPDATES_STORAGE_KEY = "nanobot-webui.sidebar.session-updates.v1";
const LEGACY_COMPLETED_RUNS_STORAGE_KEY = "nanobot-webui.sidebar.completed-runs.v1";
@@ -924,6 +930,7 @@ export default function App() {
modelName: boot.model_name ?? current.modelName,
ingressLimits: boot.limits ?? current.ingressLimits,
runtimeSurface,
+ webuiCapabilities: bootstrapCapabilities(boot),
}
: current,
);
@@ -971,6 +978,7 @@ export default function App() {
modelName: boot.model_name ?? null,
ingressLimits: boot.limits ?? null,
runtimeSurface,
+ webuiCapabilities: bootstrapCapabilities(boot),
});
} catch (e) {
if (cancelled) return;
@@ -1090,6 +1098,7 @@ export default function App() {
token={state.token}
modelName={state.modelName}
ingressLimits={state.ingressLimits}
+ webuiCapabilities={state.webuiCapabilities}
>
<RemoteInstances><Shell
runtimeSurface={state.runtimeSurface}
diff --git a/webui/src/components/thread/AgentActivityCluster.tsx b/webui/src/components/thread/AgentActivityCluster.tsx
index 957bcd918..014675b8e 100644
--- a/webui/src/components/thread/AgentActivityCluster.tsx
+++ b/webui/src/components/thread/AgentActivityCluster.tsx
@@ -52,6 +52,7 @@ import {
isReasoningOnlyAssistant,
} from "@/lib/activity-timeline";
import { useFileEditDisplayMode } from "@/hooks/useFileEditDisplayMode";
+import { useLocalPreferences } from "@/hooks/useLocalPreferences";
import { useLogoFallback } from "@/hooks/useLogoFallback";
import { usePageVisibility } from "@/hooks/usePageVisibility";
import { useThreadVisibility } from "@/hooks/useThreadVisibility";
@@ -250,7 +251,7 @@ function FoldedAgentActivity({
detailsId,
}: AgentActivityClusterProps) {
const { t } = useTranslation();
- const fileEditDisplayMode = useFileEditDisplayMode();
+ const { activityMode, fileEditDisplayMode } = useLocalPreferences();
const pageVisible = usePageVisibility();
const threadVisible = useThreadVisibility();
const activityMessages = useMemo(() => coalesceActivityMessages(messages), [messages]);
@@ -288,12 +289,15 @@ function FoldedAgentActivity({
const [now, setNow] = useState(() => Date.now());
const wasTurnStreamingRef = useRef(isTurnStreaming);
const wasTurnStreaming = wasTurnStreamingRef.current;
- /** Live work stays open; completed work briefly shows the done state, then tucks away. */
+ /** Auto follows execution; expanded keeps details open unless manually collapsed. */
const outerExpanded = expanded ?? (
userToggledOuter
? outerOpenLocal
- : isTurnStreaming || completionHoldOpen || (wasTurnStreaming && !isTurnStreaming)
+ : activityMode === "expanded" || isTurnStreaming || completionHoldOpen || (wasTurnStreaming && !isTurnStreaming)
);
+ useEffect(() => {
+ setUserToggledOuter(false);
+ }, [activityMode]);
const deferredTraceRefs = useMemo(
() => Array.from(new Set(
messages
diff --git a/webui/src/components/thread/SubagentTasks.tsx b/webui/src/components/thread/SubagentTasks.tsx
new file mode 100644
index 000000000..5e32edfd3
--- /dev/null
+++ b/webui/src/components/thread/SubagentTasks.tsx
@@ -0,0 +1,326 @@
+import { createContext, useContext, useEffect, useId, useLayoutEffect, useRef, useState, type ComponentProps, type ReactNode } from "react";
+import { Bot, CheckCircle2, ChevronDown, ChevronRight, CircleAlert, CircleMinus, LoaderCircle, Square } from "lucide-react";
+import { useTranslation } from "react-i18next";
+
+import { Button } from "@/components/ui/button";
+import { SubagentThread } from "@/components/thread/SubagentThread";
+import { ThreadMessages } from "@/components/thread/ThreadMessages";
+import { Sheet, SheetContent, SheetDescription, SheetTitle } from "@/components/ui/sheet";
+import { usePageVisibility } from "@/hooks/usePageVisibility";
+import { useLocalPreferences } from "@/hooks/useLocalPreferences";
+import { useThreadVisibility } from "@/hooks/useThreadVisibility";
+import { cancelSubagentTask, fetchSubagentTasks } from "@/lib/api";
+import type { NanobotClient } from "@/lib/nanobot-client";
+import { isSubagentTask, mergeSubagentTasks, type ObservedSubagentTask } from "@/lib/subagent-tasks";
+import type { SubagentTaskSnapshot, UIMessage } from "@/lib/types";
+
+function isActive(task: SubagentTaskSnapshot): boolean {
+ return task.state === "queued" || task.state === "running" || task.state === "stopping";
+}
+
+interface TaskContext {
+ tasks: ObservedSubagentTask[];
+ loadError: string | null;
+ stopError: string | null;
+ stoppingId: string | null;
+ open: (task: SubagentTaskSnapshot, trigger: HTMLButtonElement) => void;
+ stop: (task: SubagentTaskSnapshot) => Promise<void>;
+ register: (id: string, button: HTMLButtonElement | null, previous: HTMLButtonElement | null) => void;
+}
+const TasksContext = createContext<TaskContext | null>(null);
+
+interface SubagentTasksProviderProps {
+ client: Pick<NanobotClient, "requestMutation" | "onChat" | "onStatus">;
+ sessionKey: string | null;
+ token: string;
+ enabled: boolean;
+ liveEvents: boolean;
+ historyEnabled?: boolean;
+ active?: boolean;
+ children: ReactNode;
+}
+
+export function SubagentTasksProvider({ client, sessionKey, token, enabled, liveEvents, historyEnabled = false, active = true, children }: SubagentTasksProviderProps) {
+ const { t } = useTranslation("common");
+ const pageVisible = usePageVisibility();
+ const paneVisible = useThreadVisibility();
+ const [tasks, setTasks] = useState<ObservedSubagentTask[]>([]);
+ const [selectedId, setSelectedId] = useState<string | null>(null);
+ const [stoppingId, setStoppingId] = useState<string | null>(null);
+ const [loadError, setLoadError] = useState<string | null>(null);
+ const [stopError, setStopError] = useState<string | null>(null);
+ const scopeGeneration = useRef(0);
+ const mounted = useRef(true);
+ const buttons = useRef(new Map<string, HTMLButtonElement>());
+ const trigger = useRef<HTMLButtonElement | null>(null);
+ const detailPanel = useRef<HTMLDivElement | null>(null);
+
+ useLayoutEffect(() => {
+ scopeGeneration.current += 1;
+ setTasks([]);
+ setSelectedId(null);
+ setStoppingId(null);
+ setLoadError(null);
+ setStopError(null);
+ return () => { scopeGeneration.current += 1; };
+ }, [client, sessionKey]);
+
+ useEffect(() => {
+ mounted.current = true;
+ return () => { mounted.current = false; };
+ }, []);
+
+ useEffect(() => {
+ if (!active || !paneVisible) setSelectedId(null);
+ }, [active, paneVisible]);
+
+ useEffect(() => {
+ if (!enabled || !active || !pageVisible || !paneVisible || !sessionKey || !token) return;
+ let cancelled = false;
+ let refreshing = false;
+ let refreshPending = false;
+ const refresh = async () => {
+ if (refreshing) { refreshPending = true; return; }
+ refreshing = true;
+ try {
+ const payload = await fetchSubagentTasks(token, sessionKey);
+ if (!cancelled) {
+ setTasks((current) => mergeSubagentTasks(current, payload.tasks));
+ setLoadError(null);
+ }
+ } catch {
+ if (!cancelled) setLoadError(t("thread.subagents.loadFailed"));
+ } finally {
+ refreshing = false;
+ if (refreshPending && !cancelled) {
+ refreshPending = false;
+ void refresh();
+ }
+ }
+ };
+ const unsubscribeChat = liveEvents ? client.onChat(sessionKey.slice("websocket:".length), (event) => {
+ if (cancelled || event.event !== "subagent_task") return;
+ if (!isSubagentTask(event.task)) {
+ setLoadError(t("thread.subagents.loadFailed"));
+ return;
+ }
+ setTasks((current) => mergeSubagentTasks(current, [event.task]));
+ }) : undefined;
+ const unsubscribeStatus = liveEvents ? client.onStatus((status) => {
+ if (status === "open") void refresh();
+ }) : undefined;
+ if (!refreshing) void refresh();
+ // Protocol 1 hosts may support task reads without the optional event stream.
+ const timer = liveEvents ? undefined : window.setInterval(() => void refresh(), 3000);
+ const focus = () => void refresh();
+ window.addEventListener("focus", focus);
+ return () => {
+ cancelled = true;
+ window.clearInterval(timer);
+ unsubscribeChat?.();
+ unsubscribeStatus?.();
+ window.removeEventListener("focus", focus);
+ };
+ }, [client, enabled, liveEvents, active, sessionKey, token, pageVisible, paneVisible, t]);
+
+ const stop = async (task: SubagentTaskSnapshot) => {
+ if (!sessionKey) return;
+ const generation = scopeGeneration.current;
+ setStoppingId(task.task_id);
+ setStopError(null);
+ try {
+ const next = await cancelSubagentTask(client, sessionKey, task.task_id);
+ if (!mounted.current || generation !== scopeGeneration.current) return;
+ setTasks((current) => mergeSubagentTasks(current, [next]));
+ } catch (reason) {
+ if (mounted.current && generation === scopeGeneration.current) setStopError(reason instanceof Error ? reason.message : t("thread.subagents.stopFailed"));
+ } finally {
+ if (mounted.current && generation === scopeGeneration.current) setStoppingId(null);
+ }
+ };
+ const selected = enabled && active && paneVisible ? tasks.find((task) => task.task_id === selectedId) : undefined;
+ const value: TaskContext = {
+ tasks: enabled ? tasks : [], loadError: enabled ? loadError : null,
+ stopError: enabled ? stopError : null, stoppingId,
+ open: (task, target) => { trigger.current = target; setSelectedId(task.task_id); }, stop,
+ register: (id, button, previous) => {
+ if (button) buttons.current.set(id, button);
+ else if (buttons.current.get(id) === previous) buttons.current.delete(id);
+ },
+ };
+
+ return <TasksContext.Provider value={value}>
+ {children}
+ <Sheet open={!!selected} onOpenChange={(open) => { if (!open) setSelectedId(null); }}>
+ <SheetContent ref={detailPanel} tabIndex={-1}
+ className="w-full gap-0 overflow-hidden border-l p-0 outline-none sm:w-[min(32rem,calc(100vw-1rem))] sm:max-w-none"
+ overlayClassName="bg-black/20 backdrop-blur-[8px]"
+ closeButtonClassName="right-3 top-3 grid h-9 w-9 place-items-center rounded-full hover:bg-muted"
+ onOpenAutoFocus={(event) => {
+ event.preventDefault();
+ detailPanel.current?.focus({ preventScroll: true });
+ }}
+ onCloseAutoFocus={(event) => {
+ event.preventDefault();
+ if (!active || !paneVisible) return;
+ const target = trigger.current?.isConnected ? trigger.current
+ : buttons.current.get(trigger.current?.dataset.subagentId ?? "");
+ const focusTarget = target?.closest("[hidden]")
+ ? target.closest("[data-subagent-work]")?.querySelector<HTMLButtonElement>("[aria-expanded]") : target;
+ focusTarget?.focus({ preventScroll: true });
+ }}>
+ <div className="shrink-0 space-y-2 border-b px-5 py-5 pr-14">
+ <SheetTitle className="break-words text-base">{selected?.label}</SheetTitle>
+ <SheetDescription className="flex items-center gap-2">
+ {selected ? <><TaskStateIcon task={selected} />
+ <span className={selected.state === "done" ? "sr-only" : undefined}>{t(`thread.subagents.states.${selected.state}`)}</span>
+ <span className="tabular-nums">{selected.state !== "done" ? "· " : null}<TaskElapsed task={selected} /></span></> : null}
+ </SheetDescription>
+ </div>
+ {selected && sessionKey ? <div className="min-h-0 flex-1 overflow-y-auto overscroll-contain py-5">
+ {selected.state === "interrupted" || selected.error ? <div className="space-y-2 px-5 pb-4 text-sm">
+ {selected.state === "interrupted" ? <p className="text-muted-foreground">{t("thread.subagents.interruptedHelp")}</p> : null}
+ {selected.error ? <p role="alert" className="whitespace-pre-wrap break-words text-destructive">{selected.error}</p> : null}
+ </div> : null}
+ <SubagentThread key={`${sessionKey}:${selected.task_id}`} token={token} sessionKey={sessionKey}
+ task={selected} historyEnabled={historyEnabled} isStreaming={isActive(selected)} />
+ {Object.keys(selected.receipts).length ? <details className="mt-5 space-y-2 px-5 text-xs text-muted-foreground">
+ <summary className="cursor-pointer py-1 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">{t("thread.subagents.messages")}</summary>
+ <p>{t("thread.subagents.receiptHelp")}</p>
+ {(["accepted", "delivered", "undelivered"] as const).map((receipt) => {
+ const count = Object.values(selected.receipts).filter((entry) => entry === receipt).length;
+ return count ? <p key={receipt}>{t(`thread.subagents.receipts.${receipt}`, { count })}</p> : null;
+ })}
+ </details> : null}
+ </div> : null}
+ {selected && (selected.state === "queued" || selected.state === "running") ? <div className="shrink-0 border-t px-5 py-3 pb-[max(0.75rem,env(safe-area-inset-bottom))]">
+ <Button type="button" variant="outline" size="sm" disabled={stoppingId !== null}
+ onClick={() => void stop(selected)}><Square className="mr-2 h-3 w-3" aria-hidden />{t("thread.subagents.stopTask", { label: selected.label })}</Button>
+ {stopError ? <p role="alert" className="mt-2 text-xs text-destructive">{stopError}</p> : null}
+ </div> : null}
+ </SheetContent>
+ </Sheet>
+ </TasksContext.Provider>;
+}
+
+function TaskStateIcon({ task }: { task: SubagentTaskSnapshot }) {
+ const className = "h-3.5 w-3.5 shrink-0";
+ if (isActive(task)) return <LoaderCircle className={`${className} animate-spin motion-reduce:animate-none text-muted-foreground`} aria-hidden />;
+ if (task.state === "done") return <CheckCircle2 className={`${className} text-emerald-600 dark:text-emerald-400`} aria-hidden />;
+ if (task.state === "cancelled") return <CircleMinus className={`${className} text-muted-foreground`} aria-hidden />;
+ return <CircleAlert className={`${className} text-destructive`} aria-hidden />;
+}
+
+function TaskElapsed({ task }: { task: ObservedSubagentTask }) {
+ const pageVisible = usePageVisibility();
+ const paneVisible = useThreadVisibility();
+ const [now, setNow] = useState(() => performance.now());
+ const running = isActive(task);
+ useEffect(() => {
+ if (!running || !pageVisible || !paneVisible) return;
+ setNow(performance.now());
+ const timer = window.setInterval(() => setNow(performance.now()), 1000);
+ return () => window.clearInterval(timer);
+ }, [running, pageVisible, paneVisible]);
+ return <>{Math.round(task.elapsed_seconds + (running ? Math.max(0, now - task.observedAtMs) / 1000 : 0))}s</>;
+}
+
+function TaskButton({ task }: { task: ObservedSubagentTask }) {
+ const context = useContext(TasksContext);
+ const { t } = useTranslation("common");
+ const button = useRef<HTMLButtonElement | null>(null);
+ return <button type="button" data-subagent-id={task.task_id} ref={(node) => {
+ context?.register(task.task_id, node, button.current);
+ button.current = node;
+ }}
+ onClick={(event) => context?.open(task, event.currentTarget)}
+ className="flex min-w-0 flex-1 items-center gap-2.5 rounded-control px-3 py-2.5 text-left text-sm hover:bg-muted/70 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
+ <TaskStateIcon task={task} />
+ <span className="min-w-0 flex-1 truncate">{task.label}</span>
+ <span className="shrink-0 text-xs text-muted-foreground">{t(`thread.subagents.states.${task.state}`)}</span>
+ <span className="shrink-0 text-xs tabular-nums text-muted-foreground"><TaskElapsed task={task} /></span>
+ <ChevronRight className="h-3 w-3 shrink-0 text-muted-foreground" aria-hidden />
+ </button>;
+}
+
+export function useHasSubagentContent(): boolean {
+ const context = useContext(TasksContext);
+ return !!context && (context.tasks.length > 0 || !!context.loadError || !!context.stopError);
+}
+
+/** Prefer an exact prompt, then its turn's first prompt when replay changed message IDs. */
+function useSubagentTaskGroups(messages: UIMessage[]) {
+ const context = useContext(TasksContext);
+ const prompts = messages.filter((message) => message.role === "user");
+ const byMessage = new Map<string, ObservedSubagentTask[]>();
+ const unlinked: ObservedSubagentTask[] = [];
+ for (const task of context?.tasks ?? []) {
+ const prompt = prompts.find((message) => message.id === task.origin_message_id)
+ ?? prompts.find((message) => !!task.origin_turn_id && message.turnId === task.origin_turn_id);
+ if (prompt) {
+ const group = byMessage.get(prompt.id) ?? [];
+ group.push(task);
+ byMessage.set(prompt.id, group);
+ } else unlinked.push(task);
+ }
+ return { byMessage, unlinked };
+}
+
+export function SubagentThreadMessages(props: ComponentProps<typeof ThreadMessages>) {
+ const groups = useSubagentTaskGroups(props.messages);
+ return <ThreadMessages {...props}
+ beforeMessages={<SubagentWork tasks={groups.unlinked} unlinked />}
+ afterUserMessage={(message) => <SubagentWork tasks={groups.byMessage.get(message.id) ?? []} />}
+ afterMessages={<SubagentTaskErrors />} />;
+}
+
+function SubagentWork({ tasks, unlinked = false }: { tasks: ObservedSubagentTask[]; unlinked?: boolean }) {
+ const context = useContext(TasksContext);
+ const { t } = useTranslation("common");
+ const { activityMode } = useLocalPreferences();
+ const rowsId = useId();
+ const [expanded, setExpanded] = useState<boolean | null>(null);
+ useEffect(() => { setExpanded(null); }, [activityMode]);
+ if (!context || !tasks.length) return null;
+ const activeCount = tasks.filter(isActive).length;
+ const completedCount = tasks.filter((task) => task.state === "done").length;
+ const failedCount = tasks.filter((task) => ["error", "incomplete", "interrupted"].includes(task.state)).length;
+ const open = expanded ?? (activityMode === "expanded" || activeCount > 0);
+ const summary = activeCount
+ ? t("thread.subagents.progress", { completed: completedCount, total: tasks.length })
+ : t("thread.subagents.finished", { count: tasks.length });
+ const title = t(unlinked ? "thread.subagents.otherWorkTitle" : "thread.subagents.workTitle");
+ return <section data-subagent-work aria-label={title} className="thread-message-row mt-3">
+ <div className="overflow-hidden rounded-control border border-border/60 bg-muted/15">
+ <button type="button" aria-expanded={open} aria-controls={rowsId}
+ onClick={() => setExpanded(!open)}
+ className="flex w-full items-center gap-2.5 px-3 py-2.5 text-left text-xs text-muted-foreground hover:bg-muted/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring">
+ <Bot className="h-3.5 w-3.5 shrink-0" aria-hidden />
+ <span className="font-medium">{title}</span>
+ <span className="ml-auto min-w-0 text-right">
+ {summary}{activeCount ? ` · ${t("thread.subagents.running", { count: activeCount })}` : ""}
+ {failedCount ? <span className="ml-2 text-destructive">{t("thread.subagents.needsReview", { count: failedCount })}</span> : null}
+ </span>
+ <ChevronDown className={`h-3.5 w-3.5 shrink-0 transition-transform ${open ? "rotate-180" : ""}`} aria-hidden />
+ </button>
+ <div id={rowsId} hidden={!open} className="border-t border-border/50 py-0.5">
+ {unlinked ? <p className="px-3 py-2 text-xs text-muted-foreground">{t("thread.subagents.unlinkedHelp")}</p> : null}
+ {tasks.map((task) => <div key={task.task_id} className="flex items-center gap-1 pr-1">
+ <TaskButton task={task} />
+ {task.state === "queued" || task.state === "running" ? <Button type="button" variant="ghost" size="icon" className="h-9 w-9 shrink-0"
+ aria-label={t("thread.subagents.stopTask", { label: task.label })} disabled={context.stoppingId !== null}
+ onClick={() => void context.stop(task)}><Square className="h-3 w-3" aria-hidden /></Button> : null}
+ </div>)}
+ </div>
+ </div>
+ </section>;
+}
+
+function SubagentTaskErrors() {
+ const context = useContext(TasksContext);
+ if (!context?.loadError && !context?.stopError) return null;
+ return <div className="thread-message-row mt-2 space-y-1 text-xs text-destructive">
+ {context.loadError ? <p role="alert">{context.loadError}</p> : null}
+ {context.stopError ? <p role="alert">{context.stopError}</p> : null}
+ </div>;
+}
diff --git a/webui/src/components/thread/SubagentThread.tsx b/webui/src/components/thread/SubagentThread.tsx
new file mode 100644
index 000000000..2522717ee
--- /dev/null
+++ b/webui/src/components/thread/SubagentThread.tsx
@@ -0,0 +1,76 @@
+import { useEffect, useMemo, useRef, useState } from "react";
+import { LoaderCircle } from "lucide-react";
+import { useTranslation } from "react-i18next";
+
+import { ThreadMessages } from "@/components/thread/ThreadMessages";
+import { Button } from "@/components/ui/button";
+import { usePageVisibility } from "@/hooks/usePageVisibility";
+import { fetchSubagentThread } from "@/lib/api";
+import { projectWebuiThreadMessages } from "@/lib/thread-display-projection";
+import { projectThreadEvents } from "@/lib/thread-event-projection";
+import type { SubagentTaskSnapshot, UIMessage, WebuiThreadPersistedPayload } from "@/lib/types";
+
+interface SubagentThreadProps {
+ token: string;
+ sessionKey: string;
+ task: SubagentTaskSnapshot;
+ historyEnabled: boolean;
+ isStreaming: boolean;
+}
+
+export function SubagentThread({ token, sessionKey, task, historyEnabled, isStreaming }: SubagentThreadProps) {
+ const { t } = useTranslation();
+ const pageVisible = usePageVisibility();
+ const [thread, setThread] = useState<WebuiThreadPersistedPayload | null>(null);
+ const [failed, setFailed] = useState(false);
+ const refreshRef = useRef<(() => void) | null>(null);
+ const taskId = task.task_id;
+
+ useEffect(() => {
+ if (!historyEnabled || !pageVisible) return;
+ let cancelled = false;
+ let refreshing = false;
+ let pending = false;
+ const controller = new AbortController();
+ const refresh = async () => {
+ if (refreshing) { pending = true; return; }
+ refreshing = true;
+ try {
+ const payload = await fetchSubagentThread(token, sessionKey, taskId, controller.signal);
+ if (!cancelled) { setThread(payload); setFailed(false); }
+ } catch {
+ if (!cancelled) setFailed(true);
+ } finally {
+ refreshing = false;
+ if (pending && !cancelled) { pending = false; void refresh(); }
+ }
+ };
+ refreshRef.current = () => { void refresh(); };
+ return () => { cancelled = true; refreshRef.current = null; controller.abort(); };
+ }, [historyEnabled, pageVisible, sessionKey, taskId, token]);
+
+ // Task revisions already arrive through the owning chat's event stream.
+ useEffect(() => {
+ refreshRef.current?.();
+ }, [historyEnabled, pageVisible, sessionKey, taskId, task.revision, token]);
+
+ const messages = useMemo(() => {
+ if (historyEnabled) return thread ? projectWebuiThreadMessages(projectThreadEvents(thread.events)) : [];
+ // Protocol 1 hosts without history still expose a task description and result.
+ const summary: UIMessage[] = [{ id: `${taskId}-description`, role: "user", content: task.task_description, createdAt: task.created_at * 1000 }];
+ if (task.result) summary.push({ id: `${taskId}-result`, role: "assistant", content: task.result,
+ createdAt: (task.completed_at ?? task.created_at) * 1000 });
+ return summary;
+ }, [historyEnabled, taskId, task.task_description, task.created_at, task.completed_at, task.result, thread]);
+
+ return <>
+ {failed ? <div role="alert" className="mb-4 flex items-center gap-2 px-5 text-sm text-destructive">
+ <span>{t("thread.history.error")}</span>
+ <Button type="button" variant="ghost" size="sm" onClick={() => refreshRef.current?.()}>{t("thread.history.retry")}</Button>
+ </div> : historyEnabled && thread === null ? <p role="status" className="flex items-center gap-2 px-5 text-sm text-muted-foreground">
+ <LoaderCircle className="h-3.5 w-3.5 animate-spin motion-reduce:animate-none" aria-hidden />{t("chat.loading")}
+ </p> : null}
+ <ThreadMessages messages={messages} isStreaming={isStreaming} activeTurnId={thread?.active_turn_id}
+ runStartedAt={task.created_at} />
+ </>;
+}
diff --git a/webui/src/components/thread/ThreadMessages.tsx b/webui/src/components/thread/ThreadMessages.tsx
index b71856d57..cfaa4ec7d 100644
--- a/webui/src/components/thread/ThreadMessages.tsx
+++ b/webui/src/components/thread/ThreadMessages.tsx
@@ -1,4 +1,4 @@
-import { memo, useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState, type RefObject } from "react";
+import { Fragment, memo, useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState, type ReactNode, type RefObject } from "react";
import { MoreHorizontal } from "lucide-react";
import { useTranslation } from "react-i18next";
import { MessageBlockMenuActions, MessageBubble, MessageCopyButton } from "@/components/MessageBubble";
@@ -14,6 +14,7 @@ import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover
import { Dialog, DialogContent, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
import { useMediaQuery } from "@/hooks/useMediaQuery";
+import { useLocalPreferences } from "@/hooks/useLocalPreferences";
import { fmtDateTime, formatMessageHoverTime } from "@/lib/format";
import { projectActivityTimeline, type TurnUnit } from "@/lib/activity-timeline";
import { cn } from "@/lib/utils";
@@ -21,6 +22,9 @@ import type { CliAppInfo, McpPresetInfo, RetryStatus, SlashCommand, UIMessage }
interface ThreadMessagesProps {
messages: UIMessage[];
+ beforeMessages?: ReactNode;
+ afterUserMessage?: (message: UIMessage) => ReactNode;
+ afterMessages?: ReactNode;
temporary?: boolean;
/** When true, agent turn still in flight — keeps activity timeline expanded. */
isStreaming?: boolean;
@@ -76,6 +80,9 @@ export function assistantForkFlags(units: DisplayUnit[]): boolean[] {
export function ThreadMessages({
messages,
+ beforeMessages,
+ afterUserMessage,
+ afterMessages,
temporary = false,
isStreaming = false,
activeTurnId = null,
@@ -94,6 +101,7 @@ export function ThreadMessages({
onActivityToggle,
}: ThreadMessagesProps) {
const { t } = useTranslation();
+ const { activityMode } = useLocalPreferences();
const messageListRef = useRef<HTMLDivElement>(null);
const mobileActions = useMediaQuery("(max-width: 767px)");
const units = useMemo(
@@ -135,17 +143,19 @@ export function ThreadMessages({
),
[activeTurnId, currentTurnStartIndex, isStreaming, unitKeys, units],
);
- const [expandedActivityKeys, setExpandedActivityKeys] = useState<Set<string>>(() => new Set());
+ const [activityOverrides, setActivityOverrides] = useState<Map<string, boolean>>(() => new Map());
+ useEffect(() => {
+ setActivityOverrides(new Map());
+ }, [activityMode]);
const [activeContextBlockKey, setActiveContextBlockKey] = useState<string | null>(null);
const [openContextBlockKey, setOpenContextBlockKey] = useState<string | null>(null);
const pointedContextBlockRef = useRef<string | null>(null);
const setActivityExpanded = useCallback((key: string, expanded: boolean) => {
onActivityToggle?.();
- setExpandedActivityKeys((current) => {
- if (current.has(key) === expanded) return current;
- const next = new Set(current);
- if (expanded) next.add(key);
- else next.delete(key);
+ setActivityOverrides((current) => {
+ if (current.get(key) === expanded) return current;
+ const next = new Map(current);
+ next.set(key, expanded);
return next;
});
}, [onActivityToggle]);
@@ -171,6 +181,7 @@ export function ThreadMessages({
containerRef={messageListRef}
onQuoteSelection={onQuoteSelection}
/>
+ {beforeMessages}
{units.map((unit, index) => {
const next = units[index + 1];
const hasBodyBelow =
@@ -193,7 +204,7 @@ export function ThreadMessages({
: marginAfterPrevUnit(units[previousVisibleIndex]);
const blockActivityExpanded = showBlockContext
&& contextBlockKey !== undefined
- && expandedActivityKeys.has(contextBlockKey);
+ && (activityOverrides.get(contextBlockKey) ?? activityMode === "expanded");
const deferOffscreenRender =
index < units.length - 1
&& (
@@ -223,6 +234,7 @@ export function ThreadMessages({
) nextUserIndex += 1;
return (
+ <Fragment key={unitKeys[index]}>
<ThreadDisplayUnit
key={unitKeys[index]}
unitKey={unitKeys[index]}
@@ -264,8 +276,13 @@ export function ThreadMessages({
onContextBlockFocusChange={setContextBlockFocused}
onContextBlockMenuOpenChange={setContextBlockMenuOpen}
/>
+ {unit.type === "message" && unit.message.role === "user" ? (
+ afterUserMessage?.(unit.message)
+ ) : null}
+ </Fragment>
);
})}
+ {afterMessages}
{pendingActivity ? (
<div className={cn("thread-message-row", units.length > 0 && "mt-5")}>
<AgentActivityCluster
@@ -908,10 +925,10 @@ export function unitKeysForDisplay(units: DisplayUnit[]): string[] {
const occurrences = new Map<string, number>();
return units.map((unit, index) => {
const base = unitKeyBase(unit, index);
- if (!base.startsWith("turn-") || base.endsWith("-user")) return base;
+ if (!base.startsWith("turn-")) return base;
const next = (occurrences.get(base) ?? 0) + 1;
occurrences.set(base, next);
- return `${base}-${next}`;
+ return base.endsWith("-user") && next === 1 ? base : `${base}-${next}`;
});
}
diff --git a/webui/src/components/thread/ThreadShell.tsx b/webui/src/components/thread/ThreadShell.tsx
index 060b651ca..ae0a4dc8e 100644
--- a/webui/src/components/thread/ThreadShell.tsx
+++ b/webui/src/components/thread/ThreadShell.tsx
@@ -15,6 +15,7 @@ import { SessionHandleLabel } from "@/components/SessionHandleLabel";
import { PromptNavigator } from "@/components/thread/PromptNavigator";
import { ModelFallbackNotice } from "@/components/thread/ModelFallbackNotice";
import { RecoveryNotice } from "@/components/thread/RecoveryNotice";
+import { SubagentTasksProvider } from "@/components/thread/SubagentTasks";
import { SessionInfoPopover } from "@/components/thread/SessionInfoPopover";
import type { ComposerDraftStore } from "@/lib/composer-draft";
import { ThreadComposer } from "@/components/thread/ThreadComposer";
@@ -696,7 +697,7 @@ export function ThreadShell({
version: historyVersion,
forkBoundaryMessageCount,
} = useSessionHistory(historyKey);
- const { client, getToken, ingressLimits, modelName, token } = useClient();
+ const { client, getToken, ingressLimits, modelName, token, webuiCapabilities } = useClient();
const pickWorkspaceFolder = useCallback(async (): Promise<string | null> => {
const response = await client.requestMutation<{ path: unknown }>(
"workspace.pick_folder",
@@ -1879,6 +1880,12 @@ export function ThreadShell({
) : null;
return (
+ <SubagentTasksProvider client={client} token={token}
+ sessionKey={session?.key ?? null}
+ liveEvents={webuiCapabilities.includes("webui.subagents.events.v1")}
+ historyEnabled={webuiCapabilities.includes("webui.subagents.history.v1")}
+ active={composerActive}
+ enabled={!temporary && !!session?.key.startsWith("websocket:") && webuiCapabilities.includes("webui.subagents.v1")}>
<section ref={shellRef} data-preview-open={previewOpen || undefined} className="thread-preview-layout relative flex min-h-0 flex-1 overflow-hidden">
<div className={cn(
"thread-conversation relative flex min-w-0 flex-1 flex-col overflow-hidden",
@@ -1977,5 +1984,6 @@ export function ThreadShell({
</FileActionsProvider>
) : null}
</section>
+ </SubagentTasksProvider>
);
}
diff --git a/webui/src/components/thread/ThreadViewport.tsx b/webui/src/components/thread/ThreadViewport.tsx
index 3e2ad0028..e59cfb318 100644
--- a/webui/src/components/thread/ThreadViewport.tsx
+++ b/webui/src/components/thread/ThreadViewport.tsx
@@ -13,7 +13,7 @@ import { ArrowDown } from "lucide-react";
import { useTranslation } from "react-i18next";
import { PromptRail } from "@/components/thread/PromptRail";
-import { ThreadMessages } from "@/components/thread/ThreadMessages";
+import { SubagentThreadMessages, useHasSubagentContent } from "@/components/thread/SubagentTasks";
import { ThreadHistoryStatus } from "@/components/thread/ThreadHistoryStatus";
import { isAgentActivityMember } from "@/components/thread/AgentActivityCluster";
import { ThreadCameraController } from "@/components/thread/thread-camera";
@@ -344,7 +344,8 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
onAutoFollow: () => setAtBottom(true),
});
}
- const hasMessages = messages.length > 0;
+ const hasTaskContent = useHasSubagentContent();
+ const hasMessages = messages.length > 0 || (hasTaskContent && conversationReady);
useLayoutEffect(() => {
scrollRef.current = hasMessages
? messageRegionRef.current
@@ -973,7 +974,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
)}
>
<div ref={messageContentRef} className="w-full">
- <ThreadMessages
+ <SubagentThreadMessages
messages={visibleMessages}
temporary={temporary}
isStreaming={isStreaming}
diff --git a/webui/src/components/thread/activity/generic-tool-model.ts b/webui/src/components/thread/activity/generic-tool-model.ts
index 72167f141..5675296c1 100644
--- a/webui/src/components/thread/activity/generic-tool-model.ts
+++ b/webui/src/components/thread/activity/generic-tool-model.ts
@@ -88,7 +88,9 @@ export function parseGenericToolTrace(line: string): GenericToolTrace | null {
const call = parseCall(line);
if (!call || isExcludedTool(call.name)) return null;
const family = toolFamily(call.name);
- const fields = safeFields(call.args);
+ const fields: ToolField[] = call.name === "subagent" && typeof call.args === "string"
+ ? [{ key: "action", value: call.args.trim() }]
+ : safeFields(call.args);
if (call.name === "rg" && call.args && typeof call.args === "object") {
const argv = (call.args as Record<string, unknown>).args;
if (Array.isArray(argv) && argv.every((arg) => typeof arg === "string")) {
@@ -98,12 +100,14 @@ export function parseGenericToolTrace(line: string): GenericToolTrace | null {
}
}
const collectedSource = fields.some((field) => isCollectedSourcePath(field.value));
+ let groupKey = family === "generic"
+ ? `${family}:${call.name}`
+ : `${family}:${collectedSource ? "collected" : "workspace"}`;
+ if (call.name === "subagent") groupKey += `:${fields.find((field) => field.key === "action")?.value.toLowerCase() ?? ""}`;
return {
name: call.name,
family,
- groupKey: family === "generic"
- ? `${family}:${call.name}`
- : `${family}:${collectedSource ? "collected" : "workspace"}`,
+ groupKey,
fields,
collectedSource,
};
@@ -256,6 +260,12 @@ function activityLabel(
return activityStatus(t, status, "generatingImage", "generatedImage", "generateImageFailed");
case "spawn":
return activityStatus(t, status, "delegatingTask", "delegatedTask", "delegateTaskFailed");
+ case "subagent":
+ if (action === "create") return activityStatus(t, status, "delegatingTask", "delegatedTask", "delegateTaskFailed");
+ if (action === "check") return activityStatus(t, status, "checkingSubtask", "checkedSubtask", "checkSubtaskFailed");
+ if (action === "send") return activityStatus(t, status, "messagingSubtask", "queuedSubtaskMessage", "messageSubtaskFailed");
+ if (action === "cancel") return activityStatus(t, status, "stoppingSubtask", "requestedSubtaskStop", "stopSubtaskFailed");
+ return activityStatus(t, status, "managingSubtasks", "managedSubtasks", "manageSubtasksFailed");
case "message":
return activityStatus(t, status, "sendingMessage", "sentMessage", "sendMessageFailed");
case "my":
@@ -311,6 +321,7 @@ function activityDetail(items: GenericToolRunItem[], family: ToolFamily, name: s
switch (name) {
case "spawn":
+ case "subagent":
return safeText(fieldValue(trace, "label"));
case "message":
return safeText(fieldValue(trace, "channel"));
diff --git a/webui/src/components/ui/sheet.tsx b/webui/src/components/ui/sheet.tsx
index dcafcb179..28cbeec47 100644
--- a/webui/src/components/ui/sheet.tsx
+++ b/webui/src/components/ui/sheet.tsx
@@ -62,6 +62,7 @@ interface SheetContentProps
VariantProps<typeof sheetVariants> {
closeButtonClassName?: string;
showCloseButton?: boolean;
+ overlayClassName?: string;
}
const SheetContent = React.forwardRef<
@@ -74,6 +75,7 @@ const SheetContent = React.forwardRef<
children,
closeButtonClassName,
showCloseButton = true,
+ overlayClassName,
...props
},
ref,
@@ -81,7 +83,7 @@ const SheetContent = React.forwardRef<
const { t } = useTranslation();
return (
<SheetPortal>
- <SheetOverlay />
+ <SheetOverlay className={overlayClassName} />
<DialogPrimitive.Content
ref={ref}
className={cn(
diff --git a/webui/src/hooks/useFileEditDisplayMode.ts b/webui/src/hooks/useFileEditDisplayMode.ts
index 6effbbe21..4d66a5f5b 100644
--- a/webui/src/hooks/useFileEditDisplayMode.ts
+++ b/webui/src/hooks/useFileEditDisplayMode.ts
@@ -1,37 +1,6 @@
-import { useEffect, useState } from "react";
-
-import {
- LOCAL_PREFS_CHANGED_EVENT,
- normalizeFileEditDisplayMode,
- readLocalPreferences,
- type FileEditDisplayMode,
- type LocalPreferences,
-} from "@/lib/local-preferences";
+import { useLocalPreferences } from "@/hooks/useLocalPreferences";
+import type { FileEditDisplayMode } from "@/lib/local-preferences";
export function useFileEditDisplayMode(): FileEditDisplayMode {
- const [mode, setMode] = useState<FileEditDisplayMode>(() =>
- readLocalPreferences().fileEditDisplayMode,
- );
-
- useEffect(() => {
- const refresh = () => setMode(readLocalPreferences().fileEditDisplayMode);
- const refreshFromLocalPreferenceEvent = (event: Event) => {
- const detail = (event as CustomEvent<Partial<LocalPreferences> | undefined>).detail;
- setMode(
- detail
- ? normalizeFileEditDisplayMode(detail.fileEditDisplayMode)
- : readLocalPreferences().fileEditDisplayMode,
- );
- };
- window.addEventListener("storage", refresh);
- window.addEventListener("focus", refresh);
- window.addEventListener(LOCAL_PREFS_CHANGED_EVENT, refreshFromLocalPreferenceEvent);
- return () => {
- window.removeEventListener("storage", refresh);
- window.removeEventListener("focus", refresh);
- window.removeEventListener(LOCAL_PREFS_CHANGED_EVENT, refreshFromLocalPreferenceEvent);
- };
- }, []);
-
- return mode;
+ return useLocalPreferences().fileEditDisplayMode;
}
diff --git a/webui/src/hooks/useLocalPreferences.ts b/webui/src/hooks/useLocalPreferences.ts
new file mode 100644
index 000000000..835af7bee
--- /dev/null
+++ b/webui/src/hooks/useLocalPreferences.ts
@@ -0,0 +1,29 @@
+import { useEffect, useState } from "react";
+
+import {
+ LOCAL_PREFS_CHANGED_EVENT,
+ readLocalPreferences,
+ type LocalPreferences,
+} from "@/lib/local-preferences";
+
+export function useLocalPreferences(): LocalPreferences {
+ const [preferences, setPreferences] = useState(readLocalPreferences);
+
+ useEffect(() => {
+ const refresh = () => setPreferences(readLocalPreferences());
+ const refreshFromEvent = (event: Event) => {
+ const detail = (event as CustomEvent<LocalPreferences | undefined>).detail;
+ setPreferences(detail ?? readLocalPreferences());
+ };
+ window.addEventListener("storage", refresh);
+ window.addEventListener("focus", refresh);
+ window.addEventListener(LOCAL_PREFS_CHANGED_EVENT, refreshFromEvent);
+ return () => {
+ window.removeEventListener("storage", refresh);
+ window.removeEventListener("focus", refresh);
+ window.removeEventListener(LOCAL_PREFS_CHANGED_EVENT, refreshFromEvent);
+ };
+ }, []);
+
+ return preferences;
+}
diff --git a/webui/src/i18n/locales/en/common.json b/webui/src/i18n/locales/en/common.json
index 846a6eaaa..310d97dd6 100644
--- a/webui/src/i18n/locales/en/common.json
+++ b/webui/src/i18n/locales/en/common.json
@@ -1761,6 +1761,36 @@
"error": "Connection error"
},
"thread": {
+ "subagents": {
+ "loadFailed": "Could not load subtasks.",
+ "stopFailed": "Could not stop this task.",
+ "stopTask": "Stop {{label}}",
+ "receiptHelp": "Delivered means the message was included in the subtask’s next model request. It does not mean the instructions have been carried out.",
+ "states": {
+ "queued": "Queued",
+ "running": "Running",
+ "stopping": "Stopping",
+ "done": "Completed",
+ "incomplete": "Incomplete",
+ "error": "Failed",
+ "cancelled": "Cancelled",
+ "interrupted": "Interrupted"
+ },
+ "receipts": {
+ "accepted": "Queued: {{count}}",
+ "delivered": "Delivered: {{count}}",
+ "undelivered": "Undelivered: {{count}}"
+ },
+ "interruptedHelp": "The host restarted before this task finished. It has not been restarted automatically.",
+ "workTitle": "Delegated work",
+ "otherWorkTitle": "Other delegated work",
+ "unlinkedHelp": "These tasks have no matching request in the displayed messages.",
+ "progress": "{{completed}} of {{total}} completed",
+ "running": "Running: {{count}}",
+ "finished": "Finished: {{count}}",
+ "needsReview": "Review needed: {{count}}",
+ "messages": "Message delivery"
+ },
"compaction": {
"cancelled": "Context compaction cancelled",
"empty": "Nothing to compact.",
@@ -2136,9 +2166,21 @@
"generatingImage": "Generating image",
"generatedImage": "Generated image",
"generateImageFailed": "Could not generate image",
- "delegatingTask": "Delegating task",
- "delegatedTask": "Delegated task",
- "delegateTaskFailed": "Could not delegate task",
+ "delegatingTask": "Creating subtask",
+ "delegatedTask": "Subtask created",
+ "delegateTaskFailed": "Could not create subtask",
+ "checkingSubtask": "Checking subtask status",
+ "checkedSubtask": "Subtask status retrieved",
+ "checkSubtaskFailed": "Could not check subtask status",
+ "messagingSubtask": "Sending message to subtask",
+ "queuedSubtaskMessage": "Message queued for subtask",
+ "messageSubtaskFailed": "Could not send message to subtask",
+ "stoppingSubtask": "Stopping subtask",
+ "requestedSubtaskStop": "Stop request processed",
+ "stopSubtaskFailed": "Could not stop subtask",
+ "managingSubtasks": "Managing subtasks",
+ "managedSubtasks": "Subtask operation complete",
+ "manageSubtasksFailed": "Subtask operation failed",
"sendingMessage": "Sending message",
"sentMessage": "Sent message",
"sendMessageFailed": "Could not send message",
diff --git a/webui/src/i18n/locales/es/common.json b/webui/src/i18n/locales/es/common.json
index 17cfb13d6..7aa9119c9 100644
--- a/webui/src/i18n/locales/es/common.json
+++ b/webui/src/i18n/locales/es/common.json
@@ -1562,6 +1562,36 @@
"error": "Error de conexión"
},
"thread": {
+ "subagents": {
+ "loadFailed": "No se pudieron cargar las subtareas.",
+ "stopFailed": "No se pudo detener esta tarea.",
+ "stopTask": "Detener {{label}}",
+ "receiptHelp": "Entregado significa que el mensaje se incluyó en la siguiente solicitud del subagente, sin confirmar su ejecución.",
+ "states": {
+ "queued": "En cola",
+ "running": "En curso",
+ "stopping": "Deteniendo",
+ "done": "Completada",
+ "incomplete": "Incompleta",
+ "error": "Fallida",
+ "cancelled": "Cancelada",
+ "interrupted": "Interrumpida"
+ },
+ "receipts": {
+ "accepted": "En cola: {{count}}",
+ "delivered": "Entregados: {{count}}",
+ "undelivered": "Sin entregar: {{count}}"
+ },
+ "interruptedHelp": "El servidor se reinició antes de terminar esta tarea. No se ha vuelto a ejecutar automáticamente.",
+ "workTitle": "Trabajo delegado",
+ "otherWorkTitle": "Otros trabajos delegados",
+ "unlinkedHelp": "No se encontró la solicitud correspondiente a estas tareas en los mensajes mostrados.",
+ "progress": "{{completed}} de {{total}} completadas",
+ "running": "En curso: {{count}}",
+ "finished": "Finalizadas: {{count}}",
+ "needsReview": "Revisar: {{count}}",
+ "messages": "Estado de los mensajes"
+ },
"compaction": {
"cancelled": "Compresión de contexto cancelada",
"empty": "No hay contexto que comprimir.",
@@ -1965,9 +1995,21 @@
"generatingImage": "Generando imagen",
"generatedImage": "Imagen generada",
"generateImageFailed": "No se pudo generar la imagen",
- "delegatingTask": "Delegando tarea",
- "delegatedTask": "Tarea delegada",
- "delegateTaskFailed": "No se pudo delegar la tarea",
+ "delegatingTask": "Creando subtarea",
+ "delegatedTask": "Subtarea creada",
+ "delegateTaskFailed": "No se pudo crear la subtarea",
+ "checkingSubtask": "Consultando el estado de la subtarea",
+ "checkedSubtask": "Estado de la subtarea consultado",
+ "checkSubtaskFailed": "No se pudo consultar el estado de la subtarea",
+ "messagingSubtask": "Enviando mensaje a la subtarea",
+ "queuedSubtaskMessage": "Mensaje en cola para la subtarea",
+ "messageSubtaskFailed": "No se pudo enviar el mensaje a la subtarea",
+ "stoppingSubtask": "Deteniendo subtarea",
+ "requestedSubtaskStop": "Solicitud de detención procesada",
+ "stopSubtaskFailed": "No se pudo detener la subtarea",
+ "managingSubtasks": "Gestionando subtareas",
+ "managedSubtasks": "Operación de subtarea completada",
+ "manageSubtasksFailed": "Falló la operación de subtarea",
"sendingMessage": "Enviando mensaje",
"sentMessage": "Mensaje enviado",
"sendMessageFailed": "No se pudo enviar el mensaje",
diff --git a/webui/src/i18n/locales/fr/common.json b/webui/src/i18n/locales/fr/common.json
index e9c872cf3..de055f273 100644
--- a/webui/src/i18n/locales/fr/common.json
+++ b/webui/src/i18n/locales/fr/common.json
@@ -1561,6 +1561,36 @@
"error": "Erreur de connexion"
},
"thread": {
+ "subagents": {
+ "loadFailed": "Impossible de charger les sous-tâches.",
+ "stopFailed": "Impossible d’arrêter cette tâche.",
+ "stopTask": "Arrêter {{label}}",
+ "receiptHelp": "Livré signifie que le message a été inclus dans la prochaine requête du sous-agent, sans confirmer son exécution.",
+ "states": {
+ "queued": "En attente",
+ "running": "En cours",
+ "stopping": "Arrêt en cours",
+ "done": "Terminée",
+ "incomplete": "Incomplète",
+ "error": "Échec",
+ "cancelled": "Annulée",
+ "interrupted": "Interrompue"
+ },
+ "receipts": {
+ "accepted": "En attente : {{count}}",
+ "delivered": "Livrés : {{count}}",
+ "undelivered": "Non livrés : {{count}}"
+ },
+ "interruptedHelp": "Le serveur a redémarré avant la fin de cette tâche. Elle n’a pas été relancée automatiquement.",
+ "workTitle": "Travail délégué",
+ "otherWorkTitle": "Autres travaux délégués",
+ "unlinkedHelp": "Aucune demande correspondant à ces tâches ne figure dans les messages affichés.",
+ "progress": "{{completed}} sur {{total}} terminées",
+ "running": "En cours : {{count}}",
+ "finished": "Terminées : {{count}}",
+ "needsReview": "À vérifier : {{count}}",
+ "messages": "État des messages"
+ },
"compaction": {
"cancelled": "Compression du contexte annulée",
"empty": "Aucun contexte à compresser.",
@@ -1964,9 +1994,21 @@
"generatingImage": "Génération de l’image",
"generatedImage": "Image générée",
"generateImageFailed": "Impossible de générer l’image",
- "delegatingTask": "Délégation de la tâche",
- "delegatedTask": "Tâche déléguée",
- "delegateTaskFailed": "Impossible de déléguer la tâche",
+ "delegatingTask": "Création de la sous-tâche",
+ "delegatedTask": "Sous-tâche créée",
+ "delegateTaskFailed": "Impossible de créer la sous-tâche",
+ "checkingSubtask": "Vérification de l’état de la sous-tâche",
+ "checkedSubtask": "État de la sous-tâche obtenu",
+ "checkSubtaskFailed": "Impossible de vérifier l’état de la sous-tâche",
+ "messagingSubtask": "Envoi d’un message à la sous-tâche",
+ "queuedSubtaskMessage": "Message mis en attente pour la sous-tâche",
+ "messageSubtaskFailed": "Impossible d’envoyer un message à la sous-tâche",
+ "stoppingSubtask": "Arrêt de la sous-tâche en cours",
+ "requestedSubtaskStop": "Demande d’arrêt traitée",
+ "stopSubtaskFailed": "Impossible d’arrêter la sous-tâche",
+ "managingSubtasks": "Opération sur les sous-tâches en cours",
+ "managedSubtasks": "Opération sur les sous-tâches terminée",
+ "manageSubtasksFailed": "Échec de l’opération sur les sous-tâches",
"sendingMessage": "Envoi du message",
"sentMessage": "Message envoyé",
"sendMessageFailed": "Impossible d’envoyer le message",
diff --git a/webui/src/i18n/locales/id/common.json b/webui/src/i18n/locales/id/common.json
index b0ee5ab07..26b324a37 100644
--- a/webui/src/i18n/locales/id/common.json
+++ b/webui/src/i18n/locales/id/common.json
@@ -1561,6 +1561,36 @@
"error": "Kesalahan koneksi"
},
"thread": {
+ "subagents": {
+ "loadFailed": "Tidak dapat memuat subtugas.",
+ "stopFailed": "Tidak dapat menghentikan tugas ini.",
+ "stopTask": "Hentikan {{label}}",
+ "receiptHelp": "Terkirim berarti pesan disertakan dalam permintaan model berikutnya dari subagen, bukan konfirmasi bahwa pekerjaan selesai.",
+ "states": {
+ "queued": "Dalam antrean",
+ "running": "Berjalan",
+ "stopping": "Menghentikan",
+ "done": "Selesai",
+ "incomplete": "Belum selesai",
+ "error": "Gagal",
+ "cancelled": "Dibatalkan",
+ "interrupted": "Terputus"
+ },
+ "receipts": {
+ "accepted": "Dalam antrean: {{count}}",
+ "delivered": "Terkirim: {{count}}",
+ "undelivered": "Tidak terkirim: {{count}}"
+ },
+ "interruptedHelp": "Server dimulai ulang sebelum tugas ini selesai. Tugas tidak dijalankan ulang secara otomatis.",
+ "workTitle": "Pekerjaan yang didelegasikan",
+ "otherWorkTitle": "Pekerjaan lain yang didelegasikan",
+ "unlinkedHelp": "Permintaan yang sesuai dengan tugas ini tidak ditemukan dalam pesan yang ditampilkan.",
+ "progress": "{{completed}} dari {{total}} selesai",
+ "running": "Berjalan: {{count}}",
+ "finished": "Berakhir: {{count}}",
+ "needsReview": "Perlu diperiksa: {{count}}",
+ "messages": "Status pengiriman pesan"
+ },
"compaction": {
"cancelled": "Pemadatan konteks dibatalkan",
"empty": "Tidak ada konteks yang perlu dipadatkan.",
@@ -1964,9 +1994,21 @@
"generatingImage": "Membuat gambar",
"generatedImage": "Gambar dibuat",
"generateImageFailed": "Tidak dapat membuat gambar",
- "delegatingTask": "Mendelegasikan tugas",
- "delegatedTask": "Tugas didelegasikan",
- "delegateTaskFailed": "Tidak dapat mendelegasikan tugas",
+ "delegatingTask": "Membuat subtugas",
+ "delegatedTask": "Subtugas dibuat",
+ "delegateTaskFailed": "Tidak dapat membuat subtugas",
+ "checkingSubtask": "Memeriksa status subtugas",
+ "checkedSubtask": "Status subtugas diperoleh",
+ "checkSubtaskFailed": "Tidak dapat memeriksa status subtugas",
+ "messagingSubtask": "Mengirim pesan ke subtugas",
+ "queuedSubtaskMessage": "Pesan masuk antrean subtugas",
+ "messageSubtaskFailed": "Tidak dapat mengirim pesan ke subtugas",
+ "stoppingSubtask": "Menghentikan subtugas",
+ "requestedSubtaskStop": "Permintaan penghentian diproses",
+ "stopSubtaskFailed": "Tidak dapat menghentikan subtugas",
+ "managingSubtasks": "Mengelola subtugas",
+ "managedSubtasks": "Operasi subtugas selesai",
+ "manageSubtasksFailed": "Operasi subtugas gagal",
"sendingMessage": "Mengirim pesan",
"sentMessage": "Pesan terkirim",
"sendMessageFailed": "Tidak dapat mengirim pesan",
diff --git a/webui/src/i18n/locales/ja/common.json b/webui/src/i18n/locales/ja/common.json
index 8e09bff7c..cdea0650d 100644
--- a/webui/src/i18n/locales/ja/common.json
+++ b/webui/src/i18n/locales/ja/common.json
@@ -1561,6 +1561,36 @@
"error": "接続エラー"
},
"thread": {
+ "subagents": {
+ "loadFailed": "サブタスクを読み込めませんでした。",
+ "stopFailed": "このタスクを停止できませんでした。",
+ "stopTask": "{{label}} を停止",
+ "receiptHelp": "配信済みは子タスクの次のモデルリクエストにメッセージが含まれたことを示し、実行完了を意味しません。",
+ "states": {
+ "queued": "待機中",
+ "running": "実行中",
+ "stopping": "停止中",
+ "done": "完了",
+ "incomplete": "未完了",
+ "error": "失敗",
+ "cancelled": "キャンセル済み",
+ "interrupted": "中断"
+ },
+ "receipts": {
+ "accepted": "待機中: {{count}}",
+ "delivered": "配信済み: {{count}}",
+ "undelivered": "未配信: {{count}}"
+ },
+ "interruptedHelp": "タスクの完了前にサーバーが再起動しました。タスクは自動的に再実行されていません。",
+ "workTitle": "委任した作業",
+ "otherWorkTitle": "その他の委任した作業",
+ "unlinkedHelp": "表示中のメッセージには、これらのタスクに対応する依頼がありません。",
+ "progress": "{{total}} 件中 {{completed}} 件完了",
+ "running": "実行中: {{count}}",
+ "finished": "終了: {{count}}",
+ "needsReview": "要確認: {{count}}",
+ "messages": "メッセージの送信状況"
+ },
"compaction": {
"cancelled": "コンテキストの圧縮をキャンセルしました",
"empty": "圧縮するコンテキストはありません。",
@@ -1964,9 +1994,21 @@
"generatingImage": "画像を生成中",
"generatedImage": "画像を生成しました",
"generateImageFailed": "画像を生成できませんでした",
- "delegatingTask": "タスクを委任中",
- "delegatedTask": "タスクを委任しました",
- "delegateTaskFailed": "タスクを委任できませんでした",
+ "delegatingTask": "サブタスクを作成中",
+ "delegatedTask": "サブタスクを作成しました",
+ "delegateTaskFailed": "サブタスクを作成できませんでした",
+ "checkingSubtask": "サブタスクの状態を確認中",
+ "checkedSubtask": "サブタスクの状態を取得しました",
+ "checkSubtaskFailed": "サブタスクの状態を確認できませんでした",
+ "messagingSubtask": "サブタスクにメッセージを送信中",
+ "queuedSubtaskMessage": "サブタスクへのメッセージをキューに追加しました",
+ "messageSubtaskFailed": "サブタスクにメッセージを送信できませんでした",
+ "stoppingSubtask": "サブタスクを停止中",
+ "requestedSubtaskStop": "停止要求を処理しました",
+ "stopSubtaskFailed": "サブタスクを停止できませんでした",
+ "managingSubtasks": "サブタスクの操作を実行中",
+ "managedSubtasks": "サブタスクの操作が完了しました",
+ "manageSubtasksFailed": "サブタスクの操作に失敗しました",
"sendingMessage": "メッセージを送信中",
"sentMessage": "メッセージを送信しました",
"sendMessageFailed": "メッセージを送信できませんでした",
diff --git a/webui/src/i18n/locales/ko/common.json b/webui/src/i18n/locales/ko/common.json
index cce1250c2..91be72b65 100644
--- a/webui/src/i18n/locales/ko/common.json
+++ b/webui/src/i18n/locales/ko/common.json
@@ -1561,6 +1561,36 @@
"error": "연결 오류"
},
"thread": {
+ "subagents": {
+ "loadFailed": "하위 작업을 불러올 수 없습니다.",
+ "stopFailed": "이 작업을 중지할 수 없습니다.",
+ "stopTask": "{{label}} 중지",
+ "receiptHelp": "전달됨은 메시지가 하위 작업의 다음 모델 요청에 포함되었음을 뜻하며, 실행 완료를 의미하지 않습니다.",
+ "states": {
+ "queued": "대기 중",
+ "running": "실행 중",
+ "stopping": "중지 중",
+ "done": "완료",
+ "incomplete": "미완료",
+ "error": "실패",
+ "cancelled": "취소됨",
+ "interrupted": "중단됨"
+ },
+ "receipts": {
+ "accepted": "대기 중: {{count}}",
+ "delivered": "전달됨: {{count}}",
+ "undelivered": "미전달: {{count}}"
+ },
+ "interruptedHelp": "작업이 완료되기 전에 서버가 다시 시작되었습니다. 작업은 자동으로 다시 실행되지 않았습니다.",
+ "workTitle": "위임한 작업",
+ "otherWorkTitle": "기타 위임한 작업",
+ "unlinkedHelp": "표시된 메시지에서 이 작업에 해당하는 요청을 찾을 수 없습니다.",
+ "progress": "{{total}}개 중 {{completed}}개 완료",
+ "running": "진행 중: {{count}}",
+ "finished": "종료: {{count}}",
+ "needsReview": "확인 필요: {{count}}",
+ "messages": "메시지 전달 상태"
+ },
"compaction": {
"cancelled": "컨텍스트 압축이 취소되었습니다",
"empty": "압축할 컨텍스트가 없습니다.",
@@ -1964,9 +1994,21 @@
"generatingImage": "이미지 생성 중",
"generatedImage": "이미지 생성 완료",
"generateImageFailed": "이미지를 생성하지 못함",
- "delegatingTask": "작업 위임 중",
- "delegatedTask": "작업 위임 완료",
- "delegateTaskFailed": "작업을 위임하지 못함",
+ "delegatingTask": "하위 작업 생성 중",
+ "delegatedTask": "하위 작업 생성 완료",
+ "delegateTaskFailed": "하위 작업을 생성하지 못했습니다",
+ "checkingSubtask": "하위 작업 상태 확인 중",
+ "checkedSubtask": "하위 작업 상태 확인 완료",
+ "checkSubtaskFailed": "하위 작업 상태를 확인하지 못했습니다",
+ "messagingSubtask": "하위 작업에 메시지 전송 중",
+ "queuedSubtaskMessage": "하위 작업 메시지가 대기열에 추가되었습니다",
+ "messageSubtaskFailed": "하위 작업에 메시지를 전송하지 못했습니다",
+ "stoppingSubtask": "하위 작업 중지 중",
+ "requestedSubtaskStop": "중지 요청이 처리되었습니다",
+ "stopSubtaskFailed": "하위 작업을 중지하지 못했습니다",
+ "managingSubtasks": "하위 작업 처리 중",
+ "managedSubtasks": "하위 작업 처리 완료",
+ "manageSubtasksFailed": "하위 작업을 처리하지 못했습니다",
"sendingMessage": "메시지 전송 중",
"sentMessage": "메시지 전송 완료",
"sendMessageFailed": "메시지를 보내지 못함",
diff --git a/webui/src/i18n/locales/pt-BR/common.json b/webui/src/i18n/locales/pt-BR/common.json
index 7ccd4dbb3..a84895eef 100644
--- a/webui/src/i18n/locales/pt-BR/common.json
+++ b/webui/src/i18n/locales/pt-BR/common.json
@@ -1575,6 +1575,36 @@
"error": "Erro de conexão"
},
"thread": {
+ "subagents": {
+ "loadFailed": "Não foi possível carregar as subtarefas.",
+ "stopFailed": "Não foi possível interromper esta tarefa.",
+ "stopTask": "Interromper {{label}}",
+ "receiptHelp": "Entregue significa que a mensagem foi incluída na próxima solicitação do subagente, sem confirmar sua execução.",
+ "states": {
+ "queued": "Na fila",
+ "running": "Em execução",
+ "stopping": "Interrompendo",
+ "done": "Concluída",
+ "incomplete": "Incompleta",
+ "error": "Falhou",
+ "cancelled": "Cancelada",
+ "interrupted": "Interrompida"
+ },
+ "receipts": {
+ "accepted": "Na fila: {{count}}",
+ "delivered": "Entregues: {{count}}",
+ "undelivered": "Não entregues: {{count}}"
+ },
+ "interruptedHelp": "O servidor reiniciou antes de concluir esta tarefa. Ela não foi executada novamente automaticamente.",
+ "workTitle": "Trabalho delegado",
+ "otherWorkTitle": "Outros trabalhos delegados",
+ "unlinkedHelp": "Não foi encontrada uma solicitação correspondente a estas tarefas nas mensagens exibidas.",
+ "progress": "{{completed}} de {{total}} concluídas",
+ "running": "Em andamento: {{count}}",
+ "finished": "Encerradas: {{count}}",
+ "needsReview": "Revisar: {{count}}",
+ "messages": "Status das mensagens"
+ },
"compaction": {
"cancelled": "Compactação do contexto cancelada",
"empty": "Não há contexto para compactar.",
@@ -1950,9 +1980,21 @@
"generatingImage": "Gerando imagem",
"generatedImage": "Imagem gerada",
"generateImageFailed": "Não foi possível gerar a imagem",
- "delegatingTask": "Delegando tarefa",
- "delegatedTask": "Tarefa delegada",
- "delegateTaskFailed": "Não foi possível delegar a tarefa",
+ "delegatingTask": "Criando subtarefa",
+ "delegatedTask": "Subtarefa criada",
+ "delegateTaskFailed": "Não foi possível criar a subtarefa",
+ "checkingSubtask": "Consultando o status da subtarefa",
+ "checkedSubtask": "Status da subtarefa consultado",
+ "checkSubtaskFailed": "Não foi possível consultar o status da subtarefa",
+ "messagingSubtask": "Enviando mensagem para a subtarefa",
+ "queuedSubtaskMessage": "Mensagem na fila da subtarefa",
+ "messageSubtaskFailed": "Não foi possível enviar a mensagem para a subtarefa",
+ "stoppingSubtask": "Interrompendo subtarefa",
+ "requestedSubtaskStop": "Solicitação de interrupção processada",
+ "stopSubtaskFailed": "Não foi possível interromper a subtarefa",
+ "managingSubtasks": "Gerenciando subtarefas",
+ "managedSubtasks": "Operação da subtarefa concluída",
+ "manageSubtasksFailed": "Falha na operação da subtarefa",
"sendingMessage": "Enviando mensagem",
"sentMessage": "Mensagem enviada",
"sendMessageFailed": "Não foi possível enviar a mensagem",
diff --git a/webui/src/i18n/locales/vi/common.json b/webui/src/i18n/locales/vi/common.json
index fe979e7af..7a3e0e55d 100644
--- a/webui/src/i18n/locales/vi/common.json
+++ b/webui/src/i18n/locales/vi/common.json
@@ -1561,6 +1561,36 @@
"error": "Lỗi kết nối"
},
"thread": {
+ "subagents": {
+ "loadFailed": "Không thể tải tác vụ con.",
+ "stopFailed": "Không thể dừng tác vụ này.",
+ "stopTask": "Dừng {{label}}",
+ "receiptHelp": "Đã chuyển nghĩa là tin nhắn đã được đưa vào yêu cầu mô hình tiếp theo của tác nhân con, không xác nhận công việc đã hoàn tất.",
+ "states": {
+ "queued": "Đang chờ",
+ "running": "Đang chạy",
+ "stopping": "Đang dừng",
+ "done": "Hoàn tất",
+ "incomplete": "Chưa hoàn tất",
+ "error": "Thất bại",
+ "cancelled": "Đã hủy",
+ "interrupted": "Bị gián đoạn"
+ },
+ "receipts": {
+ "accepted": "Đang chờ: {{count}}",
+ "delivered": "Đã chuyển: {{count}}",
+ "undelivered": "Chưa chuyển: {{count}}"
+ },
+ "interruptedHelp": "Máy chủ khởi động lại trước khi tác vụ hoàn thành. Tác vụ không tự động chạy lại.",
+ "workTitle": "Công việc được giao",
+ "otherWorkTitle": "Công việc được giao khác",
+ "unlinkedHelp": "Không tìm thấy yêu cầu tương ứng với các tác vụ này trong tin nhắn đang hiển thị.",
+ "progress": "Hoàn thành {{completed}} / {{total}}",
+ "running": "Đang chạy: {{count}}",
+ "finished": "Đã kết thúc: {{count}}",
+ "needsReview": "Cần kiểm tra: {{count}}",
+ "messages": "Trạng thái tin nhắn"
+ },
"compaction": {
"cancelled": "Đã hủy nén ngữ cảnh",
"empty": "Không có ngữ cảnh cần nén.",
@@ -1964,9 +1994,21 @@
"generatingImage": "Đang tạo ảnh",
"generatedImage": "Đã tạo ảnh",
"generateImageFailed": "Không thể tạo ảnh",
- "delegatingTask": "Đang giao nhiệm vụ",
- "delegatedTask": "Đã giao nhiệm vụ",
- "delegateTaskFailed": "Không thể giao nhiệm vụ",
+ "delegatingTask": "Đang tạo tác vụ con",
+ "delegatedTask": "Đã tạo tác vụ con",
+ "delegateTaskFailed": "Không thể tạo tác vụ con",
+ "checkingSubtask": "Đang kiểm tra trạng thái tác vụ con",
+ "checkedSubtask": "Đã lấy trạng thái tác vụ con",
+ "checkSubtaskFailed": "Không thể kiểm tra trạng thái tác vụ con",
+ "messagingSubtask": "Đang gửi tin nhắn đến tác vụ con",
+ "queuedSubtaskMessage": "Tin nhắn đã vào hàng đợi của tác vụ con",
+ "messageSubtaskFailed": "Không thể gửi tin nhắn đến tác vụ con",
+ "stoppingSubtask": "Đang dừng tác vụ con",
+ "requestedSubtaskStop": "Đã xử lý yêu cầu dừng",
+ "stopSubtaskFailed": "Không thể dừng tác vụ con",
+ "managingSubtasks": "Đang thao tác với tác vụ con",
+ "managedSubtasks": "Thao tác với tác vụ con đã hoàn tất",
+ "manageSubtasksFailed": "Thao tác với tác vụ con thất bại",
"sendingMessage": "Đang gửi tin nhắn",
"sentMessage": "Đã gửi tin nhắn",
"sendMessageFailed": "Không thể gửi tin nhắn",
diff --git a/webui/src/i18n/locales/zh-CN/common.json b/webui/src/i18n/locales/zh-CN/common.json
index 7e79dc51d..3718b6e83 100644
--- a/webui/src/i18n/locales/zh-CN/common.json
+++ b/webui/src/i18n/locales/zh-CN/common.json
@@ -1761,6 +1761,36 @@
"error": "连接出错"
},
"thread": {
+ "subagents": {
+ "loadFailed": "无法加载子任务。",
+ "stopFailed": "无法停止此任务。",
+ "stopTask": "停止 {{label}}",
+ "receiptHelp": "已送达表示消息已进入子任务的下一次模型请求,不代表已执行完成。",
+ "states": {
+ "queued": "排队中",
+ "running": "执行中",
+ "stopping": "正在停止",
+ "done": "已完成",
+ "incomplete": "未完成",
+ "error": "失败",
+ "cancelled": "已取消",
+ "interrupted": "已中断"
+ },
+ "receipts": {
+ "accepted": "已排队:{{count}}",
+ "delivered": "已送达:{{count}}",
+ "undelivered": "未送达:{{count}}"
+ },
+ "interruptedHelp": "后端重启时此任务尚未结束,任务没有自动恢复或重新执行。",
+ "workTitle": "委派工作",
+ "otherWorkTitle": "其他委派工作",
+ "unlinkedHelp": "未找到这些任务在当前显示消息中的原始请求。",
+ "progress": "已完成 {{completed}} / {{total}} 项",
+ "running": "{{count}} 项进行中",
+ "finished": "{{count}} 项已结束",
+ "needsReview": "{{count}} 项需检查",
+ "messages": "消息送达状态"
+ },
"compaction": {
"cancelled": "上下文压缩已取消",
"empty": "无需压缩上下文",
@@ -2135,9 +2165,21 @@
"generatingImage": "正在生成图片",
"generatedImage": "已生成图片",
"generateImageFailed": "无法生成图片",
- "delegatingTask": "正在委派任务",
- "delegatedTask": "已委派任务",
- "delegateTaskFailed": "无法委派任务",
+ "delegatingTask": "正在创建子任务",
+ "delegatedTask": "子任务已创建",
+ "delegateTaskFailed": "无法创建子任务",
+ "checkingSubtask": "正在查询子任务状态",
+ "checkedSubtask": "已获取子任务状态",
+ "checkSubtaskFailed": "无法查询子任务状态",
+ "messagingSubtask": "正在向子任务发送消息",
+ "queuedSubtaskMessage": "消息已加入子任务队列",
+ "messageSubtaskFailed": "无法向子任务发送消息",
+ "stoppingSubtask": "正在停止子任务",
+ "requestedSubtaskStop": "已处理停止请求",
+ "stopSubtaskFailed": "无法停止子任务",
+ "managingSubtasks": "正在处理子任务操作",
+ "managedSubtasks": "子任务操作已完成",
+ "manageSubtasksFailed": "子任务操作失败",
"sendingMessage": "正在发送消息",
"sentMessage": "已发送消息",
"sendMessageFailed": "无法发送消息",
diff --git a/webui/src/i18n/locales/zh-TW/common.json b/webui/src/i18n/locales/zh-TW/common.json
index aa52f8d29..879df680c 100644
--- a/webui/src/i18n/locales/zh-TW/common.json
+++ b/webui/src/i18n/locales/zh-TW/common.json
@@ -1561,6 +1561,36 @@
"error": "連線錯誤"
},
"thread": {
+ "subagents": {
+ "loadFailed": "無法載入子任務。",
+ "stopFailed": "無法停止此任務。",
+ "stopTask": "停止 {{label}}",
+ "receiptHelp": "已送達表示訊息已進入子任務的下一次模型請求,不代表已執行完成。",
+ "states": {
+ "queued": "排隊中",
+ "running": "執行中",
+ "stopping": "正在停止",
+ "done": "已完成",
+ "incomplete": "未完成",
+ "error": "失敗",
+ "cancelled": "已取消",
+ "interrupted": "已中斷"
+ },
+ "receipts": {
+ "accepted": "已排隊:{{count}}",
+ "delivered": "已送達:{{count}}",
+ "undelivered": "未送達:{{count}}"
+ },
+ "interruptedHelp": "後端重新啟動時此任務尚未結束,任務沒有自動恢復或重新執行。",
+ "workTitle": "委派工作",
+ "otherWorkTitle": "其他委派工作",
+ "unlinkedHelp": "未找到這些任務在目前顯示訊息中的原始請求。",
+ "progress": "已完成 {{completed}} / {{total}} 項",
+ "running": "{{count}} 項進行中",
+ "finished": "{{count}} 項已結束",
+ "needsReview": "{{count}} 項需檢查",
+ "messages": "訊息傳送狀態"
+ },
"compaction": {
"cancelled": "上下文壓縮已取消",
"empty": "無需壓縮上下文",
@@ -1963,9 +1993,21 @@
"generatingImage": "正在產生圖片",
"generatedImage": "已產生圖片",
"generateImageFailed": "無法產生圖片",
- "delegatingTask": "正在委派任務",
- "delegatedTask": "已委派任務",
- "delegateTaskFailed": "無法委派任務",
+ "delegatingTask": "正在建立子任務",
+ "delegatedTask": "已建立子任務",
+ "delegateTaskFailed": "無法建立子任務",
+ "checkingSubtask": "正在查詢子任務狀態",
+ "checkedSubtask": "已取得子任務狀態",
+ "checkSubtaskFailed": "無法查詢子任務狀態",
+ "messagingSubtask": "正在傳送訊息至子任務",
+ "queuedSubtaskMessage": "訊息已加入子任務佇列",
+ "messageSubtaskFailed": "無法傳送訊息至子任務",
+ "stoppingSubtask": "正在停止子任務",
+ "requestedSubtaskStop": "已處理停止請求",
+ "stopSubtaskFailed": "無法停止子任務",
+ "managingSubtasks": "正在處理子任務操作",
+ "managedSubtasks": "子任務操作已完成",
+ "manageSubtasksFailed": "子任務操作失敗",
"sendingMessage": "正在傳送訊息",
"sentMessage": "已傳送訊息",
"sendMessageFailed": "無法傳送訊息",
diff --git a/webui/src/lib/api.ts b/webui/src/lib/api.ts
index 4551868c1..1e7e910a5 100644
--- a/webui/src/lib/api.ts
+++ b/webui/src/lib/api.ts
@@ -38,6 +38,8 @@ import type {
SkillsTrendingPayload,
SlashCommand,
SlashCommandLifecycle,
+ SubagentTaskSnapshot,
+ SubagentTasksPayload,
TranscriptionSettingsUpdate,
ThreadProjectionEvent,
WebSearchSettingsUpdate,
@@ -47,6 +49,7 @@ import type {
WorkspaceScopePayload,
} from "./types";
import { fetchWithTimeout } from "./http";
+import { isSubagentTask } from "./subagent-tasks";
const API_READ_TIMEOUT_MS = 20_000;
const API_MUTATION_TIMEOUT_MS = 20_000;
@@ -547,6 +550,37 @@ export async function updateAutomation(
return mutation<AutomationsPayload>(transport, "automation.update", { id, values });
}
+export async function fetchSubagentTasks(token: string, sessionKey: string): Promise<SubagentTasksPayload> {
+ const payload = await request<unknown>(
+ `/api/sessions/${encodeURIComponent(sessionKey)}/subagents`, token, undefined, API_READ_TIMEOUT_MS,
+ );
+ if (!isRecord(payload) || !Array.isArray(payload.tasks) || !payload.tasks.every(isSubagentTask)
+ || new Set(payload.tasks.map((task) => task.task_id)).size !== payload.tasks.length) {
+ throw new Error("Invalid subagent tasks response");
+ }
+ return { tasks: payload.tasks };
+}
+
+export async function fetchSubagentThread(
+ token: string, sessionKey: string, taskId: string, signal?: AbortSignal,
+): Promise<WebuiThreadPersistedPayload> {
+ const payload = await request<unknown>(
+ `/api/sessions/${encodeURIComponent(sessionKey)}/subagents/${encodeURIComponent(taskId)}/webui-thread`,
+ token, { signal, cache: "no-store" }, API_READ_TIMEOUT_MS,
+ );
+ return parseWebuiThreadPayload(payload);
+}
+
+export async function cancelSubagentTask(
+ transport: WebUIMutationTransport, sessionKey: string, taskId: string,
+): Promise<SubagentTaskSnapshot> {
+ const result = await mutation<unknown>(transport, "subagent.cancel", {
+ session_key: sessionKey, task_id: taskId,
+ });
+ if (!isSubagentTask(result) || result.task_id !== taskId) throw new Error("Invalid subagent cancellation response");
+ return result;
+}
+
export async function fetchSkills(
token: string,
base: string = "",
diff --git a/webui/src/lib/subagent-tasks.ts b/webui/src/lib/subagent-tasks.ts
new file mode 100644
index 000000000..deca459ea
--- /dev/null
+++ b/webui/src/lib/subagent-tasks.ts
@@ -0,0 +1,55 @@
+import type { SubagentTaskSnapshot } from "./types";
+
+export interface ObservedSubagentTask extends SubagentTaskSnapshot {
+ observedAtMs: number;
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return value !== null && typeof value === "object" && !Array.isArray(value);
+}
+
+export function isSubagentTask(value: unknown): value is SubagentTaskSnapshot {
+ if (!isRecord(value)) return false;
+ const nullableText = (entry: unknown) => entry === null || typeof entry === "string";
+ return typeof value.task_id === "string" && value.task_id.length > 0
+ && (value.revision === undefined || (typeof value.revision === "number" && Number.isSafeInteger(value.revision) && value.revision >= 0))
+ && typeof value.label === "string" && typeof value.task_description === "string"
+ && typeof value.phase === "string" && typeof value.state === "string"
+ && ["queued", "running", "stopping", "done", "incomplete", "error", "cancelled", "interrupted"].includes(value.state)
+ && typeof value.elapsed_seconds === "number" && Number.isFinite(value.elapsed_seconds) && value.elapsed_seconds >= 0
+ && typeof value.iteration === "number" && Number.isInteger(value.iteration) && value.iteration >= 0
+ && typeof value.created_at === "number" && Number.isFinite(value.created_at)
+ && (value.completed_at === null || (typeof value.completed_at === "number" && Number.isFinite(value.completed_at)))
+ && nullableText(value.origin_turn_id) && nullableText(value.origin_message_id)
+ && nullableText(value.result) && nullableText(value.error) && nullableText(value.stop_reason)
+ && typeof value.partial === "boolean"
+ && Array.isArray(value.tool_events) && value.tool_events.every((entry: unknown) => isRecord(entry) && typeof entry.name === "string" && typeof entry.status === "string")
+ && isRecord(value.receipts) && Object.values(value.receipts).every((entry) => typeof entry === "string" && ["accepted", "delivered", "undelivered"].includes(entry))
+ && (value.usage === null || (isRecord(value.usage) && Object.values(value.usage).every((entry) => entry === null || typeof entry === "string" || (typeof entry === "number" && Number.isFinite(entry)))));
+}
+
+/** Merge observations from initial reads, live events and control replies. */
+export function mergeSubagentTasks(
+ current: ObservedSubagentTask[], incoming: SubagentTaskSnapshot[],
+): ObservedSubagentTask[] {
+ const tasks = new Map(current.map((task) => [task.task_id, task]));
+ let changed = false;
+ for (const task of incoming) {
+ const previous = tasks.get(task.task_id);
+ if (previous) {
+ const revision = task.revision ?? 0;
+ const previousRevision = previous.revision ?? 0;
+ if (revision < previousRevision || (revision > 0 && revision === previousRevision)) continue;
+ // Read-only hosts predating events have no revision. Their late reads
+ // must still respect cancellation and the immutable terminal outcome.
+ if (revision === 0 && previousRevision === 0) {
+ if (!["queued", "running", "stopping"].includes(previous.state)) continue;
+ if (previous.state === "stopping" && ["queued", "running"].includes(task.state)) continue;
+ if (previous.state === "running" && task.state === "queued") continue;
+ }
+ }
+ tasks.set(task.task_id, { ...task, observedAtMs: performance.now() });
+ changed = true;
+ }
+ return changed ? [...tasks.values()].sort((a, b) => a.created_at - b.created_at || a.task_id.localeCompare(b.task_id)) : current;
+}
diff --git a/webui/src/lib/types.ts b/webui/src/lib/types.ts
index 584be199e..0b1490435 100644
--- a/webui/src/lib/types.ts
+++ b/webui/src/lib/types.ts
@@ -64,6 +64,34 @@ interface TurnUsage {
export type RoundUsage = TurnUsage;
+export type SubagentTaskState = "queued" | "running" | "stopping" | "done" | "incomplete" | "error" | "cancelled" | "interrupted";
+
+export interface SubagentTaskSnapshot {
+ task_id: string;
+ revision?: number;
+ origin_message_id: string | null;
+ origin_turn_id: string | null;
+ created_at: number;
+ completed_at: number | null;
+ label: string;
+ task_description: string;
+ state: SubagentTaskState;
+ phase: string;
+ elapsed_seconds: number;
+ iteration: number;
+ tool_events: { name: string; status: string }[];
+ usage: Record<string, number | string | null> | null;
+ receipts: Record<string, "accepted" | "delivered" | "undelivered">;
+ result: string | null;
+ partial: boolean;
+ stop_reason: string | null;
+ error: string | null;
+}
+
+export interface SubagentTasksPayload {
+ tasks: SubagentTaskSnapshot[];
+}
+
export interface ResponseSource {
provider: string;
model: string;
@@ -488,6 +516,9 @@ export interface SidebarStatePayload {
}
export interface BootstrapResponse {
+ terminal?: {
+ webui?: { capabilities?: string[] };
+ };
token?: string;
api_token?: string;
ws_path: string;
@@ -1353,6 +1384,7 @@ interface InboundTurnMetadata {
}
export type InboundEvent =
+ | { event: "subagent_task"; chat_id: string; task: SubagentTaskSnapshot }
| { event: "ready"; chat_id: string; client_id: string }
| {
event: "attached";
diff --git a/webui/src/providers/ClientProvider.tsx b/webui/src/providers/ClientProvider.tsx
index c7cf7a96a..8e16ed3f0 100644
--- a/webui/src/providers/ClientProvider.tsx
+++ b/webui/src/providers/ClientProvider.tsx
@@ -16,6 +16,7 @@ interface ClientContextValue {
getToken: () => string;
modelName: string | null;
ingressLimits: WebUIIngressLimits | null;
+ webuiCapabilities: string[];
}
const ClientContext = createContext<ClientContextValue | null>(null);
@@ -25,20 +26,22 @@ export function ClientProvider({
token,
modelName = null,
ingressLimits = null,
+ webuiCapabilities = [],
children,
}: {
client: NanobotClient;
token: string;
modelName?: string | null;
ingressLimits?: WebUIIngressLimits | null;
+ webuiCapabilities?: string[];
children: ReactNode;
}) {
const tokenRef = useRef(token);
tokenRef.current = token;
const getToken = useCallback(() => tokenRef.current, []);
const value = useMemo(
- () => ({ client, token, getToken, modelName, ingressLimits }),
- [client, getToken, ingressLimits, modelName, token],
+ () => ({ client, token, getToken, modelName, ingressLimits, webuiCapabilities }),
+ [client, getToken, ingressLimits, modelName, token, webuiCapabilities],
);
return (
diff --git a/webui/src/tests/agent-activity-cluster.test.tsx b/webui/src/tests/agent-activity-cluster.test.tsx
index b1340f366..69ab0a833 100644
--- a/webui/src/tests/agent-activity-cluster.test.tsx
+++ b/webui/src/tests/agent-activity-cluster.test.tsx
@@ -1,10 +1,10 @@
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
-import { describe, expect, it, vi } from "vitest";
+import { afterEach, describe, expect, it, vi } from "vitest";
import { AgentActivityCluster } from "@/components/thread/AgentActivityCluster";
import { preloadMarkdownText } from "@/components/MarkdownText";
import { setAppLanguage } from "@/i18n";
-import { DEFAULT_LOCAL_PREFS, writeLocalPreferences } from "@/lib/local-preferences";
+import { DEFAULT_LOCAL_PREFS, LOCAL_PREFS_STORAGE_KEY, writeLocalPreferences } from "@/lib/local-preferences";
import type { CliAppInfo, McpPresetInfo, UIMessage } from "@/lib/types";
const BLENDER_CLI_APP: CliAppInfo = {
@@ -98,6 +98,21 @@ function installReducedMotion() {
}
describe("AgentActivityCluster", () => {
+ afterEach(() => { localStorage.removeItem(LOCAL_PREFS_STORAGE_KEY); });
+
+ it("honors the activity preference for standalone completed activity with manual overrides", () => {
+ render(<AgentActivityCluster messages={activityMessages()} isTurnStreaming={false} hasBodyBelow={false} />);
+ const disclosure = screen.getByRole("button", { name: /Worked/ });
+ expect(disclosure).toHaveAttribute("aria-expanded", "false");
+ act(() => { writeLocalPreferences({ ...DEFAULT_LOCAL_PREFS, activityMode: "expanded" }); });
+ expect(disclosure).toHaveAttribute("aria-expanded", "true");
+ fireEvent.click(disclosure);
+ expect(disclosure).toHaveAttribute("aria-expanded", "false");
+ act(() => { writeLocalPreferences(DEFAULT_LOCAL_PREFS); });
+ expect(disclosure).toHaveAttribute("aria-expanded", "false");
+ act(() => { writeLocalPreferences({ ...DEFAULT_LOCAL_PREFS, activityMode: "expanded" }); });
+ expect(disclosure).toHaveAttribute("aria-expanded", "true");
+ });
it("updates existing activity when the language changes without altering raw values", async () => {
const query = "release notes";
const path = "src/app.tsx";
diff --git a/webui/src/tests/app-layout.test.tsx b/webui/src/tests/app-layout.test.tsx
index d8954b331..8b8dc168e 100644
--- a/webui/src/tests/app-layout.test.tsx
+++ b/webui/src/tests/app-layout.test.tsx
@@ -58,7 +58,8 @@ function mockFetchRoutes(routes: Record<string, unknown>): void {
vi.stubGlobal(
"fetch",
vi.fn(async (input: RequestInfo | URL) => {
- const route = routes[String(input)];
+ const route = routes[String(input)]
+ ?? (/^\/api\/sessions\/[^/]+\/subagents$/.test(String(input)) ? { tasks: [] } : undefined);
const body =
typeof route === "function"
? await (route as () => unknown | Promise<unknown>)()
@@ -338,13 +339,7 @@ describe("App layout", () => {
expires_in: 300,
});
vi.mocked(deriveWsUrl).mockReset().mockReturnValue("ws://test");
- vi.stubGlobal(
- "fetch",
- vi.fn().mockResolvedValue({
- ok: false,
- status: 404,
- }),
- );
+ mockFetchRoutes({});
});
afterEach(() => {
@@ -366,6 +361,34 @@ describe("App layout", () => {
expect(screen.queryByText("Loading nanobot…")).not.toBeInTheDocument();
});
+ it.each([false, true])("enables task controls only when bootstrap advertises support: %s", async (supported) => {
+ mockSessions = [{
+ key: "websocket:chat-a", channel: "websocket", chatId: "chat-a",
+ createdAt: null, updatedAt: null, title: "Inspection", preview: "Inspect config",
+ }];
+ window.history.replaceState(null, "", "/#/chat/websocket%3Achat-a");
+ vi.mocked(fetchBootstrap).mockResolvedValue({
+ token: "tok", api_token: "api-tok", ws_path: "/", expires_in: 300,
+ terminal: { webui: { capabilities: supported ? ["webui.core.v1", "webui.subagents.v1"] : ["webui.core.v1"] } },
+ });
+ mockFetchRoutes({
+ "/api/sessions/websocket%3Achat-a/subagents": { tasks: [{
+ task_id: "task-1", label: "Config check", task_description: "Inspect configuration",
+ state: "running", phase: "awaiting_model", elapsed_seconds: 2, iteration: 1,
+ tool_events: [], usage: null, receipts: {}, result: null, partial: false,
+ stop_reason: null, error: null, origin_turn_id: null, origin_message_id: null,
+ created_at: 100, completed_at: null,
+ }] },
+ });
+ render(<App />);
+ await screen.findByRole("textbox");
+ if (supported) await screen.findByRole("button", { name: /Config check Running/ });
+ else expect(screen.queryByText("Config check")).not.toBeInTheDocument();
+ const reads = vi.mocked(fetch).mock.calls.filter(([url]) => String(url).endsWith("/subagents"));
+ expect(reads).toHaveLength(supported ? 1 : 0);
+ expect(requestMutationSpy).not.toHaveBeenCalled();
+ });
+
it("shows the auth form without an invalid-password error on first load", async () => {
vi.mocked(fetchBootstrap).mockRejectedValueOnce(
new Error("bootstrap failed: HTTP 401"),
diff --git a/webui/src/tests/generic-tool-model.test.ts b/webui/src/tests/generic-tool-model.test.ts
index 8886fef83..42d64155f 100644
--- a/webui/src/tests/generic-tool-model.test.ts
+++ b/webui/src/tests/generic-tool-model.test.ts
@@ -3,6 +3,7 @@ import { describe, expect, it } from "vitest";
import { redactActivityText } from "@/components/thread/activity/activity-text";
import {
describeGenericToolRun,
+ canGroupGenericToolRuns,
parseGenericToolTrace,
type GenericToolStatus,
} from "@/components/thread/activity/generic-tool-model";
@@ -39,7 +40,12 @@ describe("generic tool activity semantics", () => {
['read_file({"path":"docs/guide.md"})', "Read file", "docs/guide.md"],
['memory_search({"query":"launch date"})', "Searched memory", "“launch date”"],
['generate_image({"prompt":"private launch art"})', "Generated image", ""],
- ['spawn({"label":"Research competitors","task":"private task"})', "Delegated task", "Research competitors"],
+ ['spawn({"label":"Research competitors","task":"private task"})', "Subtask created", "Research competitors"],
+ ['subagent("create")', "Subtask created", ""],
+ ['subagent({"action":"create","label":"Research competitors","task":"private task"})', "Subtask created", "Research competitors"],
+ ['subagent("check")', "Subtask status retrieved", ""],
+ ['subagent("send")', "Message queued for subtask", ""],
+ ['subagent("cancel")', "Stop request processed", ""],
['message({"channel":"telegram","content":"private message"})', "Sent message", "telegram"],
['my({"action":"check","key":"context_window_tokens"})', "Checked agent settings", "context_window_tokens"],
['my({"action":"set","key":"model","value":"private-model"})', "Updated agent settings", "model"],
@@ -125,6 +131,13 @@ describe("generic tool activity semantics", () => {
}
});
+ it("keeps different subtask actions separate while grouping repeated status checks", () => {
+ const item = (action: string) => ({ trace: parseGenericToolTrace(`subagent("${action}")`)!, status: "done" as const });
+ expect(canGroupGenericToolRuns(item("create"), item("check"))).toBe(false);
+ expect(canGroupGenericToolRuns(item("send"), item("cancel"))).toBe(false);
+ expect(canGroupGenericToolRuns(item("check"), item("check"))).toBe(true);
+ });
+
it.each([
["Authorization: Bearer top-secret-token", "Authorization: <redacted>"],
["API_KEY=sk-proj-1234567890abcdef", "API_KEY=<redacted>"],
diff --git a/webui/src/tests/i18n-agent-activity.test.tsx b/webui/src/tests/i18n-agent-activity.test.tsx
index 6731b7dd9..d6767c524 100644
--- a/webui/src/tests/i18n-agent-activity.test.tsx
+++ b/webui/src/tests/i18n-agent-activity.test.tsx
@@ -28,6 +28,21 @@ describe("localized agent activity contracts", () => {
expect(translated.actionTargetRich).toContain("<target></target>");
await setAppLanguage(locale);
+ for (const [action, keys] of [
+ ["create", ["delegatingTask", "delegatedTask", "delegateTaskFailed"]],
+ ["check", ["checkingSubtask", "checkedSubtask", "checkSubtaskFailed"]],
+ ["send", ["messagingSubtask", "queuedSubtaskMessage", "messageSubtaskFailed"]],
+ ["cancel", ["stoppingSubtask", "requestedSubtaskStop", "stopSubtaskFailed"]],
+ ] as const) {
+ for (const line of [`subagent("${action}")`, `subagent({"action":"${action}","task_id":"private-id","message":"private instructions"})`]) {
+ const subtask = parseGenericToolTrace(line)!;
+ for (const [index, status] of (["running", "done", "error"] as const).entries()) {
+ expect(describeGenericToolRun([{ trace: subtask, status }], i18n.t)).toMatchObject({
+ label: translated[keys[index]], detail: "", status,
+ });
+ }
+ }
+ }
const trace = parseGenericToolTrace('read_file({"path":"src/app.tsx"})')!;
const rg = parseGenericToolTrace('rg({"args":["-n","hello world","src"]})')!;
for (const status of ["running", "done", "error"] as const) {
@@ -99,4 +114,24 @@ describe("localized agent activity contracts", () => {
expect(screen.getByText("Could not search release notes")).toBeInTheDocument();
expect(JSON.stringify(messages)).toBe(original);
});
+
+ it("renders recorded subtask actions in Chinese and English without implying execution is complete", async () => {
+ const messages: UIMessage[] = [{
+ id: "subtask-replay", role: "tool", kind: "trace", createdAt: 1,
+ content: 'subagent("create")',
+ traces: ['subagent("create")', 'subagent("check")', 'subagent("send")', 'subagent("cancel")'],
+ }];
+ const original = JSON.stringify(messages);
+ await setAppLanguage("zh-CN");
+ render(<AgentActivityCluster messages={messages} isTurnStreaming={false} hasBodyBelow expanded />);
+ for (const label of ["子任务已创建", "已获取子任务状态", "消息已加入子任务队列", "已处理停止请求"]) {
+ expect(screen.getByText(label)).toBeInTheDocument();
+ }
+ expect(screen.queryByText("已完成 Subagent")).not.toBeInTheDocument();
+ await act(async () => setAppLanguage("en"));
+ for (const label of ["Subtask created", "Subtask status retrieved", "Message queued for subtask", "Stop request processed"]) {
+ expect(screen.getByText(label)).toBeInTheDocument();
+ }
+ expect(JSON.stringify(messages)).toBe(original);
+ });
});
diff --git a/webui/src/tests/nanobot-client.test.ts b/webui/src/tests/nanobot-client.test.ts
index e978b92f8..e8817b889 100644
--- a/webui/src/tests/nanobot-client.test.ts
+++ b/webui/src/tests/nanobot-client.test.ts
@@ -1619,6 +1619,18 @@ describe("NanobotClient", () => {
expect(chatHandler).toHaveBeenCalledTimes(deliveredBeforeLateFrames);
expect(client.getRunStartedAt("chat-canonical")).toBeNull();
+ const otherChat = vi.fn();
+ client.onChat("other-chat", otherChat);
+ const taskUpdate = {
+ event: "subagent_task", chat_id: "chat-canonical",
+ task: { task_id: "child", origin_turn_id: "turn-canonical", state: "done", revision: 4 },
+ };
+ lastSocket().fakeMessage(taskUpdate);
+ expect(chatHandler).toHaveBeenLastCalledWith(taskUpdate);
+ expect(chatHandler).toHaveBeenCalledTimes(deliveredBeforeLateFrames + 1);
+ expect(otherChat).not.toHaveBeenCalled();
+ expect(client.hasUnsettledRun("chat-canonical")).toBe(false);
+ expect(client.getRunStartedAt("chat-canonical")).toBeNull();
});
it("notifies run status subscribers and replays running chats", () => {
diff --git a/webui/src/tests/subagent-tasks.test.tsx b/webui/src/tests/subagent-tasks.test.tsx
new file mode 100644
index 000000000..fea7319fc
--- /dev/null
+++ b/webui/src/tests/subagent-tasks.test.tsx
@@ -0,0 +1,485 @@
+import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { SubagentTasksProvider, SubagentThreadMessages as ThreadMessages } from "@/components/thread/SubagentTasks";
+import { buildDisplayUnits, unitKeysForDisplay } from "@/components/thread/ThreadMessages";
+import { ThreadVisibilityContext } from "@/hooks/useThreadVisibility";
+import { setAppLanguage } from "@/i18n";
+import { DEFAULT_LOCAL_PREFS, LOCAL_PREFS_STORAGE_KEY, writeLocalPreferences } from "@/lib/local-preferences";
+import type { ConnectionStatus, InboundEvent, SubagentTaskSnapshot, UIMessage } from "@/lib/types";
+
+const requestMutation = vi.fn();
+const chatHandlers = new Map<string, Set<(event: InboundEvent) => void>>();
+const statusHandlers = new Set<(status: ConnectionStatus) => void>();
+const client = {
+ requestMutation,
+ onChat: vi.fn((chatId: string, handler: (event: InboundEvent) => void) => {
+ const handlers = chatHandlers.get(chatId) ?? new Set();
+ chatHandlers.set(chatId, handlers);
+ handlers.add(handler);
+ return () => { handlers.delete(handler); };
+ }),
+ onStatus: vi.fn((handler: (status: ConnectionStatus) => void) => {
+ statusHandlers.add(handler);
+ handler("open");
+ return () => { statusHandlers.delete(handler); };
+ }),
+};
+function emitTask(snapshot: SubagentTaskSnapshot, chatId = "a") {
+ act(() => { chatHandlers.get(chatId)?.forEach((handler) => handler({ event: "subagent_task", chat_id: chatId, task: snapshot })); });
+}
+const messages: UIMessage[] = [
+ { id: "prompt-a", role: "user", content: "Inspect config", turnId: "turn-a" },
+ { id: "answer-a", role: "assistant", content: "Main answer", turnId: "turn-a" },
+];
+
+function task(overrides: Partial<SubagentTaskSnapshot> = {}): SubagentTaskSnapshot {
+ return {
+ task_id: "task-1", revision: 1, label: "Config check", task_description: "Check configuration values",
+ state: "running", phase: "awaiting_model", elapsed_seconds: 2, iteration: 1,
+ tool_events: [], usage: null, receipts: {}, result: null, partial: false,
+ stop_reason: null, error: null, origin_turn_id: "turn-a", origin_message_id: null,
+ created_at: 100, completed_at: null, ...overrides,
+ };
+}
+function response(tasks: SubagentTaskSnapshot[]): Response {
+ return new Response(JSON.stringify({ tasks }), { headers: { "content-type": "application/json" } });
+}
+function childThread(answer: string, active = true): Response {
+ return new Response(JSON.stringify({ schemaVersion: 3, projection: "events", active_turn_id: active ? "child-turn" : null,
+ events: [
+ { event: "user_message", chat_id: "task-1", starts_turn: true, projection_id: "child-prompt", turn_id: "child-turn", text: "Inspect configuration in the child session", created_at_ms: 100000 },
+ { event: "message", chat_id: "task-1", projection_id: "child-tool", turn_id: "child-turn", kind: "tool_hint", text: 'read_file({"path":"config.py"})',
+ tool_events: [{ call_id: "read-1", name: "read_file", arguments: { path: "config.py" }, phase: "end", result: "configuration values" }] },
+ { event: "message", chat_id: "task-1", projection_id: "child-answer", turn_id: "child-turn", text: answer },
+ ],
+ }), { headers: { "content-type": "application/json" } });
+}
+function layout({ enabled = true, liveEvents = true, historyEnabled = false, sessionKey = "websocket:a", visible = true, threadMessages = messages } = {}) {
+ return <ThreadVisibilityContext.Provider value={visible}>
+ <SubagentTasksProvider client={client} sessionKey={sessionKey} token="tok" enabled={enabled} liveEvents={liveEvents} historyEnabled={historyEnabled}>
+ <div data-testid="messages"><ThreadMessages messages={threadMessages} /></div>
+ <div data-testid="composer"><textarea aria-label="Message" /></div>
+ </SubagentTasksProvider>
+ </ThreadVisibilityContext.Provider>;
+}
+
+describe("session-owned task UI", () => {
+ beforeEach(async () => {
+ localStorage.removeItem(LOCAL_PREFS_STORAGE_KEY);
+ await setAppLanguage("en");
+ requestMutation.mockReset();
+ client.onChat.mockClear();
+ client.onStatus.mockClear();
+ chatHandlers.clear();
+ statusHandlers.clear();
+ vi.stubGlobal("fetch", vi.fn().mockImplementation(async () => response([task()])));
+ });
+ afterEach(() => { vi.useRealTimers(); vi.unstubAllGlobals(); localStorage.removeItem(LOCAL_PREFS_STORAGE_KEY); });
+
+ it("applies the browser activity preference to delegated work and its shared child chat", async () => {
+ vi.stubGlobal("fetch", vi.fn(async (url: string) => url.endsWith("/webui-thread")
+ ? childThread("Configuration verified", false)
+ : response([task({ state: "done", completed_at: 102 })])));
+ const user = userEvent.setup();
+ const view = render(layout({ historyEnabled: true }));
+ const work = await screen.findByRole("button", { name: /Delegated work/ });
+ expect(work).toHaveAttribute("aria-expanded", "false");
+
+ act(() => { writeLocalPreferences({ ...DEFAULT_LOCAL_PREFS, activityMode: "expanded" }); });
+ expect(work).toHaveAttribute("aria-expanded", "true");
+ await user.click(screen.getByRole("button", { name: /Config check Completed/ }));
+ const detail = screen.getByRole("dialog", { name: "Config check" });
+ expect(await within(detail).findByText("Configuration verified")).toBeVisible();
+ expect(within(detail).getByTestId("agent-activity-content")).toBeVisible();
+ await user.click(within(detail).getByRole("button", { name: /Collapse activity details/ }));
+ expect(within(detail).queryByTestId("agent-activity-content")).not.toBeInTheDocument();
+
+ act(() => { writeLocalPreferences(DEFAULT_LOCAL_PREFS); });
+ expect(work).toHaveAttribute("aria-expanded", "false");
+ act(() => { writeLocalPreferences({ ...DEFAULT_LOCAL_PREFS, activityMode: "expanded" }); });
+ expect(within(detail).getByTestId("agent-activity-content")).toBeVisible();
+ view.unmount();
+
+ render(layout({ historyEnabled: true }));
+ expect(await screen.findByRole("button", { name: /Config check Completed/ })).toBeVisible();
+ await user.click(screen.getByRole("button", { name: /Config check Completed/ }));
+ expect(await within(screen.getByRole("dialog")).findByTestId("agent-activity-content")).toBeVisible();
+ });
+
+ it("renders the child Session in the shared chat view and refreshes it from task events", async () => {
+ let completed = false;
+ const fetcher = vi.fn(async (url: string) => url.endsWith("/webui-thread")
+ ? childThread(completed ? "## Findings\n\n- **Verified** the full session\n\n| Check | Result |\n| --- | --- |\n| Configuration | Passed |" : "Checking the configuration", !completed)
+ : response([task()]));
+ vi.stubGlobal("fetch", fetcher);
+ const user = userEvent.setup();
+ const view = render(layout({ historyEnabled: true }));
+ await user.click(await screen.findByRole("button", { name: /Config check Running/ }));
+ const detail = screen.getByRole("dialog", { name: "Config check" });
+ expect(await within(detail).findByText("Inspect configuration in the child session")).toBeVisible();
+ expect(within(detail).getByText("Checking the configuration")).toBeVisible();
+ expect(fetcher).toHaveBeenCalledWith(
+ "/api/sessions/websocket%3Aa/subagents/task-1/webui-thread", expect.objectContaining({ signal: expect.any(AbortSignal) }),
+ );
+ completed = true;
+ emitTask(task({ revision: 2, state: "done", completed_at: 102, result: "Bounded task summary" }));
+ expect(await within(detail).findByRole("heading", { name: "Findings" })).toBeVisible();
+ expect(within(detail).getByRole("table")).toHaveTextContent("ConfigurationPassed");
+ expect(within(detail).getByText("Inspect configuration in the child session")).toBeVisible();
+ // Opening and reading details never mutates execution; a fresh view reads the same saved child.
+ expect(requestMutation).not.toHaveBeenCalled();
+ view.unmount();
+ fetcher.mockImplementation(async (url) => url.endsWith("/webui-thread") ? childThread("## Findings\n\nVerified the full session", false)
+ : response([task({ revision: 2, state: "done", completed_at: 102 })]));
+ render(layout({ historyEnabled: true }));
+ await user.click(await screen.findByRole("button", { name: /Delegated work/ }));
+ await user.click(screen.getByRole("button", { name: /Config check Completed/ }));
+ expect(await within(screen.getByRole("dialog")).findByRole("heading", { name: "Findings" })).toBeVisible();
+ });
+
+ it("coalesces history reads and discards an outstanding read when the session changes", async () => {
+ let resolveFirst!: (value: Response) => void;
+ let resolveOld!: (value: Response) => void;
+ let reads = 0;
+ const readSignals: AbortSignal[] = [];
+ const fetcher = vi.fn(async (url: string, init?: RequestInit) => {
+ if (!url.endsWith("/webui-thread")) return response([task()]);
+ if (init?.signal) readSignals.push(init.signal);
+ reads += 1;
+ if (reads === 1) return new Promise<Response>((resolve) => { resolveFirst = resolve; });
+ if (reads === 3) return new Promise<Response>((resolve) => { resolveOld = resolve; });
+ return childThread("Latest child response", false);
+ });
+ vi.stubGlobal("fetch", fetcher);
+ const user = userEvent.setup();
+ const view = render(layout({ historyEnabled: true }));
+ await user.click(await screen.findByRole("button", { name: /Config check Running/ }));
+ await waitFor(() => expect(reads).toBe(1));
+ emitTask(task({ revision: 2, iteration: 2 }));
+ emitTask(task({ revision: 3, iteration: 3 }));
+ expect(reads).toBe(1);
+ await act(async () => { resolveFirst(childThread("Earlier checkpoint")); });
+ expect(await within(screen.getByRole("dialog")).findByText("Latest child response")).toBeVisible();
+ expect(reads).toBe(2);
+ emitTask(task({ revision: 4, iteration: 4 }));
+ await waitFor(() => expect(reads).toBe(3));
+ const oldSignal = readSignals.at(-1);
+ view.rerender(layout({ historyEnabled: true, sessionKey: "websocket:b" }));
+ await screen.findByRole("button", { name: /Config check Running/ });
+ expect(oldSignal?.aborted).toBe(true);
+ await act(async () => { resolveOld(childThread("Old session response")); });
+ await user.click(screen.getByRole("button", { name: /Config check Running/ }));
+ expect(await within(screen.getByRole("dialog")).findByText("Latest child response")).toBeVisible();
+ });
+
+ it("retries a failed history read through the shared history controls", async () => {
+ let offline = true;
+ vi.stubGlobal("fetch", vi.fn(async (url: string) => {
+ if (!url.endsWith("/webui-thread")) return response([task()]);
+ if (offline) throw new Error("offline");
+ return childThread("Recovered child response");
+ }));
+ const user = userEvent.setup();
+ render(layout({ historyEnabled: true }));
+ await user.click(await screen.findByRole("button", { name: /Config check Running/ }));
+ const detail = screen.getByRole("dialog");
+ expect(await within(detail).findByRole("alert")).toHaveTextContent("Loading failed.");
+ offline = false;
+ await user.click(within(detail).getByRole("button", { name: "Retry" }));
+ expect(await within(detail).findByText("Recovered child response")).toBeVisible();
+ });
+
+ it("keeps the same work block under its prompt, folds completed work and restores it after refresh", async () => {
+ const view = render(layout());
+ const runningRow = await screen.findByRole("button", { name: /Config check Running/ });
+ const work = runningRow.closest("section");
+ const header = within(work!).getByRole("button", { name: /Delegated work/ });
+ expect(screen.getByTestId("messages")).toContainElement(runningRow);
+ expect(header).toHaveAttribute("aria-expanded", "true");
+ vi.mocked(fetch).mockImplementation(async () => response([task({ revision: 2, state: "done", result: "Verified", completed_at: 102 })]));
+ fireEvent(window, new Event("focus"));
+ await waitFor(() => expect(header).toHaveAttribute("aria-expanded", "false"));
+ fireEvent.click(header);
+ const row = screen.getByRole("button", { name: /Config check Completed/ });
+ expect(row).toBe(runningRow);
+ expect(row.closest("section")).toBe(work);
+ expect(within(screen.getByTestId("composer")).queryByText("Config check")).not.toBeInTheDocument();
+ expect(work).toHaveAccessibleName("Delegated work");
+ view.unmount();
+ render(layout());
+ fireEvent.click(await screen.findByRole("button", { name: /Delegated work Finished: 1/ }));
+ expect(screen.getByRole("button", { name: /Config check Completed/ })).toBeVisible();
+ expect(requestMutation).not.toHaveBeenCalled();
+ });
+
+ it("shows truthful partial output, interruption and receipts, and restores keyboard focus", async () => {
+ vi.mocked(fetch).mockResolvedValue(response([task({
+ state: "interrupted", partial: true, result: "Found a conflicting setting",
+ stop_reason: "host_restarted", completed_at: 102, receipts: { a: "delivered", b: "undelivered" },
+ })]));
+ const user = userEvent.setup();
+ render(layout());
+ await user.click(await screen.findByRole("button", { name: /Delegated work/ }));
+ const row = await screen.findByRole("button", { name: /Config check Interrupted/ });
+ await user.click(row);
+ const detail = screen.getByRole("dialog", { name: "Config check" });
+ expect(within(detail).getByText(/has not been restarted automatically/)).toBeVisible();
+ expect(detail).toHaveFocus();
+ expect(within(detail).getByText("Interrupted")).toBeVisible();
+ expect(within(detail).getByText("Found a conflicting setting")).toBeVisible();
+ await user.click(within(detail).getByText("Message delivery"));
+ expect(within(detail).getByText("Delivered: 1")).toBeVisible();
+ expect(screen.queryByRole("button", { name: "Stop Config check" })).not.toBeInTheDocument();
+ await user.keyboard("{Escape}");
+ await waitFor(() => expect(row).toHaveFocus());
+ });
+
+ it("keeps cancellation and an open detail consistent when an older read completes later", async () => {
+ let resolveRefresh!: (value: Response) => void;
+ let resolveStop!: (value: SubagentTaskSnapshot) => void;
+ requestMutation.mockImplementation(() => new Promise((resolve) => { resolveStop = resolve; }));
+ const user = userEvent.setup();
+ render(layout());
+ await user.click(await screen.findByRole("button", { name: /Config check Running/ }));
+ await user.keyboard("{Escape}");
+ await user.click(screen.getByRole("button", { name: "Stop Config check" }));
+ vi.mocked(fetch).mockImplementationOnce(() => new Promise((resolve) => { resolveRefresh = resolve; }));
+ fireEvent(window, new Event("focus"));
+ await waitFor(() => expect(fetch).toHaveBeenCalledTimes(2));
+ await act(async () => { resolveStop(task({ revision: 3, state: "cancelled", completed_at: 102 })); });
+ await user.click(screen.getByRole("button", { name: /Delegated work Finished: 1/ }));
+ await screen.findByRole("button", { name: /Config check Cancelled/ });
+ await act(async () => { resolveRefresh(response([task()])); });
+ expect(screen.queryByRole("button", { name: "Stop Config check" })).not.toBeInTheDocument();
+ expect(requestMutation).toHaveBeenCalledWith("subagent.cancel", { session_key: "websocket:a", task_id: "task-1" }, 20_000);
+ });
+
+ it("does not request an unsupported feature and detaches events in hidden panes", async () => {
+ const view = render(layout({ enabled: false }));
+ expect(fetch).not.toHaveBeenCalled();
+ view.rerender(layout({ visible: false }));
+ expect(fetch).not.toHaveBeenCalled();
+ view.rerender(layout());
+ fireEvent.click(await screen.findByRole("button", { name: /Config check Running/ }));
+ expect(screen.getByRole("dialog", { name: "Config check" })).toBeVisible();
+ view.rerender(layout({ visible: false }));
+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
+ fireEvent(window, new Event("focus"));
+ expect(fetch).toHaveBeenCalledTimes(1);
+ expect(chatHandlers.get("a")?.size).toBe(0);
+ expect(statusHandlers.size).toBe(0);
+ });
+
+ it("keeps load failures visible and keeps stop failures across a successful refresh", async () => {
+ const user = userEvent.setup();
+ requestMutation.mockRejectedValue(new Error("Cannot stop task"));
+ render(layout());
+ await user.click(await screen.findByRole("button", { name: "Stop Config check" }));
+ await screen.findByText("Cannot stop task");
+ fireEvent(window, new Event("focus"));
+ await waitFor(() => expect(fetch).toHaveBeenCalledTimes(2));
+ expect(screen.getByText("Cannot stop task")).toBeVisible();
+ vi.mocked(fetch).mockRejectedValue(new Error("offline"));
+ fireEvent(window, new Event("focus"));
+ await screen.findByText("Could not load subtasks.");
+ expect(screen.getByRole("button", { name: /Config check Running/ })).toBeVisible();
+ });
+
+ it("shows a read error for malformed or duplicate task records", async () => {
+ vi.mocked(fetch).mockImplementation(async () => new Response(JSON.stringify({
+ tasks: [{ ...task(), label: { unexpected: true } }],
+ }), { headers: { "content-type": "application/json" } }));
+ render(layout());
+ await screen.findByText("Could not load subtasks.");
+ expect(screen.queryByText("Config check")).not.toBeInTheDocument();
+ vi.mocked(fetch).mockImplementation(async () => response([task(), task()]));
+ fireEvent(window, new Event("focus"));
+ await waitFor(() => expect(fetch).toHaveBeenCalledTimes(2));
+ expect(screen.getByText("Could not load subtasks.")).toBeVisible();
+ expect(screen.queryByText("Config check")).not.toBeInTheDocument();
+ });
+
+ it("discards reads from the previous session after switching", async () => {
+ let resolveOld!: (value: Response) => void;
+ vi.mocked(fetch).mockImplementationOnce(() => new Promise((resolve) => { resolveOld = resolve; }));
+ const view = render(layout());
+ vi.mocked(fetch).mockResolvedValue(response([task({ task_id: "task-b", label: "Other work" })]));
+ view.rerender(layout({ sessionKey: "websocket:b" }));
+ await screen.findByRole("button", { name: /Other work Running/ });
+ await act(async () => { resolveOld(response([task()])); });
+ expect(screen.queryByText("Config check")).not.toBeInTheDocument();
+ });
+
+ it("keeps task details open through completion and renders Markdown results", async () => {
+ const user = userEvent.setup();
+ render(layout());
+ const row = await screen.findByRole("button", { name: /Config check Running/ });
+ await user.click(row);
+ const detail = screen.getByRole("dialog", { name: "Config check" });
+ vi.mocked(fetch).mockImplementation(async () => response([task({ revision: 2, state: "done", completed_at: 102,
+ result: "## Findings\n\n- **Release** resources\n- Cover exceptions\n\n```python\nawait connection.close()\n```\n\n| Check | Result |\n| --- | --- |\n| Cancellation | Passed |\n\n[Evidence](https://example.com/review)",
+ })]));
+ fireEvent(window, new Event("focus"));
+ expect(await within(detail).findByRole("heading", { name: "Findings" })).toBeVisible();
+ expect(within(detail).getByRole("list")).toHaveTextContent("Release resources");
+ expect(within(detail).getByRole("table")).toHaveTextContent("CancellationPassed");
+ expect(await within(detail).findByText("await connection.close()", { exact: false })).toBeVisible();
+ expect(within(detail).getByRole("link", { name: /Evidence/ })).toHaveAttribute("href", "https://example.com/review");
+ expect(detail).toBeVisible();
+ await user.keyboard("{Escape}");
+ await waitFor(() => expect(screen.getByRole("button", { name: /Delegated work/ })).toHaveFocus());
+ expect(requestMutation).not.toHaveBeenCalled();
+ });
+
+ it("anchors replay once when multiple prompts share a turn and preserves row order", async () => {
+ const replay = [...messages, { id: "followup", role: "user", content: "Focus on errors", turnId: "turn-a" } satisfies UIMessage];
+ const keys = unitKeysForDisplay(buildDisplayUnits(replay));
+ expect(new Set(keys).size).toBe(keys.length);
+ vi.mocked(fetch).mockImplementation(async () => response([
+ task({ task_id: "second", label: "Second check", created_at: 101, origin_message_id: "old-prompt-id" }),
+ task({ origin_message_id: "old-prompt-id" }),
+ ]));
+ render(layout({ threadMessages: replay }));
+ await screen.findByRole("button", { name: /Config check Running/ });
+ expect(screen.getAllByRole("region", { name: "Delegated work" })).toHaveLength(1);
+ const rows = screen.getAllByRole("button", { name: /check Running/ });
+ expect(rows.map((row) => row.dataset.subagentId)).toEqual(["task-1", "second"]);
+ vi.mocked(fetch).mockImplementation(async () => response([
+ task({ task_id: "second", revision: 2, label: "Second check", created_at: 101, origin_message_id: "old-prompt-id", state: "error", error: "Unreadable file" }),
+ task({ origin_message_id: "old-prompt-id" }),
+ ]));
+ fireEvent(window, new Event("focus"));
+ await screen.findByRole("button", { name: /Second check Failed/ });
+ expect(screen.getAllByRole("button", { name: /check (Running|Failed)/ }).map((row) => row.dataset.subagentId)).toEqual(["task-1", "second"]);
+ expect(screen.getByRole("button", { name: /Review needed: 1/ })).toBeVisible();
+ expect(screen.getByText("Main answer").compareDocumentPosition(screen.getByText("Second check")) & Node.DOCUMENT_POSITION_PRECEDING).toBeTruthy();
+ });
+
+ it("prefers the exact initiating follow-up over a turn fallback", async () => {
+ vi.mocked(fetch).mockImplementation(async () => response([task({ origin_message_id: "followup" })]));
+ render(layout({ threadMessages: [...messages, { id: "followup", role: "user", content: "Check more", turnId: "turn-a" }] }));
+ await screen.findByRole("button", { name: /Config check Running/ });
+ const group = screen.getByRole("region", { name: "Delegated work" });
+ expect(screen.getByText("Check more").compareDocumentPosition(group) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
+ });
+
+ it("keeps legacy work with an unknown origin separate from the latest request after refresh", async () => {
+ vi.mocked(fetch).mockImplementation(async () => response([
+ task({ task_id: "legacy", revision: 0, label: "Nanjing weather", state: "done", completed_at: 102,
+ origin_turn_id: "websocket:a:1791046873588004336", result: "## Nanjing\n\n- **Rain**" }),
+ task({ created_at: 200 }),
+ ]));
+ const user = userEvent.setup();
+ const view = render(layout());
+ await screen.findByRole("button", { name: /Config check Running/ });
+ const otherWork = screen.getByRole("region", { name: "Other delegated work" });
+ const header = within(otherWork).getByRole("button", { name: /Other delegated work/ });
+ expect(header).toHaveAttribute("aria-expanded", "false");
+ expect(otherWork.compareDocumentPosition(screen.getByText("Inspect config")) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
+ expect(within(screen.getByRole("region", { name: "Delegated work" })).queryByText("Nanjing weather")).not.toBeInTheDocument();
+ await user.click(header);
+ expect(within(otherWork).getByText("These tasks have no matching request in the displayed messages.")).toBeVisible();
+ await user.click(within(otherWork).getByRole("button", { name: /Nanjing weather Completed/ }));
+ const detail = screen.getByRole("dialog", { name: "Nanjing weather" });
+ expect(within(detail).getByRole("heading", { name: "Nanjing" })).toBeVisible();
+ expect(within(detail).getByRole("list")).toHaveTextContent("Rain");
+ await user.keyboard("{Escape}");
+ view.unmount();
+ render(layout());
+ const restored = await screen.findByRole("region", { name: "Other delegated work" });
+ expect(within(restored).getByRole("button", { name: /Other delegated work/ })).toHaveAttribute("aria-expanded", "false");
+ expect(restored.compareDocumentPosition(screen.getByText("Inspect config")) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
+ expect(requestMutation).not.toHaveBeenCalled();
+ });
+
+ it("reattaches work when its initiating prompt is loaded without duplicating it or closing details", async () => {
+ vi.mocked(fetch).mockImplementation(async () => response([
+ task({ task_id: "older", label: "Earlier check", origin_turn_id: "older-turn", origin_message_id: "older-prompt" }),
+ task({ created_at: 200 }),
+ ]));
+ const user = userEvent.setup();
+ const view = render(layout());
+ const otherWork = await screen.findByRole("region", { name: "Other delegated work" });
+ await user.click(within(otherWork).getByRole("button", { name: /Earlier check Running/ }));
+ const detail = screen.getByRole("dialog", { name: "Earlier check" });
+ view.rerender(layout({ threadMessages: [
+ { id: "older-prompt", role: "user", content: "Inspect earlier work", turnId: "older-turn" },
+ ...messages,
+ ] }));
+ expect(detail).toBeVisible();
+ await user.keyboard("{Escape}");
+ expect(screen.queryByRole("region", { name: "Other delegated work" })).not.toBeInTheDocument();
+ const row = screen.getByRole("button", { name: /Earlier check Running/ });
+ expect(screen.getAllByRole("button", { name: /Earlier check Running/ })).toHaveLength(1);
+ expect(screen.getByText("Inspect earlier work").compareDocumentPosition(row) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
+ expect(screen.getByText("Inspect config").compareDocumentPosition(row) & Node.DOCUMENT_POSITION_PRECEDING).toBeTruthy();
+ await waitFor(() => expect(row).toHaveFocus());
+ });
+
+ it("merges live work before the initial read without polling or rolling back completed work", async () => {
+ let resolveRead!: (value: Response) => void;
+ vi.mocked(fetch).mockImplementationOnce(() => new Promise((resolve) => { resolveRead = resolve; }));
+ render(layout());
+ emitTask(task({ revision: 3, state: "done", result: "Verified", completed_at: 102 }));
+ emitTask(task({ task_id: "task-2", label: "Sibling check", created_at: 101 }));
+ await screen.findByRole("button", { name: /Sibling check Running/ });
+ await act(async () => { resolveRead(response([task()])); });
+ expect(screen.getByRole("button", { name: /Config check Completed/ })).toBeVisible();
+ expect(screen.getAllByRole("region", { name: "Delegated work" })).toHaveLength(1);
+ vi.useFakeTimers();
+ await act(async () => { vi.advanceTimersByTime(10_000); });
+ expect(fetch).toHaveBeenCalledTimes(1);
+ expect(requestMutation).not.toHaveBeenCalled();
+ });
+
+ it("keeps elapsed time consistent when inspecting a task long after its last event", async () => {
+ vi.useFakeTimers();
+ vi.spyOn(performance, "now").mockImplementation(() => Date.now());
+ render(layout());
+ await act(async () => { await Promise.resolve(); });
+ await act(async () => { await vi.advanceTimersByTimeAsync(10_000); });
+ const row = screen.getByRole("button", { name: /Config check Running/ });
+ expect(row).toHaveTextContent("12s");
+ fireEvent.click(row);
+ expect(screen.getByRole("dialog", { name: "Config check" })).toHaveTextContent("12s");
+ expect(fetch).toHaveBeenCalledTimes(1);
+ vi.mocked(performance.now).mockRestore();
+ });
+
+ it("recovers missed siblings after reconnect even when an older read is still pending", async () => {
+ let resolveOld!: (value: Response) => void;
+ render(layout());
+ await screen.findByRole("button", { name: /Config check Running/ });
+ vi.mocked(fetch).mockImplementationOnce(() => new Promise((resolve) => { resolveOld = resolve; }));
+ fireEvent(window, new Event("focus"));
+ emitTask(task({ revision: 3, state: "cancelled", completed_at: 102 }));
+ vi.mocked(fetch).mockImplementationOnce(async () => response([
+ task({ revision: 2 }), task({ task_id: "task-2", label: "Recovered check", created_at: 101 }),
+ ]));
+ act(() => { statusHandlers.forEach((handler) => { handler("closed"); handler("open"); }); });
+ await act(async () => { resolveOld(response([task()])); });
+ await screen.findByRole("button", { name: /Recovered check Running/ });
+ expect(screen.getByRole("button", { name: /Config check Cancelled/ })).toBeVisible();
+ expect(fetch).toHaveBeenCalledTimes(3);
+ emitTask({ ...task(), revision: -1 });
+ expect(screen.getByText("Could not load subtasks.")).toBeVisible();
+ });
+
+ it("keeps protocol 1 task controls usable on a host without event support", async () => {
+ vi.mocked(fetch).mockImplementation(async () => response([task({ revision: undefined })]));
+ vi.useFakeTimers();
+ const view = render(layout({ liveEvents: false }));
+ await act(async () => { await Promise.resolve(); });
+ expect(screen.getByRole("button", { name: /Config check Running/ })).toBeVisible();
+ vi.mocked(fetch).mockImplementation(async () => response([task({ revision: undefined, state: "done", completed_at: 102 })]));
+ await act(async () => { await vi.advanceTimersByTimeAsync(3000); });
+ expect(screen.getByRole("button", { name: /Delegated work Finished: 1/ })).toBeVisible();
+ expect(client.onChat).not.toHaveBeenCalled();
+ view.rerender(layout({ liveEvents: false, visible: false }));
+ const reads = vi.mocked(fetch).mock.calls.length;
+ await act(async () => { vi.advanceTimersByTime(6000); });
+ expect(fetch).toHaveBeenCalledTimes(reads);
+ });
+});
diff --git a/webui/src/tests/thread-shell.test.tsx b/webui/src/tests/thread-shell.test.tsx
index a9d44c35d..0290aa231 100644
--- a/webui/src/tests/thread-shell.test.tsx
+++ b/webui/src/tests/thread-shell.test.tsx
@@ -222,12 +222,14 @@ function wrap(
children: ReactNode,
modelName?: string | null,
token = "tok",
+ webuiCapabilities: string[] = [],
) {
return (
<ClientProvider
client={client as unknown as import("@/lib/nanobot-client").NanobotClient}
token={token}
modelName={modelName ?? null}
+ webuiCapabilities={webuiCapabilities}
>
{children}
</ClientProvider>
@@ -491,6 +493,39 @@ describe("ThreadShell", () => {
);
});
+ it("renders one persisted task entry at the initiating prompt through the full shell", async () => {
+ const client = makeClient();
+ vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => {
+ if (String(input).endsWith("/subagents")) return httpJson({ tasks: [{
+ task_id: "completed-task", label: "Inspect settings", task_description: "Inspect settings",
+ origin_turn_id: "delegation-turn", origin_message_id: null, created_at: 100, completed_at: 102,
+ state: "done", phase: "done", elapsed_seconds: 2, iteration: 1, tool_events: [],
+ usage: null, receipts: {}, result: "Verified", partial: false, stop_reason: "completed", error: null,
+ }] });
+ if (String(input).includes("/webui-thread")) return httpJson(transcriptFromSimpleMessages([
+ { role: "user", content: "Delegate inspection", turnId: "delegation-turn" },
+ { role: "assistant", content: "Parent conclusion", turnId: "delegation-turn" },
+ ]));
+ return { ok: false, status: 404, json: async () => ({}) };
+ }));
+ const shell = () => wrap(client, <ThreadShell session={session("persisted-tasks")} title="Task history"
+ onToggleSidebar={() => {}} />, null, "tok", ["webui.core.v1", "webui.subagents.v1"]);
+ const view = render(shell());
+ await screen.findByText("Delegate inspection");
+ fireEvent.click(await screen.findByRole("button", { name: /Delegated work Finished: 1/ }));
+ const task = await screen.findByRole("button", { name: /Inspect settings Completed/ });
+ await screen.findByText("Delegate inspection");
+ expect(screen.getAllByRole("button", { name: /Inspect settings/ })).toHaveLength(1);
+ expect(screen.getByTestId("thread-message-region")).toContainElement(task);
+ expect(within(screen.getByTestId("thread-composer-motion")).queryByText("Inspect settings")).not.toBeInTheDocument();
+ view.unmount();
+ render(shell());
+ await screen.findByText("Delegate inspection");
+ fireEvent.click(await screen.findByRole("button", { name: /Delegated work Finished: 1/ }));
+ await screen.findByRole("button", { name: /Inspect settings Completed/ });
+ expect(client.sendMessage).not.toHaveBeenCalled();
+ });
+
it("clears the welcome draft after a delayed new-chat send and an unchanged round-trip", async () => {
const client = makeClient();
const store = new ComposerDraftStore();