* fix(session): move persistence off event loop * refactor(session): isolate async persistence boundary * refactor(session): keep a single session manager * refactor(session): use stateless async adapters * fix(session): serialize local persistence without file-lock contention * refactor(session): own async persistence and snapshot commits * refactor(session): narrow persistence changes to async adapters * refactor(session): remove redundant async forwarding helpers * fix(command): offload compact session persistence * fix(session): adapt idle compaction to current main * fix(webui): offload session metadata persistence * refactor(session): centralize state ownership in SQLite * fix(session): skip storage for non-recoverable followups * test(webui): honor the full gateway event deadline * perf(session): persist incremental changes and reuse owner snapshots * test(agent): allow durable worker shutdown in burst test * fix(gateway): drain session storage on Windows console shutdown * fix(session): enforce bounded ownership and lifecycle-safe persistence * fix: reject unresolved home paths and stabilize platform tests * fix(session): preserve request context compatibility and owner-backed tests * docs: focus configuration guide on user-facing behavior * fix(session): adapt goal admission to async ownership after rebase * fix(session): integrate current gateway and subagent contracts * fix(session): align rebased workspace admission and async tests * fix(session): support compatible SQLite schema evolution * test(agent): use session owner in workspace context regressions * test: stabilize Windows lifecycle and browser checks * refactor(session): remove premature JSONL file export * ci: bound Windows full-suite worker concurrency * chore: remove session state refactor notes * fix(session): queue writes and retain worker connections * perf(webui): read detached metadata for session and task lists * perf(agent): bound prompt preparation and local token counting * docs: remove internal session storage guide * perf(session): skip archived transcripts during idle scans * fix(session): coordinate turns and isolate legacy session data Bind WebUI input generations to the execution session and serialize idle and SDK compaction with turns. Keep turn drafts through preparation so the latest channel route persists. Move imported workspace JSONL and checkpoints to durable private backups before gateway admission, resuming cleanup after interruptions. Remove committed child sessions when task creation is cancelled. Validation: focused Python and frontend regressions, Ruff, BasedPyright, import boundaries, WebUI build, and isolated gateway/browser flows. * fix(agent): keep cancellation hooks independent of prompt preparation * fix(session): preserve admission, delivery, and migration contracts * fix(agent): preserve cancellation settlement after rebase * fix(session): preserve request attribution through async ownership
121 lines
4.7 KiB
Python
121 lines
4.7 KiB
Python
"""WebUI session read models exposed to interactive clients."""
|
|
|
|
from __future__ import annotations
|
|
|
|
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.state import SessionState
|
|
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."""
|
|
|
|
@property
|
|
def state(self) -> SessionState: ...
|
|
|
|
|
|
class WebUISessionProjection:
|
|
"""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
|
|
|
|
async 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:
|
|
return {}
|
|
snapshot = await self._sessions.state.read_metadata(session_key)
|
|
raw_metadata = snapshot.get("metadata") if snapshot is not None else None
|
|
metadata = cast(dict[str, object], raw_metadata) if isinstance(raw_metadata, dict) else None
|
|
|
|
fields: dict[str, Any] = {}
|
|
try:
|
|
fields["model_preset"] = model_preset_from_metadata(metadata)
|
|
except ValueError:
|
|
self._log.warning("ignoring invalid model preset metadata for session_key={}", session_key)
|
|
fields["model_preset"] = None
|
|
if metadata is None:
|
|
return fields
|
|
|
|
recovery_state = recovery_state_from_metadata(metadata)
|
|
if recovery_state is not None:
|
|
fields["recovery_state"] = recovery_state
|
|
usage = LLMUsage.from_dict(metadata.get("_last_usage"))
|
|
if usage is not None:
|
|
fields["usage"] = usage.to_turn_dict()
|
|
return fields
|
|
|
|
async def hydration_events(self, session_key: str, chat_id: str) -> tuple[dict[str, Any], ...]:
|
|
"""Return reconnect events for durable and same-process session state."""
|
|
events: list[dict[str, Any]] = []
|
|
goal_state = await self.persisted_goal_state(session_key)
|
|
if goal_state is not None:
|
|
events.append(
|
|
{
|
|
"event": "goal_state",
|
|
"chat_id": chat_id,
|
|
"goal_state": goal_state,
|
|
}
|
|
)
|
|
active_turn = self.active_turn_status(chat_id)
|
|
if active_turn is not None:
|
|
started_at, turn_id = active_turn
|
|
event: dict[str, Any] = {
|
|
"event": "goal_status",
|
|
"chat_id": chat_id,
|
|
"status": "running",
|
|
"started_at": started_at,
|
|
}
|
|
if turn_id is not None:
|
|
event["turn_id"] = turn_id
|
|
events.append(event)
|
|
return tuple(events)
|
|
|
|
async def persisted_goal_state(self, session_key: str) -> dict[str, Any] | None:
|
|
"""Return an actionable persisted goal state for reconnect hydration."""
|
|
if self._sessions is None:
|
|
return None
|
|
snapshot = await self._sessions.state.read_metadata(session_key)
|
|
raw_metadata = snapshot.get("metadata") if snapshot is not None else None
|
|
metadata = cast(dict[str, Any], raw_metadata) if isinstance(raw_metadata, dict) else {}
|
|
goal_state = goal_state_ws_blob(metadata)
|
|
if not goal_state.get("active") and goal_state.get("status") != "blocked":
|
|
return None
|
|
return goal_state
|
|
|
|
@staticmethod
|
|
def active_turn_status(chat_id: str) -> tuple[float, str | None] | None:
|
|
"""Return same-process running-turn state for reconnect hydration."""
|
|
started_at = websocket_turn_wall_started_at(chat_id)
|
|
if started_at is None:
|
|
return None
|
|
return started_at, websocket_turn_id(chat_id)
|