refactor(session): centralize state ownership in SQLite (#5943)

* 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
This commit is contained in:
chengyongru authored and GitHub committed 2026-10-16 17:28:47 +08:00
1 parent 33ff520d12
commit 8f6a5594fb
144 files changed
+8293 -4912

No files matched your search

+2
View File
@@ -459,6 +459,7 @@ class WebSocketChannel(BaseChannel):
is_dm: bool,
session_key: str | None,
require_existing_session: bool,
session_generation: str | None,
) -> None:
await self._handle_message(
sender_id=sender_id,
@@ -469,6 +470,7 @@ class WebSocketChannel(BaseChannel):
is_dm=is_dm,
session_key=session_key,
require_existing_session=require_existing_session,
session_generation=session_generation,
)
def _attach(self, connection: ServerConnection, chat_id: str) -> None:
@@ -2,6 +2,7 @@
import asyncio
import json
import threading
import time
import uuid
from pathlib import Path
@@ -52,7 +53,7 @@ from nanobot.providers.base import LLMUsage
from nanobot.runtime_context import RUNTIME_CONTEXT_INPUT_META, WEBUI_QUOTE_SOURCE
from nanobot.security.workspace_access import WORKSPACE_SCOPE_METADATA_KEY
from nanobot.session import webui_turns as wth
from nanobot.session.manager import SessionManager
from nanobot.session.manager import Session, SessionManager
from nanobot.session.model_selection import SESSION_MODEL_PRESET_METADATA_KEY
from nanobot.session.session_handles import session_handle_for_name
from nanobot.webui.gateway_services import GatewayServices, build_gateway_services
@@ -2034,7 +2035,7 @@ async def test_webui_set_workspace_scope_rejects_running_chat(bus: MagicMock, tm
},
},
)
channel.gateway.workspaces.persist_scope(
await channel.gateway.workspaces.persist_scope(
"chat-running",
channel.gateway.workspaces.scope_for_session_key("websocket:chat-running"),
)
@@ -2974,6 +2975,56 @@ async def test_stream_transcript_persists_without_subscribers() -> None:
assert _thread_conversation_events(body)[-1]["latencyMs"] == 42
@pytest.mark.asyncio
@pytest.mark.parametrize("temporary", [False, True])
async def test_stream_policy_does_not_copy_history_on_runtime_loop(
bus, tmp_path, monkeypatch, temporary,
) -> None:
import nanobot.session.state as session_state
sessions = SessionManager(tmp_path)
channel = WebSocketChannel(
{"enabled": True, "allowFrom": ["*"]}, bus,
gateway=_basic_handler(bus, session_manager=sessions, workspace_path=tmp_path),
)
owner = object()
chat_id = (
await channel.gateway.temporary_chats.create(owner, trusted_webui=True)
if temporary else "history-copy"
)
history = [
{"role": "user", "content": f"history {i}"} for i in range(1000)
]
draft = await sessions.state.import_messages(f"websocket:{chat_id}", history)
await sessions.state.checkpoint_view(draft, {"messages": history})
runtime_thread = threading.get_ident()
original_copy = session_state.deepcopy
def copy_off_loop(value, *args, **kwargs):
if (
isinstance(value, Session) and value.messages
or isinstance(value, dict) and "runtime_checkpoint" in value
):
assert threading.get_ident() != runtime_thread, "history copied on runtime loop"
return original_copy(value, *args, **kwargs)
monkeypatch.setattr(session_state, "deepcopy", copy_off_loop)
append = MagicMock()
monkeypatch.setattr("nanobot.webui.transcript.append_transcript_object", append)
try:
policy = channel.gateway.temporary_chats.message_policy(owner, chat_id, "hello")
assert (policy is not None) is temporary
await channel.send_delta(chat_id, "one", stream_id="s1")
await channel.send_delta(chat_id, " two", stream_id="s1")
await channel.send_delta(chat_id, "", stream_id="s1", stream_end=True)
await channel.send_reasoning_delta(chat_id, "plan", stream_id="r1")
await channel.send_reasoning_end(chat_id, stream_id="r1")
assert append.call_count == (0 if temporary else 2)
finally:
channel.gateway.temporary_chats.close()
await sessions.state.aclose()
@pytest.mark.asyncio
async def test_stream_transcript_writes_once_per_completed_segment(monkeypatch) -> None:
bus = MagicMock()
@@ -3913,7 +3964,8 @@ async def test_hydrate_noop_without_session_manager() -> None:
async def test_hydrate_skips_when_no_goal_on_disk() -> None:
bus = MagicMock()
sm = MagicMock()
sm.read_session_metadata.return_value = None
sm.state.read_metadata = AsyncMock()
sm.state.read_metadata.return_value = None
channel = WebSocketChannel(
{"enabled": True, "allowFrom": ["*"]},
bus,
@@ -3929,7 +3981,8 @@ async def test_hydrate_skips_when_no_goal_on_disk() -> None:
async def test_hydrate_notifies_when_goal_active_on_disk() -> None:
bus = MagicMock()
sm = MagicMock()
sm.read_session_metadata.return_value = {
sm.state.read_metadata = AsyncMock()
sm.state.read_metadata.return_value = {
"metadata": {
"goal_state": {
"status": "active",
@@ -3960,7 +4013,8 @@ async def test_hydrate_notifies_when_goal_active_on_disk() -> None:
async def test_hydrate_restores_blocked_attention_on_disk() -> None:
bus = MagicMock()
sm = MagicMock()
sm.read_session_metadata.return_value = {
sm.state.read_metadata = AsyncMock()
sm.state.read_metadata.return_value = {
"metadata": {
"goal_state": {
"status": "blocked",
@@ -5692,13 +5746,17 @@ def test_sessions_list_includes_active_run_started_at(monkeypatch) -> None:
"updated_at": "2026-05-19T10:01:00Z",
},
]
monkeypatch.setattr(ws_http_module, "list_webui_sessions", lambda _session_manager: sessions)
session_manager.state.query_metadata = AsyncMock(side_effect=lambda project: project([]))
monkeypatch.setattr(ws_http_module, "list_webui_sessions", lambda _session_manager, _stored: sessions)
handle = session_handle_for_name("websocket:chat-1", "luma")
monkeypatch.setattr(
ws_http_module,
"SessionHandleResolver",
lambda _session_manager: SimpleNamespace(
list_all_by_key=lambda: {handle.session_key: handle}
handles_from_metadata=MagicMock(return_value={handle.session_key: handle}),
alist_all_by_key=AsyncMock(
return_value={handle.session_key: handle}
)
),
)
channel = WebSocketChannel(
@@ -6673,3 +6731,48 @@ async def test_webui_access_mode_can_toggle_back_to_full(bus, tmp_path, headers)
assert channel.gateway.workspaces.scope_for_session_key(
"websocket:handshake-scope"
).access_mode == mode
@pytest.mark.parametrize("command_type", ["new_chat", "attach", "set_workspace_scope", "message"])
async def test_webui_commands_keep_session_io_off_event_loop(
bus: MagicMock, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, command_type: str,
) -> None:
import threading
sessions = SessionManager(tmp_path / "sessions")
sessions.save(sessions.get_or_create("websocket:io-chat"))
channel = WebSocketChannel(
{"enabled": True, "allowFrom": ["*"], "host": "127.0.0.1"},
bus,
gateway=_basic_handler(bus, session_manager=sessions, workspace_path=tmp_path),
)
conn = AsyncMock()
conn.remote_address = ("127.0.0.1", 50123)
loop_thread = threading.get_ident()
calls: list[str] = []
def require_worker(name):
operation = getattr(sessions._store, name)
def checked(*args, **kwargs):
assert threading.get_ident() != loop_thread, name
calls.append(name)
return operation(*args, **kwargs)
return checked
for name in ("read_metadata", "load", "save", "replace_metadata"):
monkeypatch.setattr(sessions._store, name, require_worker(name))
await channel._dispatch_envelope(
conn,
"webui-client",
{"type": command_type, "chat_id": "io-chat", "content": "/help", "webui": True},
)
assert "read_metadata" in calls
if command_type in {"set_workspace_scope", "message"}:
assert "load" in calls
assert "save" in calls or "replace_metadata" in calls
assert all(json.loads(call.args[0])["event"] != "error" for call in conn.send.await_args_list)
await channel._cleanup_connection(conn)
@@ -194,7 +194,7 @@ async def test_webui_message_forwards_verified_session_mentions(tmp_path) -> Non
channel._handle_message.assert_awaited_once()
metadata = channel._handle_message.call_args.kwargs["metadata"]
handle = SessionHandleResolver(manager).handle_for_session("websocket:pricing")
handle = await SessionHandleResolver(manager).ahandle_for_session("websocket:pricing")
assert handle is not None
assert metadata["session_mentions"] == [{
**handle.public_payload(),
@@ -313,7 +313,7 @@ async def test_sessions_list_and_thread_restore_transcript_without_canonical_fil
key,
{"event": "message", "chat_id": "restored-history", "text": "original answer"},
)
assert not sm._get_session_path(key).exists()
assert sm.read_session_snapshot(key) is None
port = _free_port()
channel = _ch(bus, session_manager=sm, port=port)
@@ -344,7 +344,7 @@ async def test_sessions_list_and_thread_restore_transcript_without_canonical_fil
"original question",
"original answer",
]
assert not sm._get_session_path(key).exists()
assert sm.read_session_snapshot(key) is None
finally:
await channel.stop()
await server_task
@@ -2306,7 +2306,7 @@ async def test_sessions_list_only_returns_websocket_sessions_by_default(
rows = {row["key"]: row for row in sessions}
handles = {
handle.session_key: handle
for handle in SessionHandleResolver(sm).list_all()
for handle in await SessionHandleResolver(sm).alist_all()
}
assert rows["websocket:alpha"]["handle"] == handles[
"websocket:alpha"
@@ -2385,8 +2385,8 @@ async def test_session_delete_removes_file(
channel = _ch(bus, session_manager=sm, port=29903)
server_task = asyncio.create_task(channel.start())
try:
path = sm._get_session_path("websocket:doomed")
assert path.exists()
session_key = "websocket:doomed"
assert sm.read_session_snapshot(session_key) is not None
webui_path = tmp_path / "webui" / f"{SessionManager.safe_key('websocket:doomed')}.jsonl"
assert webui_path.is_file()
resp = await _webui_mutate(
@@ -2396,7 +2396,7 @@ async def test_session_delete_removes_file(
)
assert resp.status_code == 200
assert resp.json()["deleted"] is True
assert not path.exists()
assert sm.read_session_snapshot(session_key) is None
assert not webui_path.exists()
finally:
await channel.stop()
@@ -2416,7 +2416,7 @@ async def test_session_delete_removes_transcript_without_canonical_file(
key,
{"event": "user", "chat_id": "transcript-only", "text": "recover me"},
)
assert not sm._get_session_path(key).exists()
assert sm.read_session_snapshot(key) is None
webui_path = tmp_path / "webui" / f"{SessionManager.safe_key(key)}.jsonl"
assert webui_path.is_file()
@@ -2998,7 +2998,7 @@ async def test_session_delete_blocks_when_bound_automation_exists(
channel = _ch(bus, session_manager=sm, cron_service=cron, port=29915)
server_task = asyncio.create_task(channel.start())
try:
path = sm._get_session_path("websocket:doomed")
session_key = "websocket:doomed"
resp = await _webui_mutate(
channel,
"session.delete",
@@ -3010,7 +3010,7 @@ async def test_session_delete_blocks_when_bound_automation_exists(
assert body["deleted"] is False
assert body["blocked_by_automations"] is True
assert [job["name"] for job in body["automations"]] == ["Daily check"]
assert path.exists()
assert sm.read_session_snapshot(session_key) is not None
assert cron.list_bound_cron_jobs_for_session("websocket:doomed")
finally:
await channel.stop()
@@ -3086,7 +3086,7 @@ async def test_session_delete_can_cascade_bound_automations(
channel = _ch(bus, session_manager=sm, cron_service=cron, port=29916)
server_task = asyncio.create_task(channel.start())
try:
path = sm._get_session_path("websocket:doomed")
session_key = "websocket:doomed"
resp = await _webui_mutate(
channel,
"session.delete",
@@ -3095,7 +3095,7 @@ async def test_session_delete_can_cascade_bound_automations(
assert resp.status_code == 200
assert resp.json()["deleted"] is True
assert not path.exists()
assert sm.read_session_snapshot(session_key) is None
assert cron.list_bound_cron_jobs_for_session("websocket:doomed") == []
assert cron.list_jobs(include_disabled=True) == []
finally:
@@ -3126,7 +3126,7 @@ async def test_session_delete_blocks_origin_automation_when_unified_enabled(
)
server_task = asyncio.create_task(channel.start())
try:
path = sm._get_session_path("websocket:doomed")
session_key = "websocket:doomed"
resp = await _webui_mutate(
channel,
"session.delete",
@@ -3138,7 +3138,7 @@ async def test_session_delete_blocks_origin_automation_when_unified_enabled(
assert body["deleted"] is False
assert body["blocked_by_automations"] is True
assert [job["name"] for job in body["automations"]] == ["Chat daily check"]
assert path.exists()
assert sm.read_session_snapshot(session_key) is not None
assert [job.name for job in cron.list_bound_cron_jobs_for_session("websocket:doomed")] == [
"Chat daily check"
]
@@ -3155,8 +3155,8 @@ async def test_session_delete_action_accepts_websocket_keys(
channel = _ch(bus, session_manager=sm, port=29910)
server_task = asyncio.create_task(channel.start())
try:
path = sm._get_session_path("websocket:encoded-key")
assert path.exists()
session_key = "websocket:encoded-key"
assert sm.read_session_snapshot(session_key) is not None
deleted = await _webui_mutate(
channel,
"session.delete",
@@ -3164,7 +3164,7 @@ async def test_session_delete_action_accepts_websocket_keys(
)
assert deleted.status_code == 200
assert deleted.json()["deleted"] is True
assert not path.exists()
assert sm.read_session_snapshot(session_key) is None
finally:
await channel.stop()
await server_task
@@ -3511,8 +3511,8 @@ async def test_session_delete_rejects_non_websocket_keys(
token = channel.gateway.tokens.issue_api_token(300)
auth = {"Authorization": f"Bearer {token}"}
doomed = sm._get_session_path("slack:C123")
assert doomed.exists()
session_key = "slack:C123"
assert sm.read_session_snapshot(session_key) is not None
get_delete = await _http_get(
"http://127.0.0.1:29909/api/sessions/slack:C123/delete",
headers=auth,
@@ -3525,7 +3525,7 @@ async def test_session_delete_rejects_non_websocket_keys(
{"key": "slack:C123"},
)
assert deny_delete.status_code == 404
assert doomed.exists()
assert sm.read_session_snapshot(session_key) is not None
finally:
await channel.stop()
await server_task
@@ -4254,3 +4254,42 @@ async def test_project_favorites_mutation_persists_without_selecting_project(
response = await _webui_mutate(channel, "workspace.favorite", {"path": str(project), "pinned": False}, connection=connection)
assert response.status_code == 200
assert response.json() == {"favorite_projects": []}
@pytest.mark.asyncio
async def test_session_delete_waiting_on_sqlite_does_not_block_event_loop(
bus: MagicMock,
tmp_path: Path,
) -> None:
import sqlite3
sm = _seed_session(tmp_path, key="websocket:locked-delete")
channel = _ch(bus, session_manager=sm, port=_free_port())
blocker = sqlite3.connect(sm._store.path, isolation_level=None)
blocker.execute("BEGIN IMMEDIATE")
try:
deletion = asyncio.create_task(
_webui_mutate(
channel,
"session.delete",
{"key": "websocket:locked-delete"},
)
)
ticked = False
async def tick() -> None:
nonlocal ticked
await asyncio.sleep(0.05)
ticked = True
await asyncio.wait_for(tick(), timeout=0.25)
assert ticked
assert not deletion.done()
blocker.rollback()
response = await asyncio.wait_for(deletion, timeout=2)
assert response.status_code == 200
assert sm.read_session_snapshot("websocket:locked-delete") is None
finally:
if blocker.in_transaction:
blocker.rollback()
blocker.close()
@@ -1,6 +1,6 @@
"""Test websocket subscribe hydration only replays known active turns."""
from unittest.mock import MagicMock, patch
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
@@ -15,7 +15,7 @@ async def test_hydrate_after_subscribe_is_quiet_when_no_turn_active():
channel = WebSocketChannel.__new__(WebSocketChannel)
channel.gateway = MagicMock()
channel.gateway.session_manager = MagicMock()
channel.gateway.session_manager.read_session_metadata = MagicMock(return_value={})
channel.gateway.session_manager.state.read_metadata = AsyncMock(return_value={})
channel._session_projection = WebUISessionProjection(channel.gateway.session_manager)
channel._outbound = WebUIOutboundProjector(channel, channel._session_projection)
channel._turn_models = {}
@@ -43,7 +43,7 @@ async def test_hydrate_after_subscribe_pushes_running_when_turn_active():
channel = WebSocketChannel.__new__(WebSocketChannel)
channel.gateway = MagicMock()
channel.gateway.session_manager = MagicMock()
channel.gateway.session_manager.read_session_metadata = MagicMock(return_value={})
channel.gateway.session_manager.state.read_metadata = AsyncMock(return_value={})
channel._session_projection = WebUISessionProjection(channel.gateway.session_manager)
channel._outbound = WebUIOutboundProjector(channel, channel._session_projection)
channel._turn_models = {}
@@ -0,0 +1,177 @@
"""WebUI admission binds the generation of the session that executes the turn."""
from __future__ import annotations
import asyncio
import json
from collections.abc import AsyncIterator
from dataclasses import dataclass
from pathlib import Path
from typing import Any
import pytest
from nanobot.agent.loop import AgentLoop
from nanobot.bus.events import InboundMessage
from nanobot.bus.queue import MessageBus
from nanobot.channels.manager import ChannelManager
from nanobot.channels.websocket.runtime import WebSocketChannel
from nanobot.config.schema import Config
from nanobot.providers.base import LLMProvider, LLMResponse
from nanobot.runtime_context import public_history_message
from nanobot.session.keys import UNIFIED_SESSION_KEY, session_key_for_channel
from nanobot.session.manager import SessionManager
from nanobot.session.webui_turns import clear_websocket_turns
from nanobot.webui.transcript import read_transcript_lines
class _Provider(LLMProvider):
def __init__(self) -> None:
super().__init__(provider_name="test")
self.calls = 0
def get_default_model(self) -> str:
return "test-model"
async def chat(self, messages: list[dict[str, Any]], **kwargs: Any) -> LLMResponse:
self.calls += 1
return LLMResponse(content="hello back", finish_reason="stop")
class _Connection:
remote_address = None
def __init__(self) -> None:
self.sent: list[dict[str, Any]] = []
async def send(self, raw: str) -> None:
self.sent.append(json.loads(raw))
@dataclass
class _Runtime:
bus: MessageBus
sessions: SessionManager
loop: AgentLoop
channel: WebSocketChannel
connection: _Connection
provider: _Provider
async def message(self, chat_id: str, text: str = "hello") -> InboundMessage:
await self.channel._dispatch_envelope(
self.connection,
"webui-client",
{"type": "message", "chat_id": chat_id, "content": text, "webui": True},
)
return await self.bus.consume_inbound()
async def execute(self, message: InboundMessage) -> None:
await self.loop._enqueue_session_message(message)
tasks = self.loop._active_tasks[self.loop._effective_session_key(message)]
await asyncio.gather(*tuple(tasks))
@pytest.fixture(params=[False, True], ids=["separate", "shared"])
async def runtime(request: pytest.FixtureRequest, tmp_path: Path) -> AsyncIterator[_Runtime]:
unified = request.param
workspace = tmp_path / "workspace"
workspace.mkdir()
config = Config.model_validate({"agents": {"defaults": {
"workspace": str(workspace), "unifiedSession": unified,
}}})
bus = MessageBus()
sessions = SessionManager(workspace)
provider = _Provider()
loop = AgentLoop(
bus=bus, provider=provider, workspace=workspace,
session_manager=sessions, unified_session=unified,
)
manager = ChannelManager(
config, bus, session_manager=sessions, webui_static_dist=False,
config_path=tmp_path / "config.json",
)
channel = manager.channels["websocket"]
assert isinstance(channel, WebSocketChannel)
connection = _Connection()
channel._webui_connections.add(connection)
try:
yield _Runtime(bus, sessions, loop, channel, connection, provider)
finally:
chat_ids = tuple(channel._subs)
await channel._cleanup_connection(connection)
channel.gateway.temporary_chats.close()
for chat_id in chat_ids:
clear_websocket_turns(chat_id)
await loop.aclose()
async def test_webui_admission_executes_with_the_routed_session(runtime: _Runtime) -> None:
for chat_id in ("chat-a", "chat-b"):
message = await runtime.message(chat_id)
await runtime.execute(message)
key = session_key_for_channel(
"websocket", chat_id, unified_session=runtime.channel.gateway.unified_session,
)
session = await runtime.sessions.state.read(key)
assert session is not None
assert [public_history_message(record)["content"] for record in session.messages
if record["role"] == "user"] == (
["hello", "hello"] if key == UNIFIED_SESSION_KEY and chat_id == "chat-b"
else ["hello"]
)
display = await runtime.sessions.state.read_metadata(f"websocket:{chat_id}")
assert display is not None and display["metadata"]["webui"] is True
assert runtime.provider.calls == 2
@pytest.mark.parametrize("operation", ["reset", "delete"])
async def test_replaced_execution_session_rejects_accepted_input(
runtime: _Runtime, operation: str,
) -> None:
message = await runtime.message("chat-stale")
key = runtime.loop._effective_session_key(message)
if operation == "reset":
await runtime.sessions.state.reset(key)
else:
await runtime.sessions.state.delete(key)
await runtime.execute(message)
assert runtime.provider.calls == 0
remaining = await runtime.sessions.state.read(key)
assert remaining is None or remaining.messages == []
async def test_failed_transport_admission_removes_new_sessions(
runtime: _Runtime, monkeypatch: pytest.MonkeyPatch,
) -> None:
async def reject(message: InboundMessage) -> None:
raise RuntimeError("queue unavailable")
monkeypatch.setattr(runtime.bus, "publish_inbound", reject)
with pytest.raises(RuntimeError, match="queue unavailable"):
await runtime.message("chat-rejected")
assert await runtime.sessions.state.list_sessions() == []
async def test_temporary_chat_retains_its_own_generation(runtime: _Runtime) -> None:
await runtime.channel._dispatch_envelope(
runtime.connection, "webui-client", {"type": "new_temporary_chat"},
)
chat_id = next(event["chat_id"] for event in runtime.connection.sent
if event["event"] == "attached")
first = await runtime.message(chat_id)
await runtime.execute(first)
assert runtime.provider.calls == 1
assert runtime.loop._effective_session_key(first) == f"websocket:{chat_id}"
assert await runtime.sessions.state.list_sessions() == []
assert read_transcript_lines(f"websocket:{chat_id}") == []
queued = await runtime.message(chat_id, "discarded input")
await runtime.channel.gateway.temporary_chats.discard(runtime.connection, chat_id)
await runtime.execute(queued)
assert runtime.provider.calls == 1
assert await runtime.sessions.state.read(first.session_key) is None
assert await runtime.sessions.state.list_sessions() == []