Skip to content

Self-improving AI Employees for everyone

feat(chat): say how each message's run ended in the thread read

trohitg0aaa66f43842
diff --git a/server/services/chat/handlers.py b/server/services/chat/handlers.py
index 264f5715..e7f279a8 100644
--- a/server/services/chat/handlers.py
+++ b/server/services/chat/handlers.py
@@ -43,7 +43,19 @@ PROTOCOL_VERSION = 1
_DENIED = {"success": False, "error": "access_denied"}
-def _wire_message(row: Dict[str, Any]) -> Dict[str, Any]:
+def _wire_run(run: Any) -> Dict[str, Any]:
+ """The run a message started or answers, as a message carries it: enough
+ to show how it ended after a reload (a failed run leaves no reply)."""
+ wire: Dict[str, Any] = {"run_id": run.run_id, "state": run.state, "outcome": run.outcome}
+ if run.state == "error":
+ wire["error"] = {"message": run.error, "code": run.error_code}
+ hint = (run.result or {}).get("hint")
+ if hint:
+ wire["error"]["hint"] = hint
+ return wire
+
+
+def _wire_message(row: Dict[str, Any], runs: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
"""A stored message as ``get_chat_messages`` sends it."""
message_id = row.get("uid") or f"m{row.get('id')}"
wire: Dict[str, Any] = {
@@ -68,6 +80,9 @@ def _wire_message(row: Dict[str, Any]) -> Dict[str, Any]:
client_message_id = (row.get("meta") or {}).get("client_message_id")
if client_message_id:
wire["client_message_id"] = client_message_id
+ run = (runs or {}).get(row.get("run_id") or "")
+ if run is not None:
+ wire["run"] = _wire_run(run)
return wire
@@ -225,6 +240,7 @@ async def handle_get_chat_messages(data: Dict[str, Any], websocket: WebSocket) -
)
thread = await _thread_state(database, session_id)
active_runs = await run_snapshots(database, session_id)
+ runs = await ledger.runs_by_id(database, [row.get("run_id") for row in rows])
except Exception:
logger.warning("Chat messages could not be read", session_id=session_id, exc_info=True)
return {"success": False, "error": "read_failed", "session_id": session_id}
@@ -232,7 +248,7 @@ async def handle_get_chat_messages(data: Dict[str, Any], websocket: WebSocket) -
"success": True,
"protocol_version": PROTOCOL_VERSION,
"session_id": session_id,
- "messages": [_wire_message(row) for row in rows],
+ "messages": [_wire_message(row, runs) for row in rows],
"thread": thread,
"active_runs": active_runs,
}
diff --git a/server/services/chat/ledger.py b/server/services/chat/ledger.py
index ac044935..86599aa6 100644
--- a/server/services/chat/ledger.py
+++ b/server/services/chat/ledger.py
@@ -129,6 +129,16 @@ async def lane_run(database: Any, session_id: str) -> Optional[ChatRun]:
return result.scalar_one_or_none()
+async def runs_by_id(database: Any, run_ids: List[str]) -> Dict[str, ChatRun]:
+ """The named runs that exist, by id (one query)."""
+ wanted = sorted({run_id for run_id in run_ids if run_id})
+ if not wanted:
+ return {}
+ async with database.get_session() as session:
+ result = await session.execute(select(ChatRun).where(ChatRun.run_id.in_(wanted)))
+ return {run.run_id: run for run in result.scalars().all()}
+
+
async def live_runs(database: Any, session_id: Optional[str] = None) -> List[ChatRun]:
"""Live runs, oldest first: one session's, or every session's."""
async with database.get_session() as session:
@@ -527,6 +537,7 @@ __all__ = [
"publish_started",
"publish_terminal",
"reply_uid",
+ "runs_by_id",
"start_run",
"sweep",
]
diff --git a/server/tests/services/chat/test_handlers.py b/server/tests/services/chat/test_handlers.py
index f0a53a83..1fcf821c 100644
--- a/server/tests/services/chat/test_handlers.py
+++ b/server/tests/services/chat/test_handlers.py
@@ -113,6 +113,33 @@ async def test_reading_the_thread_returns_the_v2_shape(chat):
assert (run["run_id"], run["state"], run["user_message_id"], run["seq"]) == (sent["run_id"], "pending", message["id"], 0)
+async def test_each_message_says_how_its_run_ended(chat):
+ """A reload still shows a failed run's error (it leaves no reply), and a
+ finished run on both the owner's message and the reply."""
+ await talking(chat.database)
+ failed = await send(chat)
+ await ledger.start_run(chat.database, run_id=failed["run_id"], temporal_workflow_id="tw", temporal_run_id="tr")
+ await ledger.finish_run(
+ chat.database, run_id=failed["run_id"], temporal_workflow_id="tw", temporal_run_id="tr",
+ success=False, error="Calendar said no", hint="Reconnect Google",
+ )
+ answered = await send(chat, "Try again")
+ run = await ledger.start_run(chat.database, run_id=answered["run_id"], temporal_workflow_id="tw2", temporal_run_id="tr")
+ await ledger.post_reply(chat.database, run=run, node_id="n", text="Booked.", execution_id="gen-1")
+ await ledger.finish_run(chat.database, run_id=answered["run_id"], temporal_workflow_id="tw2", temporal_run_id="tr", success=True)
+
+ result = await chat.handlers.handle_get_chat_messages({"session_id": "wf", "all_generations": True}, None)
+ first, second, reply = result["messages"]
+ assert first["run"] == {
+ "run_id": failed["run_id"],
+ "state": "error",
+ "outcome": None,
+ "error": {"message": "Calendar said no", "code": "run_failed", "hint": "Reconnect Google"},
+ }
+ assert second["run"] == reply["run"] == {"run_id": answered["run_id"], "state": "finished", "outcome": "success"}
+ assert result["active_runs"] == []
+
+
async def test_a_failed_read_is_never_an_empty_thread(chat, monkeypatch):
async def broken(*_args, **_kwargs):
raise RuntimeError("database is locked")