fix(sessions): preserve cross-session input ownership and history (#6613)

* fix(webui): reconcile cross-session history by message ID

* fix(sessions): preserve target authority and input ownership

Resolve cross-session follow-ups through the target route, carry stable input IDs through admission and recovery, and associate live and replayed answers with the inputs actually consumed.

Keep ordinary input scope isolation and omit historical anomaly repair. Resolves NAN-430.

* fix(sessions): complete input identity integration across boundaries

Carry input identity explicitly in projected input events, keep runner annotations out of public history, and reuse the canonical WebUI session parser during recovery.

Type validated recovery metadata and align existing channel and subagent regressions with explicit response ownership. All nine failed compatibility cases and adjacent recovery coverage pass in a focused 58-test run.

* fix(sessions): unify input recording and block remote commands

* fix(webui): keep input ownership checks page-bounded

Look up referenced inputs through the existing identity index before invoking transcript backfill. Complete pages no longer scan the full prompt history, including answers whose inputs live on earlier pages.

Cover cold-cache pagination and cross-turn ownership in existing regressions. Focused pagination, replay and follow-up recovery checks: 88 passed.

* fix(webui): preserve response ownership during history replay

* fix: resolve strict typing in response replay

* fix: preserve continuation ownership during recovery

* test: diagnose stuck gateway asyncio shutdown

* test: retain gateway thread stack diagnostics

* test(webui): stabilize native autoscroll browser setup
This commit is contained in:
chengyongru authored and GitHub committed 2026-11-11 10:46:44 +08:00
1 parent 0ce335bf12
commit 394a78e82d
51 files changed
+1412 -334

No files matched your search

+19 -3
View File
@@ -18,6 +18,7 @@ from nanobot.session.recovery import (
pending_followups,
restore_runtime_checkpoint,
)
from nanobot.session.session_messages import SESSION_MESSAGE_METADATA_KEY
from nanobot.webui.recovery import RecoveryCoordinator
@@ -148,7 +149,8 @@ async def test_recovered_input_keeps_admission_identity_and_timestamp(tmp_path):
@pytest.mark.parametrize("interrupt", [False, True], ids=["completed", "checkpoint-recovery"])
async def test_injected_inputs_keep_their_own_identity_through_runner_and_commit(tmp_path, monkeypatch, interrupt):
@pytest.mark.parametrize("cross_session", [False, True])
async def test_injected_inputs_keep_their_own_identity_through_runner_and_commit(tmp_path, monkeypatch, interrupt, cross_session):
import asyncio
provider = MagicMock(aclose=AsyncMock())
@@ -173,12 +175,19 @@ async def test_injected_inputs_keep_their_own_identity_through_runner_and_commit
draft = await loop.sessions.state.get("websocket:chat")
draft.add_message(
"user", "intentionally identical text", **{INBOUND_META_TURN_ID: "initial-input"},
timestamp="2026-10-18T19:00:00",
timestamp="2026-10-18T19:00:00", input_id="user:initial-input",
)
await loop.sessions.state.prepare_input(draft)
queue = asyncio.Queue()
for turn_id in ("first-input", "second-input"):
message = _input("intentionally identical text", turn_id)
if cross_session:
message.channel, message.input_role = "system", "user"
message.chat_id = message.session_key_override = draft.key
message.metadata = {SESSION_MESSAGE_METADATA_KEY: {
"message_id": turn_id, "created_at_ms": 1, "expect_reply": False,
"source_handle": "luma", "source_session_key": "websocket:source", "target_session_key": draft.key,
}}
identifier = await loop.sessions.state.queue_followup(draft.key, message)
message.metadata[PENDING_FOLLOWUP_ID_KEY] = identifier
queue.put_nowait(message)
@@ -218,7 +227,14 @@ async def test_injected_inputs_keep_their_own_identity_through_runner_and_commit
stored = await reopened.state.get(draft.key)
inputs = [row for row in stored.messages if row.get("role") == "user"]
assert [public_history_message(row)["content"] for row in inputs] == ["intentionally identical text"] * 3
assert [row[INBOUND_META_TURN_ID] for row in inputs] == ["initial-input", "first-input", "second-input"]
if cross_session:
assert [row["session_message"]["message_id"] for row in inputs[1:]] == ["first-input", "second-input"]
else:
assert [row[INBOUND_META_TURN_ID] for row in inputs] == ["initial-input", "first-input", "second-input"]
prefix = "session-message" if cross_session else "user"
input_ids = ["user:initial-input", f"{prefix}:first-input", f"{prefix}:second-input"]
assert [row["input_id"] for row in inputs] == input_ids
assert stored.messages[-1]["response_input_ids"] == input_ids
assert [row["timestamp"] for row in inputs] == ["2026-10-18T19:00:00"] * 3
assert pending_followups(stored) == []
assert bus.inbound.empty()
+20 -11
View File
@@ -20,6 +20,7 @@ from nanobot.session.recovery import (
pending_followups,
record_pending_followup,
)
from nanobot.session.session_messages import SESSION_MESSAGE_METADATA_KEY
from nanobot.webui import history as history_module
from nanobot.webui.recovery import RecoveryActionError, RecoveryCoordinator
@@ -204,20 +205,21 @@ async def test_scan_loads_only_sessions_that_need_webui_recovery(
@pytest.mark.asyncio
async def test_live_turn_followup_survives_restart_until_it_is_committed(tmp_path: Path) -> None:
@pytest.mark.parametrize("cross_session", [False, True])
async def test_live_turn_followup_survives_restart_until_it_is_committed(tmp_path: Path, cross_session: bool) -> None:
sessions = SessionManager(tmp_path)
session = sessions.get_or_create("websocket:chat")
_persist(sessions, session)
followup_id = record_pending_followup(
session,
InboundMessage(
channel="websocket",
sender_id="user",
chat_id="chat",
content="also check the logs",
metadata={"webui": True},
),
metadata = {SESSION_MESSAGE_METADATA_KEY: {
"message_id": "source-message", "created_at_ms": 1, "expect_reply": False,
"source_handle": "luma", "source_session_key": "websocket:source", "target_session_key": session.key,
}} if cross_session else {"webui": True}
message = InboundMessage(
channel="system" if cross_session else "websocket", sender_id="session" if cross_session else "user",
chat_id=session.key if cross_session else "chat", content="/stop" if cross_session else "also check the logs", metadata=metadata,
session_key_override=session.key, input_role="user" if cross_session else None,
)
followup_id = record_pending_followup(session, message)
assert followup_id is not None
sessions.save(session)
@@ -225,9 +227,16 @@ async def test_live_turn_followup_survives_restart_until_it_is_committed(tmp_pat
await coordinator.scan()
queued = bus.inbound.get_nowait()
assert queued.content == "also check the logs"
assert (queued.channel, queued.content, queued.input_role, queued.timestamp) == (
message.channel, message.content, message.input_role, message.timestamp,
)
assert queued.session_key == session.key
assert queued.require_existing_session
if cross_session:
assert queued.metadata[SESSION_MESSAGE_METADATA_KEY] == metadata[SESSION_MESSAGE_METADATA_KEY]
assert queued.metadata["_recovery_followup_id"] == followup_id
restored = restarted.get_or_create("websocket:chat")
assert record_pending_followup(restored, queued) == followup_id
assert len(pending_followups(restored)) == 1
acknowledge_pending_followups(restored, [followup_id])
@@ -0,0 +1,31 @@
import pytest
from nanobot.agent.tools.session_messages import SendSessionMessageTool, SessionMessageError
from nanobot.bus.queue import MessageBus
from nanobot.session.manager import SessionManager
from nanobot.session.session_handles import SessionHandleResolver
async def test_session_send_rejects_commands_and_delivers_normal_input(tmp_path):
manager = SessionManager(tmp_path)
bus = MessageBus()
tool = SendSessionMessageTool(sessions=manager, bus=bus)
try:
await manager.state.get("websocket:source")
await manager.state.get("websocket:target")
handles = SessionHandleResolver(manager)
target = await handles.ahandle_for_session("websocket:target")
assert target is not None
for content in ("/stop", " /stop", "\n\t/restart", "/restart"):
with pytest.raises(SessionMessageError, match="slash commands"):
await tool.enqueue(source_session_key="websocket:source", target_handle=target.name,
content=content, expect_reply=False)
assert bus.inbound_size == 0
await tool.enqueue(source_session_key="websocket:source", target_handle=target.name,
content="Please review /restart", expect_reply=False)
message = await bus.consume_inbound()
assert message.content == "Please review /restart"
assert message.session_key == "websocket:target"
assert bus.inbound_size == 0
finally:
await manager.state.aclose()
+1 -1
View File
@@ -251,7 +251,7 @@ def test_v4_archive_upgrade_removes_orphans_and_preserves_existing_membership(tm
db.execute("INSERT INTO storage_meta (key, value) VALUES ('session_archives_imported', '1')")
store.initialize(workspace)
store.initialize(workspace)
assert _database_snapshot(store.path)[0] == 4
assert _database_snapshot(store.path)[0] == len(sqlite_store._SCHEMA_MIGRATIONS)
assert store.archived_keys() == ["chat:empty-fork", "chat:extensions"]
assert store.archives_imported()
assert store.load("chat:extensions") == original