* 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
128 lines
4.0 KiB
Python
128 lines
4.0 KiB
Python
"""WebUI chat fork orchestration."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import uuid
|
|
from collections.abc import Mapping
|
|
from typing import TYPE_CHECKING, Any, Protocol
|
|
|
|
from loguru import logger
|
|
|
|
from nanobot.session.manager import SessionManager
|
|
from nanobot.session.webui_turns import clean_generated_title
|
|
from nanobot.webui.session_identity import is_valid_webui_chat_id, webui_session_key
|
|
from nanobot.webui.transcript import (
|
|
append_fork_marker,
|
|
delete_webui_transcript,
|
|
fork_transcript_before_user_index,
|
|
write_session_messages_as_transcript,
|
|
)
|
|
|
|
if TYPE_CHECKING:
|
|
from websockets.asyncio.server import ServerConnection
|
|
|
|
from nanobot.webui.gateway_services import GatewayServices
|
|
|
|
|
|
class WebUIForkHost(Protocol):
|
|
gateway: GatewayServices
|
|
|
|
async def send_webui_protocol_error(
|
|
self,
|
|
connection: ServerConnection,
|
|
detail: str,
|
|
) -> None: ...
|
|
|
|
async def attach_webui_fork(
|
|
self,
|
|
connection: ServerConnection,
|
|
*,
|
|
fork_id: str,
|
|
fork_key: str,
|
|
) -> None: ...
|
|
|
|
|
|
async def create_webui_chat_fork(
|
|
session_manager: SessionManager,
|
|
*,
|
|
source_chat_id: str,
|
|
before_user_index: int,
|
|
title: str | None = None,
|
|
) -> tuple[str, str] | None:
|
|
"""Return ``(chat_id, session_key)`` for a new fork, or ``None`` for bad input."""
|
|
new_id = str(uuid.uuid4())
|
|
source_key = webui_session_key(source_chat_id)
|
|
target_key = webui_session_key(new_id)
|
|
try:
|
|
forked = await session_manager.state.fork(
|
|
source_key,
|
|
target_key,
|
|
before_user_index,
|
|
title=clean_generated_title(title),
|
|
)
|
|
if forked is None:
|
|
return None
|
|
|
|
def write_transcript() -> None:
|
|
transcript_ok = fork_transcript_before_user_index(
|
|
source_key, target_key, before_user_index,
|
|
)
|
|
if not transcript_ok:
|
|
write_session_messages_as_transcript(target_key, forked.messages)
|
|
append_fork_marker(target_key)
|
|
await asyncio.to_thread(write_transcript)
|
|
except Exception:
|
|
await asyncio.to_thread(delete_webui_transcript, target_key)
|
|
await session_manager.state.delete(target_key)
|
|
raise
|
|
return new_id, target_key
|
|
|
|
|
|
async def handle_webui_fork_chat(
|
|
channel: WebUIForkHost,
|
|
connection: ServerConnection,
|
|
envelope: Mapping[str, Any],
|
|
) -> None:
|
|
"""Handle the WebUI ``fork_chat`` websocket command.
|
|
|
|
``websocket.py`` owns the transport. This module owns WebUI fork semantics:
|
|
validate the request, clone session/transcript state, attach the new chat,
|
|
and hydrate the client.
|
|
"""
|
|
source_chat_id = envelope.get("source_chat_id")
|
|
raw_index = envelope.get("before_user_index")
|
|
if not is_valid_webui_chat_id(source_chat_id):
|
|
await channel.send_webui_protocol_error(connection, "invalid source_chat_id")
|
|
return
|
|
if isinstance(raw_index, bool) or not isinstance(raw_index, int) or raw_index < 0:
|
|
await channel.send_webui_protocol_error(connection, "invalid before_user_index")
|
|
return
|
|
|
|
session_manager = channel.gateway.session_manager
|
|
if session_manager is None:
|
|
await channel.send_webui_protocol_error(connection, "session_manager_unavailable")
|
|
return
|
|
|
|
try:
|
|
forked = await create_webui_chat_fork(
|
|
session_manager,
|
|
source_chat_id=source_chat_id,
|
|
before_user_index=raw_index,
|
|
title=envelope.get("title") if isinstance(envelope.get("title"), str) else None,
|
|
)
|
|
if forked is None:
|
|
await channel.send_webui_protocol_error(connection, "invalid fork source or index")
|
|
return
|
|
fork_id, fork_key = forked
|
|
except Exception as exc:
|
|
logger.warning("fork_chat failed: {}", exc)
|
|
await channel.send_webui_protocol_error(connection, "fork_chat_failed")
|
|
return
|
|
|
|
await channel.attach_webui_fork(
|
|
connection,
|
|
fork_id=fork_id,
|
|
fork_key=fork_key,
|
|
)
|