Agent Zero AI framework
Prune deleted saved chats from sidebar state
Alessandro6ab402172f14
diff --git a/helpers/persist_chat.py b/helpers/persist_chat.pyindex 2fbc1111c..199fa3ef5 100644--- a/helpers/persist_chat.py+++ b/helpers/persist_chat.py@@ -14,6 +14,7 @@ from helpers.log import Log, LogItemCHATS_FOLDER = "usr/chats"LOG_SIZE = 1000CHAT_FILE_NAME = "chat.json"+SAVED_CHAT_CONTEXT_DATA_KEY = "_persist_chat_saved"def _fallback_datetime_iso() -> str:@@ -54,6 +55,7 @@ def save_tmp_chat(context: AgentContext):data = _serialize_context(context)js = _safe_json_serialize(data, ensure_ascii=False)files.write_file(path, js)+ mark_chat_saved(context)def save_tmp_chats():@@ -81,6 +83,7 @@ def load_tmp_chats():js = files.read_file(file)data = json.loads(js)ctx = _deserialize_context(data)+ mark_chat_saved(ctx)ctxids.append(ctx.id)except Exception as e:print(f"Error loading chat {file}: {e}")@@ -91,6 +94,19 @@ def _get_chat_file_path(ctxid: str):return files.get_abs_path(CHATS_FOLDER, ctxid, CHAT_FILE_NAME)+def mark_chat_saved(context: AgentContext) -> None:+ context.data[SAVED_CHAT_CONTEXT_DATA_KEY] = True+++def saved_chat_ids() -> set[str]:+ return {+ files.basename(files.dirname(path))+ for path in files.find_existing_paths_by_pattern(+ files.get_abs_path(CHATS_FOLDER, "*", CHAT_FILE_NAME)+ )+ }++def _convert_v080_chats():json_files = files.list_files(CHATS_FOLDER, "*.json")for file in json_files:diff --git a/helpers/persist_chat.py.dox.md b/helpers/persist_chat.py.dox.mdindex 262013e9f..e75fe80d5 100644--- a/helpers/persist_chat.py.dox.md+++ b/helpers/persist_chat.py.dox.md@@ -24,6 +24,8 @@- `export_json_chat(context: AgentContext)`: Export context as JSON string- `remove_chat(ctxid)`: Remove a chat or task context- `remove_msg_files(ctxid)`: Remove all message files for a chat or task context+- `mark_chat_saved(context: AgentContext) -> None`+- `saved_chat_ids() -> set[str]`- `_serialize_context(context: AgentContext)`- `_serialize_agent(agent: Agent)`- `_serialize_log(log: Log)`@@ -32,7 +34,7 @@- `_deserialize_agents(agents: list[dict[str, Any]], config: AgentConfig, context: AgentContext) -> Agent`- `_deserialize_log(data: dict[str, Any]) -> 'Log'`- `_safe_json_serialize(obj, **kwargs)`-- Notable constants/configuration names: `CHATS_FOLDER`, `LOG_SIZE`, `CHAT_FILE_NAME`.+- Notable constants/configuration names: `CHATS_FOLDER`, `LOG_SIZE`, `CHAT_FILE_NAME`, `SAVED_CHAT_CONTEXT_DATA_KEY`.## Runtime Contracts@@ -43,6 +45,7 @@- Serialized chats store `agent_profile` both at the context level for the main chat and on each serialized agent so subordinate profiles survive server restart.- Deserialization must rebuild each agent with its serialized profile when present, falling back to the context profile for older chat files.- Chat loading skips directories that do not contain `chat.json`; malformed existing chat files still report load errors.+- Contexts are marked with private `SAVED_CHAT_CONTEXT_DATA_KEY` only after a successful save or load from disk so snapshot code can detect deleted chat files without hiding fresh unsaved chats.## Key Conceptsdiff --git a/helpers/state_snapshot.py b/helpers/state_snapshot.pyindex a51f6239e..9a1db075d 100644--- a/helpers/state_snapshot.py+++ b/helpers/state_snapshot.py@@ -140,6 +140,20 @@ def _apply_agent_profile_metadata(context_data["agent_profile_label"] = labels.get(profile, profile) if profile else ""+def _prune_missing_saved_contexts() -> None:+ from helpers import persist_chat++ saved_ids = persist_chat.saved_chat_ids()+ for ctx in AgentContext.all():+ if ctx.type == AgentContextType.BACKGROUND or ctx.is_running():+ continue+ if (+ ctx.data.get(persist_chat.SAVED_CHAT_CONTEXT_DATA_KEY)+ and ctx.id not in saved_ids+ ):+ AgentContext.remove(ctx.id)++def parse_state_request_payload(payload: Mapping[str, Any]) -> StateRequestV1:context = payload.get("context")log_from = payload.get("log_from")@@ -255,6 +269,8 @@ async def build_snapshot_from_request(*, request: StateRequestV1) -> SnapshotV1:from_no = _coerce_non_negative_int(request.log_from, default=0)notifications_from_no = _coerce_non_negative_int(request.notifications_from, default=0)+ _prune_missing_saved_contexts()+active_context = AgentContext.get(ctxid) if ctxid else Noneif active_context:diff --git a/helpers/state_snapshot.py.dox.md b/helpers/state_snapshot.py.dox.mdindex ac27b97c5..69fccccf2 100644--- a/helpers/state_snapshot.py.dox.md+++ b/helpers/state_snapshot.py.dox.md@@ -21,6 +21,7 @@- `_coerce_non_negative_int(value: Any, default: int=...) -> int`- `_get_agent_profile_labels() -> dict[str, str]`- `_apply_agent_profile_metadata(context_data: dict[str, Any], ctx: AgentContext, labels: dict[str, str]) -> None`+- `_prune_missing_saved_contexts() -> None`- `parse_state_request_payload(payload: Mapping[str, Any]) -> StateRequestV1`- `_coerce_state_request_inputs(context: Any, log_from: Any, notifications_from: Any, timezone: Any) -> StateRequestV1`- `advance_state_request_after_snapshot(request: StateRequestV1, snapshot: Mapping[str, Any]) -> StateRequestV1`@@ -33,12 +34,13 @@- Helper modules own reusable framework APIs and must preserve public callers unless all callers, tests, and docs are updated together.- Update this file whenever public functions, classes, persistence behavior, path/security assumptions, side effects, or cross-module contracts change.-- Observed side-effect areas: plugin state, settings/state persistence, secret handling, scheduler state.-- Imported dependency areas include: `__future__`, `agent`, `dataclasses`, `helpers.dotenv`, `helpers.localization`, `helpers.task_scheduler`, `pytz`, `types`, `typing`.+- Observed side-effect areas: filesystem reads, plugin state, settings/state persistence, secret handling, scheduler state, in-memory context removal.+- Imported dependency areas include: `__future__`, `agent`, `dataclasses`, `helpers.dotenv`, `helpers.localization`, `helpers.persist_chat`, `helpers.task_scheduler`, `pytz`, `types`, `typing`.## Key Concepts- Important called helpers/classes observed in the source: `dataclass`, `_build_schema_from_typeddict`, `get_origin`, `timezone.strip`, `StateRequestV1`, `localization.get_timezone`, `localization.set_timezone`, `ctxid.strip`, `_coerce_non_negative_int`, `AgentContext.get_notification_manager`, `notification_manager.output`, `_get_agent_profile_labels`, `ctxs.sort`, `tasks.sort`, `validate_snapshot_schema_v1`, `_coerce_state_request_inputs`, `super.__init__`, `get_args`, `_annotation_to_isinstance_types`, `TypeError`.+- Snapshot building prunes non-running in-memory contexts that were previously saved but no longer have a `chat.json`, preventing stale sidebar rows after chat files are deleted outside `/chat_remove`.- Keep request/response, tool, or helper semantics documented here at the same time as source changes.## Work Guidancediff --git a/tests/test_persist_chat_log_ids.py b/tests/test_persist_chat_log_ids.pyindex 53120375f..d9c97f3f7 100644--- a/tests/test_persist_chat_log_ids.py+++ b/tests/test_persist_chat_log_ids.py@@ -48,7 +48,7 @@ def test_load_tmp_chats_skips_directories_without_chat_json(monkeypatch, capsys)monkeypatch.setattr(persist_chat,"_deserialize_context",- lambda data: SimpleNamespace(id=data["id"]),+ lambda data: SimpleNamespace(id=data["id"], data={}),)assert persist_chat.load_tmp_chats() == ["valid"]diff --git a/tests/test_snapshot_parity.py b/tests/test_snapshot_parity.pyindex 4364426b7..ddb433609 100644--- a/tests/test_snapshot_parity.py+++ b/tests/test_snapshot_parity.py@@ -75,3 +75,34 @@ async def test_snapshot_builder_active_context_includes_incremental_logs():assert second["log_version"] == first["log_version"]finally:AgentContext.remove(ctxid)+++async def test_snapshot_prunes_saved_context_missing_from_chat_files(monkeypatch):+ from helpers import persist_chat+ from helpers import state_snapshot as snapshot++ missing_id = "ctx-saved-missing-chat-file"+ unsaved_id = "ctx-unsaved-chat-file"+ missing = AgentContext(config=initialize_agent(), id=missing_id, set_current=False)+ unsaved = AgentContext(config=initialize_agent(), id=unsaved_id, set_current=False)+ persist_chat.mark_chat_saved(missing)+ monkeypatch.setattr(persist_chat, "saved_chat_ids", lambda: set())++ try:+ payload = await snapshot.build_snapshot(+ context=missing_id,+ log_from=0,+ notifications_from=0,+ timezone="UTC",+ )++ context_ids = {ctx["id"] for ctx in payload["contexts"]}+ assert payload["deselect_chat"] is True+ assert payload["context"] == ""+ assert missing_id not in context_ids+ assert unsaved_id in context_ids+ assert AgentContext.get(missing_id) is None+ finally:+ AgentContext.remove(missing_id)+ AgentContext.remove(unsaved_id)