Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
refactor(chat): drop the run events and outcomes nothing produces
trohitg203678f609a9
diff --git a/server/models/chat.py b/server/models/chat.pyindex 97831892..22e57771 100644--- a/server/models/chat.py+++ b/server/models/chat.py@@ -5,11 +5,11 @@ A run is admitted in the same transaction as the owner's messageor ``pending`` -> ``running`` -> ``finished`` | ``error`` | ``stopped``, eachstep a compare-and-swap on ``state``; Stop moves a pending or running run to``stopping`` on the way to ``stopped``. ``kind`` says what started it:-``message`` (the owner wrote), ``edit``, ``regenerate``, ``action`` (a button-in generated UI) or ``resume`` (an approved send executing later).+``message`` (the owner wrote), ``edit``, ``regenerate`` or ``action`` (a button+in generated UI).-**The lane.** At most one non-terminal run per session, resume runs aside,-enforced by a partial unique index: two runs that loaded the same stored+**The lane.** At most one non-terminal run per session, enforced by a+partial unique index: two runs that loaded the same storedconversation would each save over the other's (docs-internal/agent_context_flow.md). A second message while one is live is refused with``run_in_progress``; the composer shows Stop instead of Send meanwhile.@@ -47,7 +47,9 @@ LIVE_STATES = ("queued", "pending", "running", "stopping")#: States a run ends in.TERMINAL_STATES = ("finished", "error", "stopped")-_LANE_WHERE = "state IN ('queued', 'pending', 'running', 'stopping') AND kind != 'resume'"+#: Databases made before October 2026 keep ``AND kind != 'resume'`` in it; no+#: run has that kind, so both refuse the same runs.+_LANE_WHERE = "state IN ('queued', 'pending', 'running', 'stopping')"class ChatThread(SQLModel, table=True):@@ -80,8 +82,8 @@ class ChatRun(SQLModel, table=True):options: Dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON))#: Working steps as they finished, for "Worked for Ns · N steps" on reload.steps: List[Dict[str, Any]] = Field(default_factory=list, sa_column=Column(JSON))- #: How a finished run ended: ``success``, ``stopped`` or ``interrupt``- #: (drafts wait for the owner). None until it ends, and for errors.+ #: How a finished run ended: ``success`` or ``stopped``. None until it+ #: ends, and for errors.outcome: Optional[str] = Field(default=None, max_length=20)#: The terminal event's ``result`` (``reply_message_id`` or ``no_reply``).result: Dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON))diff --git a/server/services/chat/branches.py b/server/services/chat/branches.pyindex 9d7b795f..acc6b5c5 100644--- a/server/services/chat/branches.py+++ b/server/services/chat/branches.py@@ -418,9 +418,7 @@ async def _session_rows(session: Any, session_id: str) -> List[ChatMessage]:async def _lane_held(session: Any, session_id: str) -> bool:result = await session.execute(- select(ChatRun.run_id)- .where(ChatRun.session_id == session_id, ChatRun.state.in_(LIVE_STATES), ChatRun.kind != "resume")- .limit(1)+ select(ChatRun.run_id).where(ChatRun.session_id == session_id, ChatRun.state.in_(LIVE_STATES)).limit(1))return result.scalar_one_or_none() is not Nonediff --git a/server/services/chat/events.py b/server/services/chat/events.pyindex 6a0f4caf..92f76aef 100644--- a/server/services/chat/events.py+++ b/server/services/chat/events.py@@ -44,14 +44,8 @@ RUN_SUFFIXES = frozenset("text.started","text.content","text.ended",- "tool_call.started",- "tool_call.args",- "tool_call.ended",- "tool_call.result","activity.snapshot","activity.delta",- "reasoning.started",- "reasoning.ended","custom",})diff --git a/server/services/chat/ledger.py b/server/services/chat/ledger.pyindex cdc65428..2ae89aac 100644--- a/server/services/chat/ledger.py+++ b/server/services/chat/ledger.py@@ -3,8 +3,8 @@ run that answers it, and ended by the watchdog when nothing will.**Admission** (``admit_message``) writes the owner's message and its run inone reserved transaction (``Database.reserved_session``), after checking the-lane: one live run per session, resume runs aside, also enforced by the-partial unique index on ``chat_runs``. A message re-sent with the same+lane: one live run per session, also enforced by the partial unique index+on ``chat_runs``. A message re-sent with the same``client_message_id`` returns the first send's message and run instead ofwriting a second one; the id maps to a message id that only this session canproduce (``client_message_uid``).@@ -143,9 +143,7 @@ async def lane_run(database: Any, session_id: str) -> Optional[ChatRun]:"""The run holding the session's lane, if any."""async with database.get_session() as session:result = await session.execute(- select(ChatRun)- .where(ChatRun.session_id == session_id, ChatRun.state.in_(LIVE_STATES), ChatRun.kind != "resume")- .limit(1)+ select(ChatRun).where(ChatRun.session_id == session_id, ChatRun.state.in_(LIVE_STATES)).limit(1))return result.scalar_one_or_none()@@ -253,9 +251,7 @@ async def admit_message(run_id: Optional[str] = Noneif track:held = await session.execute(- select(ChatRun)- .where(ChatRun.session_id == session_id, ChatRun.state.in_(LIVE_STATES), ChatRun.kind != "resume")- .limit(1)+ select(ChatRun).where(ChatRun.session_id == session_id, ChatRun.state.in_(LIVE_STATES)).limit(1))holder = held.scalar_one_or_none()if holder is not None:@@ -411,14 +407,15 @@ def publish_terminal(run: ChatRun) -> None:fields[key] = result[key]_publish(run, "failed", fields, "terminal")return- outcome: Dict[str, Any] = {"type": run.outcome or "success"}- interrupts = result.pop("interrupts", None)- if run.outcome == "interrupt":- outcome["interrupts"] = list(interrupts or [])_publish(run,"finished",- {"outcome": outcome, "result": result, "duration_ms": duration_ms, "step_count": len(run.steps or [])},+ {+ "outcome": {"type": run.outcome or "success"},+ "result": result,+ "duration_ms": duration_ms,+ "step_count": len(run.steps or []),+ },"terminal",)diff --git a/server/services/chat/reducer.py b/server/services/chat/reducer.pyindex 95c0b937..6da7643b 100644--- a/server/services/chat/reducer.py+++ b/server/services/chat/reducer.py@@ -49,7 +49,6 @@ def empty_snapshot(run_id: str) -> Dict[str, Any]:"steps": [],"segments": [],"activities": [],- "interrupts": [],"outcome": None,"result": {},"error": None,@@ -62,9 +61,6 @@ def snapshot_from_row(run: Any) -> Dict[str, Any]:finish); text is not stored until the reply is, so a run read after arestart has no segments."""snapshot = empty_snapshot(run.run_id)- outcome = {"type": run.outcome} if run.outcome else None- if outcome is not None and run.outcome == "interrupt":- outcome["interrupts"] = list((run.result or {}).get("interrupts") or [])snapshot.update({"session_id": run.session_id,@@ -78,8 +74,8 @@ def snapshot_from_row(run: Any) -> Dict[str, Any]:"started_at": _iso(run.started_at),"finished_at": _iso(run.finished_at),"steps": [dict(step) for step in (run.steps or [])],- "outcome": outcome,- "result": {key: value for key, value in (run.result or {}).items() if key != "interrupts"},+ "outcome": {"type": run.outcome} if run.outcome else None,+ "result": dict(run.result or {}),"error": run.error,"error_code": run.error_code,}@@ -94,7 +90,7 @@ def merge_snapshot(stored: Mapping[str, Any], live: Optional[Mapping[str, Any]])merged = deepcopy(dict(stored))if not live:return merged- for key in ("seq", "steps", "segments", "activities", "interrupts"):+ for key in ("seq", "steps", "segments", "activities"):merged[key] = deepcopy(live.get(key, merged.get(key)))if stored.get("state") in LIVE_STATES and live.get("state") not in (None, "pending"):merged["state"] = live["state"]@@ -153,7 +149,6 @@ def apply_event(snapshot: Mapping[str, Any], event: Mapping[str, Any]) -> Dict[soutcome = dict(data.get("outcome") or {"type": "success"})out["outcome"] = outcomeout["result"] = dict(data.get("result") or {})- out["interrupts"] = list(outcome.get("interrupts") or [])out["state"] = "stopped" if outcome.get("type") == "stopped" else "finished"elif suffix == "failed":out["state"] = "error"diff --git a/server/tests/services/chat/test_ledger.py b/server/tests/services/chat/test_ledger.pyindex a74b12c4..05280dd5 100644--- a/server/tests/services/chat/test_ledger.py+++ b/server/tests/services/chat/test_ledger.py@@ -69,10 +69,6 @@ async def test_the_lane_index_refuses_a_second_live_run(database):async with database.get_session() as session:session.add(ChatRun(run_id="r_sneaky", session_id="wf", state="running", kind="message"))await session.commit()- # A resume run (an approved send executing) never holds the lane.- async with database.get_session() as session:- session.add(ChatRun(run_id="r_resume", session_id="wf", state="running", kind="resume"))- await session.commit()async def test_concurrent_sends_admit_one_run(database, hub):