Skip to content

Self-improving AI Employees for everyone

feat(agent): live LangGraph iteration counter via CloudEvents broadcast

trohitgb6aecd395521
diff --git a/client/src/contexts/WebSocketContext.tsx b/client/src/contexts/WebSocketContext.tsx
index f3a3e419..510d30cb 100644
--- a/client/src/contexts/WebSocketContext.tsx
+++ b/client/src/contexts/WebSocketContext.tsx
@@ -841,6 +841,42 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi
}
break;
+ case 'agent_progress': {
+ // CloudEvents v1.0 envelope from broadcaster.broadcast_agent_progress.
+ // Inner payload: { node_id, iteration, max_iterations, phase? }.
+ // Routes into nodeStatusStore (same per-workflow / per-node slot
+ // the existing useNodeStatus consumers read) so the AI-agent body
+ // can render "iteration / max_iterations" live without a parallel
+ // store. Wire-key parity with `credential_catalogue_updated`.
+ const envelope = data as WorkflowEvent<{
+ node_id?: string;
+ iteration?: number;
+ max_iterations?: number;
+ phase?: string;
+ }> | undefined;
+ const inner = envelope?.data;
+ const targetNodeId = inner?.node_id || envelope?.subject;
+ const progressWorkflowId =
+ envelope?.workflow_id || message.workflow_id || 'unknown';
+ if (targetNodeId && inner) {
+ const store = useNodeStatusStore.getState();
+ const previous =
+ store.allStatuses[progressWorkflowId]?.[targetNodeId] ||
+ ({} as NodeStatus);
+ store.setStatus(progressWorkflowId, targetNodeId, {
+ ...previous,
+ workflow_id: progressWorkflowId,
+ data: {
+ ...(previous.data || {}),
+ iteration: inner.iteration,
+ max_iterations: inner.max_iterations,
+ ...(inner.phase ? { phase: inner.phase } : {}),
+ },
+ });
+ }
+ break;
+ }
+
case 'node_status_cleared':
// Handle broadcast from server when node status is cleared
if (node_id || message.node_id) {
diff --git a/server/services/ai.py b/server/services/ai.py
index 9444c07e..38423170 100644
--- a/server/services/ai.py
+++ b/server/services/ai.py
@@ -1970,6 +1970,18 @@ class AIService:
stream_mode="values",
):
final_state = snapshot
+ # Per-step iteration broadcast (CloudEvents envelope
+ # via broadcast_agent_progress -> wire key
+ # `agent_progress`). The FE updates nodeStatusStore
+ # so the AI agent body shows live "iteration / max".
+ if broadcaster:
+ iter_count = snapshot.get("iteration", 0) if isinstance(snapshot, dict) else 0
+ await broadcaster.broadcast_agent_progress(
+ node_id,
+ workflow_id=workflow_id,
+ iteration=iter_count,
+ max_iterations=recursion_limit,
+ )
except GraphRecursionError:
# Append a terminal AIMessage so downstream extraction (and
# the post-loop _track_token_usage / compact_context call)
@@ -2411,6 +2423,16 @@ class AIService:
stream_mode="values",
):
final_state = snapshot
+ # Per-step iteration broadcast — see execute_agent
+ # for the rationale.
+ if broadcaster:
+ iter_count = snapshot.get("iteration", 0) if isinstance(snapshot, dict) else 0
+ await broadcaster.broadcast_agent_progress(
+ node_id,
+ workflow_id=workflow_id,
+ iteration=iter_count,
+ max_iterations=recursion_limit,
+ )
except GraphRecursionError:
msgs = list((final_state or {}).get("messages") or [])
msgs.append(AIMessage(content=(
diff --git a/server/services/events/envelope.py b/server/services/events/envelope.py
index d6a298e4..1e769ea5 100644
--- a/server/services/events/envelope.py
+++ b/server/services/events/envelope.py
@@ -180,6 +180,45 @@ class WorkflowEvent(BaseModel):
data=dict(data) if data else {},
)
+ @classmethod
+ def agent_progress(
+ cls,
+ node_id: str,
+ *,
+ workflow_id: Optional[str],
+ iteration: int,
+ max_iterations: int,
+ phase: Optional[str] = None,
+ data: Optional[Mapping[str, Any]] = None,
+ ) -> "WorkflowEvent":
+ """Live LangGraph supervised-loop progress for one agent node.
+
+ Emitted from inside the ``astream`` loop in
+ ``services/ai.py:execute_agent`` and ``execute_chat_agent`` after
+ each super-step. ``iteration`` advances on every ``agent_node``
+ invocation; ``max_iterations`` mirrors the LangGraph
+ ``recursion_limit`` (sourced from
+ ``llm_defaults.json:agent.recursion_limit``).
+
+ ``subject`` carries the executing node id so the FE routes the
+ update straight to ``nodeStatusStore`` for that node. The
+ ``workflow_id`` extension attribute scopes per-workflow displays
+ the same way ``node_status`` broadcasts do.
+ """
+ return cls(
+ source="machinaos://services/agent",
+ type="agent.progress",
+ subject=node_id,
+ workflow_id=workflow_id,
+ data={
+ "node_id": node_id,
+ "iteration": iteration,
+ "max_iterations": max_iterations,
+ **({"phase": phase} if phase else {}),
+ **(dict(data) if data else {}),
+ },
+ )
+
@classmethod
def task_completed(
cls,
diff --git a/server/services/status_broadcaster.py b/server/services/status_broadcaster.py
index 19d7275f..d8897778 100644
--- a/server/services/status_broadcaster.py
+++ b/server/services/status_broadcaster.py
@@ -278,6 +278,39 @@ class StatusBroadcaster:
"data": event.model_dump(mode="json"),
})
+ async def broadcast_agent_progress(
+ self,
+ node_id: str,
+ *,
+ workflow_id: Optional[str],
+ iteration: int,
+ max_iterations: int,
+ phase: Optional[str] = None,
+ ) -> None:
+ """Emit a CloudEvents-typed agent-progress event.
+
+ Wire key ``agent_progress`` is a parallel channel to
+ ``node_status``: same per-node scope, but the inner payload is a
+ full CloudEvents envelope instead of a raw dict. The FE routes
+ envelope.data into ``nodeStatusStore`` so the existing
+ ``useNodeStatus`` consumers see ``iteration`` /
+ ``max_iterations`` without a separate store.
+ """
+ from services.events import WorkflowEvent
+
+ event = WorkflowEvent.agent_progress(
+ node_id,
+ workflow_id=workflow_id,
+ iteration=iteration,
+ max_iterations=max_iterations,
+ phase=phase,
+ )
+
+ await self.broadcast({
+ "type": "agent_progress",
+ "data": event.model_dump(mode="json"),
+ })
+
# =========================================================================
# Android Status Updates
# =========================================================================