feat(subagent): add session-owned task messaging and cancellation (#5985)
let's go!
This commit is contained in:
1 parent
f75470e72f
commit
6ff96f2a8f
93 files changed
+5632
-1156
No files matched your search
@@ -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],
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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"})
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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"})
|
||||
|
||||
+75
-31
@@ -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,
|
||||
*,
|
||||
|
||||
@@ -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(
|
||||
|
||||
Reference in new issue
Block a user