Skip to content

Tool Event Lifecycle

This document maps the live Mozaiks workflow UI transport to AG-UI and CopilotKit.

AG-UI and CopilotKit are research inputs in this document, not canonical authorities and not an adapter roadmap.

It focuses on the actual implementation path in this repo:

  • how use_ui_tool(...) becomes frontend UI
  • where chat.tool_call is canonical
  • how the frontend preserves tool_call semantics through rendering
  • what Mozaiks should keep
  • what should be normalized next

Current live lifecycle

1. Interactive workflow UI

Current interactive UI tools follow this runtime path:

workflow tool
  -> use_ui_tool(...)
  -> _emit_tool_call_core(...)
  -> transport.send_tool_call_event(...)
  -> kind=tool_call
  -> UnifiedEventDispatcher maps to chat.tool_call
  -> ChatPage detects component_type
  -> dynamicUIHandler annotates the event with onResponse(...)
  -> ChatPage stores a `toolCall` render object in message/artifact state
  -> WorkflowUIRouter resolves the workflow component
  -> generated React component renders and calls onResponse(...)
  -> authenticated POST /api/tool-call/respond
  -> submit_tool_call_response(...)
  -> pending future resolves inside use_ui_tool(...)

This is the live path today.

The important point is that the wire contract is chat.tool_call, and the frontend now preserves that shape through rendering instead of inventing a second event type.

Pending calls also persist in ChatSessions.workflow_ui_state.tool_calls, including a first-turn inline card emitted before an assistant message is committed. A browser reconnect replays that pending card independently of the transcript cursor, with its original tool_call_id and payload. A review's review_id therefore still binds the response to the waiting tool invocation. WebSocket connection and workflow-switch replay both forward these calls as chat.tool_call events. Their transport adapters preserve the pending payload and correlation fields even when no transcript message is available. Calls already replayed through transcript metadata are not emitted twice; pending-call and transcript replay suppress actionable cards for responded or completed calls and terminal chats. This protects inline interactions such as the DesignDocs role review. The separate last_artifact cache can still render an artifact-display card after completion; this change does not make that cache completion-aware.

This covers browser reload and reconnect while the backend response waiter is still live. Persisting the card does not recreate an interrupted waiter after a backend-process restart.

2. Auto-tool and fire-and-forget surfaces

Auto-tool execution uses the same render lane, but without waiting for user response:

  • producer: AutoToolEventHandler
  • transport: chat.tool_call
  • required hint: awaiting_response=false
  • completion lane: chat.tool_response

This is closer to generated status/artifact rendering than to human-in-the-loop.

An automatic tool response with success=false displays a fixed failure notice in the conversation even when diagnostic messages are disabled. The notice does not expose the tool's content, result payload, or exception details. Repeated responses for the same tool invocation do not duplicate the notice; successful automatic responses remain hidden. This is presentation only: it does not mark the workflow terminal, consume a pending reply, or permit a retry. A workflow paused after a blocked tool outcome can still show its normal waiting state alongside the failure notice; the declared outcome and retry budget remain authoritative.

A validated componentless automatic-tool agent_message displayed as conversation text is also appended to the existing run transcript before live delivery. Its stable app/chat/turn key makes delivery retries idempotent, including after a handler restart. Reusing that key with different content fails rather than changing the saved message. This lets a saved interview resume with its visible question. Raw structured model output remains hidden, and tools that emit their own UI keep their existing persisted-card path.

These public message projections are marked as presentation-only. They add no model invocation or token usage; native AG2 conversation state remains owned by the Hub knowledge store.

3. Input requests after normalization

Runtime-generated AG2 input requests now normalize onto the same workflow UI lane:

  • transport event: chat.tool_call
  • discriminator: interaction_type=input_request
  • wire-level display mode: display=composer
  • fallback component identity: UserInputRequest

That means response-required UI from InputRequestEvent follows the same render lane as use_ui_tool(...).

