feat(webui): add lightweight session messaging via mentions

This commit is contained in:
chengyongru authored and chengyongru committed 2026-08-19 01:15:56 +08:00
1 parent 2bdb11eeba
commit 0e184965e8
76 files changed
+8297 -658

No files matched your search

+80 -2
View File
@@ -14,9 +14,17 @@ from nanobot.runtime_context import (
)
from nanobot.session.history_visibility import is_hidden_history_message
from nanobot.session.manager import SessionManager
from nanobot.webui.session_list_index import list_webui_sessions
from nanobot.session.session_handles import (
SessionHandle,
SessionHandleDirectory,
)
from nanobot.session.session_messages import is_persisted_webui_session
from nanobot.webui.session_list_index import (
list_webui_sessions,
)
from nanobot.webui.transcript import (
build_webui_thread_response,
normalize_session_handles_metadata,
normalize_session_mentions_metadata,
)
@@ -29,6 +37,13 @@ class SessionMention(TypedDict):
title: str
class SessionHandleMention(TypedDict):
id: str
name: str
session_key: str
color_slot: int
class SessionMessage(TypedDict):
message_index: int
role: str
@@ -103,6 +118,7 @@ class WebuiSessionAccess:
def __init__(self, sessions: SessionManager) -> None:
self._sessions = sessions
self._handles = SessionHandleDirectory(sessions)
def _metadata(
self,
@@ -228,7 +244,7 @@ class WebuiSessionAccess:
for raw_mention in normalize_session_mentions_metadata(raw):
mention = cast(SessionMention, raw_mention)
key = mention["session_key"]
folded_name = mention["name"].lower()
folded_name = mention["name"].casefold()
payload = self._metadata(key, exclude_session_key=exclude_session_key)
if payload is None or key in seen_keys or folded_name in seen_names:
continue
@@ -241,6 +257,68 @@ class WebuiSessionAccess:
seen_names.add(folded_name)
return normalized
def normalize_session_handles(
self,
raw: object,
*,
source_session_key: str,
) -> list[SessionHandleMention]:
"""Validate active session handles selected by a WebUI user turn."""
normalized: list[SessionHandleMention] = []
seen_keys: set[str] = set()
seen_names: set[str] = set()
source_handle = self._session_handle(source_session_key)
if source_handle is None:
return []
for raw_handle in normalize_session_handles_metadata(raw):
key = str(raw_handle["session_key"])
raw_handle_id = cast(object, raw_handle.get("id"))
if not isinstance(raw_handle_id, str) or key in seen_keys:
continue
if key == source_session_key:
handle = source_handle
else:
payload = self._metadata(key, exclude_session_key=None)
if payload is None or not key.startswith("websocket:"):
continue
raw_metadata = payload.get("metadata")
if not isinstance(raw_metadata, Mapping):
continue
metadata = cast(Mapping[str, object], raw_metadata)
if metadata.get("webui") is not True:
continue
handle = self._handles.resolve(
str(raw_handle["name"]),
)
if (
handle is None
or handle.session_key != key
or handle.id != raw_handle_id
or handle.name != str(raw_handle["name"])
):
continue
folded_name = handle.name.casefold()
if folded_name in seen_names:
continue
normalized.append({
"id": handle.id,
"name": handle.name,
"session_key": key,
"color_slot": handle.color_slot,
})
seen_keys.add(key)
seen_names.add(folded_name)
return normalized
def _session_handle(
self,
session_key: str,
) -> SessionHandle | None:
payload = self._metadata(session_key, exclude_session_key=None)
if payload is None or not is_persisted_webui_session(session_key, payload):
return None
return self._handles.handle_for_session(session_key)
def session_mentions_runtime_context(
mentions: list[SessionMention],
+27 -3
View File
@@ -32,16 +32,21 @@ from nanobot.session.manager import (
)
from nanobot.session.model_selection import model_preset_from_metadata
_INDEX_VERSION = 7
_INDEX_VERSION = 8
_INDEX_FILENAME = ".webui_session_index.json"
_MODEL_PRESET_FIELD = "model_preset"
_ROW_SOURCE_FIELD = "_source"
_SESSION_SOURCE = "session"
_TRANSCRIPT_SOURCE = "webui_transcript"
_PERSISTED_WEBUI_FIELD = "_persisted_webui"
_WORKSPACE_SCOPE_PRESENT_FIELD = "_workspace_scope_present"
_WORKSPACE_SCOPE_VALUE_FIELD = "_workspace_scope_value"
WEBUI_SESSION_INDEX_INTERNAL_FIELDS = frozenset(
{_WORKSPACE_SCOPE_PRESENT_FIELD, _WORKSPACE_SCOPE_VALUE_FIELD}
{
_PERSISTED_WEBUI_FIELD,
_WORKSPACE_SCOPE_PRESENT_FIELD,
_WORKSPACE_SCOPE_VALUE_FIELD,
}
)
_INDEXED_WORKSPACE_SCOPE_KEYS = ("project_path", "path", "access_mode")
_MAX_INDEXED_WORKSPACE_SCOPE_BYTES = 4096
@@ -245,12 +250,18 @@ def _public_row(sessions_dir: Path, webui_dir: Path, row: dict[str, Any]) -> dic
"title": row.get("title", ""),
"preview": row.get("preview", ""),
_MODEL_PRESET_FIELD: row.get(_MODEL_PRESET_FIELD),
_PERSISTED_WEBUI_FIELD: row.get(_PERSISTED_WEBUI_FIELD) is True,
_WORKSPACE_SCOPE_PRESENT_FIELD: row.get(_WORKSPACE_SCOPE_PRESENT_FIELD, False),
_WORKSPACE_SCOPE_VALUE_FIELD: row.get(_WORKSPACE_SCOPE_VALUE_FIELD),
"path": str(path),
}
def is_persisted_webui_session_row(row: dict[str, Any]) -> bool:
"""Return whether an indexed row has a canonical, addressable WebUI session."""
return row.get(_PERSISTED_WEBUI_FIELD) is True
def indexed_workspace_scope(row: dict[str, Any]) -> tuple[bool, object]:
"""Return the cached sidebar scope value while preserving missing vs null."""
return (
@@ -485,6 +496,9 @@ def _indexed_row_for_session(session: Session, path: Path, webui_dir: Path) -> d
"title": _metadata_title(session.metadata),
"preview": _preview_from_messages(session.messages),
_MODEL_PRESET_FIELD: model_preset_from_metadata(session.metadata),
_PERSISTED_WEBUI_FIELD: (
session.key.startswith("websocket:") and session.metadata.get("webui") is True
),
**_indexed_workspace_scope_fields(session.metadata),
_ROW_SOURCE_FIELD: _SESSION_SOURCE,
"file": path.name,
@@ -601,6 +615,7 @@ def _scan_transcript_row(
"title": "",
"preview": preview or fallback_preview,
_MODEL_PRESET_FIELD: None,
_PERSISTED_WEBUI_FIELD: False,
**_indexed_workspace_scope_fields({}),
_ROW_SOURCE_FIELD: _TRANSCRIPT_SOURCE,
"file": stem,
@@ -673,7 +688,12 @@ def _scan_session_row(
created_at_s = created_at_s or fallback_time
updated_at_s = updated_at_s or fallback_time
key = data.get("key") or storage_key
metadata = data.get("metadata", {})
raw_metadata: object = data.get("metadata")
metadata = (
cast(dict[str, Any], raw_metadata)
if isinstance(raw_metadata, dict)
else {}
)
activity_signature = _webui_activity_signature(key, webui_dir)
activity_updated_at = _webui_activity_updated_at(activity_signature)
return {
@@ -687,6 +707,10 @@ def _scan_session_row(
"title": _metadata_title(metadata),
"preview": preview or fallback_preview,
_MODEL_PRESET_FIELD: model_preset_from_metadata(metadata),
_PERSISTED_WEBUI_FIELD: (
key.startswith("websocket:")
and metadata.get("webui") is True
),
**_indexed_workspace_scope_fields(metadata),
_ROW_SOURCE_FIELD: _SESSION_SOURCE,
"file": path.name,
+159 -28
View File
@@ -22,6 +22,10 @@ from nanobot.runtime_context import public_history_message
from nanobot.session.automation_turns import is_automation_kind
from nanobot.session.history_visibility import is_hidden_history_message
from nanobot.session.manager import SessionManager
from nanobot.session.session_messages import (
session_message_envelope,
session_message_public_metadata,
)
from nanobot.webui.metadata import WEBUI_MESSAGE_SOURCE_METADATA_KEY, WEBUI_TURN_METADATA_KEY
WEBUI_TRANSCRIPT_SCHEMA_VERSION = 3
@@ -70,6 +74,7 @@ _TURN_DISPLAY_EVENTS: frozenset[str] = frozenset({
})
MAX_SESSION_MENTIONS = 8
_SESSION_MENTION_NAME_RE = re.compile(r"^[\w-]+$")
_SESSION_HANDLE_ID_RE = re.compile(r"^handle_[0-9a-f]{32}$")
def rewrite_local_markdown_images(
@@ -682,6 +687,33 @@ def append_transcript_object(session_key: str, obj: dict[str, Any]) -> None:
_rotate_active_transcript_if_needed(session_key)
def append_session_message_input(
session_key: str,
*,
content: str,
created_at_ms: int,
session_message: Mapping[str, Any],
) -> None:
"""Append one admitted cross-session user input to its WebUI transcript."""
chat_id = _chat_id_from_session_key(session_key)
if chat_id is None:
return
message_id = session_message.get("message_id")
if isinstance(message_id, str) and any(
isinstance(record.get("session_message"), Mapping)
and cast(Mapping[str, Any], record["session_message"]).get("message_id")
== message_id
for record in read_transcript_lines(session_key)
):
return
event = build_user_transcript_event(chat_id, content)
if event is None:
return
event["created_at_ms"] = created_at_ms
event["session_message"] = dict(session_message)
append_transcript_object(session_key, event)
def normalize_webui_turn_id(value: Any) -> str:
if isinstance(value, str):
candidate = value.strip()
@@ -696,7 +728,9 @@ def webui_message_source(metadata: dict[str, Any] | None) -> dict[str, str] | No
return None
source_metadata = cast(dict[str, Any], raw)
kind = source_metadata.get("kind")
if not isinstance(kind, str) or not is_automation_kind(kind):
if not isinstance(kind, str) or (
not is_automation_kind(kind) and kind != "session"
):
return None
source: dict[str, str] = {"kind": kind}
label = source_metadata.get("label")
@@ -760,6 +794,7 @@ class WebUITranscriptRecorder:
cli_apps: list[dict[str, Any]] | None = None,
mcp_presets: list[dict[str, Any]] | None = None,
session_mentions: Sequence[Mapping[str, Any]] | None = None,
session_handles: Sequence[Mapping[str, Any]] | None = None,
) -> bool:
if text.strip() == "/stop" and not media_paths:
return False
@@ -770,6 +805,7 @@ class WebUITranscriptRecorder:
cli_apps=cli_apps,
mcp_presets=mcp_presets,
session_mentions=session_mentions,
session_handles=session_handles,
)
if payload is None:
return False
@@ -878,36 +914,17 @@ def write_session_messages_as_transcript(
messages: list[dict[str, Any]],
) -> None:
"""Write a minimal WebUI transcript from already-truncated session messages."""
target_chat_id = _chat_id_from_session_key(target_key)
rows: list[dict[str, Any]] = []
for msg in messages:
if is_hidden_history_message(msg):
continue
msg = public_history_message(msg)
role = msg.get("role")
content = msg.get("content")
text = content if isinstance(content, str) else ""
if role == "user":
row: dict[str, Any] = {"event": "user", "chat_id": target_chat_id, "text": text}
media = msg.get("media")
if isinstance(media, list) and media:
row["media_paths"] = [
str(p) for p in cast(list[Any], media) if isinstance(p, str) and p
]
for key in ("cli_apps", "mcp_presets", "session_mentions"):
value = msg.get(key)
if isinstance(value, list) and value:
row[key] = json.loads(json.dumps(value, ensure_ascii=False))
elif role == "assistant" and text.strip():
row = {"event": "message", "chat_id": target_chat_id, "text": text}
media = msg.get("media")
if isinstance(media, list) and media:
row["media"] = [
str(p) for p in cast(list[Any], media) if isinstance(p, str) and p
]
row = _session_user_event(target_key, msg)
elif role == "assistant":
row = _session_assistant_event(target_key, msg)
else:
continue
rows.append(row)
if row is not None:
rows.append(row)
_write_transcript_lines(target_key, rows)
@@ -957,6 +974,86 @@ def normalize_session_mentions_metadata(raw: object) -> list[dict[str, str]]:
return normalized
def normalize_session_handles_metadata(raw: object) -> list[dict[str, Any]]:
"""Validate session-handle metadata crossing a persistence seam."""
if not isinstance(raw, Sequence) or isinstance(raw, (str, bytes, bytearray)):
return []
normalized: list[dict[str, Any]] = []
for raw_item in cast(Sequence[object], raw)[:MAX_SESSION_MENTIONS]:
if not isinstance(raw_item, Mapping):
continue
item = cast(Mapping[str, object], raw_item)
name = item.get("name")
session_key = item.get("session_key")
handle_id = item.get("id")
if (
not isinstance(name, str)
or not isinstance(session_key, str)
or not isinstance(handle_id, str)
or _SESSION_HANDLE_ID_RE.fullmatch(handle_id) is None
):
continue
name = name.strip()[:80]
session_key = session_key.strip()[:512]
if not name or not session_key or _SESSION_MENTION_NAME_RE.fullmatch(name) is None:
continue
mention: dict[str, Any] = {
"id": handle_id,
"name": name,
"session_key": session_key,
}
color_slot = item.get("color_slot")
if (
isinstance(color_slot, int)
and not isinstance(color_slot, bool)
and 0 <= color_slot < 8
):
mention["color_slot"] = color_slot
normalized.append(mention)
return normalized
def normalize_session_message_ui_metadata(raw: object) -> dict[str, Any] | None:
"""Validate session-message provenance at the transcript-to-WebUI boundary."""
if not isinstance(raw, Mapping):
return None
raw_data = cast(Mapping[str, object], raw)
session = raw_data.get("session")
direction = raw_data.get("direction")
message_id = raw_data.get("message_id")
if (
direction not in {"incoming", "outgoing"}
or not isinstance(message_id, str)
or not message_id.strip()
or not isinstance(session, Mapping)
):
return None
session_data = cast(Mapping[str, object], session)
handle_id = session_data.get("id")
name = session_data.get("name")
color_slot = session_data.get("color_slot")
if (
not isinstance(handle_id, str)
or not handle_id.strip()
or not isinstance(name, str)
or not name.strip()
or not isinstance(color_slot, int)
or isinstance(color_slot, bool)
or not 0 <= color_slot < 8
):
return None
handle: dict[str, Any] = {
"id": handle_id.strip()[:128],
"name": name.strip()[:80],
"color_slot": color_slot,
}
return {
"direction": direction,
"message_id": message_id.strip()[:128],
"session": handle,
}
def build_user_transcript_event(
chat_id: str,
text: str,
@@ -965,6 +1062,7 @@ def build_user_transcript_event(
cli_apps: list[Any] | None = None,
mcp_presets: list[Any] | None = None,
session_mentions: Sequence[Any] | None = None,
session_handles: Sequence[Any] | None = None,
) -> dict[str, Any] | None:
paths = [str(path) for path in (media_paths or []) if path]
if not text and not paths:
@@ -993,6 +1091,9 @@ def build_user_transcript_event(
mentions = normalize_session_mentions_metadata(session_mentions)
if mentions:
event["session_mentions"] = mentions
handles = normalize_session_handles_metadata(session_handles)
if handles:
event["session_handles"] = handles
return event
@@ -1017,6 +1118,7 @@ def _session_user_event(
return None
if is_hidden_history_message(message):
return None
message_envelope = session_message_envelope(message)
message = public_history_message(message)
if _is_legacy_raw_subagent_result(message):
return None
@@ -1026,8 +1128,9 @@ def _session_user_event(
cli_apps = message.get("cli_apps")
mcp_presets = message.get("mcp_presets")
session_mentions = message.get("session_mentions")
session_handles = message.get("session_handles")
chat_id = session_key.split(":", 1)[1] if ":" in session_key else session_key
return build_user_transcript_event(
event = build_user_transcript_event(
chat_id,
text,
media_paths=cast(list[Any], media) if isinstance(media, list) else None,
@@ -1036,7 +1139,13 @@ def _session_user_event(
session_mentions=(
cast(list[Any], session_mentions) if isinstance(session_mentions, list) else None
),
session_handles=(
cast(list[Any], session_handles) if isinstance(session_handles, list) else None
),
)
if event is not None and message_envelope is not None:
event["session_message"] = session_message_public_metadata(message_envelope)
return event
def _assistant_text_signature(value: Any) -> str:
@@ -1222,7 +1331,9 @@ def _find_unique_session_turn(
def _user_recovery_signature(event: dict[str, Any]) -> str:
fields = {
key: event[key]
for key in ("text", "media_paths", "cli_apps", "mcp_presets", "session_mentions")
for key in (
"text", "media_paths", "cli_apps", "mcp_presets", "session_mentions", "session_handles"
)
if key in event
}
return json.dumps(fields, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
@@ -1679,7 +1790,9 @@ def replay_transcript_to_ui_messages(
return {}
source_data = cast(dict[str, Any], source)
kind = source_data.get("kind")
if not isinstance(kind, str) or not is_automation_kind(kind):
if not isinstance(kind, str) or (
not is_automation_kind(kind) and kind != "session"
):
return {}
out: dict[str, Any] = {"source": {"kind": kind}}
label = source_data.get("label")
@@ -2040,6 +2153,17 @@ def replay_transcript_to_ui_messages(
for idx, rec in enumerate(lines):
ev = rec.get("event")
if ev == "user":
if buffer_message_id is not None:
for message_index, message in enumerate(messages):
if message.get("id") == buffer_message_id:
messages[message_index] = {
**message,
"isStreaming": False,
}
break
buffer_message_id = None
buffer_parts = []
close_reasoning(messages)
active_activity_segment_id = None
active_file_edit_segment_id = None
text = rec.get("text")
@@ -2079,6 +2203,13 @@ def replay_transcript_to_ui_messages(
)
if session_mentions:
row["sessionMentions"] = session_mentions
session_handles = normalize_session_handles_metadata(rec.get("session_handles"))
if session_handles:
row["sessionHandles"] = session_handles
if session_message := normalize_session_message_ui_metadata(
rec.get("session_message")
):
row["sessionMessage"] = session_message
messages.append(row)
continue
+58 -29
View File
@@ -101,6 +101,7 @@ from nanobot.webui.session_context import session_context_payload
from nanobot.webui.session_list_index import (
WEBUI_SESSION_INDEX_INTERNAL_FIELDS,
indexed_workspace_scope,
is_persisted_webui_session_row,
list_webui_sessions,
)
from nanobot.webui.sidebar_state import (
@@ -728,34 +729,57 @@ class GatewayHTTPHandler:
def _sessions_list_payload(self) -> dict[str, Any]:
assert self.session_manager is not None
sessions = list_webui_sessions(self.session_manager)
from nanobot.session.session_handles import (
SessionHandleDirectory,
SessionHandleSnapshot,
)
from nanobot.session.webui_turns import websocket_turn_wall_started_at
cleaned: list[dict[str, Any]] = []
default_scope: WorkspaceScope | None = None
for s in sessions:
key = s.get("key")
if not (isinstance(key, str) and key.startswith("websocket:")):
continue
row = {
k: v
for k, v in s.items()
if k != "path" and k not in WEBUI_SESSION_INDEX_INTERNAL_FIELDS
}
chat_id = key.split(":", 1)[1]
started_at = websocket_turn_wall_started_at(chat_id)
if started_at is not None:
row["run_started_at"] = started_at
if default_scope is None:
default_scope = self.workspaces.default_scope()
scope_present, raw_scope = indexed_workspace_scope(s)
scope = self.workspaces.scope_for_indexed_metadata(
raw_scope,
scope_present=scope_present,
default_scope=default_scope,
)
row["workspace_scope"] = scope.payload()
cleaned.append(row)
with self.session_manager.locked_session_files():
sessions = list_webui_sessions(self.session_manager)
cleaned: list[dict[str, Any]] = []
identity_snapshots: list[SessionHandleSnapshot] = []
stale_identity_keys: list[str] = []
default_scope: WorkspaceScope | None = None
for s in sessions:
key = s.get("key")
if not (isinstance(key, str) and key.startswith("websocket:")):
continue
row = {
k: v
for k, v in s.items()
if k != "path" and k not in WEBUI_SESSION_INDEX_INTERNAL_FIELDS
}
chat_id = key.split(":", 1)[1]
started_at = websocket_turn_wall_started_at(chat_id)
if started_at is not None:
row["run_started_at"] = started_at
if default_scope is None:
default_scope = self.workspaces.default_scope()
scope_present, raw_scope = indexed_workspace_scope(s)
scope = self.workspaces.scope_for_indexed_metadata(
raw_scope,
scope_present=scope_present,
default_scope=default_scope,
)
row["workspace_scope"] = scope.payload()
if is_persisted_webui_session_row(s):
identity_snapshots.append(SessionHandleSnapshot(
session_key=key,
workspace=scope.project_path,
))
else:
stale_identity_keys.append(key)
cleaned.append(row)
directory = SessionHandleDirectory(self.session_manager)
directory.remove_many(stale_identity_keys)
handles = directory.ensure_snapshot_many(identity_snapshots)
for row in cleaned:
key = cast(str, row["key"])
handle = handles.get(key)
if handle is not None:
row["handle"] = handle.public_payload()
return {"sessions": cleaned}
def _handle_webui_thread_get(self, request: WsRequest, key: str) -> Response:
@@ -905,9 +929,14 @@ class GatewayHTTPHandler:
self.local_trigger_store.delete(job.id)
elif self.cron_service is not None:
self.cron_service.remove_job(job.id)
session_deleted = self.session_manager.delete_session(decoded_key)
transcript_deleted = delete_webui_thread(decoded_key)
return _http_json_response({"deleted": bool(session_deleted or transcript_deleted)})
with self.session_manager.locked_session_files():
deleted = self.session_manager.delete_session(decoded_key)
transcript_deleted = delete_webui_thread(decoded_key)
if deleted or transcript_deleted:
from nanobot.session.session_handles import SessionHandleDirectory
SessionHandleDirectory(self.session_manager).remove_many([decoded_key])
return _http_json_response({"deleted": bool(deleted or transcript_deleted)})
# -- Automation routes --------------------------------------------------