Skip to content

API Reference parrot.flows.dev_loop.streaming

github-actions[bot] edited this page Nov 5, 2026 · 4 revisions

parrot.flows.dev_loop.streaming

View source

FlowStreamMultiplexer — aiohttp WebSocket fan-in for two Redis streams.

Implements Module 3 of the dev-loop spec. The UI (nav-admin Svelte plugin) consumes a single WebSocket per flow run; the multiplexer fans in:

  • flow:{run_id}:flow — flow-level events emitted by AgentsFlow.
  • flow:{run_id}:dispatch:{node_id} — per-dispatch events emitted by :class:ClaudeCodeDispatcher.

Goal (spec G4): the UI never speaks Redis directly. The multiplexer emits flat JSON envelopes:

.. code-block:: json

{"source": "flow"|"dispatch", "node_id": str|null,
 "event_kind": str, "ts": float, "payload": {...}}

Query parameters on the WebSocket URL:

  • view — "flow" | "dispatch" | "both" | "state" (default "both").
  • replay — true|false (default true).
  • last_seen — int, view="state" only (AHP reconnect semantics, FEAT-322 TASK-1854): replays flow:{run_id}:actions envelopes with server_seq > last_seen instead of the initial snapshot.

The handler is intentionally a thin wrapper over :class:FlowStreamMultiplexer so the merge / dispatch-discovery logic is unit-testable without an aiohttp test server.

view="state" (FEAT-322) is a separate code path from the legacy flow/dispatch/both views: it reads ONLY the operational flow:{run_id}:actions stream (never the flow/dispatch streams) and folds it through the transport-free session_state.reduce() — this works identically for a live run or a finished one (crash-rebuild invariant, spec §7), and deliberately never looks up a live SessionHost/DevLoopRunner (the multiplexer may run in another worker process). Legacy views are untouched — zero changes to their code paths.

Class FlowStreamMultiplexer

Merge events from a flow stream and many dispatch streams.

Parameter Type Default Description
redis Any An redis.asyncio.Redis instance with decode_responses=True.
run_id str The flow run id; appears in stream keys.
view ViewLiteral 'both' Which sources to emit (flow/dispatch/both).
dispatch_refresh_seconds float 2.0 Polling interval for the KEYS flow:{run_id}:dispatch:* discovery loop.
block_ms int 1000 XREAD BLOCK <ms> timeout — controls how often the live loop wakes up to re-check dispatch discovery.

Method FlowStreamMultiplexer.replay

Replay historical events from every subscribed stream.

Reads XRANGE 0 + from each stream, decodes the :class:DispatchEvent payload, merges by ts ascending, and yields one envelope per event. The cursor for each stream is updated to the last seen entry id so the subsequent tail() call only forwards genuinely new events.

replay() -> AsyncIterator[Dict[str, Any]]

Returns: AsyncIterator[Dict[str, Any]]

Method FlowStreamMultiplexer.tail

Forward live events as they arrive.

Uses XREAD BLOCK <ms> with the per-stream cursor populated by :meth:replay (or initialised to "$" for streams discovered only after replay). Periodically re-discovers dispatch streams so events from late-arriving nodes are picked up.

Stops automatically when a terminal flow event (flow.flow_completed / flow.flow_failed) is received, so the WebSocket handler exits cleanly instead of blocking until the client disconnects.

tail() -> AsyncIterator[Dict[str, Any]]

Returns: AsyncIterator[Dict[str, Any]]

Method FlowStreamMultiplexer.close

Stop the tail loop. Idempotent.

close() -> None

Method FlowStreamMultiplexer.state_replay

view="state" connect sequence — snapshot or gap replay.

Folds every envelope on flow:{run_id}:actions from seq 0 through :func:reduce (works identically for a live run or a finished one — no live host lookup, spec §7 crash-rebuild invariant).

  • last_seen is None (fresh connect): yields the folded :class:Snapshot as the FIRST frame, then nothing else from this historical batch (the snapshot already reflects it).
  • last_seen is not None (AHP reconnect): skips the snapshot and yields only envelopes with server_seq > last_seen — no gaps, no duplicates.

Sets self._state_cursor to the last raw stream entry id seen (in stream order, not fold order), so a subsequent :meth:state_tail call continues from exactly where this method left off.

state_replay(*, last_seen: Optional[int] = None) -> AsyncIterator[Dict[str, Any]]

Parameter Type Default Description
last_seen Optional[int] None

Returns: AsyncIterator[Dict[str, Any]]

Method FlowStreamMultiplexer.state_tail

view="state" live continuation after :meth:state_replay.

Uses XREAD BLOCK from self._state_cursor (populated by state_replay, or "$" — new entries only — if that method was never called). Malformed entries are logged and skipped, same forward-compat contract as :meth:_read_action_envelopes.

Stops when a terminal action (run/closed or run/cancelled) arrives, so the WebSocket handler exits cleanly — but only after one final non-blocking sweep of whatever is already on the stream. That sweep is the safety net for the truncation this used to cause: a terminal action is the last envelope a well-ordered stream carries (DevLoopRunner._close_host flushes the run's envelope queue before it returns), yet on a stream written when the sink spawned a task per envelope, a node's node/completed could land after run/closed — and stopping on sight dropped it, leaving a finished node stuck "running" in the console with its projections lost.

state_tail() -> AsyncIterator[Dict[str, Any]]

Returns: AsyncIterator[Dict[str, Any]]

Function flow_stream_ws

aiohttp WebSocket handler bound to GET /api/flow/{run_id}/ws.

Query parameters:

  • view — "flow" | "dispatch" | "both" | "state" (default "both").
  • replay — true|false (default true, legacy views only).
  • last_seen — int, view="state" only (FEAT-322): reconnect replay — envelopes with server_seq > last_seen instead of the initial snapshot.

Emits a JSON envelope per event:

.. code-block:: json

{"source": "flow"|"dispatch", "node_id": str|null,
 "event_kind": str, "ts": float, "payload": {...}}

view="state" emits the AHP-style snapshot/action shape instead (source="state", event_kind="snapshot"|"action", payload = Snapshot/ActionEnvelope — see :meth:FlowStreamMultiplexer.state_replay); legacy views are byte-identical to before this parameter existed.

The owning aiohttp app must populate request.app["redis_url"] (or request.app["redis"] with a pre-built client). The handler closes both the Redis connection it created and the WebSocket on client disconnect.

flow_stream_ws(request: web.Request) -> web.WebSocketResponse

Parameter Type Default Description
request web.Request

Returns: web.WebSocketResponse

Architecture

Clients

Bots & Agents

Memory

Knowledge

Tools & Toolkits

Flows

Experts

Skills

Stores & Loaders

MCP & A2A

Server & APIs

Integrations

Outputs & A2UI

Prompts

Security

Operations

Migration

SDD Tooling

LLM Wiki

Deployment

Decisions

API Reference

Clone this wiki locally