Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
fix(home): clear the chat on every restart, and draw both sides alike
trohitgb6f87a0154f5
diff --git a/CLAUDE.md b/CLAUDE.mdindex 74c15425..55c24395 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -987,7 +987,7 @@ const [selectedConsoleId, setSelectedConsoleId] = useState<string>('');```#### Chat Message Persistence-Chat messages are persisted to SQLite database and survive server restarts. A workflow's session id is its workflow id (`"default"` with no workflow open), and Home shows the same thread as Talk on the employee's page. Every row is written through [`services/chat_thread.py`](./server/services/chat_thread.py) (`record_chat_message` / `clear_chat_thread`), which stamps the session's live generation and broadcasts the identity-only `chat.updated`; agents answer into the thread through the `chatReply` ("Reply in Chat") node.+Chat messages are persisted to SQLite database and survive server restarts. A workflow's session id is its workflow id (`"default"` with no workflow open), and Home shows the same thread as Talk on the employee's page. Every row is written through [`services/chat_thread.py`](./server/services/chat_thread.py) (`record_chat_message` / `clear_chat_thread`), which stamps the session's live generation and broadcasts the identity-only `chat.updated`; agents answer into the thread through the `chatReply` ("Reply in Chat") node. The thread lives as long as the generation: a workflow Reset (every restart, Home's Apply and Turn on Talk included) clears it through the `chatTrigger` / `chatReply` `reset_execution_state` hook, in the same Reset in which the Context node forgets the conversation, and deleting the workflow deletes it (a workflow-deleted hook the `chatReply` plugin registers).**Database Model** (`server/models/database.py`):```python@@ -1005,7 +1005,7 @@ class ChatMessage(SQLModel, table=True):| Handler | Description ||---------|-------------|| `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 spans restarts) |+| `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 || `save_chat_message` | Save one message with the given role |diff --git a/client/src/contexts/WebSocketContext.tsx b/client/src/contexts/WebSocketContext.tsxindex 50db496d..d92ab9ca 100644--- a/client/src/contexts/WebSocketContext.tsx+++ b/client/src/contexts/WebSocketContext.tsx@@ -1810,7 +1810,8 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chireturn next;});queryClient.removeQueries({ queryKey: queryKeys.compactionStats._def });- // Home's thread spans restarts: refetch it rather than clear it.+ // The Reset cleared the thread on the server (the chat nodes'+ // Reset hook); Home refetches it.void queryClient.invalidateQueries({ queryKey: queryKeys.chatThread.bySession(workflowId).queryKey });if (useAppStore.getState().currentWorkflow?.id === workflowId) {setConsoleLogs([]);diff --git a/client/src/features/home/data/talk.ts b/client/src/features/home/data/talk.tsindex 50b854e7..35a60e23 100644--- a/client/src/features/home/data/talk.ts+++ b/client/src/features/home/data/talk.ts@@ -2,8 +2,9 @@* Talking to an employee on its page, over the chat session whose id is the* employee's workflow id:*- * - `useTalkThread(workflowId)`: the conversation across restarts- * (`get_chat_messages` with `all_generations`), the newest 200 messages.+ * - `useTalkThread(workflowId)`: the conversation (`get_chat_messages` with+ * `all_generations`, so a message from before a Start shows too), the+ * newest 200 messages. A Reset clears the thread on the server.* WebSocketContext invalidates it on `chat.updated`, on a runtime reset* and when the socket reopens.* - `useSendTalkMessage(workflowId)`: `send_chat_message`. The message showsdiff --git a/client/src/features/home/employee/EmployeeTalk.tsx b/client/src/features/home/employee/EmployeeTalk.tsxindex f11f3fbf..4f769f30 100644--- a/client/src/features/home/employee/EmployeeTalk.tsx+++ b/client/src/features/home/employee/EmployeeTalk.tsx@@ -2,10 +2,12 @@* Talking to an employee, under their name: the conversation, and a message* box pinned to the bottom of the page.*- * - The thread keeps every message across restarts, with a divider where- * the employee restarted (they start fresh from there). Replies,- * questions and routine reports all land in it, and `drafts` (the ones- * waiting for the owner's OK) follow the messages.+ * - The thread is the conversation since the employee last started: a+ * restart clears it on the server, as the employee forgets it too. A+ * message left from before a Start (a test run in Dev mode) sits above a+ * divider saying they started fresh. Replies, questions and routine+ * reports all land in it, and `drafts` (the ones waiting for the owner's+ * OK) follow the messages.* - While the employee runs, a message goes to them at once, and* "Working…" holds the box until they answer (useReplyWait); overlapping* runs would each save over the other's conversation. While they are@@ -46,23 +48,36 @@ const ThreadMarkdown = lazy(() => import('./ThreadMarkdown'));/** Lines up an answer's time under its text, past the avatar. */const PAST_AVATAR = 'pl-10.5';+/*+ * One bubble for both sides of the conversation: the same raised surface,+ * border and type in every theme. Only the side (the owner's on the right,+ * the employee's on the left beside their avatar) and the corner that+ * points at the speaker differ. `chat-msg-user` / `chat-msg-bot` are the+ * theme hooks the editor's chat pane carries too.+ */+const BUBBLE =+ 'chat-msg min-w-0 max-w-4/5 border border-border-default bg-bg-elevated px-3.5 py-2.5 text-md leading-normal break-words';+const MINE = 'chat-msg-user rounded-l-card rounded-br-card rounded-tr-sm text-fg-default';+const THEIRS = 'chat-msg-bot rounded-r-card rounded-bl-card rounded-tl-sm';+function MessageRow({ message, employee, now }: { message: ThreadMessage; employee: EmployeeSummary; now: Date }) {const mine = message.role === 'user';const time = message.pending ? 'Sending…' : timeLabel(message.timestamp, now);- const text = 'm-0 min-w-0 text-md leading-normal break-words whitespace-pre-wrap text-fg-default';return (<div data-message={message.id} className={cn('flex flex-col gap-1', mine ? 'items-end' : 'items-start')}>{mine ? (- <p className={cn(text, 'max-w-4/5 rounded-card border border-border-default bg-bg-panel px-3.5 py-2.5')}>{message.message}</p>+ <p className={cn('m-0 whitespace-pre-wrap', BUBBLE, MINE)}>{message.message}</p>) : (- <div className="flex w-full gap-3">+ <div className="flex w-full items-start gap-3"><Avatar name={employee.name} colorRole={employee.color_role} size="sm" />- <Suspense fallback={<p className={text}>{message.message}</p>}>- <ThreadMarkdown text={message.message} />- </Suspense>+ <div className={cn(BUBBLE, THEIRS, 'text-fg-default')}>+ <Suspense fallback={<p className="m-0 whitespace-pre-wrap">{message.message}</p>}>+ <ThreadMarkdown text={message.message} />+ </Suspense>+ </div></div>)}- {time && <span className={cn('font-mono text-2xs text-fg-faint', !mine && PAST_AVATAR)}>{time}</span>}+ {time && <span className={cn('text-xs text-fg-muted', !mine && PAST_AVATAR)}>{time}</span>}</div>);}@@ -235,9 +250,9 @@ function Conversation({ employee, control, drafts }: { employee: EmployeeSummary),)}{waiting && (- <div className="flex items-center gap-3">+ <div className="flex items-start gap-3"><Avatar name={name} colorRole={employee.color_role} size="sm" />- <span className="text-sm text-fg-muted">Working…</span>+ <p className={cn('m-0', BUBBLE, THEIRS, 'text-fg-muted')}>Working…</p></div>)}{unanswered && !waiting && <p className={cn('m-0 text-xs text-fg-muted', PAST_AVATAR)}>No answer from {name} yet.</p>}diff --git a/client/src/features/home/employee/PendingChangesNotice.tsx b/client/src/features/home/employee/PendingChangesNotice.tsxindex f4a4978c..36f8ed6d 100644--- a/client/src/features/home/employee/PendingChangesNotice.tsx+++ b/client/src/features/home/employee/PendingChangesNotice.tsx@@ -38,8 +38,8 @@ export function PendingChangesNotice({ employee }: { employee: EmployeeSummary }return (<div className="flex flex-wrap items-center gap-3 rounded-card border border-border-default bg-bg-panel px-4 py-3"><p className="m-0 min-w-60 flex-1 text-sm text-fg-default">- {name} has new abilities for this conversation. Apply to make them part of all their work (restarts {name}; the- conversation continues after a divider).+ {name} has new abilities for this conversation. Apply to make them part of all their work (restarts {name} and+ clears this conversation).{drafts > 0 && ` ${restartDraftsWarning(name, drafts)}`}</p><ActionButton intent="config" disabled={apply.isPending} onClick={onApply} className="h-9 rounded-row px-4">diff --git a/client/src/features/home/employee/ThreadMarkdown.tsx b/client/src/features/home/employee/ThreadMarkdown.tsxindex a97be7b4..a82def73 100644--- a/client/src/features/home/employee/ThreadMarkdown.tsx+++ b/client/src/features/home/employee/ThreadMarkdown.tsx@@ -1,8 +1,9 @@/**- * An employee's message in the thread, as markdown (lists, links, bold).- * Its own chunk: the talk thread loads it lazily, so the markdown stack- * stays out of Home's first load. Links open in a new tab, so following- * one never leaves the conversation.+ * An employee's message in the thread, as markdown (lists, links, bold),+ * in the type and colour of the bubble around it. Its own chunk: the talk+ * thread loads it lazily, so the markdown stack stays out of Home's first+ * load. Links open in a new tab, so following one never leaves the+ * conversation.*/import ReactMarkdown, { type Components } from 'react-markdown';@@ -15,7 +16,7 @@ const COMPONENTS: Components = {export default function ThreadMarkdown({ text }: { text: string }) {return (- <div className="chat-markdown min-w-0 text-md leading-normal break-words text-fg-default">+ <div className="chat-markdown min-w-0"><ReactMarkdown remarkPlugins={[remarkGfm, remarkBreaks]} components={COMPONENTS}>{text}</ReactMarkdown>diff --git a/docs-internal/node-logic-flows/chat_utility/chatReply.md b/docs-internal/node-logic-flows/chat_utility/chatReply.mdindex f2949637..6b5d871e 100644--- a/docs-internal/node-logic-flows/chat_utility/chatReply.md+++ b/docs-internal/node-logic-flows/chat_utility/chatReply.md@@ -84,7 +84,18 @@ flowchart TDnothing was started since the last Reset). The editor's chat pane reads thelatest generation only, so a row without the stamp would not show therewhile one is live; Home's Talk reads every generation and draws a restart- divider where the stamp changes.+ divider where the stamp changes (a row left from before a Start).+- **Reset** (`reset_execution_state`): clears the workflow's thread, every+ generation, through `chat_thread.clear_chat_thread`. The conversation+ ended with the generation (the Context node forgets it in the same Reset,+ and every restart, Home's Apply and Turn on Talk included, is a Reset), so+ neither Talk nor the editor's chat pane keeps showing it. Returns+ `{reset, cleared_chat_messages}`; `reset` is false when there was nothing+ to clear, as when `chatTrigger`'s identical hook ran first in the same+ Reset.+- **Workflow deleted**: the plugin registers `clear_chat_thread` as a+ workflow-deleted hook (`services/workflow_storage/hooks.py`), so a deleted+ workflow's thread goes with it.- **Error paths**: no `ctx.workflow_id` raises`NodeUserError("Reply in Chat posts to the workflow's chat: save the workflow first.")`(one WARN line, no traceback); a row the database did not save@@ -96,7 +107,8 @@ flowchart TD- **Database writes**: one `chat_messages` row: `session_id` = the workflow id,`role` = `assistant`, `message` = the trimmed text, `execution_id` = the- live generation.+ live generation. On a Reset or a workflow delete, every row of the+ workflow's thread is deleted.- **Broadcasts**: `chat.updated` (CloudEvents `com.opencompany.chat.updated`,data `{workflow_id, session_id, role: "assistant"}`), sent directly throughthe status broadcaster, not `services.events.dispatch.emit`. Home's threaddiff --git a/docs-internal/node-logic-flows/workflow_triggers/chatTrigger.md b/docs-internal/node-logic-flows/workflow_triggers/chatTrigger.mdindex 4358ac14..d29f9ea1 100644--- a/docs-internal/node-logic-flows/workflow_triggers/chatTrigger.md+++ b/docs-internal/node-logic-flows/workflow_triggers/chatTrigger.md@@ -94,10 +94,15 @@ flowchart TD## Side Effects-- **Database writes**: none in the trigger plugin itself. (`send_chat_message`- keeps the message in the session's thread first, through+- **Database writes**: none while it fires. (`send_chat_message` keeps the+ message in the session's thread first, through`services/chat_thread.record_chat_message`, which stamps the live generation- and broadcasts `chat.updated`.)+ and broadcasts `chat.updated`.) On a workflow Reset its+ `reset_execution_state` clears the workflow's own thread (session = the+ workflow id, never a custom `session_id` another workflow may share),+ as `chatReply`'s does: the conversation ended with the generation. It+ matters for a graph with a trigger and no reply yet, such as the one+ Turn on Talk resets before its new reply node runs.- **Broadcasts**: the producer emits a CloudEvents `WorkflowEvent` via`dispatch.emit` (Temporal Signal fan-out + in-process WS broadcast). The`TriggerListenerWorkflow` emits firing-pulse status viadiff --git a/docs-internal/normal_mode.md b/docs-internal/normal_mode.mdindex 5e070890..916e33e0 100644--- a/docs-internal/normal_mode.md+++ b/docs-internal/normal_mode.md@@ -365,14 +365,21 @@ the page (`HomeShell`'s scroll area is a column the view fills). Its queriesand mutations are in [data/talk.ts](../client/src/features/home/data/talk.ts).- **The thread** is `get_chat_messages` with `all_generations: true` (the- newest `THREAD_LIMIT` messages), so it spans restarts. Where a message's- `run_key` (its generation) differs from the one before, a divider reads- "{Name} restarted — they start fresh from here". The owner's messages sit on- the right; answers carry the avatar and render as markdown (`ThreadMarkdown`,- in its own chunk). An empty thread is just the box. The list is an- `aria-live` log. It refetches on `chat.updated`, after a runtime reset,- and when the socket reopens. The drafts waiting for the owner's OK follow- the messages (`EmployeeTalk`'s `drafts`).+ newest `THREAD_LIMIT` messages): the conversation since the employee last+ started, since a Reset clears it (see [Turn on Talk and Apply](#turn-on-talk-and-apply)).+ Where a message's `run_key` (its generation) differs from the one before+ (a message left from before a Start, such as a test run in Dev mode), a+ divider reads "{Name} restarted — they start fresh from here". Both sides+ are one bubble, the same raised surface, border and type in every theme;+ only the side (the owner's on the right, answers on the left beside the+ avatar) and the corner that points at the speaker differ. Answers render+ as markdown (`ThreadMarkdown`, in its own chunk). The bubbles carry+ `chat-msg-user` / `chat-msg-bot`, the theme hooks the editor's chat pane+ uses too. Times, "Working…" and the divider share the body font. An empty+ thread is just the box. The list is an `aria-live` log. It refetches on+ `chat.updated`, after a runtime reset, and when the socket reopens. The+ drafts waiting for the owner's OK follow the messages (`EmployeeTalk`'s+ `drafts`).- **The box** follows the control state the way `send_chat_message` does(`talkMode` in `presentation.ts`):- *send* (running, starting, resuming): a message shows at once@@ -401,8 +408,8 @@ and mutations are in [data/talk.ts](../client/src/features/home/data/talk.ts).setup has no way to answer.- **Pending changes**: while `pending_changes` is true, a notice above the boxreads "{Name} has new abilities for this conversation. Apply to make them- part of all their work (restarts {name}; the conversation continues after a- divider)." Its Apply (`ActionButton intent="config"`) calls+ part of all their work (restarts {name} and clears this conversation)."+ Its Apply (`ActionButton intent="config"`) calls`apply_employee_changes`.- **Asking first**: under the page, a line says whether the employee asksbefore sending anything on the owner's behalf (the summary's `asks_first`).@@ -484,8 +491,13 @@ running → Reset, then Start again (ends running); paused or failed → Reset(ends ready, and the next Start takes the saved graph); ready or neverstarted → nothing to do; starting, pausing, resuming or resetting →`conflict`. The same idempotency key reports the restart it already made. A-Reset clears the workflow's Context conversations (hence the divider), drops-messages queued while paused, and cancels the drafts waiting for the owner.+Reset ends the chat session with the generation: the Context node clears+the workflow's conversations and the chat nodes (`chatTrigger`, `chatReply`)+clear its thread through the same `reset_execution_state` hook, so Talk and+the editor's chat pane never show a conversation the agent no longer has.+It also drops messages queued while paused and cancels the drafts waiting+for the owner. Deleting the workflow deletes its thread (a workflow-deleted+hook `chatReply` registers).`pending_changes` is true while a generation is live (starting, running,pausing, paused, resuming) and the saved graph, put through Start's own@@ -732,10 +744,10 @@ chat's rollback), `lib/__tests__/workflowOps.test.ts` andthe saved node, bind-only). The worker gets it only after Apply.- Messages queued while paused each start a run on Resume; the page allowsone queued message at a time.-- Turn on Talk and Apply reset the employee: its Context conversations start- fresh (the thread's divider says so), messages queued while paused are- dropped, and drafts waiting for the owner are cancelled (the confirmation- and the notice warn about those).+- Turn on Talk and Apply reset the employee: the conversation starts fresh+ (its thread is cleared with the agent's Context), messages queued while+ paused are dropped, and drafts waiting for the owner are cancelled (the+ confirmation and the notice warn about those).- A Dev editor holding unsaved edits made before a server-side change (Turn onTalk, the Agent Builder) can still overwrite it on its next save, becausesaves carry no revision check. Adopting persisted batches narrows thediff --git a/server/nodes/chat/chat_reply/__init__.py b/server/nodes/chat/chat_reply/__init__.pyindex 7520d637..ec37495f 100644--- a/server/nodes/chat/chat_reply/__init__.py+++ b/server/nodes/chat/chat_reply/__init__.py@@ -8,6 +8,11 @@ which stamps the live generation and announces ``chat.updated``.A message that is empty, or exactly NO_REPLY (the agent had nothing tosay), posts nothing.++The thread ends with the workflow's generation: a Reset (every restart)+clears it through ``reset_execution_state``, as the Context node forgets+the conversation in the same Reset, and deleting the workflow deletes it+(the workflow-deleted hook registered below)."""from __future__ import annotations@@ -79,3 +84,30 @@ class ChatReplyNode(ActionNode):if not await record_chat_message(get_database(), ctx.workflow_id, "assistant", text):raise RuntimeError("The reply could not be saved to the chat")return ChatReplyOutput(posted=True, message=text)++ @classmethod+ async def reset_execution_state(+ cls,+ *,+ node_id: str,+ workflow_id: str,+ execution_id: str,+ generation: int,+ graph: dict,+ database,+ ) -> dict:+ """A Reset clears the workflow's thread: the conversation it holds+ ended with the generation (the Context node forgets it in the same+ Reset), so neither Talk nor the editor's chat pane keeps showing it."""+ del node_id, execution_id, generation, graph+ from services.chat_thread import clear_chat_thread++ cleared = await clear_chat_thread(database, str(workflow_id))+ return {"reset": bool(cleared), "cleared_chat_messages": cleared}+++# The thread belongs to its workflow: deleting the workflow deletes it.+from services.chat_thread import clear_chat_thread # noqa: E402+from services.workflow_storage.hooks import register_workflow_deleted_hook # noqa: E402++register_workflow_deleted_hook(clear_chat_thread)diff --git a/server/nodes/trigger/chat_trigger/__init__.py b/server/nodes/trigger/chat_trigger/__init__.pyindex 7acc2f26..313d682f 100644--- a/server/nodes/trigger/chat_trigger/__init__.py+++ b/server/nodes/trigger/chat_trigger/__init__.py@@ -4,6 +4,11 @@ Event-based trigger that fires when the Console panel's chat tabsends a message. Filter narrows to ``session_id`` so two chatTriggernodes with different session IDs receive independent streams.+A Reset clears the workflow's chat thread (``reset_execution_state``), as+``chatReply`` does: a workflow with a trigger and no reply yet (Turn on+Talk resets on that graph before adding the reply) must not carry its old+messages into the next generation.+Replaces:- ``nodes/triggers.py:chatTrigger`` metadata-only registration.- ``event_waiter.build_chat_filter`` stays wired until the generic@@ -66,6 +71,26 @@ class ChatTriggerNode(TriggerNode):async def wait(self, ctx: NodeContext, params: ChatTriggerParams) -> ChatTriggerOutput:raise NotImplementedError("Event triggers return via TriggerNode.execute, not the op body")+ @classmethod+ async def reset_execution_state(+ cls,+ *,+ node_id: str,+ workflow_id: str,+ execution_id: str,+ generation: int,+ graph: Dict[str, Any],+ database: Any,+ ) -> Dict[str, Any]:+ """A Reset clears the workflow's chat thread: the session ended with+ the generation. Only the workflow's own thread (session = workflow+ id), never a custom ``session_id`` another workflow may share."""+ del node_id, execution_id, generation, graph+ from services.chat_thread import clear_chat_thread++ cleared = await clear_chat_thread(database, str(workflow_id))+ return {"reset": bool(cleared), "cleared_chat_messages": cleared}+# Wave 12 C1 rollout #1: opt this trigger into the TriggerListenerWorkflow# consumer path. Producer side: dispatch_chat_message_received indiff --git a/server/routers/websocket.py b/server/routers/websocket.pyindex 9483c486..cd4ba243 100644--- a/server/routers/websocket.py+++ b/server/routers/websocket.py@@ -1140,7 +1140,9 @@ async def handle_get_chat_messages(data: Dict[str, Any], websocket: WebSocket) -"""A session's messages, oldest first, the newest ``limit`` of them:``{id, role, message, timestamp, run_key}``. ``run_key`` is thegeneration the message was written in. The live generation's only,- unless ``all_generations`` (Home's thread, which spans restarts)."""+ unless ``all_generations`` (Home's thread, which also shows a message+ from before a Start). A Reset clears a workflow's thread (the chat+ nodes' Reset hook), so generations rarely mix."""session_id = data.get("session_id", "default")limit = data.get("limit") # Optional limitdiff --git a/server/services/chat_thread.py b/server/services/chat_thread.pyindex 1580c9c0..2f15dbe4 100644--- a/server/services/chat_thread.py+++ b/server/services/chat_thread.py@@ -16,9 +16,18 @@ Talk, and the editor shows it in its chat pane.editor's chat reads one generation, so a row without it would never showthere), then announce it.- ``clear_chat_thread``: delete the session's rows, every generation, then- announce it.--Every insert and clear is announced as ``chat.updated`` (CloudEvent type+ announce it when there were any.++A workflow's thread lives as long as its generation and its workflow. A+Reset (every restart, Home's Apply and Turn on Talk included) clears it+through the chat nodes' ``reset_execution_state`` (``chatTrigger`` and+``chatReply``), in the same Reset in which the Context node forgets the+conversation, so no screen shows a conversation the agent no longer has.+Deleting the workflow deletes its thread (a workflow-deleted hook the+``chatReply`` plugin registers).++Every insert, and every clear that removed rows, is announced as+``chat.updated`` (CloudEvent type``com.opencompany.chat.updated``, data ``{workflow_id, session_id, role}``,``role`` None for a clear). Identity only: the frame reaches every socket,and clients refetch the thread through ``get_chat_messages``. Broadcast@@ -102,10 +111,12 @@ async def record_chat_message(database: Any, session_id: str, role: str, messageasync def clear_chat_thread(database: Any, session_id: str) -> int:- """Delete the thread, every generation of it, and announce it. Returns+ """Delete the thread, every generation of it, and announce it when there+ was anything to delete (a Reset runs one clear per chat node). Returnsthe rows deleted."""count = await database.clear_chat_messages(session_id)- await _announce(session_id, None)+ if count:+ await _announce(session_id, None)return countdiff --git a/server/tests/services/test_chat_thread.py b/server/tests/services/test_chat_thread.pyindex 6eb70a67..41a3ca79 100644--- a/server/tests/services/test_chat_thread.py+++ b/server/tests/services/test_chat_thread.py@@ -1,8 +1,9 @@"""A workflow's chat thread (services/chat_thread.py) and the chatWebSocket handlers built on it: rows carry the live generation, every-insert and clear is announced on ``chat.updated``, a message reaches a-workflow only while a deployment would read it, and Home's history spans-restarts with the generation on every row."""+insert and every clear that removed rows is announced on ``chat.updated``,+a message reaches a workflow only while a deployment would read it, the+generation is on every row, a Reset clears the thread through the chat+nodes' Reset hook, and deleting the workflow deletes it."""from __future__ import annotations@@ -146,6 +147,42 @@ async def test_clearing_removes_every_generation_and_is_announced(database, framassert updates(frames) == [{"workflow_id": "7", "session_id": "7", "role": None}]+async def test_clearing_an_empty_thread_says_nothing(database, frames):+ assert await chat_thread.clear_chat_thread(database, "7") == 0+ assert frames == []++[email protected]("node", ["chatTrigger", "chatReply"])+async def test_a_reset_ends_the_workflows_chat_session(database, frames, node):+ from nodes.chat.chat_reply import ChatReplyNode+ from nodes.trigger.chat_trigger import ChatTriggerNode++ reset = {"chatTrigger": ChatTriggerNode, "chatReply": ChatReplyNode}[node].reset_execution_state+ await database.add_chat_message("7", "user", "What's on today?", execution_id="gen-1")+ await database.add_chat_message("7", "assistant", "Two calls.", execution_id="gen-1")+ await database.add_chat_message("8", "user", "another workflow's thread", execution_id="gen-5")+ args = {"node_id": f"7:{node}:1", "workflow_id": "7", "execution_id": "gen-1", "generation": 1, "graph": {}, "database": database}++ assert await reset(**args) == {"reset": True, "cleared_chat_messages": 2}+ assert await database.get_chat_messages("7") == []+ assert [row["message"] for row in await database.get_chat_messages("8")] == ["another workflow's thread"]+ # The next chat node in the same Reset finds nothing, and says nothing.+ assert await reset(**args) == {"reset": False, "cleared_chat_messages": 0}+ assert updates(frames) == [{"workflow_id": "7", "session_id": "7", "role": None}]+++async def test_deleting_the_workflow_deletes_its_thread(database, frames, monkeypatch):+ import nodes.chat.chat_reply # noqa: F401 (registers the hook on import)+ from services.workflow_storage import hooks++ assert chat_thread.clear_chat_thread in hooks._HOOKS+ # Run it alone: other plugins' hooks have nothing to do with this test.+ monkeypatch.setattr(hooks, "_HOOKS", [chat_thread.clear_chat_thread])+ await database.add_chat_message("7", "user", "hello", execution_id="gen-1")+ await hooks.run_workflow_deleted_hooks(database, "7")+ assert await database.get_chat_messages("7") == []++async def test_history_is_the_newest_rows_oldest_first_in_utc(database):for text in ("one", "two", "three"):await database.add_chat_message("7", "user", text, execution_id="gen-1")@@ -211,7 +248,8 @@ async def test_history_is_one_generation_unless_all_are_asked_for(router):assert [m["message"] for m in newest["messages"]] == ["an answer", "after it"]-async def test_after_a_reset_only_all_generations_shows_the_thread(router):+async def test_after_a_reset_the_live_read_is_empty(router):+ # A row a Reset left (its graph had no chat node to clear it).await router.database.add_chat_message("7", "user", "kept", execution_id="gen-1")await control(router.database, "7", "reset", generation=1)assert (await ws_router.handle_get_chat_messages({"session_id": "7"}, None))["messages"] == []