The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
docs(web_chat): document the web chat module
Steven Enamakel4a05e2d600ea
diff --git a/crates/openhuman-core/src/web_chat/README.md b/crates/openhuman-core/src/web_chat/README.mdindex 9f7316bd1d..d539db7058 100644--- a/crates/openhuman-core/src/web_chat/README.md+++ b/crates/openhuman-core/src/web_chat/README.md@@ -1,11 +1,19 @@# Web chat-The turn runner for the in-app chat (desktop and web). It takes a raw user+The in-app chat (desktop and web) as a thin host. It takes a raw usermessage, runs it through the agent harness on the thread's own session, andends with a reply that is stored durably and announced to the client exactlyonce. It owns the `channel.web_*` RPC namespace and the business logic behindthe Socket.IO `chat:start` and `chat:cancel` handlers.+Two shared engines do the generic work, and this module is only what OpenHuman+alone can supply:++| Engine | Owns | Where |+| --- | --- | --- |+| TinyAgents' turn runner | The lifecycle of a turn: ingress order, per-thread serialization, the five queue modes, cancellation generations, the idle and wall-clock guards, reply persistence, exactly one terminal event | `vendor/tinyagents/crates/tinyagents-harness/src/turn_runner/` |+| The `tinychannels` web adapter | The projection of canonical output events onto the web wire, with per-turn `seq` | `vendor/tinychannels/crates/tinychannels-runtime/src/adapters/web/` and `tinychannels-bus` (`web.rs`, the wire types) |+External messaging providers (Telegram, Discord and so on) live in`channels/`, but their inbound messages are dispatched through this module's`start_chat` as well (`channels/bus/subscriber.rs`). So this is the single@@ -24,27 +32,24 @@ subscriber all listen to.v v v+-----------------------------------------------------+| start_chat (ops/start_chat.rs) |- | attachments -> prompt guard -> approval reply? |- | -> beforeSubmitPrompt hook -> queue mode |+ | validate -> TurnRequest<QueuedPayload> -> runner |+ | answers: started | queued | approval reply | refused|+-----------------------------------------------------+- | Interrupt (default) | Steer/Followup/Collect -> RunQueue- | Parallel -> spawn_parallel_turn (ops/parallel_turn.rs)- v- tokio::spawn( run_turn_under_cancel_and_deadline( )- cancel token + wall-clock backstop- + WebChat origin + chat approval context- run_chat_task (run_task.rs) )- |- | checkout_session_agent (session.rs)- | spawn_progress_bridge (progress_bridge.rs) ---> WebChannelEvent- | agent.run_single_with_origin (deltas, tools,- | checkin_session_agent heartbeat, ...)- v- Ok(reply) --> presentation::deliver_response- persist_reply (reply_persistence.rs) -> conversation store- announce_reply -> one chat_done- spawn_follow_up_suggestions -> chat_suggestions (later)- Err(e) --> web_errors::classify_inference_error -> one chat_error+ v tokio::spawn( TurnRunner::run ) (runner.rs)+ +-----------------------------------------------------++ | ingress (ingress.rs) attachments -> guardrail |+ | -> approval reply -> hook |+ | queue mode Interrupt | Steer/Followup/Collect | Parallel+ | checkout (turn_host.rs, session.rs) |+ | run agent.run_single_with_approval |+ | progress --tap--> runner --> ProgressProjection |+ | --> web adapter --> bus |+ | persist (turn_events.rs WebReplies) |+ | terminal (turn_events.rs WebEvents) |+ +-----------------------------------------------------++ Completed -> one chat_done (+ chat_suggestions later)+ Failed -> web_errors::classify_inference_error -> one chat_error+ Cancelled -> chat_error{cancelled} + chat_cancelled```1. A `chat:start` socket event arrives in `openhuman-rpc/src/server/socketio.rs`@@ -52,79 +57,92 @@ subscriber all listen to.calls `start_chat` with the raw message, the thread and client ids, and anymodel, temperature, locale or queue-mode overrides.-2. `start_chat` stages `[FILE:...]` and `[IMAGE:...]` markers through- `agent::attachments::stage` first. A multi-megabyte base64 blob must never- reach prompt-injection scanning or persistence. It then runs- `security::prompt_injection::enforce_prompt_input`; a block comes back as- `StartChatError::Guardrail` with a verdict, score and reasons so the- frontend can classify on `chat_error.error_type == "guardrail"` instead of- matching copy. Next it checks whether the thread has a parked chat-native- approval and the message parses as an approval reply- (`security::approval::parse_approval_reply`); if so the reply goes to the- approval gate and no new turn starts. Only after that does a configured- `beforeSubmitPrompt` hook see the message, so a bare "yes" answering an- approval can never be blocked by a hook.--3. The queue mode decides what happens to a turn already in flight on the- thread. `QueueMode` ([`types.rs`](./types.rs)) has five values. `Interrupt` (the default)- cancels the current turn and starts this one. `Steer`, `Followup` and- `Collect` map to TinyAgents run-queue lanes (`QueueMode::queue_lane`) and- are pushed onto the running turn's `RunQueue` instead of starting a turn;- with nothing in flight they start a normal turn.- `Parallel` starts an isolated fork alongside whatever is running- ([`ops/parallel_turn.rs`](./ops/parallel_turn.rs)), tracked in its own `parallel_in_flight()` table- keyed by request id so it never touches interrupt or queue semantics.--4. For a primary turn, `start_chat` records an `InFlightEntry` in `in_flight()`- and spawns a task (under `CoreContext::propagate`) that drives- `run_task::run_chat_task` through `run_turn_under_cancel_and_deadline`- ([`ops/turn_guards.rs`](./ops/turn_guards.rs)). That wrapper puts four things around the same- future: a cooperative `CancellationToken`, the wall-clock backstop, the- `AgentTurnOrigin::WebChat` scope, and the turn's `ApprovalTurnContext`- (handed to `run_chat_task`, which gives it to the session turn).--5. `run_chat_task` checks the session agent out of the per-thread cache- (`session::checkout_session_agent`). The entry is removed from- `thread_sessions()` for the duration of the turn so two turns can never- drive one agent. It is reused when its `SessionCacheFingerprint` still- matches; otherwise a new agent is built. A new agent needs no history+2. `start_chat` builds a `TurnRequest<QueuedPayload>` (the payload,+ `agent/queued_turn.rs`, carries the context, client id, model, temperature,+ locale and `ChatRequestMetadata`) and spawns `TurnRunner::run` under+ `CoreContext::propagate`. It then waits for the first answer on the+ request's `Admission` and returns it: the new request id (`Started`), the+ queued JSON (`Queued`), the approval request id (`Consumed`) or the refusal+ (`Rejected`). The generic `TurnRunner` runs one request at a time per+ `(agent, profile, thread)`; `WebRuntime` (`runner.rs`) holds one runner per+ core context, so two embedded agents never share a turn table.++3. **Ingress** (`ingress.rs`, `WebIngress`) is the runner's `IngressPolicy`,+ called once per stage in a fixed order. `[FILE:...]` and `[IMAGE:...]`+ markers are staged through `agent::attachments::stage` first, so a+ multi-megabyte base64 blob never reaches prompt-injection scanning or+ persistence. `security::prompt_injection::enforce_prompt_input` follows; a+ block comes back as `StartChatError::Guardrail` with a verdict, score and+ reasons so the frontend can classify on `chat_error.error_type ==+ "guardrail"` instead of matching copy. Next, a parked chat-native approval+ plus a message that parses as an approval reply+ (`security::approval::parse_approval_reply`) goes to the approval gate and+ no turn starts. Only then does a configured `beforeSubmitPrompt` hook see+ the message, so a bare "yes" answering an approval can never be blocked by a+ hook. A refusal or a consumed reply is answered through the `Admission` and+ publishes nothing.++4. **Queue modes.** `QueueMode` (`tinychannels_bus::web`) has five values.+ `Interrupt` (the default) cancels the thread's turn and starts this one;+ the superseded turn is announced as `chat_cancelled{superseded}` naming its+ replacement. `Steer`, `Followup` and `Collect` join the running turn's+ `RunQueue` (the very queue the agent's steering feed drains mid-turn) and+ are answered `queued`; with nothing in flight they start a normal turn.+ What the turn did not absorb is handed back by the runner once it+ completed: steers and follow-ups start as fresh turns, leftover collects+ start as follow-ups (`WebEvents::collected`). A failed or cancelled turn+ drops its queue (those messages are never announced). `Parallel` runs an+ isolated fork (`checkout_fork`) beside the primary turn without touching+ interrupt or queue semantics.++5. **Checkout and run** (`turn_host.rs`, `WebHost`). `checkout` resolves the+ config and the thread's working folder, then takes the session agent out of+ the per-thread cache (`session::checkout_session_agent`). The entry is+ removed from `thread_sessions()` for the duration of the turn so two turns+ can never drive one agent; it is reused when its `SessionCacheFingerprint`+ still matches, otherwise a new agent is built. A new agent needs no historyseeding: `set_thread_id` binds the session's durable identity- (`SessionRef`) and the turn resumes the thread's one transcript by it. The- task then spawns the progress bridge, awaits- `agent.run_single_with_origin`, and checks the agent back in with- `checkin_session_agent` unless the turn poisoned it. A fork never takes or- returns the cached agent.--6. While the turn runs, `spawn_progress_bridge` turns each `AgentProgress`- event into `WebChannelEvent`s (`text_delta`, `thinking_delta`,- `tool_call`, `tool_result`, `chat_interim`, `turn_cost`, sub-agent events- and so on), mirrors turn state into the `TurnStates` port,- and emits an `inference_heartbeat` every `INFERENCE_HEARTBEAT_SECS` (20 s)- so a long silent prefill does not trip the frontend's roughly 120 s- silence timeout (#4270). Sub-agent arms live in- [`progress_bridge_subagent_events.rs`](./progress_bridge_subagent_events.rs); time to first visible output is- stamped by [`turn_timing.rs`](./turn_timing.rs); at the end of a turn- [`journal_shadow.rs`](./journal_shadow.rs) compares the live trace spans with the spans- reprojected from the durable journal and logs what differs.--7. On success the spawned task calls `presentation::deliver_response`. It- first writes the reply to the thread's conversation store- (`persist_reply`, which uses `reply_persistence::persist_delivered_reply`)- under the deterministic id `run_reply_message_id(request_id)`, so the- answer survives a client reconnect or reload (#6034) and the client's own- append collapses onto the same row. Then `announce_reply` emits exactly one- `chat_done` carrying the model's unmodified text. For the main single-user- turn it also spawns `suggestions::spawn_follow_up_suggestions`, a cheap+ (`SessionRef`) and the turn resumes the thread's one transcript by it.+ `run` drives `agent.run_single_with_approval` under the `WebChat` turn+ origin and the chat `ApprovalTurnContext`, applies the per-thread budget+ correlation on error, speaks the reply when asked, and keeps the reply for+ the reply store. `checkin` returns a healthy agent to the cache and drops a+ failed one, so the next request cold-boots from the durable transcript.++6. **Progress, projected once.** The agent's `AgentProgress` stream goes+ through a tap (`turn_host::tap_progress`) that folds each event into the+ idle record and tells the runner when model or tool work opens and closes+ (`WorkStarted` / `WorkFinished`, `turn_activity::WorkTracker`), then+ hands it to the runner, which calls `WebEvents::progress` in order. That is+ `ProgressProjection::on_event` (`progress.rs`), the one consumer: it maps the+ event to the canonical output vocabulary (`progress_map.rs`), publishes it+ through the web adapter (`surface.rs`), and does the host's side effects in+ the same pass: the run ledger (`progress_ledger.rs`), the `TurnStates`+ mirror, the tracing export (`progress_trace.rs`, `journal_shadow.rs`),+ first-token timing and the throttled live `turn_cost`. An+ `inference_heartbeat` every `INFERENCE_HEARTBEAT_SECS` (20 s) keeps a long+ silent prefill from tripping the frontend's roughly 120 s silence timeout+ (#4270). The Flow Canvas copilot drives the same projection from a channel+ through `spawn_progress_bridge`.++7. **Completion.** The runner persists the reply (`WebReplies`, which uses+ `reply_persistence::persist_delivered_reply`) under the deterministic id+ `run_reply_message_id(request_id)`, so the answer survives a client+ reconnect or reload (#6034) and the client's own append collapses onto the+ same row. It then releases the thread and emits the terminal event, so a+ `chat_done` is never what lets the next message interrupt the turn that+ just finished. `WebEvents::terminal` announces exactly one `chat_done`+ carrying the model's unmodified text (`presentation.rs`), and for the main+ single-user turn spawns `suggestions::spawn_follow_up_suggestions`, a cheap`summarization`-role call that may emit `chat_suggestions` after- `chat_done`. It never delays the reply and is gated on- `web_chat.suggestions_enabled`.+ `chat_done` (gated on `web_chat.suggestions_enabled`).-8. On failure, `run_chat_task` first consults the per-thread budget signal- ([`ops/budget_correlation.rs`](./ops/budget_correlation.rs)). An empty 200 on the same provider binding as+8. **Failure.** `run` first consults the per-thread budget signal+ (`ops/budget_correlation.rs`): an empty 200 on the same provider binding asa recent budget-exhausted failure is reclassified as out-of-credits (#3386),because the managed route closes the stream cleanly when credits run out.- The spawned task then runs the error string through- `web_errors::classify_inference_error` and emits one `chat_error`, and+ `WebEvents::terminal` runs the error through+ `web_errors::classify_inference_error`, emits one `chat_error`, and`sentry_suppression_reason` decides whether it pages.### The chat_error payload@@ -143,8 +161,8 @@ events (they become the turn's reply text), so they carry no key.Background-delivery notices (`agent::orchestration::background_delivery`) andgoal continuations enter through `run_system_turn_on_thread`-([`ops/system_turn.rs`](./ops/system_turn.rs)) instead of `start_chat`. They skip ingress, `in_flight()`-and the progress bridge, run with `SYSTEM_CLIENT_ID` ("system"), and return+([`ops/system_turn.rs`](./ops/system_turn.rs)) instead of `start_chat`. They skip ingress, the turn runner+and the progress projection, run with `SYSTEM_CLIENT_ID` ("system"), and returnthe reply text for the caller to deliver. They still go through the samesession checkout, so the model sees the conversation and the turn lands in thethread's transcript. A turn run on a throwaway session host would write a@@ -177,37 +195,42 @@ role routes; hints and unqualified legacy model ids keep their configuredprovider route. `provider_role_for_model_override` picks the provider rolethat feeds the fingerprint's binding.-### Cancellation and the backstop+### Cancellation and the guards-`cancel_chat` and `cancel_chat_scoped` ([`ops/channel_ops.rs`](./ops/channel_ops.rs)) cancel by-thread, or by request id when one is given. A stale cancel for a superseded-request is ignored (`cancel_should_target`) so the newer turn survives. Without-a request id, a cancel also stops the thread's parallel forks and detached-background sub-agents. `state::cancel_in_flight_gracefully` cancels the token-first and only hard-aborts the task if it has not unwound after a short grace-period.+`cancel_chat_scoped` and `channel_web_cancel` (`ops/channel_ops.rs`) cancel by+thread, or by request id when one is given, through the runner's+`cancel_requests`. A stale cancel for a superseded request is ignored, because+the runner cancels only the generation the id names, so the newer turn+survives. Without a request id, a cancel also stops the thread's parallel forks+and its detached background sub-agents. The cancelled turn gets a short grace+(`cancel_grace`, 3 s) to hand back the rounds it completed, with its own+cancellation token already fired. The runner publishes each cancelled turn's+terminal event; `CancelNote` (`runner.rs`) tells it why (a Stop, or which+request superseded it) and which client to address.Two guards make sure a turn always ends in a terminal event instead of an-endless heartbeat stream (#4746):--- The **idle guard** ([`turn_activity.rs`](./turn_activity.rs)) ends a turn- that has emitted no progress event, with no model or tool call in flight, for- 900 s (`OPENHUMAN_WEB_TURN_IDLE_SECS`, `0` disables it). `run_chat_task` taps- the turn's progress stream into a per-turn activity record on its way to the- bridge. Every event restarts the clock, and an open model call- (`IterationStarted` → `ModelCallCompleted`) or tool call (`ToolCallStarted`- → `ToolCallCompleted`) holds it, so a silent provider retry or a long shell- build is never idle. What it catches is silence nothing else bounds: session- checkout, the persistence plumbing, or a harness that stopped with no call- open.+endless heartbeat stream (#4746), both owned by the runner:++- The **idle guard** ends a turn that has emitted no progress event, with no+ model or tool call in flight, for 900 s (`OPENHUMAN_WEB_TURN_IDLE_SECS`, `0`+ disables it). The host feeds it: every event is progress, and+ `turn_activity::WorkTracker` reports open calls, so a silent provider retry+ or a long shell build is never idle. What it catches is silence nothing else+ bounds: session checkout, the persistence plumbing, or a harness that+ stopped with no call open.- The **wall-clock backstop** is the fixed total ceiling, 3600 s by default- (`agent::turn_deadline`, `OPENHUMAN_WEB_TURN_TIMEOUT_SECS`, `0` disables it- and the derived deadlines). The harness winds the turn down at 3480 s and- writes the grounded close, and its own `max_wall_clock_ms` is clamped to- 3540 s, so a busy turn still delivers an answer before the backstop drops it.--The backstop used to be 900 s and did both jobs, so a turn that was working-steadily was wound down at 780 s like a wedged one.+ (`agent::session_host::turn_backstop`, `OPENHUMAN_WEB_TURN_TIMEOUT_SECS`, `0`+ disables it and the derived deadlines). The harness winds the turn down at+ 3480 s and writes the grounded close, and its own `max_wall_clock_ms` is+ clamped to 3540 s, so a busy turn still delivers an answer before the+ backstop drops it.++When either fires, the runner asks `WebSummarizer::grounded_close`+(`turn_close.rs`) for a reply that says what the turn got done and where it got+stuck, built from the turn-state snapshot and `turn_activity::StuckPoint`. That+reply is delivered like any other. A turn that stopped before it resolved its+own config has no workspace to write to and ends in a retryable `turn_timeout`+`chat_error`.### The event bus@@ -235,30 +258,35 @@ and artifact bridges itself (`openhuman-tui/src/runner.rs`).| Path | What it does || --- | --- || [`mod.rs`](./mod.rs) | Module wiring and re-exports. No business logic. |+| [`runner.rs`](./runner.rs) | `WebRuntime` (the runner plus its shared state, one per core context), `Shared`/`TurnSlot` per-request state, `Admission`, `CancelNote`. |+| [`ingress.rs`](./ingress.rs) | `WebIngress`: the runner's ingress policy (attachments, guardrail, approval reply, hook). |+| [`turn_host.rs`](./turn_host.rs) | `WebHost`: session checkout/checkin and the agent run, the progress tap, the heartbeat. |+| [`turn_events.rs`](./turn_events.rs) | `WebEvents` (progress and the terminal event), `WebFailures` (error copy), `WebReplies` (reply store), `WebSummarizer` (grounded close). Sentry suppression and timeout tagging. |+| [`turn_activity.rs`](./turn_activity.rs) | The idle guard's inputs (`WorkTracker`) and where a turn got stuck (`TurnActivity`, `StuckPoint`). |+| [`turn_close.rs`](./turn_close.rs) | The reply that closes a turn a guard stopped. |+| [`progress.rs`](./progress.rs) | `ProgressProjection`, the single consumer of a turn's progress, and `spawn_progress_bridge`. |+| [`progress_map.rs`](./progress_map.rs) | `AgentProgress` to the canonical `ChannelOutputEvent`, with payload caps. |+| [`progress_ledger.rs`](./progress_ledger.rs) | The run-ledger rows and telemetry a turn's progress writes. |+| [`progress_trace.rs`](./progress_trace.rs), [`journal_shadow.rs`](./journal_shadow.rs) | Tracing export and the live-versus-journal span comparison. |+| [`surface.rs`](./surface.rs) | The host side of the web adapter: `Surface` (one adapter per turn) and the sink onto the broadcast bus. || [`ops.rs`](./ops.rs) | Thin shell over [`ops/`](./ops/); re-exports the request surface and state. |-| [`ops/start_chat.rs`](./ops/start_chat.rs) | `start_chat` and `StartChatError`: ingress, guardrail, approval-reply routing, queue dispatch, and the spawned turn body that delivers or classifies. |-| [`ops/channel_ops.rs`](./ops/channel_ops.rs) | `cancel_chat`, `cancel_chat_scoped`, and the `channel_web_*` RPC handlers. |-| [`ops/parallel_turn.rs`](./ops/parallel_turn.rs) | Spawns and cancels `QueueMode::Parallel` forks. |+| [`ops/start_chat.rs`](./ops/start_chat.rs) | `start_chat`, `StartChatError`, and the backstop resolution. |+| [`ops/channel_ops.rs`](./ops/channel_ops.rs) | `cancel_chat_scoped`, `cancel_all_turns`, and the `channel_web_*` RPC handlers. || [`ops/system_turn.rs`](./ops/system_turn.rs) | `run_system_turn_on_thread` for host-authored turns. |-| [`ops/state.rs`](./ops/state.rs) | `thread_sessions()`, `in_flight()`, `parallel_in_flight()`, keying helpers, `invalidate_thread_sessions`, `cancel_should_target`. Each table is a slot of the ambient agent context, so two embedded agents never share an entry; outside an agent context it is the process default. |-| [`ops/turn_guards.rs`](./ops/turn_guards.rs) | `run_turn_under_cancel_and_deadline`, the wall-clock backstop, Sentry suppression and timeout tagging. |+| [`ops/state.rs`](./ops/state.rs) | `thread_sessions()`, keying helpers, `invalidate_thread_sessions`, `cancel_should_target`, the test accessors over the runner. Each table is a slot of the ambient agent context, so two embedded agents never share an entry; outside an agent context it is the process default. || [`ops/budget_correlation.rs`](./ops/budget_correlation.rs) | `thread_budget_signals()` and `classify_budget_correlation` for the empty-200-after-budget case. |-| [`ops/test_hooks.rs`](./ops/test_hooks.rs) | Debug/test hooks that force or block `run_chat_task`. |-| [`run_task.rs`](./run_task.rs) | `run_chat_task`: checkout, progress bridge, run, budget correlation on error, checkin. |+| [`ops/test_hooks.rs`](./ops/test_hooks.rs) | Debug/test hooks that force or park a turn. || [`session.rs`](./session.rs) | Session checkout and checkin, fingerprinting, `CheckoutPolicy`, target agent id, locale reply directive, per-turn provider and model routing. |-| [`progress_bridge.rs`](./progress_bridge.rs) | `spawn_progress_bridge`: `AgentProgress` to `WebChannelEvent`, turn-state mirror, heartbeat. |-| [`progress_bridge_subagent_events.rs`](./progress_bridge_subagent_events.rs) | The bridge's `AgentProgress::Subagent*` handlers. |-| [`turn_timing.rs`](./turn_timing.rs) | Time to first visible output, and rate limiting for live `turn_cost` events. |-| [`journal_shadow.rs`](./journal_shadow.rs) | Compares live trace spans with spans reprojected from the journal and logs divergences. |-| [`presentation.rs`](./presentation.rs) | `deliver_response` (persist, then one `chat_done`), `deliver_response_single_bubble` for core-initiated turns, and legacy `chat_segment` helpers. |+| [`presentation.rs`](./presentation.rs) | The terminal `chat_done` event, `deliver_response` (persist, then one `chat_done`) for the Flow Canvas, and `deliver_response_single_bubble` for core-initiated turns. || [`reply_persistence.rs`](./reply_persistence.rs) | `persist_delivered_reply`: durable reply row under the deterministic reply id. || [`suggestions.rs`](./suggestions.rs) | Post-turn follow-up suggestions (`chat_suggestions`). |-| [`channel_event.rs`](./channel_event.rs) | `WebChannelEvent` and its payload types (`TurnUsagePayload`, `GuardrailPayload`, `QueueItemPayload`, `ChatSuggestion`, ...). |+| [`channel_event.rs`](./channel_event.rs) | The flat in-process `WebChannelEvent` every consumer reads, re-exports of the wire payloads, and the conversion from the typed wire enum. || [`event_bus.rs`](./event_bus.rs) | The broadcast channel and the `DomainEvent` surface subscribers. || [`egress_surface.rs`](./egress_surface.rs) | The `external_transfer_pending` bridge. || [`web_errors.rs`](./web_errors.rs) | Thin shell over [`web_errors/`](./web_errors/): `classify.rs` (the classification ladder and `ClassifiedError`), `backend_error_code.rs`, `budget.rs`, `retry.rs`, `timeout.rs`. The class to copy table is in `inference/failure_copy/`. || [`schemas.rs`](./schemas.rs) | Controller schemas and thin handlers for the `channel` namespace. |-| `types.rs` | `QueueMode`, `SessionEntry`, `SessionCacheFingerprint`, `InFlightEntry`, `ParallelEntry`, `WebChatTaskResult`, `ChatRequestMetadata`, RPC param structs. |+| [`voice_notes.rs`](./voice_notes.rs) | In-app voice-note storage and reply-speech policy. |+| `types.rs` | `SessionEntry`, `SessionCacheFingerprint`, `WebChatTaskResult`, RPC param structs; re-exports `ChatRequestMetadata`. |## Key types and entry points@@ -266,14 +294,17 @@ and artifact bridges itself (`openhuman-tui/src/runner.rs`).It returns the new request id, or a `StartChatError`.- `run_system_turn_on_thread` (`ops/system_turn.rs`) runs a host-authored turnon a thread's own session and returns the reply text.-- `cancel_chat` / `cancel_chat_scoped` (`ops/channel_ops.rs`) stop a turn by- thread or request id.+- `cancel_chat_scoped` (`ops/channel_ops.rs`) stops a turn by thread or+ request id.- `invalidate_thread_sessions` ([`ops/state.rs`](./ops/state.rs)) drops a thread's cached agent.Thread edit and regenerate (`threads/ops/edit.rs`) and channel remotecontrol (`channels/host/remote_control.rs`) call it.-- `ChatRequestMetadata` (`types.rs`) is per-request metadata (`speak_reply`,- `source`, `session_id`, `agent_id` for trace attribution) passed by every- caller of `start_chat` and `spawn_progress_bridge`.+- `QueuedTurn` / `QueuedPayload` (`agent/queued_turn.rs`) are the runner's+ `TurnRequest` and the host metadata it carries; the same type is the run+ queue's item in the agent harness.+- `ChatRequestMetadata` (`tinychannels_bus::web`) is per-request metadata+ (`speak_reply`, `source`, `session_id`, `agent_id` for trace attribution)+ passed by every caller of `start_chat` and `spawn_progress_bridge`.- `WebChannelEvent` (`channel_event.rs`) is the event payload sent to clients.New fields are additive so older clients keep working.- `publish_web_channel_event` / `subscribe_web_channel_events`@@ -304,10 +335,11 @@ because the in-app chat is core product surface (#5002).## Boundaries-- The agent loop, run queue, sessions and transcripts belong to TinyAgents- (`vendor/tinyagents`); this module calls `run_single_with_origin` and uses- `run_queue::{RunQueue, QueueLane}`. Segmentation helpers come from- `tinychannels_bus::delivery` (`vendor/tinychannels`).+- The turn lifecycle belongs to TinyAgents (`turn_runner`), the agent loop, run+ queue, sessions and transcripts too (`vendor/tinyagents`). The wire types,+ the output projection and the web adapter belong to TinyChannels+ (`tinychannels-bus` `web`, `tinychannels-runtime` `adapters::web`). A change+ to either goes upstream first; this module keeps only the host ports.- The Socket.IO transport and the `/events` SSE endpoint live in`openhuman-rpc` (`src/server/socketio.rs`, `src/server/http/events.rs`).This module only produces events.@@ -328,28 +360,37 @@ because the in-app chat is core product surface (#5002).origin and are marked detached (#5499). The wallet quote owner is taken fromthat context by the wallet and Web3 tools; a tool dispatched without a runcontext has none and cannot prepare or execute an owned quote.-- Approval-reply routing runs before the `beforeSubmitPrompt` hook on- purpose. Reordering them lets a hook strand a turn waiting on an approval.-- Attachment staging must stay ahead of prompt scanning and persistence.-- A reply persistence error is non-fatal: the reply is announced anyway, since- the client's own append is still a working fallback.-- Host-authored turns are not in `in_flight()`, so they neither interrupt nor- get interrupted by user messages. Callers gate on idleness themselves.+- Ingress order is the runner's and is fixed: attachments, guardrail, approval+ reply, hook. Approval-reply routing runs before the `beforeSubmitPrompt` hook+ on purpose; reordering them lets a hook strand a turn waiting on an approval.+- A reply persistence error is non-fatal on the delivery path+ (`presentation::persist_reply` logs and carries on): the reply is announced+ anyway, since the client's own append is still a working fallback.+- Host-authored turns are not in the runner, so they neither interrupt nor get+ interrupted by user messages. Callers gate on idleness themselves.+- The terminal event comes last. `WebEvents::terminal` removes the request's+ state, so nothing may read a turn's slot after its terminal event.+- The web adapter's output events carry the round of a `chat_interim` only+ through the host (`Surface::interim`): the canonical `Clarification` output+ has none.- Debug/test hooks (`set_test_forced_run_chat_task_error`,`RUN_CHAT_TASK_TEST_LOCK`, `set_test_run_chat_task_block`,`TestRunChatTaskBlock`, `parallel_in_flight_entries_for_test`,`fresh_approval_surface_subscription`) are compiled only under`cfg(any(test, debug_assertions))` or `cfg(debug_assertions)`.`in_flight_entries_for_test` is exported unconditionally because- `test_support/introspect.rs` uses it.+ `test_support/introspect.rs` uses it. A turn parked or failed by a hook skips+ session checkout.## TestsTests live in sibling `*_tests.rs` files. [`web_tests.rs`](./web_tests.rs) and its`web_tests_*_tests.rs` siblings cover `start_chat`, cancellation, queueing,-session concurrency and error classification end to end;-[`mod_test_support_tests.rs`](./mod_test_support_tests.rs) is the debug/test `test_support` module-(`classify_error_for_test`). The rest are per-file unit tests.+the turn lifecycle (supersede, stop, queued drop), session concurrency and+error classification end to end; [`mod_test_support_tests.rs`](./mod_test_support_tests.rs)+is the debug/test `test_support` module (`classify_error_for_test`). The rest+are per-file unit tests. The runner's own behaviour is tested upstream in+TinyAgents.```bashcargo test -p openhuman web_chat