# WebSocket command lifecycle

## Command and disconnect flow

| Event | Response | Then |
| --- | --- | --- |
| Invalid JSON | Sanitized diagnostics; an error frame with no echo of the text | Keep receiving |
| Unknown action | `operation_error(code=unknown_action)`, echoing a valid `request_id` | Keep receiving |
| Handler exception | Logs only action, session and type; `code=handler_error` on the same socket | Keep receiving |
| Transport disconnect | Remove the socket from the connection set | Check whether another connection still focuses its session |
| No other connection, and a legacy follow-up queue exists | Enqueue `_FOLLOW_UP_DISCONNECTED` | The waiter in `_web_follow_up` receives it |
| Waiter gets the sentinel | Turns it into `None`; a real empty string stays `""` | Its `finally` deletes the queue |

## Entry points

| Entry point | Behavior | Boundary |
| --- | --- | --- |
| `_websocket_handler` (`server_runtime/websocket_dispatch.py`) | Isolates JSON parsing and handler exceptions; a handler failure returns `operation_error` and receiving continues | `WebSocketDisconnect` and failure to send an error frame end the connection; socket writes never retry indefinitely |
| `_handle_ws_command` | Actions on one connection run in order, so a slow one delays every later frame on it. An action that takes 2 s or more is logged with its name and session, and says whether later frames waited. Unknown action returns `unknown_action`; registered handler exceptions propagate to the loop | Wire response holds only constrained action, session, request metadata and registered error categories |
| `CONCURRENT_ACTIONS` | Read-only actions whose reply the client matches by its own request id (`load_session`, `project_folder_size`, `project_file_info`, `project_file_tree`, `project_file_search`) each run as a task beside the ordered lane: after the frames before them and the previous frame of the same action. A slow folder walk, search or first read never holds a `chat` or `stop`. `list_projects` stays ordered: the web matches `projects_list` by type, so a listing answered after a later `create_project` would be read as the fresh list | Same-action replies keep their order; at most 32 side reads per connection are in flight, and a further one waits in the receive loop; the tasks are cancelled when the connection ends |
| `load_session` beside a turn | The web matches `session_loaded` and history pages by request id; the conversation's row frames are parked until the read's frame is queued; run frames carry `run_seq`. After the frame, the running task and open questions go out before context is counted | A chat or stop sent during a first read starts at once |
| `_web_follow_up` (`server_runtime/session_persistence.py`) | Waits on a session queue; `None` when the last observer disconnects or on cancel | Process-local; no durable recovery across worker restarts |
| Stop, delete | Cancellation objects and sentinels are both non-answers; the owner's `finally` cleans the queue | Dispatcher never cleans by session. The action that acquired a resource rolls back with its own owner token, as `_release_run_reservation(session_id, msg_id)` does |

## Trust and compatibility

- Client payloads are untrusted. Error frames never echo payloads, exception messages, paths, credentials or tracebacks; tracebacks go only to the local logger.
- The frontend still consumes an older server's `action_error`.
- Closing one tab does not cancel the question while another connection focuses the session.
- `follow_up_answer`'s wire shape is unchanged; strings and real empty strings stay valid.

**Choices and exclusions**

| Decision | Items |
| --- | --- |
| Adopted | Command-level error frames (Starlette: `WebSocketDisconnect` ends the connection, cleanup in `finally`); a sentinel on last-observer disconnect; owner-scoped cleanup; "cancellation is not an answer" from `QuestionRegistry.cancel_session()`; a legacy queue that can return `None` |
| Rejected | Cancelling whenever any tab disconnects; dispatcher deleting reservations by session; closing the connection after an application exception; passing sentinels to business functions |
| Out of scope | Moving legacy `set_ask_user` into QuestionRegistry; changing `runtime.ask`, ACP, channel questions, the send queue or the run reservation protocol; persistent error storage, acknowledgement and reconnect recovery |

## Interaction responsiveness

| Moment | Rule |
| --- | --- |
| After a successful socket write | Clears only the captured draft and renders a locally pending user message in its conversation. A New chat has no conversation id until `chat_ack`; the list draws its provisional `local_*` key meanwhile, so the message and the waiting reply show however late the acknowledgement comes. The reservation keeps text and attachments until acknowledgement. Not proof that execution started. |
| Server acknowledgement | Reconciles the local identity without duplicating |
| Rejection | Keeps a recoverable message without overwriting a newer draft |
| Unrelated work | Resource projection and session or sidebar work cannot delay acceptance or block the event loop |
| Resource close | Targets exact page and association identities, keeps generation and sequence ordering, scans no unrelated inputs. Local feedback is separate from native confirmation; failure or a newer generation cannot hide behind an old pending action |

**Acceptance**

| Entry point | Scenario | Assertion |
| --- | --- | --- |
| `_websocket_handler` | First action raises `KeyError`, second is ping | Same connection gets sanitized `operation_error`, then pong |
| `_websocket_handler` | Invalid JSON | Frame not echoed; next one processed |
| `_web_follow_up` plus disconnect | Only focused connection disconnects | Waiter returns `None` within the test deadline, not after 300 seconds; queue deleted |
| Disconnect | Another connection focuses the session | No sentinel; returns the other connection's answer |
| `follow_up_answer` | Empty string | Returns `""`, not read as a disconnect |

Regression: `tests/component/webui/runtime/test_websocket_command_lifecycle.py`. Controlled tests also cover delayed acknowledgement, rejection, session switching, bound composers, queue and steer, resource close ordering and event-loop progress. Production latency is not inferred from synthetic timings.

## Implementation status

Implemented: command-level isolation, sanitized `operation_error`, compatibility with old frames, follow-up disconnect semantics, interaction responsiveness.
