Messaging turn workflows
A messaging turn carries one user message from a platform event to a managed Claude Code task and back to the same conversation. The workflow normalizes platform data, separates commands from prompts, admits prompts to a conversation tree, streams a node result into a transcript, and updates the platform through one status message.
This page complements Messaging platforms, Messaging conversation trees, and Messaging transcripts, rendering, and voice.
Turn lifecycle
The turn lifecycle joins platform ingress, workflow state, Claude Code execution, and outbound delivery. A platform adapter gives the workflow one common message shape, while the workflow keeps conversation state independent from Telegram or Discord details.
The main path is:
- A platform runtime receives a message and checks its platform access rules.
- The runtime converts the event into an
IncomingMessage, which defines the platform, chat, message ID, text, reply target, and optional thread data. MessagingWorkflowrecords the incoming message and captures a stop/clear generation. This token prevents a turn from being admitted after a matching cancellation boundary.MessagingTurnIntakedispatches a known slash command. It drops status messages and sends other messages to reply lookup and queue admission.- The workflow creates or selects a conversation tree. A new root starts at once when no other node owns the tree. A reply joins the tree under the referenced node. A busy tree places the node in FIFO order.
- The tree processor runs the active node through a managed Claude Code session. A reply can fork from the parent node's session.
- The runner parses CLI events and applies them to an ordered transcript. The transcript editor renders the current answer and status into the platform status message.
- Completion or failure changes the node state. The tree then releases the claim and starts the next queued node, if one exists.
This diagram shows the normal path and the separate command path through the same platform boundary.
flowchart TD
A[Telegram or Discord event] --> B[Platform normalization]
B --> C[MessagingWorkflow]
C --> D{Slash command?}
D -->|Yes| E[Command handler]
E --> F[Send, edit, delete, stop, or clear]
D -->|No| G[Reply lookup and admission]
G --> H{Tree available?}
H -->|No| I[Create root or queue node]
H -->|Yes| I
I --> J[Node claim]
J --> K[Managed Claude Code session]
K --> L[CLI event parser]
L --> M[Transcript and status editor]
M --> N[Platform outbox]
K --> O[Complete or fail tree claim]
O --> P[Next queued node]
P --> K
References: src/…/workflow.py• L330-414 src/…/turn_intake.py• L56-161 src/…/manager.py• L118-190 src/…/node_runner.py• L113-235
Platform event intake
Platform runtimes own connection life cycles and event filtering. They pass only accepted text or audio work to the shared workflow, so the rest of the turn does not need to know which messaging SDK produced the event.
| Platform | Accepted text path | Reply and thread identity | Access boundary |
|---|---|---|---|
| Telegram | Text and slash-command updates become IncomingMessage values. | Keeps reply message ID and forum topic ID. | Optional allowed user ID. |
| Discord | Non-bot messages in allowed channels become IncomingMessage values. | Keeps reply message ID. | Configured channel allowlist. |
Audio follows a related intake path. The platform adapter creates a voice request, the voice flow transcribes it, and the result is handed back to the same message handler as an incoming prompt. A status message created during transcription can be edited in place when the prompt enters the normal turn path.
The platform runtime registers MessagingWorkflow.handle_message as its callback. Telegram uses polling and Discord uses a client event, but both expose the same runtime and outbound ports to the workflow.
References: src/…/models.py• L24-57 src/…/telegram_inbound.py• L12-73 src/…/discord_inbound.py• L31-74 src/…/telegram.py• L137-145 src/…/discord.py• L171-205 src/…/application.py• L416-434
Command dispatch
Command dispatch handles control actions before a message can create or join a Claude Code turn. The dispatcher reads the first slash token and removes a bot mention suffix, then maps the base command to a small command handler.
| Command | Scope | Product effect |
|---|---|---|
/stop | Replied message or whole messaging workflow. | Cancels the selected owner or all active and pending work. |
/clear | Replied subtree or whole chat. | Removes the selected conversation branch or resets the chat state and managed messages. |
/stats | Whole workflow. | Reports active CLI sessions and conversation tree count. |
An unknown slash token is not handled by the command dispatcher. It continues through prompt intake, which allows the platform to decide how to treat ordinary text that is not a supported control command.
References: src/…/command_dispatcher.py• L7-31 src/…/commands.py• L29-182 src/…/command_context.py• L37-96 src/…/turn_intake.py• L65-72
Prompt admission
Prompt admission creates the user-visible status message before it commits the turn to the conversation state. This order gives the node a stable status target and lets the system remove temporary UI if a concurrent stop or clear makes the admission invalid.
When intake handles a prompt, it follows this decision path:
- Resolve a reply reference within the same platform and chat scope. A reply can target the original prompt or its status message.
- Create or edit the initial status message. A new root says it is launching. A reply says it is continuing. A busy reply can show its queue position.
- Recheck the admission token inside the workflow state boundary.
- Ask the tree manager to reject a duplicate, reject a removed parent, claim the node, or queue the node.
- Delete the status message, and sometimes the prompt, when admission is rejected. Otherwise keep the status ID as the node's UI target.
- Update queue positions when another node leaves the queue. Change the selected node to
Processing...when its claim starts.
This diagram shows why the status message is part of admission rather than a later display concern.
sequenceDiagram
participant U as User
participant R as Runtime
participant W as Workflow
participant I as Turn intake
participant T as Tree manager
participant O as Outbox
U->>R: Message or reply
R->>W: IncomingMessage
W->>I: Classify and prepare turn
I->>W: Resolve reply
I->>O: Send or edit status
I->>W: Admit with generation token
W->>T: Claim, queue, or reject
alt accepted and queued
T-->>I: Queue position
I->>O: Edit queued status
else rejected
T-->>I: Rejection
I->>O: Delete temporary messages
else claimed
T-->>W: Node claim
end
References: src/…/turn_intake.py• L74-161 src/…/workflow.py• L350-414 src/…/manager.py• L118-190 src/…/runtime.py• L105-163
Conversation tree coordination
A conversation tree represents one chat's reply structure and permits one active node at a time. Each node keeps its prompt, reply relation, status target, execution state, and optional Claude session link. The tree manager coordinates several trees without exposing their mutable state to the rest of the workflow.
Replies preserve conversation context. The active node's session can be reused for a root continuation or forked for a reply child, while the tree still serializes node execution. A child that waits behind an active node remains visible as a queued status and moves forward only after the current claim finishes.
The tree manager also owns cancellation boundaries. Stop marks runnable nodes as cancelled and interrupts their active task. Clear removes a whole chat or a literal reply subtree, unindexes its references, and returns the message IDs that the command layer must delete. Failure can propagate to pending descendants so they do not run under a failed parent.
References: src/…/runtime.py• L38-39 src/…/runtime.py• L165-274 src/…/runtime.py• L276-347 src/…/runtime.py• L366-426 src/…/manager.py• L293-305 src/…/transitions.py• L42-80
Node execution
Node execution turns one admitted claim into one managed Claude Code interaction. The runner creates a transcript and render context, obtains a new or parent-linked session, sends the node prompt, and consumes the session's event stream until a terminal result or failure appears.
Session identity becomes durable only after the CLI reports the real session ID. This lets the workflow track a temporary session handle during startup while keeping the tree linked to the session that can be resumed or forked later.
The runner treats terminal outcomes as state transitions:
| Outcome | Node effect | User-facing effect |
|---|---|---|
Successful complete | Completes the active claim. | Shows the final transcript and Complete. |
| CLI or task error | Fails the claim. | Shows Error or Task Failed; pending children can also fail. |
| Stop cancellation | Fails the claim without parent propagation. | Shows Stopped.. |
| Other cancellation | Fails the claim without parent propagation. | Shows Cancelled unless clear owns message removal. |
| No terminal event | Fails the claim with a synthetic error. | Shows Task Failed. |
After the runner returns, the processor completes the claim transition even when the runner was cancelled. The manager then starts the next queued claim under the tree lock, which prevents two nodes in one conversation tree from running at the same time.
References: src/…/node_runner.py• L134-235 src/…/node_runner.py• L242-337 src/…/node_runner.py• L339-405 src/…/processor.py• L157-225 src/…/manager.py• L293-305
CLI event parsing
CLI event parsing converts raw Claude Code stream data into a small ordered event language for transcript and status handling. The parser accepts full messages, streaming deltas, block starts and stops, tool results, errors, and process exits while ignoring system events and unknown shapes.
The parser keeps content order. Text and thinking become transcript chunks. Tool calls carry their IDs and inputs. A successful exit becomes completion, while an error event or non-zero exit becomes failure data. Raw error text is logged only when the diagnostic setting allows it.
References: src/…/event_parser.py• L12-23 src/…/event_parser.py• L30-85 src/…/event_parser.py• L88-150 src/…/event_parser.py• L151-184
Transcript and UI updates
The transcript buffer is the view model for one node's streamed answer. It groups text, thinking, tool calls, tool results, errors, and subagent markers into ordered segments, then renders those segments with the platform's formatting rules and character limit.
The editor uses the node's single status message as the live display. It skips edits that occur too soon after the previous edit, avoids sending unchanged text, and forces a final edit for block stops and terminal states. This reduces platform traffic while keeping the visible answer close to the CLI stream.
References: src/…/buffer.py• L30-102 src/…/buffer.py• L138-200 src/…/renderer.py• L10-65 src/…/ui_updates.py• L13-99 src/…/node_event_pipeline.py• L58-120
Platform I/O
Platform I/O is the boundary that sends, edits, and deletes customer-visible messages. The shared OutboundMessenger port keeps workflow actions platform-neutral, while each platform messenger maps those actions to its SDK and platform limits.
All outbound work passes through a per-platform outbox and rate limiter. Edits and bulk deletes use deduplication keys, so newer display state can replace older queued work. Awaited operations return a delivery result when the workflow needs a message ID. Fire-and-forget operations remain owned until they finish or the platform shuts down.
| Concern | Shared behavior | Platform-specific behavior |
|---|---|---|
| Send | Queue, rate-limit, and optionally await for a message ID. | Create a Telegram reply or Discord message. |
| Edit | Queue by chat and message ID, with latest-update compaction. | Apply Markdown mode or Discord text rules. |
| Delete | Queue a stable bulk-delete request. | Use Telegram batches or Discord per-message deletion. |
| Failure | Report through the owning task or safe logs. | Ignore known missing-message cases where the platform permits it. |
References: src/…/ports.py• L32-62 src/…/outbox.py• L20-113 src/…/limiter.py• L17-23 src/…/limiter.py• L61-169 src/…/telegram_io.py• L40-126 src/…/discord_io.py• L22-110
State and restart behavior
The session store preserves conversation snapshots and managed platform message IDs. The workflow saves tree changes as turns are admitted, sessions become real, nodes finish, or cancellations change the tree, so a later process can restore the conversation shape and clear-owned messages.
Restoration does not resume an in-flight node. Pending and in-progress nodes are normalized to interrupted failures before the restored tree is published. Once platform delivery is available, the workflow replaces stale queued or processing status with Interrupted by server restart.
References: src/…/store.py• L19-44 src/…/store.py• L91-113 src/…/store.py• L114-161 src/…/workflow.py• L182-216 src/…/runtime.py• L472-484 src/…/application.py• L412-433
Change checklist
When these files or sections are changed, remember to consider these:
- Keep
IncomingMessagereply and thread fields aligned with both platform normalizers and the outbound reply calls. - Keep command names in command_dispatcher.py aligned with the command behavior and the message-kind records used by
/clear. - Keep admission generation checks aligned with stop and clear changes so a status message cannot survive a rejected turn.
- Keep tree claim completion and processor task cleanup coupled. A new terminal path must still release the claim and allow the next queue entry to start.
- Keep parsed CLI event types aligned with
TranscriptBufferandget_status_for_event; an event accepted by one but not the other can silently lose transcript or status output. - Keep status message edits within both platform message limits and the outbox's edit deduplication model.
- Keep restored tree state and managed-message ownership consistent when adding a new message that
/clearmust remove.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| Stop or clear advances its generation before admission commits. | The prompt's temporary status is deleted and the turn is not added to a tree. | Admission compares its token with current stop and clear generations under the workflow lock. |
| A reply parent was removed before admission. | The child is rejected and its status, and in this case the prompt, are discarded. | Reply resolution and tree admission validate the parent reference. |
| The CLI ends without a success exit or error exit. | The node could remain runnable without a terminal user result. | The runner creates a synthetic error and fails the claim. |
| A queued edit is followed by a newer edit for the same status message. | Old transcript text can reach the platform after newer text. | Outbox edit keys compact pending work to the latest operation. |
| A node task is cancelled before its runner starts. | The claim can remain attached and block later work. | The tree processor creates recovery work that completes and advances the claim. |
| A status message no longer exists on the platform. | A live update or cleanup action cannot change that message. | Platform I/O treats known missing-message errors as best-effort failures while tree state remains authoritative. |
Key files
| File | Why to read it |
|---|---|
| src/…/workflow.py | Main coordinator for ingress, admission, cancellation, persistence, and platform side effects. |
| src/…/turn_intake.py | Classification and admission path for commands, prompts, replies, status messages, and queue positions. |
| src/…/node_runner.py | Lifecycle of one admitted node from session creation through terminal cleanup. |
| src/…/node_event_pipeline.py | Link between parsed CLI events, transcript state, UI status, and tree outcomes. |
| src/…/event_parser.py | Common event language produced from raw Claude Code stream events. |
| src/…/manager.py | Public coordination layer for tree lookup, claims, cancellation, persistence snapshots, and successor tasks. |
| src/…/runtime.py | Single-tree rules for reply structure, one active claim, FIFO queueing, completion, failure, and clear operations. |
| src/…/telegram.py | Telegram ingress and runtime lifecycle. |
| src/…/discord.py | Discord ingress and runtime lifecycle. |
| src/…/outbox.py | Shared outbound queue and delivery ownership model. |
| src/…/ui_updates.py | Throttled rendering and live status-message edits. |
| src/…/store.py | Durable conversation and managed-message state used by restart and clear flows. |