Skip to content

Self-improving AI Employees for everyone

fix(chat): a run's end tells open threads

trohitg1d41eef478a3
diff --git a/CLAUDE.md b/CLAUDE.md
index 3c4f7592..7409d34e 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -2527,7 +2527,7 @@ Updated `client_left` and presence handlers use `has_real_android_devices()` ins
| `agent_capability` | CloudEvents v1.0 envelope (`com.opencompany.agent.(skill|tool).*`) — exact-agent capability lifecycle with deterministic Temporal IDs, `(source,id)` deduplication, sanitized data, and an optional exact target node |
| `employee_lifecycle` | CloudEvents v1.0 envelope (type=`com.opencompany.employee.{hired,updated,removed}`, subject = workflow id) — Home's team list; `updated` is coalesced to one per second per employee, control changes go out at once |
| `approval_lifecycle` | CloudEvents v1.0 envelope (type=`com.opencompany.approval.{requested,decided,expired,cancelled}`) — identity only, never the draft or the recipient; the card refetches via `list_approvals` |
-| `chat.updated` | CloudEvents v1.0 envelope (type=`com.opencompany.chat.updated`, data `{workflow_id, session_id, role}`) — sent directly (not `dispatch.emit`) by `services/chat_thread.py` after every chat insert and clear; identity only, Home's thread and the editor's chat pane refetch via `get_chat_messages` |
+| `chat.updated` | CloudEvents v1.0 envelope (type=`com.opencompany.chat.updated`, data `{workflow_id, session_id, role}`) — sent directly (not `dispatch.emit`) by `services/chat_thread.py` after every chat insert and clear, and when a chat run ends; identity only, Home's thread and the editor's chat pane refetch via `get_chat_messages` |
| `chat_run_event` | CloudEvents v1.0 envelope (type=`com.opencompany.chat.run.<suffix>`, id `<run id>:<seq>`, subject = run id) — AG-UI run events, sent by `services/chat/hub.py` only to sockets subscribed to the session through `chat_subscribe`, never on the broadcast; see [chat_protocol.md](./docs-internal/chat_protocol.md) |
| `workflow_lifecycle` | CloudEvents v1.0 envelope for workflow stages (`deployment.*`, `lock.*`, `execution.*`, `imported`, `renamed`, `created`, `deleted`) — other tabs invalidate their workflow lists |
| `deployment_snapshot` | CloudEvents v1.0 envelope (type=`workflow.deployment.snapshot`) — pushed once per WS connect from `broadcaster._send_deployment_snapshot`; lets the FE reconcile stale `deploymentStatus.isRunning=true` after a backend restart wiped `DeploymentManager._deployments`. Empty list is meaningful (forces reset). |
diff --git a/client/src/contexts/WebSocketContext.tsx b/client/src/contexts/WebSocketContext.tsx
index ec354770..457d42a9 100644
--- a/client/src/contexts/WebSocketContext.tsx
+++ b/client/src/contexts/WebSocketContext.tsx
@@ -1191,9 +1191,10 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi
case 'chat.updated': {
// CloudEvents-typed chat row change from services/chat_thread.py,
- // sent after every chat insert and clear. Identity only: every
- // chat showing the session (Home's employee page, the editor's
- // Chat pane) refetches its thread through `get_chat_messages`.
+ // sent after every chat insert and clear, and when a chat run
+ // ends. Identity only: every chat showing the session (Home's
+ // employee page, the editor's Chat pane) refetches its thread
+ // through `get_chat_messages`.
const identity = (data as WorkflowEvent<{ workflow_id?: string; session_id?: string; role?: string }>)?.data;
const sessionId = identity?.session_id;
if (sessionId) {
diff --git a/docs-internal/chat_protocol.md b/docs-internal/chat_protocol.md
index 85eb22ec..b7465323 100644
--- a/docs-internal/chat_protocol.md
+++ b/docs-internal/chat_protocol.md
@@ -56,7 +56,9 @@ internal socket, load the workflow, and compare its owner with the socket's exec
(`python -m services.temporal.worker`) has no sockets, so it relays instead; see
[Standalone workers](#standalone-workers).
- `chat.updated` remains an identity-only broadcast (`{workflow_id, session_id, role}`) that tells every open thread
- to refetch `get_chat_messages`.
+ to refetch `get_chat_messages`: after a message is added, after a clear, and when a run ends (`role` null), since
+ a run's end changes what its thread offers (its answer can be tried again, the owner's message edited:
+ `editable`).
## Events
diff --git a/docs-internal/normal_mode.md b/docs-internal/normal_mode.md
index 69261836..1a24a748 100644
--- a/docs-internal/normal_mode.md
+++ b/docs-internal/normal_mode.md
@@ -818,7 +818,7 @@ every frame but `workflow_ops_apply` carries the whole envelope:
| `employee_lifecycle` | `com.opencompany.employee.{hired,updated,removed}` | Subject is the workflow id; `updated` is coalesced to one per second per employee, except control changes and browser control changes (each agent step, and the wait for the owner), which go out at once. Home refetches on `hired` and `updated` rather than taking the summary the event carries, which can already be out of date; `removed` drops the employee |
| `approval_lifecycle` | `com.opencompany.approval.{requested,decided,expired,cancelled}` | Identity only, never the message or the recipient |
| `workflow_lifecycle` | gains `created` and `deleted` stages | So open editors refresh their workflow lists. `deleted` also makes every tab forget the workflow and its employee (`forgetWorkflow`, see [Deleting an employee](#deleting-an-employee)) |
-| `chat.updated` | `com.opencompany.chat.updated` | Sent after every chat insert and clear (`services/chat_thread.py`). Data `{workflow_id, session_id, role}`, identity only: `role` is null for a clear, `workflow_id` null for session `"default"`. Home's thread and the editor's chat pane refetch |
+| `chat.updated` | `com.opencompany.chat.updated` | Sent after every chat insert and clear (`services/chat_thread.py`), and when a chat run ends. Data `{workflow_id, session_id, role}`, identity only: `role` is null for a clear or a run's end, `workflow_id` null for session `"default"`. Home's thread and the editor's chat pane refetch |
| `workflow_ops_apply` | `com.opencompany.workflow.ops.applied` | The frame is the event's flat data, `{workflow_id, caller_node_id, operations, persisted?}`, not the envelope. `persisted: true` marks a batch the server already saved (`apply_graph_additions`: Turn on Talk, the Agent Builder), whose ops carry the server's ids; editors adopt it without saving. See [Workflow Operations Protocol](./workflow_ops_protocol.md#persisted-batches) |
## Tests
diff --git a/server/services/chat/ledger.py b/server/services/chat/ledger.py
index 2ae89aac..0981b276 100644
--- a/server/services/chat/ledger.py
+++ b/server/services/chat/ledger.py
@@ -465,7 +465,7 @@ async def start_run(
async def _settle(database: Any, run: ChatRun, values: Dict[str, Any]) -> Optional[ChatRun]:
"""Move ``run`` from the state it was read in to a terminal one, then
- publish it. None when the run moved meanwhile."""
+ publish it and tell open threads. None when the run moved meanwhile."""
async with database.get_session() as session:
result = await session.execute(
update(ChatRun).where(ChatRun.run_id == run.run_id, ChatRun.state == run.state).values(finished_at=_utcnow(), **values)
@@ -477,9 +477,20 @@ async def _settle(database: Any, run: ChatRun, values: Dict[str, Any]) -> Option
if settled is not None and settled.state in TERMINAL_STATES:
await _tell_notes(database, settled)
publish_terminal(settled)
+ await _announce_end(settled)
return settled
+async def _announce_end(run: ChatRun) -> None:
+ """A run's end changes its thread even when it wrote nothing new: its
+ answer can now be tried again and the owner's message edited
+ (``editable``), and what its tools showed is sealed on its reply. Read
+ while the run was live, a thread kept none of that."""
+ from services.chat_thread import announce_chat_updated
+
+ await announce_chat_updated(run.session_id, None)
+
+
async def _tell_notes(database: Any, run: ChatRun) -> None:
"""Mark the notes the run's turn carried as told (``services/chat/
notes.py``) when it answered: it finished, or it stopped having written
@@ -498,12 +509,10 @@ async def _tell_notes(database: Any, run: ChatRun) -> None:
async def _seal(database: Any, run: ChatRun) -> None:
"""Put what the run's tools showed on its reply (``services/chat/
- parts.py``), and tell open threads when that changed the thread."""
+ parts.py``). Every caller then ends the run, which tells open threads."""
from services.chat.parts import seal_parts
- from services.chat_thread import announce_chat_updated
- if await seal_parts(database, run):
- await announce_chat_updated(run.session_id, "assistant")
+ await seal_parts(database, run)
async def _success_values(database: Any, run: ChatRun, outcome: str) -> Dict[str, Any]:
@@ -591,6 +600,7 @@ async def request_stop(database: Any, run_id: str) -> Optional[ChatRun]:
run = await get_run(database, run_id)
if run is not None and ended:
publish_terminal(run)
+ await _announce_end(run)
elif run is not None and stopping:
_publish(run, "custom", {"name": "opencompany.stopping", "value": {}}, "stopping")
return run
diff --git a/server/services/chat_thread.py b/server/services/chat_thread.py
index 2e17e6cc..8c005d03 100644
--- a/server/services/chat_thread.py
+++ b/server/services/chat_thread.py
@@ -107,8 +107,9 @@ def chat_updated(*, session_id: str, role: Optional[str]) -> WorkflowEvent:
async def announce_chat_updated(session_id: str, role: Optional[str]) -> None:
- """Send ``chat.updated`` for a session: a message was added (``role``)
- or the thread was cleared (``role`` None). Never raises."""
+ """Send ``chat.updated`` for a session: a message was added (``role``),
+ or the thread was cleared or a run in it ended (``role`` None). Never
+ raises."""
from services.chat.relay import active_relay
from services.status_broadcaster import get_status_broadcaster
diff --git a/server/tests/services/chat/test_ledger.py b/server/tests/services/chat/test_ledger.py
index bbdaea99..63894d97 100644
--- a/server/tests/services/chat/test_ledger.py
+++ b/server/tests/services/chat/test_ledger.py
@@ -13,7 +13,7 @@ from sqlalchemy import text
from models.chat import ChatRun
from services.chat import ledger
-from tests.services.chat._helpers import add_control
+from tests.services.chat._helpers import add_control, chat_updates
async def admit(database, session_id="wf", *, text_="Book Saturday", track=True, state="pending", client_message_id=None):
@@ -214,6 +214,24 @@ async def test_finishing_without_a_reply_says_so(database, hub):
assert finished.result == {"no_reply": True}
+async def test_a_run_ending_tells_open_threads(database, hub, frames):
+ # Its answer can now be tried again and the owner's message edited: a
+ # thread read while it ran shows neither until it reads again.
+ admission = await admit(database)
+ run = await started(database, admission)
+ await ledger.post_reply(database, run=run, node_id="wf:chatReply:1", text="Booked.", execution_id="gen-1")
+ args = dict(run_id=run.run_id, temporal_workflow_id="tw-1", temporal_run_id="tr-1", success=True)
+ await ledger.finish_run(database, **args)
+ assert chat_updates(frames) == [{"workflow_id": "wf", "session_id": "wf", "role": None}]
+ # A retried finish changes nothing and says nothing.
+ await ledger.finish_run(database, **args)
+ assert len(chat_updates(frames)) == 1
+ # A run stopped before anything picked it up ends at once.
+ second = await admit(database, text_="And Sunday?")
+ await ledger.request_stop(database, second.run.run_id)
+ assert len(chat_updates(frames)) == 2
+
+
async def test_a_failed_run_keeps_its_error(database, hub):
admission = await admit(database)
await started(database, admission)