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:
1 parent
33ff520d12
commit
8f6a5594fb
144 files changed
+8293
-4912
No files matched your search
+111
-332
@@ -1,4 +1,4 @@
|
||||
"""Cache-only WebUI session list index.
|
||||
"""SQLite sidebar queries and a rebuildable display-transcript cache.
|
||||
|
||||
The core ``SessionManager`` owns model context while the WebUI transcript owns
|
||||
durable display history. The sidebar discovers both without reconstructing one
|
||||
@@ -11,6 +11,8 @@ import json
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
import stat
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any, cast
|
||||
@@ -19,17 +21,12 @@ from loguru import logger
|
||||
|
||||
from nanobot.config.paths import get_webui_dir
|
||||
from nanobot.security.workspace_access import WORKSPACE_SCOPE_METADATA_KEY
|
||||
from nanobot.session.history_visibility import is_hidden_history_message
|
||||
from nanobot.session.manager import (
|
||||
_PROVIDER_STATE_RECORD_TYPE, # pyright: ignore[reportPrivateUsage]
|
||||
_SESSION_LIST_PREVIEW_MAX_CHARS, # pyright: ignore[reportPrivateUsage]
|
||||
_SESSION_LIST_PREVIEW_MAX_RECORDS, # pyright: ignore[reportPrivateUsage]
|
||||
Session,
|
||||
SessionManager,
|
||||
_is_provider_state_record_line, # pyright: ignore[reportPrivateUsage]
|
||||
_message_preview_text, # pyright: ignore[reportPrivateUsage]
|
||||
_metadata_title, # pyright: ignore[reportPrivateUsage]
|
||||
)
|
||||
message_preview_text, # pyright: ignore[reportPrivateUsage]
|
||||
)
|
||||
from nanobot.session.model_selection import model_preset_from_metadata
|
||||
from nanobot.session.recovery import recovery_state_from_metadata
|
||||
from nanobot.webui.session_identity import (
|
||||
@@ -62,28 +59,73 @@ _TRANSCRIPT_SEGMENTS_SUFFIX = ".segments"
|
||||
_TRANSCRIPT_NON_ANSWER_KINDS = {"progress", "reasoning", "tool_hint"}
|
||||
|
||||
|
||||
def list_webui_sessions(session_manager: SessionManager) -> list[dict[str, Any]]:
|
||||
@dataclass
|
||||
class _WebuiFiles:
|
||||
signature: dict[str, int] = field(default_factory=lambda: {
|
||||
_WEBUI_ACTIVITY_MTIME_NS: 0, _WEBUI_ACTIVITY_SIZE: 0, _WEBUI_ACTIVITY_FILES: 0,
|
||||
})
|
||||
records: list[tuple[Path, float]] = field(default_factory=list)
|
||||
|
||||
|
||||
def list_webui_sessions(
|
||||
session_manager: SessionManager,
|
||||
stored_sessions: list[dict[str, Any]] | None = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Return session rows for the WebUI sidebar, backed by a rebuildable cache."""
|
||||
with session_manager.locked_session_files():
|
||||
rows, changed = _reconcile_index(session_manager)
|
||||
if changed:
|
||||
try:
|
||||
_write_index_rows(session_manager.sessions_dir, rows)
|
||||
except Exception as e:
|
||||
logger.debug("Failed to write WebUI session list index: {}", e)
|
||||
sessions = [
|
||||
_public_row(session_manager.sessions_dir, get_webui_dir(), row)
|
||||
for row in rows
|
||||
]
|
||||
sessions = [
|
||||
row for row in sessions if session_manager.types.public_history(
|
||||
(session_manager.read_session_metadata(row["key"]) or {}).get("metadata", {})
|
||||
)
|
||||
]
|
||||
webui_dir = get_webui_dir()
|
||||
rows, changed = _reconcile_index(session_manager, stored_sessions, webui_dir)
|
||||
if changed:
|
||||
try:
|
||||
_write_index_rows(session_manager.sessions_dir, [row for row in rows if row.get(_ROW_SOURCE_FIELD) == _TRANSCRIPT_SOURCE])
|
||||
except Exception as e:
|
||||
logger.debug("Failed to write WebUI transcript list cache: {}", e)
|
||||
sessions = [_public_row(session_manager.sessions_dir, webui_dir, row) for row in rows]
|
||||
return sorted(sessions, key=lambda row: row.get("updated_at", ""), reverse=True)
|
||||
|
||||
|
||||
def _reconcile_index(session_manager: SessionManager) -> tuple[list[dict[str, Any]], bool]:
|
||||
def _reconcile_index(
|
||||
session_manager: SessionManager,
|
||||
stored_sessions: list[dict[str, Any]] | None,
|
||||
webui_dir: Path,
|
||||
) -> tuple[list[dict[str, Any]], bool]:
|
||||
files_by_stem = _read_webui_files(webui_dir)
|
||||
activity_by_stem: dict[str, dict[str, int]] = {}
|
||||
for stem, files in files_by_stem.items():
|
||||
identity = os.path.normcase(stem)
|
||||
previous = activity_by_stem.get(identity)
|
||||
activity_by_stem[identity] = files.signature if previous is None else {
|
||||
_WEBUI_ACTIVITY_MTIME_NS: max(previous[_WEBUI_ACTIVITY_MTIME_NS], files.signature[_WEBUI_ACTIVITY_MTIME_NS]),
|
||||
_WEBUI_ACTIVITY_SIZE: previous[_WEBUI_ACTIVITY_SIZE] + files.signature[_WEBUI_ACTIVITY_SIZE],
|
||||
_WEBUI_ACTIVITY_FILES: previous[_WEBUI_ACTIVITY_FILES] + files.signature[_WEBUI_ACTIVITY_FILES],
|
||||
}
|
||||
stored = session_manager.list_session_metadata() if stored_sessions is None else stored_sessions
|
||||
session_keys = {row["key"] for row in stored}
|
||||
session_stems = {os.path.normcase(SessionManager.safe_key(key)) for key in session_keys if is_webui_session_key(key)}
|
||||
rows: list[dict[str, Any]] = []
|
||||
for row in stored:
|
||||
metadata = row["metadata"]
|
||||
if not session_manager.types.public_history(metadata):
|
||||
continue
|
||||
signature = activity_by_stem.get(os.path.normcase(SessionManager.safe_key(row["key"])))
|
||||
activity = _webui_activity_updated_at(signature) if signature is not None else None
|
||||
rows.append({
|
||||
"key": row["key"], "created_at": row["created_at"],
|
||||
"updated_at": _visible_activity_updated_at(row["updated_at"], row["visible_updated_at"], activity),
|
||||
"title": row["title"], "preview": row["preview"],
|
||||
_MODEL_PRESET_FIELD: model_preset_from_metadata(metadata),
|
||||
"recovery_state": recovery_state_from_metadata(metadata),
|
||||
**_indexed_workspace_scope_fields(metadata),
|
||||
_ROW_SOURCE_FIELD: _SESSION_SOURCE, "file": "sessions.sqlite3",
|
||||
})
|
||||
|
||||
transcripts = [
|
||||
(stem, files) for stem, files in sorted(files_by_stem.items())
|
||||
if stem.startswith(_WEBUI_SESSION_STEM_PREFIX) and files.records
|
||||
and os.path.normcase(stem) not in session_stems
|
||||
]
|
||||
if not transcripts:
|
||||
return rows, False
|
||||
# Only transcript-only sessions use the file cache; SQLite rows are fresh.
|
||||
existing_rows = _read_index_rows(session_manager.sessions_dir)
|
||||
existing_by_source = {
|
||||
(row.get(_ROW_SOURCE_FIELD), row.get("file")): row
|
||||
@@ -91,39 +133,10 @@ def _reconcile_index(session_manager: SessionManager) -> tuple[list[dict[str, An
|
||||
if isinstance(row.get(_ROW_SOURCE_FIELD), str)
|
||||
and isinstance(row.get("file"), str)
|
||||
}
|
||||
webui_dir = get_webui_dir()
|
||||
session_paths: dict[str, Path] = {}
|
||||
for path in sorted(session_manager.sessions_dir.glob("*.jsonl")):
|
||||
key = SessionManager._session_key_from_path(path) # pyright: ignore[reportPrivateUsage]
|
||||
if key is not None:
|
||||
session_paths[key] = path
|
||||
|
||||
session_keys_by_stem = {
|
||||
SessionManager.safe_key(key): key
|
||||
for key in session_paths
|
||||
if is_webui_session_key(key)
|
||||
}
|
||||
rows: list[dict[str, Any]] = []
|
||||
changed = existing_rows is None
|
||||
expected_sources: set[tuple[str, str]] = set()
|
||||
|
||||
for key, path in sorted(session_paths.items()):
|
||||
identity = (_SESSION_SOURCE, path.name)
|
||||
row = existing_by_source.get(identity)
|
||||
if row is not None and _indexed_row_matches_file(row, path, webui_dir):
|
||||
rows.append(row)
|
||||
expected_sources.add(identity)
|
||||
continue
|
||||
|
||||
changed = True
|
||||
scanned = _scan_session_row(session_manager, path, webui_dir)
|
||||
if scanned is not None:
|
||||
rows.append(scanned)
|
||||
expected_sources.add(identity)
|
||||
|
||||
for stem, paths in _webui_transcript_sources(webui_dir).items():
|
||||
if stem in session_keys_by_stem:
|
||||
continue
|
||||
for stem, files in transcripts:
|
||||
files.signature = activity_by_stem[os.path.normcase(stem)]
|
||||
identity = (_TRANSCRIPT_SOURCE, stem)
|
||||
row = existing_by_source.get(identity)
|
||||
cached_key = row.get("key") if row is not None else None
|
||||
@@ -135,22 +148,23 @@ def _reconcile_index(session_manager: SessionManager) -> tuple[list[dict[str, An
|
||||
if key is not None and row is not None and _indexed_transcript_row_matches(
|
||||
row,
|
||||
key,
|
||||
webui_dir,
|
||||
files.signature,
|
||||
):
|
||||
rows.append(row)
|
||||
expected_sources.add(identity)
|
||||
continue
|
||||
|
||||
changed = True
|
||||
scanned = _scan_transcript_row(key, stem, paths, webui_dir)
|
||||
scanned = _scan_transcript_row(key, stem, files, webui_dir)
|
||||
scanned_key = scanned.get("key") if scanned is not None else None
|
||||
if scanned is not None and scanned_key not in session_paths:
|
||||
if scanned is not None and scanned_key not in session_keys:
|
||||
rows.append(scanned)
|
||||
expected_sources.add(identity)
|
||||
|
||||
if set(existing_by_source) != expected_sources:
|
||||
changed = True
|
||||
if existing_rows is not None and rows != existing_rows:
|
||||
transcript_rows = [row for row in rows if row.get(_ROW_SOURCE_FIELD) == _TRANSCRIPT_SOURCE]
|
||||
if existing_rows is not None and transcript_rows != existing_rows:
|
||||
changed = True
|
||||
return rows, changed
|
||||
|
||||
@@ -193,38 +207,11 @@ def _write_index_rows(sessions_dir: Path, rows: list[dict[str, Any]]) -> None:
|
||||
tmp_path.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def _file_signature(path: Path) -> dict[str, int]:
|
||||
stat = path.stat()
|
||||
return {"mtime_ns": stat.st_mtime_ns, "size": stat.st_size}
|
||||
|
||||
|
||||
def _indexed_row_matches_file(row: dict[str, Any], path: Path, webui_dir: Path) -> bool:
|
||||
if not all(isinstance(row.get(key), str) for key in ("key", "created_at", "updated_at")):
|
||||
return False
|
||||
if not isinstance(row.get("title", ""), str) or not isinstance(row.get("preview", ""), str):
|
||||
return False
|
||||
if not isinstance(row.get(_WORKSPACE_SCOPE_PRESENT_FIELD), bool):
|
||||
return False
|
||||
if row.get(_ROW_SOURCE_FIELD) != _SESSION_SOURCE or row.get("file") != path.name:
|
||||
return False
|
||||
try:
|
||||
signature = _file_signature(path)
|
||||
except OSError:
|
||||
return False
|
||||
activity_signature = _webui_activity_signature(str(row.get("key")), webui_dir)
|
||||
return (
|
||||
row.get("mtime_ns") == signature["mtime_ns"]
|
||||
and row.get("size") == signature["size"]
|
||||
and row.get(_WEBUI_ACTIVITY_MTIME_NS) == activity_signature[_WEBUI_ACTIVITY_MTIME_NS]
|
||||
and row.get(_WEBUI_ACTIVITY_SIZE) == activity_signature[_WEBUI_ACTIVITY_SIZE]
|
||||
and row.get(_WEBUI_ACTIVITY_FILES) == activity_signature[_WEBUI_ACTIVITY_FILES]
|
||||
)
|
||||
|
||||
|
||||
def _indexed_transcript_row_matches(
|
||||
row: dict[str, Any],
|
||||
session_key: str,
|
||||
webui_dir: Path,
|
||||
signature: dict[str, int],
|
||||
) -> bool:
|
||||
if not all(isinstance(row.get(key), str) for key in ("key", "created_at", "updated_at")):
|
||||
return False
|
||||
@@ -236,7 +223,6 @@ def _indexed_transcript_row_matches(
|
||||
return False
|
||||
if not isinstance(row.get(_WORKSPACE_SCOPE_PRESENT_FIELD), bool):
|
||||
return False
|
||||
signature = _webui_activity_signature(session_key, webui_dir)
|
||||
return (
|
||||
row.get(_WEBUI_ACTIVITY_MTIME_NS) == signature[_WEBUI_ACTIVITY_MTIME_NS]
|
||||
and row.get(_WEBUI_ACTIVITY_SIZE) == signature[_WEBUI_ACTIVITY_SIZE]
|
||||
@@ -309,72 +295,43 @@ def _indexed_workspace_scope_fields(metadata: object) -> dict[str, object]:
|
||||
}
|
||||
|
||||
|
||||
def _preview_from_messages(messages: list[dict[str, Any]]) -> str:
|
||||
fallback_preview = ""
|
||||
scanned_records = 0
|
||||
scanned_chars = 0
|
||||
for item in messages:
|
||||
scanned_records += 1
|
||||
scanned_chars += len(json.dumps(item, ensure_ascii=False)) + 1
|
||||
if (
|
||||
scanned_records > _SESSION_LIST_PREVIEW_MAX_RECORDS
|
||||
or scanned_chars > _SESSION_LIST_PREVIEW_MAX_CHARS
|
||||
):
|
||||
break
|
||||
if is_hidden_history_message(item):
|
||||
continue
|
||||
text = _message_preview_text(item)
|
||||
if not text:
|
||||
continue
|
||||
if item.get("role") == "user":
|
||||
return text
|
||||
if not fallback_preview and item.get("role") == "assistant":
|
||||
fallback_preview = text
|
||||
return fallback_preview
|
||||
|
||||
def _read_webui_files(webui_dir: Path) -> dict[str, _WebuiFiles]:
|
||||
"""Discover present display files once per request, including all segment activity."""
|
||||
files_by_stem: dict[str, _WebuiFiles] = {}
|
||||
|
||||
def _webui_transcript_record_paths(stem: str, webui_dir: Path) -> tuple[Path, ...]:
|
||||
paths: list[Path] = []
|
||||
segments_dir = webui_dir / f"{stem}{_TRANSCRIPT_SEGMENTS_SUFFIX}"
|
||||
if segments_dir.is_dir() and not segments_dir.is_symlink():
|
||||
def add_file(stem: str, entry: os.DirEntry[str]) -> None:
|
||||
try:
|
||||
paths.extend(
|
||||
sorted(
|
||||
path
|
||||
for path in segments_dir.glob("*.jsonl")
|
||||
if path.is_file() and not path.is_symlink()
|
||||
)
|
||||
)
|
||||
info = entry.stat(follow_symlinks=False)
|
||||
except OSError:
|
||||
pass
|
||||
active = webui_dir / f"{stem}.jsonl"
|
||||
if active.is_file() and not active.is_symlink():
|
||||
paths.append(active)
|
||||
return tuple(paths)
|
||||
return
|
||||
if not stat.S_ISREG(info.st_mode):
|
||||
return
|
||||
files = files_by_stem.setdefault(stem, _WebuiFiles())
|
||||
signature = files.signature
|
||||
signature[_WEBUI_ACTIVITY_MTIME_NS] = max(signature[_WEBUI_ACTIVITY_MTIME_NS], info.st_mtime_ns)
|
||||
signature[_WEBUI_ACTIVITY_SIZE] += info.st_size
|
||||
signature[_WEBUI_ACTIVITY_FILES] += 1
|
||||
if os.path.normcase(entry.name).endswith(".jsonl"):
|
||||
files.records.append((Path(entry.path), info.st_mtime))
|
||||
|
||||
|
||||
def _webui_transcript_sources(webui_dir: Path) -> dict[str, tuple[Path, ...]]:
|
||||
stems: set[str] = set()
|
||||
try:
|
||||
entries = tuple(webui_dir.iterdir())
|
||||
with os.scandir(webui_dir) as entries:
|
||||
for entry in entries:
|
||||
name = os.path.normcase(entry.name)
|
||||
if name.endswith(_TRANSCRIPT_SEGMENTS_SUFFIX) and entry.is_dir(follow_symlinks=False):
|
||||
stem = entry.name[:-len(_TRANSCRIPT_SEGMENTS_SUFFIX)]
|
||||
try:
|
||||
with os.scandir(entry.path) as segments:
|
||||
for segment in segments:
|
||||
add_file(stem, segment)
|
||||
except OSError:
|
||||
pass
|
||||
elif name.endswith((".jsonl", ".json")):
|
||||
add_file(entry.name.rsplit(".", 1)[0], entry)
|
||||
except OSError:
|
||||
return {}
|
||||
for path in entries:
|
||||
if path.is_symlink():
|
||||
continue
|
||||
if path.is_file() and path.suffix == ".jsonl":
|
||||
stem = path.stem
|
||||
elif path.is_dir() and path.name.endswith(_TRANSCRIPT_SEGMENTS_SUFFIX):
|
||||
stem = path.name.removesuffix(_TRANSCRIPT_SEGMENTS_SUFFIX)
|
||||
else:
|
||||
continue
|
||||
if stem.startswith(_WEBUI_SESSION_STEM_PREFIX):
|
||||
stems.add(stem)
|
||||
return {
|
||||
stem: paths
|
||||
for stem in sorted(stems)
|
||||
if (paths := _webui_transcript_record_paths(stem, webui_dir))
|
||||
}
|
||||
pass
|
||||
return files_by_stem
|
||||
|
||||
|
||||
def _transcript_record(line: str) -> dict[str, Any] | None:
|
||||
@@ -392,48 +349,6 @@ def _valid_transcript_session_key(key: str, stem: str) -> bool:
|
||||
return _WEBUI_CHAT_ID_RE.fullmatch(chat_id) is not None and SessionManager.safe_key(key) == stem
|
||||
|
||||
|
||||
def _webui_activity_paths(session_key: str, webui_dir: Path) -> list[Path]:
|
||||
stem = SessionManager.safe_key(session_key)
|
||||
paths = [
|
||||
webui_dir / f"{stem}.jsonl",
|
||||
webui_dir / f"{stem}.json",
|
||||
]
|
||||
segments_dir = webui_dir / f"{stem}{_TRANSCRIPT_SEGMENTS_SUFFIX}"
|
||||
if segments_dir.is_dir() and not segments_dir.is_symlink():
|
||||
try:
|
||||
paths.extend(
|
||||
sorted(
|
||||
path
|
||||
for path in segments_dir.iterdir()
|
||||
if path.is_file() and not path.is_symlink()
|
||||
)
|
||||
)
|
||||
except OSError:
|
||||
pass
|
||||
return paths
|
||||
|
||||
|
||||
def _webui_activity_signature(session_key: str, webui_dir: Path) -> dict[str, int]:
|
||||
latest_mtime_ns = 0
|
||||
total_size = 0
|
||||
file_count = 0
|
||||
for path in _webui_activity_paths(session_key, webui_dir):
|
||||
try:
|
||||
stat = path.stat()
|
||||
except OSError:
|
||||
continue
|
||||
if not path.is_file():
|
||||
continue
|
||||
file_count += 1
|
||||
latest_mtime_ns = max(latest_mtime_ns, stat.st_mtime_ns)
|
||||
total_size += stat.st_size
|
||||
return {
|
||||
_WEBUI_ACTIVITY_MTIME_NS: latest_mtime_ns,
|
||||
_WEBUI_ACTIVITY_SIZE: total_size,
|
||||
_WEBUI_ACTIVITY_FILES: file_count,
|
||||
}
|
||||
|
||||
|
||||
def _webui_activity_updated_at(signature: dict[str, int]) -> str | None:
|
||||
mtime_ns = signature.get(_WEBUI_ACTIVITY_MTIME_NS, 0)
|
||||
if mtime_ns <= 0:
|
||||
@@ -456,23 +371,6 @@ def _latest_updated_at(stored: str | None, activity: str | None) -> str | None:
|
||||
return stored
|
||||
|
||||
|
||||
def _visible_message_timestamp(item: dict[str, Any]) -> str | None:
|
||||
if item.get("role") not in _VISIBLE_TRANSCRIPT_ROLES:
|
||||
return None
|
||||
if is_hidden_history_message(item):
|
||||
return None
|
||||
timestamp = item.get("timestamp")
|
||||
return timestamp if isinstance(timestamp, str) else None
|
||||
|
||||
|
||||
def _last_visible_message_at(messages: list[dict[str, Any]]) -> str | None:
|
||||
latest: str | None = None
|
||||
for item in messages:
|
||||
timestamp = _visible_message_timestamp(item)
|
||||
if timestamp is not None:
|
||||
latest = _latest_updated_at(latest, timestamp)
|
||||
return latest
|
||||
|
||||
|
||||
def _visible_activity_updated_at(
|
||||
stored: str | None,
|
||||
@@ -482,37 +380,12 @@ def _visible_activity_updated_at(
|
||||
return _latest_updated_at(visible_message_at, webui_activity) or stored
|
||||
|
||||
|
||||
def _indexed_row_for_session(session: Session, path: Path, webui_dir: Path) -> dict[str, Any]:
|
||||
signature = _file_signature(path)
|
||||
activity_signature = _webui_activity_signature(session.key, webui_dir)
|
||||
activity_updated_at = _webui_activity_updated_at(activity_signature)
|
||||
visible_message_at = _last_visible_message_at(session.messages)
|
||||
return {
|
||||
"key": session.key,
|
||||
"created_at": session.created_at.isoformat(),
|
||||
"updated_at": _visible_activity_updated_at(
|
||||
session.updated_at.isoformat(),
|
||||
visible_message_at,
|
||||
activity_updated_at,
|
||||
),
|
||||
"title": _metadata_title(session.metadata),
|
||||
"preview": _preview_from_messages(session.messages),
|
||||
_MODEL_PRESET_FIELD: model_preset_from_metadata(session.metadata),
|
||||
"recovery_state": recovery_state_from_metadata(session.metadata),
|
||||
**_indexed_workspace_scope_fields(session.metadata),
|
||||
_ROW_SOURCE_FIELD: _SESSION_SOURCE,
|
||||
"file": path.name,
|
||||
"mtime_ns": signature["mtime_ns"],
|
||||
"size": signature["size"],
|
||||
**activity_signature,
|
||||
}
|
||||
|
||||
|
||||
def _transcript_preview(record: dict[str, Any]) -> tuple[str, str]:
|
||||
text = record.get("text")
|
||||
if not isinstance(text, str) or not text.strip():
|
||||
return "", ""
|
||||
preview = _message_preview_text({"content": text})
|
||||
preview = message_preview_text({"content": text})
|
||||
if not preview:
|
||||
return "", ""
|
||||
event = record.get("event")
|
||||
@@ -543,13 +416,10 @@ def _transcript_created_at(record: dict[str, Any]) -> str | None:
|
||||
def _scan_transcript_row(
|
||||
session_key: str | None,
|
||||
stem: str,
|
||||
paths: tuple[Path, ...],
|
||||
files: _WebuiFiles,
|
||||
webui_dir: Path,
|
||||
) -> dict[str, Any] | None:
|
||||
path_key = session_key or webui_session_key(
|
||||
stem.removeprefix(_WEBUI_SESSION_STEM_PREFIX)
|
||||
)
|
||||
signature = _webui_activity_signature(path_key, webui_dir)
|
||||
signature = files.signature
|
||||
activity_updated_at = _webui_activity_updated_at(signature)
|
||||
if activity_updated_at is None:
|
||||
return None
|
||||
@@ -560,6 +430,7 @@ def _scan_transcript_row(
|
||||
saw_record = False
|
||||
scanned_records = 0
|
||||
scanned_chars = 0
|
||||
paths = [path for path, _ in sorted(files.records, key=lambda item: (item[0].parent == webui_dir, item[0]))]
|
||||
for path in paths:
|
||||
try:
|
||||
with open(path, encoding="utf-8") as handle:
|
||||
@@ -606,7 +477,7 @@ def _scan_transcript_row(
|
||||
|
||||
if created_at is None:
|
||||
try:
|
||||
earliest_mtime = min(path.stat().st_mtime for path in paths)
|
||||
earliest_mtime = min(mtime for _, mtime in files.records)
|
||||
created_at = datetime.fromtimestamp(earliest_mtime).isoformat()
|
||||
except (OSError, OverflowError, ValueError):
|
||||
created_at = activity_updated_at
|
||||
@@ -625,95 +496,3 @@ def _scan_transcript_row(
|
||||
"size": signature[_WEBUI_ACTIVITY_SIZE],
|
||||
**signature,
|
||||
}
|
||||
|
||||
|
||||
def _scan_session_row(
|
||||
session_manager: SessionManager,
|
||||
path: Path,
|
||||
webui_dir: Path,
|
||||
) -> dict[str, Any] | None:
|
||||
storage_key = SessionManager._session_key_from_path(path) # pyright: ignore[reportPrivateUsage]
|
||||
if storage_key is None:
|
||||
return None
|
||||
try:
|
||||
signature = _file_signature(path)
|
||||
with open(path, encoding="utf-8") as f:
|
||||
first_line = f.readline().strip()
|
||||
if not first_line:
|
||||
return None
|
||||
data = json.loads(first_line)
|
||||
if data.get("_type") != "metadata":
|
||||
return None
|
||||
preview = ""
|
||||
fallback_preview = ""
|
||||
visible_message_at = None
|
||||
preview_done = False
|
||||
scanned_records = 0
|
||||
scanned_chars = 0
|
||||
for line in f:
|
||||
if not line.strip():
|
||||
continue
|
||||
if _is_provider_state_record_line(line):
|
||||
continue
|
||||
item = json.loads(line)
|
||||
if item.get("_type") == _PROVIDER_STATE_RECORD_TYPE:
|
||||
continue
|
||||
timestamp = _visible_message_timestamp(item)
|
||||
if timestamp is not None:
|
||||
visible_message_at = _latest_updated_at(visible_message_at, timestamp)
|
||||
if not preview_done:
|
||||
scanned_records += 1
|
||||
scanned_chars += len(line)
|
||||
if (
|
||||
scanned_records > _SESSION_LIST_PREVIEW_MAX_RECORDS
|
||||
or scanned_chars > _SESSION_LIST_PREVIEW_MAX_CHARS
|
||||
):
|
||||
preview_done = True
|
||||
continue
|
||||
if item.get("_type") == "metadata":
|
||||
continue
|
||||
if is_hidden_history_message(item):
|
||||
continue
|
||||
text = _message_preview_text(item)
|
||||
if not text:
|
||||
continue
|
||||
if item.get("role") == "user":
|
||||
preview = text
|
||||
preview_done = True
|
||||
continue
|
||||
if not fallback_preview and item.get("role") == "assistant":
|
||||
fallback_preview = text
|
||||
created_at_s = data.get("created_at")
|
||||
updated_at_s = data.get("updated_at")
|
||||
if not created_at_s or not updated_at_s:
|
||||
fallback_time = datetime.fromtimestamp(signature["mtime_ns"] / 1e9).isoformat()
|
||||
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", {})
|
||||
activity_signature = _webui_activity_signature(key, webui_dir)
|
||||
activity_updated_at = _webui_activity_updated_at(activity_signature)
|
||||
return {
|
||||
"key": key,
|
||||
"created_at": created_at_s,
|
||||
"updated_at": _visible_activity_updated_at(
|
||||
updated_at_s,
|
||||
visible_message_at,
|
||||
activity_updated_at,
|
||||
),
|
||||
"title": _metadata_title(metadata),
|
||||
"preview": preview or fallback_preview,
|
||||
_MODEL_PRESET_FIELD: model_preset_from_metadata(metadata),
|
||||
"recovery_state": recovery_state_from_metadata(metadata),
|
||||
**_indexed_workspace_scope_fields(metadata),
|
||||
_ROW_SOURCE_FIELD: _SESSION_SOURCE,
|
||||
"file": path.name,
|
||||
"mtime_ns": signature["mtime_ns"],
|
||||
"size": signature["size"],
|
||||
**activity_signature,
|
||||
}
|
||||
except Exception:
|
||||
repaired = session_manager._repair(storage_key) # pyright: ignore[reportPrivateUsage]
|
||||
if repaired is None:
|
||||
return None
|
||||
return _indexed_row_for_session(repaired, path, webui_dir)
|
||||
Reference in new issue
Block a user