Banner suppression for bare conversational turns: When the input request has component type UserInputRequest and carries no explicit prompt, the frontend suppresses the "Awaiting Workflow Reply" composer banner. The banner only renders when the agent provides an explicit prompt or requests a named component other than UserInputRequest — i.e., an intentional interaction, not a routine AG2 Network human turn. The pending tool_call_response callback remains registered and active regardless.

chat.input_request is not emitted to browser clients for runtime-managed interactive input.

An AG2 Network human turn is represented by the channel expecting its registered HumanClient. The runtime surfaces that state as chat.awaiting_reply; it does not fabricate a manager prompt or auto-submit an empty reply. The pending input request stays live so the user can answer through the normal workflow composer or tool_call_response.

When the AG2 run slice ends after emitting one of these input requests, the runtime emits chat.run_complete with status=0 and reason=awaiting_user_input. Terminal workflow completion uses status=1.

4. Native AG2 user handoff without InputRequestEvent

Some AG2 flows hand control back to the user through RevertToUserTarget without emitting a dedicated InputRequestEvent.

Mozaiks now preserves that as explicit runtime state:

  • transport event: chat.awaiting_reply
  • shell behavior: composer remains the reply surface
  • follow-up completion event: non-terminal chat.run_complete with status=0

This is not a second rendered workflow UI lane. It is the canonical signal that the workflow paused for another free-form human turn.

For a native AG2 workflow, the transport publishes the free-form pause after the current run slice releases its admission lease. A client can reply as soon as it sees the pause. A workflow user.input.submit may include a context.client_message_id. The runtime echoes this identifier and the authenticated chat ID in chat.input_ack after admission. If the local task or a different worker holds the chat, the submitting socket receives a matching CHAT_BUSY or CHAT_LOCK_BUSY refusal. If the runtime cannot acquire the lease before starting, it returns CHAT_LOCK_UNAVAILABLE. When a selected model rejects that submission before execution, its WORKFLOW_MODEL_UNAVAILABLE error identifies the same turn. ChatUI returns the refused text to the original composer for the user to edit and send. An unconfirmed socket or HTTP outcome requires checking the conversation before trying again.

When a submitted turn ends with an error, its sender receives chat.error with the same chat and message IDs and a delivery_state. A refused turn can be edited and sent again. An accepted turn stays in the conversation. An unknown outcome leaves the next draft available while the user checks the conversation. A workflow can also broadcast an error with recovery details such as its token top-up action. The sender uses the matching receipt to finish its turn and enable the composer.

The key difference from AG-UI and CopilotKit

AG-UI and CopilotKit make the tool call itself the UI interaction contract.

Mozaiks often emits UI from inside a workflow tool implementation. That means there are two related but distinct things:

  • the underlying workflow tool invocation
  • the UI interaction request emitted by that tool

That is why Mozaiks has historically leaned on a separate UI event id (corr / toolCallId) instead of relying only on the original AG2 tool call_id.

This is also why AG-UI examples feel cleaner: they collapse those two ideas into one protocol lifecycle.

Side-by-side lifecycle mapping

Concern AG-UI / CopilotKit Current Mozaiks Judgment
Render request Tool lifecycle starts on the wire and the frontend renders directly from that tool call use_ui_tool(...) emits chat.tool_call; frontend stores a toolCall render object in chat/artifact state Mozaiks should keep the runtime-owned authoring model
Tool args Explicit tool-call argument lifecycle in AG-UI Fully materialized payload is sent in one chat.tool_call envelope Fine for generated app UI, less reusable as a general protocol
Response wait CopilotKit renderAndWaitForResponse, AG-UI interrupts/resume awaiting_response=true plus tool_call_response; transport resolves either a pending tool-call future or a pending AG2 input callback Capability is present, but the pause/resume model is still implicit rather than first-class
Result delivery Explicit tool result event chat.tool_response for tool results, plus chat.tool_call_dismiss for artifact close Good enough, but less explicit than AG-UI lifecycle phases
Shared state AG-UI snapshot/delta stream; CopilotKit useCoAgent / useAgent No active protocol-level shared-state stream; shell state lives in ChatUIContext Mozaiks should not pretend shell cache equals runtime shared state
Frontend registration Frontend-defined tools and renderer hooks Workflow-local React component registry through WorkflowUIRouter This is a Mozaiks strength and should stay
Primitive UI bus Usually not the main generative UI lane Separate ui.* primitive lane through useAppEventBus Good separation; keep it separate from workflow UI

