Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
feat(chat): clearing a workflow's chat makes its agents forget it too
trohitg8cab5d775bac
diff --git a/CLAUDE.md b/CLAUDE.mdindex 55c24395..96789ffa 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -1006,7 +1006,7 @@ class ChatMessage(SQLModel, table=True):|---------|-------------|| `send_chat_message` | Save the message and dispatch it to the workflow's chatTriggers. A workflow session answers `delivery: "now"` (running / starting / resuming) or `"queued"` (paused / pausing, runs on Resume); in any other state `not_running`, saving nothing || `get_chat_messages` | A session's messages, oldest first: `{id, role, message, timestamp, run_key}` (UTC-offset timestamps; `run_key` = the generation). The latest generation only (none after a Reset), unless `all_generations` (Home's thread; a Reset clears the thread, so only a row from before a Start shows beside the live ones) |-| `clear_chat_messages` | Clear all messages for session |+| `clear_chat_messages` | Clear a session's chat, every generation; for a workflow's session its agents forget the conversation too (`chat_thread.clear_chat_session` tells the listeners registered with `register_chat_cleared_listener`: the Context plugin clears the workflow's conversations) || `save_chat_message` | Save one message with the given role |**Database Methods** (`server/core/database.py`):diff --git a/client/src/components/ui/ConsolePanel.tsx b/client/src/components/ui/ConsolePanel.tsxindex 6cec5707..9ee73c3c 100644--- a/client/src/components/ui/ConsolePanel.tsx+++ b/client/src/components/ui/ConsolePanel.tsx@@ -397,6 +397,7 @@ const ConsolePanel: React.FC<ConsolePanelProps> = ({variant="outline"size="xs"onClick={handleClearChat}+ title="Clear the chat, and what the agent remembers of it"className="border-destructive/40 text-destructive hover:bg-destructive/10">Cleardiff --git a/docs-internal/agent_context_flow.md b/docs-internal/agent_context_flow.mdindex 3bf3946b..0c0a1e31 100644--- a/docs-internal/agent_context_flow.md+++ b/docs-internal/agent_context_flow.md@@ -232,7 +232,14 @@ messages}`, where `messages` is the requested `agent_node_id`'s transcript,else the newest row's; `clear_agent_context` deletes rows and fences warmclaude processes), and one CloudEvents broadcast (`context.updated`, fired from theregistered save listener; payload is identity + count only — the panel-refetches through the authorized handler). The node declares **no+refetches through the authorized handler). Both ways of forgetting share+`_handlers.forget_conversations` (delete, fence warm claude processes,+announce). The plugin also registers `on_chat_cleared` with+`services/chat_thread.register_chat_cleared_listener`: when the owner clears+a workflow's chat (`clear_chat_messages` → `clear_chat_session`), every+conversation of that workflow goes too, so the agent starts over with the+chat. A Reset forgets them through the node's `reset_execution_state`, and+clears the chat thread through the chat nodes' own Reset hook. The node declares **noparameters**; the connection is the whole configuration.The node is optional and user-owned. `normalize_workflow_graph` neverdiff --git a/docs-internal/normal_mode.md b/docs-internal/normal_mode.mdindex 916e33e0..4c007ecf 100644--- a/docs-internal/normal_mode.md+++ b/docs-internal/normal_mode.md@@ -355,7 +355,10 @@ row goes throughmessages from `send_chat_message`, answers and reports from the[chatReply](./node-logic-flows/chat_utility/chatReply.md) ("Reply in Chat")node. Each row is stamped with the live generation, and each insert or clear-is announced as `chat.updated`.+is announced as `chat.updated`. Clearing the chat in the editor's chat pane+(`clear_chat_messages`, `chat_thread.clear_chat_session`) deletes the thread+and, through the Context plugin's chat-cleared listener, every conversation+of the workflow, so the employee starts over with the chat.### On the employee's pagediff --git a/server/nodes/context/__init__.py b/server/nodes/context/__init__.pyindex 1451b3c4..0bf85a00 100644--- a/server/nodes/context/__init__.py+++ b/server/nodes/context/__init__.py@@ -148,6 +148,7 @@ __all__ = [from services.agent_context.listeners import ( # noqa: E402register_conversation_listener,)+from services.chat_thread import register_chat_cleared_listener # noqa: E402from services.plugin.edge_walker import ( # noqa: E402register_agent_context_builder,)@@ -155,7 +156,7 @@ from services.ws_handler_registry import register_ws_handlers # noqa: E402from ._descriptor import build_agent_context_descriptor # noqa: E402from ._events import on_conversation_saved # noqa: E402-from ._handlers import WS_HANDLERS # noqa: E402+from ._handlers import WS_HANDLERS, on_chat_cleared # noqa: E402register_ws_handlers(WS_HANDLERS)# The framework walks `input-context` edges but knows nothing about this@@ -165,3 +166,6 @@ register_agent_context_builder(build_agent_context_descriptor)# `context.updated` broadcast. Registering here keeps the store free of any# knowledge that a UI exists.register_conversation_listener(on_conversation_saved)+# The owner's chat Clear forgets the conversation too, so the agent starts+# over with the chat (services/chat_thread.clear_chat_session).+register_chat_cleared_listener(on_chat_cleared)diff --git a/server/nodes/context/_handlers.py b/server/nodes/context/_handlers.pyindex 223142ba..439daf16 100644--- a/server/nodes/context/_handlers.py+++ b/server/nodes/context/_handlers.py@@ -172,31 +172,23 @@ async def handle_get_agent_context(}-@ws_response-async def handle_clear_agent_context(- data: Dict[str, Any],- websocket: WebSocket,-) -> Dict[str, Any]:- """Delete stored conversations for one workflow's Context node.-- Narrowable by ``generation`` and/or ``agent_node_id``; without either,- every conversation for the workflow is deleted. Warm claude+async def forget_conversations(+ database: Any,+ *,+ workflow_id: str,+ announce_as: str,+ generation: Optional[int] = None,+ agent_node_id: Optional[str] = None,+) -> int:+ """Delete stored conversations, every one of the workflow's unless+ narrowed by ``generation`` and/or ``agent_node_id``. Warm claudesubprocesses holding a cleared conversation in memory are terminated so- the next turn cannot silently continue from wiped state.- """-- workflow_id = str(data.get("workflow_id") or "")- context_node_id = str(data.get("context_node_id") or "")- await _authorize_context_node(- websocket=websocket,- workflow_id=workflow_id,- context_node_id=context_node_id,- )- generation = _optional_generation(data)- agent_node_id = str(data.get("agent_node_id") or "") or None+ the next turn cannot silently continue from wiped state, and+ ``context.updated`` (subject ``announce_as``) refreshes an open panel.+ Returns the conversations deleted."""cleared = await clear_conversation(- _database(),+ database,workflow_id=workflow_id,generation=generation,agent_node_id=agent_node_id,@@ -217,11 +209,49 @@ async def handle_clear_agent_context(await dispatch_context_updated(workflow_id=workflow_id,generation=generation or 0,- agent_node_id=agent_node_id or context_node_id,+ agent_node_id=announce_as,message_count=0,)except Exception as exc:logger.debug("[Context] clear broadcast failed: %s", exc)+ return cleared+++async def on_chat_cleared(*, database: Any, workflow_id: str) -> None:+ """The owner cleared the workflow's chat (services/chat_thread+ ``clear_chat_session``): its agents forget the conversation too, so they+ start over with the chat. Every conversation of the workflow, as a+ Reset clears them."""++ await forget_conversations(database, workflow_id=workflow_id, announce_as=workflow_id)+++@ws_response+async def handle_clear_agent_context(+ data: Dict[str, Any],+ websocket: WebSocket,+) -> Dict[str, Any]:+ """Delete stored conversations for one workflow's Context node.++ Narrowable by ``generation`` and/or ``agent_node_id``; without either,+ every conversation for the workflow is deleted (``forget_conversations``).+ """++ workflow_id = str(data.get("workflow_id") or "")+ context_node_id = str(data.get("context_node_id") or "")+ await _authorize_context_node(+ websocket=websocket,+ workflow_id=workflow_id,+ context_node_id=context_node_id,+ )+ agent_node_id = str(data.get("agent_node_id") or "") or None+ cleared = await forget_conversations(+ _database(),+ workflow_id=workflow_id,+ announce_as=agent_node_id or context_node_id,+ generation=_optional_generation(data),+ agent_node_id=agent_node_id,+ )return {"success": True, "cleared": cleared}@@ -234,6 +264,8 @@ WS_HANDLERS: Dict[str, WSHandler] = {__all__ = ["WS_HANDLERS",+ "forget_conversations","handle_clear_agent_context","handle_get_agent_context",+ "on_chat_cleared",]diff --git a/server/routers/websocket.py b/server/routers/websocket.pyindex cd4ba243..8ef7cadf 100644--- a/server/routers/websocket.py+++ b/server/routers/websocket.py@@ -1168,11 +1168,14 @@ async def handle_get_chat_messages(data: Dict[str, Any], websocket: WebSocket) -@ws_handler()async def handle_clear_chat_messages(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:- """Clear all chat messages for a session."""- from services.chat_thread import clear_chat_thread+ """Clear a session's chat, every generation of it. For a workflow's+ session the agent forgets the conversation too+ (``services.chat_thread.clear_chat_session``: the Context plugin clears+ the workflow's conversations), so it starts over with the chat."""+ from services.chat_thread import clear_chat_sessionsession_id = data.get("session_id", "default")- count = await clear_chat_thread(container.database(), session_id)+ count = await clear_chat_session(container.database(), session_id)return {"success": True, "message": f"Cleared {count} chat messages", "cleared_count": count}diff --git a/server/services/chat_thread.py b/server/services/chat_thread.pyindex 2f15dbe4..a4e58c19 100644--- a/server/services/chat_thread.py+++ b/server/services/chat_thread.py@@ -17,6 +17,10 @@ Talk, and the editor shows it in its chat pane.there), then announce it.- ``clear_chat_thread``: delete the session's rows, every generation, thenannounce it when there were any.+- ``clear_chat_session``: the owner's Clear. The thread goes, and the+ listeners registered with ``register_chat_cleared_listener`` forget what+ it held: the Context plugin clears the workflow's conversations, so the+ agent starts over with the chat.A workflow's thread lives as long as its generation and its workflow. AReset (every restart, Home's Apply and Turn on Talk included) clears it@@ -39,13 +43,20 @@ query that matches nothing on every message (the same reason asfrom __future__ import annotations-from typing import Any, Optional+from typing import Any, Awaitable, Callable, List, Optionalfrom core.logging import get_loggerfrom services.events.envelope import WorkflowEventlogger = get_logger(__name__)+#: ``await listener(database=..., workflow_id=...)`` after the owner clears+#: a workflow's chat. Plugins register (this module never imports+#: ``nodes/``); a Reset and a workflow delete forget the conversation+#: through their own paths.+ChatClearedListener = Callable[..., Awaitable[None]]+_CLEARED_LISTENERS: List[ChatClearedListener] = []+#: The editor's chat when no workflow is open: not a workflow's thread.DEFAULT_SESSION = "default"WIRE_KEY = "chat.updated"@@ -120,12 +131,45 @@ async def clear_chat_thread(database: Any, session_id: str) -> int:return count+def register_chat_cleared_listener(listener: ChatClearedListener) -> None:+ """Run ``await listener(database=..., workflow_id=...)`` after the owner+ clears a workflow's chat. Registering the same listener twice is a+ no-op."""+ if listener not in _CLEARED_LISTENERS:+ _CLEARED_LISTENERS.append(listener)+++async def clear_chat_session(database: Any, session_id: str) -> int:+ """The owner's Clear: delete the thread, then let the listeners forget+ what it held, so the agent starts over with the chat. Only a workflow's+ session has listeners to tell (``"default"`` is no workflow's). A+ failing listener is logged and never fails the clear. Returns the rows+ deleted."""+ count = await clear_chat_thread(database, session_id)+ if session_id == DEFAULT_SESSION:+ return count+ for listener in list(_CLEARED_LISTENERS):+ try:+ await listener(database=database, workflow_id=session_id)+ except Exception:+ logger.warning(+ "Chat-cleared listener failed",+ listener=getattr(listener, "__qualname__", repr(listener)),+ workflow_id=session_id,+ exc_info=True,+ )+ return count++__all__ = ["DEFAULT_SESSION","WIRE_KEY",+ "ChatClearedListener","chat_execution_id","chat_updated",+ "clear_chat_session","clear_chat_thread","delivery_for","record_chat_message",+ "register_chat_cleared_listener",]diff --git a/server/tests/nodes/test_context_handlers.py b/server/tests/nodes/test_context_handlers.pyindex 75cff7a7..993fb3fb 100644--- a/server/tests/nodes/test_context_handlers.py+++ b/server/tests/nodes/test_context_handlers.py@@ -177,6 +177,48 @@ async def test_workflow_reset_clears_the_stored_conversations(assert broadcasts and broadcasts[0]["workflow_id"] == "wf-1"+async def test_clearing_the_chat_forgets_the_workflows_conversations(+ handler_database, monkeypatch+):+ """The owner's chat Clear (services/chat_thread.clear_chat_session)+ reaches the plugin's listener: every conversation of that workflow+ goes, so the agent starts over with the chat; other workflows keep+ theirs."""++ from nodes.context import _handlers+ from services import chat_thread+ from services.agent_context import list_conversations++ assert _handlers.on_chat_cleared in chat_thread._CLEARED_LISTENERS++ database = handler_database+ for workflow_id, generation in (("wf-1", 1), ("wf-1", 2), ("wf-2", 1)):+ await save_conversation(+ database,+ workflow_id=workflow_id,+ generation=generation,+ agent_node_id="agent-a",+ messages=[{"role": "user", "content": "what did I ask?"}],+ )++ broadcasts: list[dict] = []++ async def capture(**kwargs):+ broadcasts.append(kwargs)++ monkeypatch.setattr(_handlers, "dispatch_context_updated", capture)++ await _handlers.on_chat_cleared(database=database, workflow_id="wf-1")++ assert await list_conversations(database, workflow_id="wf-1") == []+ assert len(await list_conversations(database, workflow_id="wf-2")) == 1+ # An open Context panel refreshes off the broadcast.+ assert broadcasts == [+ {"workflow_id": "wf-1", "generation": 0, "agent_node_id": "wf-1", "message_count": 0}+ ]++@pytest.mark.asyncioasync def test_reset_without_an_admitted_generation_is_a_no_op(handler_database,diff --git a/server/tests/services/test_chat_thread.py b/server/tests/services/test_chat_thread.pyindex 41a3ca79..2d9548ff 100644--- a/server/tests/services/test_chat_thread.py+++ b/server/tests/services/test_chat_thread.py@@ -68,6 +68,8 @@ def router(monkeypatch, database, frames):monkeypatch.setattr(ws_router, "container", SimpleNamespace(database=lambda: database))monkeypatch.setattr(chat_events, "dispatch_chat_message_received", dispatch)+ # The Clear's listeners are whatever a test registers, never the plugins'.+ monkeypatch.setattr(chat_thread, "_CLEARED_LISTENERS", [])return SimpleNamespace(database=database, frames=frames, dispatched=dispatched)@@ -256,6 +258,31 @@ async def test_after_a_reset_the_live_read_is_empty(router):assert len((await ws_router.handle_get_chat_messages({"session_id": "7", "all_generations": True}, None))["messages"]) == 1+async def test_the_owners_clear_lets_the_agent_forget_too(router):+ heard: list = []++ async def forget(*, database, workflow_id):+ heard.append((database, workflow_id))++ async def broken(**_):+ raise RuntimeError("a listener that fails")++ chat_thread.register_chat_cleared_listener(broken)+ chat_thread.register_chat_cleared_listener(forget)+ chat_thread.register_chat_cleared_listener(forget) # registering twice is a no-op+ await router.database.add_chat_message("7", "user", "hello", execution_id="gen-1")++ cleared = await ws_router.handle_clear_chat_messages({"session_id": "7"}, None)+ assert cleared["cleared_count"] == 1+ assert await router.database.get_chat_messages("7") == []+ # A failing listener never fails the clear, nor stops the next one.+ assert heard == [(router.database, "7")]++ # The editor's "default" chat is no workflow's: nothing to forget.+ await ws_router.handle_clear_chat_messages({"session_id": "default"}, None)+ assert heard == [(router.database, "7")]++async def test_save_and_clear_go_through_the_thread(router):await control(router.database, "7", "running", generation=4)saved = await ws_router.handle_save_chat_message({"message": "An answer", "role": "assistant", "session_id": "7"}, None)