* 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
219 lines
8.3 KiB
Python
219 lines
8.3 KiB
Python
"""Connection-owned Temporary Chat behavior for the WebUI."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import uuid
|
|
from dataclasses import dataclass
|
|
from pathlib import Path
|
|
from typing import Any
|
|
|
|
from nanobot.bus.events import (
|
|
INBOUND_META_RUNTIME_CONTROL,
|
|
RUNTIME_CONTROL_SESSION_DISCARD,
|
|
InboundMessage,
|
|
)
|
|
from nanobot.bus.queue import MessageBus
|
|
from nanobot.command.builtin import register_builtin_commands
|
|
from nanobot.command.router import CommandRouter
|
|
from nanobot.security.workspace_access import WorkspaceScope
|
|
from nanobot.session.manager import SessionManager
|
|
from nanobot.webui.workspaces import WebUIWorkspaceController
|
|
|
|
_TEMPORARY_CHAT_DISABLED_TOOLS = frozenset({
|
|
"create_goal",
|
|
"update_goal",
|
|
"subagent",
|
|
"cron",
|
|
})
|
|
_TEMPORARY_CHAT_COMMANDS = frozenset({"/model", "/stop"})
|
|
|
|
|
|
class TemporaryChatError(ValueError):
|
|
"""A stable WebUI protocol error for a Temporary Chat operation."""
|
|
|
|
def __init__(self, detail: str) -> None:
|
|
super().__init__(detail)
|
|
self.detail = detail
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class TemporaryChatMessagePolicy:
|
|
"""Server-owned message rules for one active Temporary Chat."""
|
|
|
|
session_key: str
|
|
session_generation: str
|
|
workspace_scope: WorkspaceScope
|
|
require_existing_session: bool = True
|
|
hydrate_transcript: bool = False
|
|
persist_transcript: bool = False
|
|
|
|
|
|
class WebUITemporaryChats:
|
|
"""Own Temporary Chat creation, policy, attachments, and disposal."""
|
|
|
|
def __init__(
|
|
self,
|
|
*,
|
|
bus: MessageBus,
|
|
session_manager: SessionManager | None,
|
|
workspaces: WebUIWorkspaceController,
|
|
logger: Any,
|
|
channel_name: str = "websocket",
|
|
) -> None:
|
|
self._bus = bus
|
|
self._sessions = session_manager
|
|
self._workspaces = workspaces
|
|
self._logger = logger
|
|
self._channel_name = channel_name
|
|
self._commands = CommandRouter()
|
|
register_builtin_commands(self._commands)
|
|
self._owners: dict[str, object] = {}
|
|
self._owner_chat_ids: dict[object, set[str]] = {}
|
|
# Retain policy-derived tombstones until shutdown so late outbound
|
|
# events cannot create a durable transcript after a chat is discarded.
|
|
self._known_transient_chat_ids: set[str] = set()
|
|
self._media_paths: dict[str, set[str]] = {}
|
|
|
|
def _session_key(self, chat_id: str) -> str:
|
|
return f"{self._channel_name}:{chat_id}"
|
|
|
|
def _cached_session_is_transient(self, chat_id: str) -> bool:
|
|
if self._sessions is None:
|
|
return False
|
|
identity = self._sessions.state.peek_identity(self._session_key(chat_id))
|
|
return identity is not None and not identity.policy.persist
|
|
|
|
async def create(self, owner: object, *, trusted_webui: bool) -> str:
|
|
"""Create a server-identified chat owned by one authenticated WebUI connection."""
|
|
if not trusted_webui:
|
|
raise TemporaryChatError("access_denied")
|
|
if self._sessions is None:
|
|
raise TemporaryChatError("temporary_chat_unavailable")
|
|
|
|
chat_id = str(uuid.uuid4())
|
|
session = await self._sessions.state.register_transient(
|
|
self._session_key(chat_id),
|
|
disabled_tools=_TEMPORARY_CHAT_DISABLED_TOOLS,
|
|
)
|
|
if session.policy.persist:
|
|
raise RuntimeError("Temporary Chat must use a non-persistent session policy")
|
|
self._owners[chat_id] = owner
|
|
self._owner_chat_ids.setdefault(owner, set()).add(chat_id)
|
|
self._known_transient_chat_ids.add(chat_id)
|
|
return chat_id
|
|
|
|
def message_policy(
|
|
self,
|
|
owner: object,
|
|
chat_id: str,
|
|
content: str,
|
|
) -> TemporaryChatMessagePolicy | None:
|
|
"""Return Temporary Chat rules, or ``None`` for an ordinary chat."""
|
|
if not self._cached_session_is_transient(chat_id):
|
|
if chat_id in self._known_transient_chat_ids:
|
|
raise TemporaryChatError("temporary_chat_unavailable")
|
|
return None
|
|
if self._owners.get(chat_id) is not owner or self._sessions is None:
|
|
raise TemporaryChatError("temporary_chat_unavailable")
|
|
|
|
identity = self._sessions.state.peek_identity(self._session_key(chat_id))
|
|
if identity is None:
|
|
raise TemporaryChatError("temporary_chat_unavailable")
|
|
|
|
command = self._commands.command_name(content)
|
|
if command is not None and command not in _TEMPORARY_CHAT_COMMANDS:
|
|
raise TemporaryChatError("temporary_chat_command_rejected")
|
|
|
|
return TemporaryChatMessagePolicy(
|
|
session_key=self._session_key(chat_id),
|
|
session_generation=identity.generation,
|
|
workspace_scope=self._workspaces.restricted_default_scope(),
|
|
)
|
|
|
|
def validate_attach(self, chat_id: str) -> None:
|
|
"""Reject attempts to recover a non-persistent session."""
|
|
if not self._cached_session_is_transient(chat_id):
|
|
if chat_id in self._known_transient_chat_ids:
|
|
raise TemporaryChatError("temporary_chat_unavailable")
|
|
return
|
|
raise TemporaryChatError("temporary_chat_unavailable")
|
|
|
|
def validate_workspace_update(self, chat_id: str) -> None:
|
|
"""Prevent non-persistent sessions from acquiring durable workspace state."""
|
|
if self._cached_session_is_transient(chat_id):
|
|
raise TemporaryChatError("temporary_chat_workspace_rejected")
|
|
if chat_id in self._known_transient_chat_ids:
|
|
raise TemporaryChatError("temporary_chat_unavailable")
|
|
|
|
def register_media(self, owner: object, chat_id: str, paths: list[str]) -> None:
|
|
if not paths:
|
|
return
|
|
if self._owners.get(chat_id) is not owner:
|
|
raise TemporaryChatError("temporary_chat_unavailable")
|
|
self._media_paths.setdefault(chat_id, set()).update(paths)
|
|
|
|
def chat_ids_for_owner(self, owner: object) -> tuple[str, ...]:
|
|
return tuple(self._owner_chat_ids.get(owner, ()))
|
|
|
|
def owns(self, owner: object, chat_id: str) -> bool:
|
|
return self._owners.get(chat_id) is owner
|
|
|
|
def should_persist_transcript(self, chat_id: str) -> bool:
|
|
"""Apply the session policy and retain it for late events after disposal."""
|
|
return (
|
|
not self._cached_session_is_transient(chat_id)
|
|
and chat_id not in self._known_transient_chat_ids
|
|
)
|
|
|
|
def _discard_media(self, chat_id: str) -> None:
|
|
for raw_path in self._media_paths.pop(chat_id, set()):
|
|
try:
|
|
Path(raw_path).unlink(missing_ok=True)
|
|
except OSError:
|
|
self._logger.warning("failed to remove a temporary WebUI attachment")
|
|
|
|
def _forget_owner(self, owner: object, chat_id: str) -> None:
|
|
self._owners.pop(chat_id, None)
|
|
chat_ids = self._owner_chat_ids.get(owner)
|
|
if chat_ids is None:
|
|
return
|
|
chat_ids.discard(chat_id)
|
|
if not chat_ids:
|
|
self._owner_chat_ids.pop(owner, None)
|
|
|
|
async def discard(self, owner: object, chat_id: str) -> None:
|
|
"""Forget one owned chat and cancel any active work through the message bus."""
|
|
if (
|
|
not self._cached_session_is_transient(chat_id)
|
|
or self._owners.get(chat_id) is not owner
|
|
):
|
|
raise TemporaryChatError("temporary_chat_unavailable")
|
|
|
|
session_key = self._session_key(chat_id)
|
|
self._forget_owner(owner, chat_id)
|
|
self._discard_media(chat_id)
|
|
if self._sessions is not None:
|
|
await self._sessions.state.discard(session_key)
|
|
await self._bus.publish_inbound(
|
|
InboundMessage(
|
|
channel=self._channel_name,
|
|
sender_id="webui",
|
|
chat_id=chat_id,
|
|
content="",
|
|
metadata={
|
|
INBOUND_META_RUNTIME_CONTROL: RUNTIME_CONTROL_SESSION_DISCARD,
|
|
},
|
|
session_key_override=session_key,
|
|
)
|
|
)
|
|
|
|
def close(self) -> None:
|
|
"""Release process-local resources during gateway shutdown."""
|
|
for chat_id in tuple(self._owners):
|
|
self._discard_media(chat_id)
|
|
if self._sessions is not None:
|
|
self._sessions.state.forget_transient(self._session_key(chat_id))
|
|
self._owners.clear()
|
|
self._owner_chat_ids.clear()
|
|
self._known_transient_chat_ids.clear()
|