Current canonical contract

For workflow-owned UI, the current canonical contract should be treated as:

Authoring contract

  • Python side uses use_ui_tool(...) for response-bearing UI
  • Python side uses emit_ui_surface(...) for fire-and-forget UI
  • React side is mounted by WorkflowUIRouter
  • Generated React responds through onResponse(...)

Wire contract

Workflow-owned UI renders through chat.tool_call.

Current required fields for workflow UI transport:

type: chat.tool_call
data:
  tool_call_id: ui_123
  corr: ui_123
  tool_name: request_api_key
  component_type: AgentAPIKeysBundleInput
  workflow_name: AgentGenerator
  interaction_type: ui_tool
  awaiting_response: true
  display: artifact
  display_type: artifact
  payload:
    workflow_name: AgentGenerator
    interaction_type: ui_tool
    display: artifact

Current rules:

  • component_type is required for workflow UI rendering
  • tool_call_id is the primary UI interaction id
  • corr is the wire-level response correlation key
  • workflow_name should be available at the top level and in payload
  • workflow_primitive should be copied from the manifest into payload
  • ui_contract should be copied from the manifest into payload for response-bearing workflow UI
  • shared workflow components should treat ui_contract.actions_schema as the canonical action contract
  • interaction_type should be one of ui_tool, ui_surface, auto_tool, or input_request
  • awaiting_response=true means the frontend is expected to answer
  • display controls composer, inline, artifact, or view behavior

Generic tool invocations that do not carry component_type are not workflow UI surfaces. They are transport/telemetry events, not component-mount requests.

Response contract

Generated React components answer through onResponse(...). ChatPage binds both live and restored tool responses to the existing authenticated POST /api/tool-call/respond helper. Only a successful response containing status: success acknowledges the decision; an open WebSocket or a successful socket write does not. This submission path does not require a connected workflow WebSocket. The WebSocket tool_call_response endpoint remains available to other transport consumers, with its existing owner checks and acknowledgement.

DownloadCenter disables actions while awaiting acknowledgement, displays submission failures, and keeps the decision available after rejection. It does not automatically retry a response after a network failure, which may leave acceptance uncertain. ChatPage reads the current access token when the user submits, not when the artifact first renders.

The response is correlated by the UI interaction id, not by raw message text.

This response contract is only for workflow-owned UI. Persistent app pages that launch workflows do so through declarative page actions (action_type: workflow), not through tool_call_response.

Mozaiks should not switch to CopilotKit wholesale.

It should keep its stronger generated-app model:

  • runtime-owned use_ui_tool(...)
  • workflow-local component registry
  • artifact-aware shell layouts
  • app/workflow/module composition

But it should normalize the contract around those strengths:

  1. chat.tool_call stays the only workflow UI render lane.
  2. The frontend should keep tool_call_id / tool_name as the canonical identifiers all the way through render state.
  3. ui.* stays limited to primitive refresh/update/open/close behavior.
  4. response-required interactions should not introduce any second browser-facing lane instead of remaining a parallel primary HITL lane.
  5. If Mozaiks later needs protocol reuse beyond its own shell, it should evolve chat.tool_call toward AG-UI-style explicit phases rather than adding more side channels.

The next protocol step should be:

  • keep the current authoring model
  • keep the chat.* namespace if desired
  • make the Mozaiks-owned wire lifecycle more explicit, using AG-UI as a comparison point where helpful

That means:

  • explicit call lifecycle fields or events
  • one canonical interrupt/resume model
  • one canonical shared-state model if shared runtime state is needed
  • no overlap between workflow UI rendering and primitive ui.* events

The goal is not “become CopilotKit.”

The goal is:

  • AG-UI-grade protocol discipline without adopting AG-UI identity or adapters by default
  • plus Mozaiks-grade generated app composition