# Turn occupancy

A conversation branch admits one live turn. The composer holds the selected branch's slot, so typing while it runs queues; a turn on another branch takes that branch's own slot ([two branches running at once](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/execution/control.html#branch-run-slots)).

Switching branches never waits: the composer then holds the entered branch's slot, and the turn left runs on in its own ([switching branches](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/execution/control.html#branch-switch)).

Stop is an interrupt: occupancy is released on cancel intent, not when the old turn's thread dies.

## Stop

1. Send `execution.cancel` for the canonical execution (`stopSession` in `use-chat-submit.ts`). Before the ack gives the turn an id, the cancel names the send instead, by `session_id` and `client_request_id`; a `/compact` or rewind is stopped with `operation.cancel` ([one foreground operation per branch](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/execution/control.html#branch-operations)).
2. Draw the live reply as `cancelled` through a Stop overlay (`stopOverlay`), keeping streamed text. The overlay sits over the row and never writes it: it ends when the server's row reaches a settled status, or when the server rejects that cancel's command id.
3. `setRunningTaskFor(sessionId, null, "always")`: the queue drains at 0ms and send is enabled. Send is never disabled for the old unwind.

`cancelling: true` on the running task or `drain: "never"` would lock the composer until `running_task_clear`. Claude Code: Enter while running queues, Esc interrupts then sends the queue. Vercel AI SDK: stop aborts now.

## Invariants

| Rule | Detail |
| --- | --- |
| One occupancy source per side | Client: `runningTasks`, mirrored to the composer. Server: `_running_tasks` plus the canonical driver. Row `status` renders bubbles and never gates the composer, and the reverse. The server's `transcript_update` is the only writer of a row's status; occupancy frames write no row |
| Terminal states are irreversible | Once `cancelled`, `completed`, `failed`, `error`, `interrupted` or `done`, no later frame restores a running look. `cancelling` is server-internal; the client treats it as cancelled |
| Placeholders never overwrite identity | An empty `{ msg_id: "" }` reservation writes only into an empty slot; `msg_id` and `execution_id` are what lets stop cancel |
| Only the turn's own terminal frame releases | A nested `display:"runtime"` result finalizes its card. Late `running_task` frames for a cancelled turn do not revive the slot |
| Stop never fails silently | If no execution resolves, the server sends an error frame, the HTTP route's 404 equivalent |

Shared with Codex CLI (authority on the core session's running turn, UI state from `TurnStarted`, `TurnCompleted`, `TurnAborted`, no protocol-level cancelling) and Claude Code (`QueryGuard` flips idle in the same frame, partial text commits as a normal message).

## Release on cancel intent

The slot is `_running_tasks`; the canonical driver owns the active attempt, its cooperative cancel event and attempt generation. Transport reservations claim no `run_control` token and derive no id from `{msg_id}_reply`. When `cancel_execution` succeeds:

1. Match the admitted `execution_id` to `session_id` and `msg_id`.
2. `_finish_owned_run(session_id, msg_id)` removes the transport slot. It no-ops on a mismatched `msg_id`, so a newer reservation is safe and the cancelled turn's `finally` is harmless.
3. Broadcast the slot's state. While the execution is still ending the frame is `running_task` with status `cancelling`; the turn's end broadcasts `running_task_clear`, naming the finished turn. If another owner already holds the slot, the frame is still that clear, never a `running_task` for the new owner.

The next `_try_reserve_run` does not wait for the old driver thread. A clear is honored only when it matches the slot's execution; an unscoped clear after stop-and-send is stale.

## A message sent the moment a turn ends

A turn's terminal frame (`result`, or `error`) goes out before its slot is free: the turn still closes its execution record and context figures, then sends `running_task_clear`, about a tenth of a second later. A message sent on seeing "done" used to be refused `run_active` in that gap, and only the web page re-sends a refusal.

Holder of the branch's slot, as a request for it arrives

| Holder | The request |
| --- | --- |
| A turn that has sent its terminal frame | Waits, with no lock held, until the slot is given back, then takes it; up to 5 seconds (`FINISHING_WAIT_SECONDS`), after which it is refused as before |
| A turn still running, any other operation | Refused at once, `run_active` |
| The same request (its key) | A repeat ([one foreground operation per branch](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/execution/control.html#branch-operations)), never waited for |

- **The mark**: the turn runtime calls `run_slot.finishing` just before it sends the frame, so no one sees "done" while the slot does not know it. The slot is the one the turn's message id holds, wherever a switch moved it (`mark_run_finishing`).
- **Every entry**: a send, a side-branch send, `reserve_operation` (retry, edit, function run) and the runtime's own turns (owner turns, channels, `--print --resume` through the Worker) all wait the same way.
- **Why not free the slot first**: the finish-up writes the branch's execution record and figures, so a turn admitted then could write beside it. Codex does the same as here: the active turn is marked `finishing` before `TurnComplete`, and input that arrives meanwhile waits on it (`codex-rs/core/src/tasks/mod.rs` `on_task_finished`, `session/inject.rs`).
- **Why not in the client**: the terminal client, `--print`, channels and scripts would each need their own retry.
- **Test**: `tests/component/webui/chat/test_send_after_result.py` sends through the real chat handler the instant the first turn's `result` is broadcast.

## Turns the runtime starts on its own

A turn nobody typed holds the same slot a typed one does, for as long as it runs: clients are told it runs (`running_task`, or `branch_running_task` on a branch that is not selected), Stop names it, and no other turn starts on its branch.

| Turn | How it takes the slot |
| --- | --- |
| Reminder wake, handed-over message | Reserves before admission (`owner_turn.start_owner_turn`); refused while a turn holds it |
| Notice of a background command that ended | Reserves before admission without waiting (`process_notices.deliver`); a busy conversation gets it at the next sweep |
| A Goal's next turn, its verification, a Goal started from the controls | Admitted first, from inside the turn before it, then waits on its own thread for the branch's slot and takes it (`run_slot.hold_admitted`, `ServerRunSlot.adopt`) |

- **Why the Goal's turn is admitted first**: the turn before it still holds the slot when it admits the next one, and the admission is what makes the continuation durable. Reserving first would wait on the thread that has to free the slot.
- **Which slot**: the turn's own branch (`branch_id`): the selected branch's slot, or that branch's own when another one is selected.
- **Why a slot at all**: a turn with no slot is announced to no client, and a load answers `run_active: false` for a conversation that is working; a notice and a Goal's next turn could also run on one branch at once.
- **A queued turn that is stopped or superseded while it waits** takes nothing and does not run.
- **Tests**: `tests/component/runtime/test_owner_turn_run_slot.py`, `tests/unit/processes/test_exit_notices.py`, `tests/unit/agent/workflows/test_chat_goal.py`.

## A client that connects mid-turn

Run frames announce a turn as it starts, so a new connection asks once: `get_running_sessions` is answered `running_sessions`, one run state per conversation with a turn on any branch, each shaped like `run_state` (`run_active`, `run_task`, `running_branches`, `run_seq`). The client applies each (`applyRunState`) and sends `get_run_state` for a conversation it still shows running that the answer leaves out, which clears it.

One rule decides whether a durable turn is the page's running turn: its `branch_id` against the branch selected now, on the server (`on_selected_branch`) and on the page (`onSelectedBranch`); the `side_branch` flag frozen at admission answers only when one of the two is unknown.

## Run-state frames are ordered by `run_seq`

`running_task`, `running_task_clear`, `run_state` and `session_loaded` (`run_active`, `run_task`) carry it: a server-wide increasing number (`server._next_run_seq()`, microsecond wall time, increasing across worker restarts and exact in JSON), taken before the frame's run state is read.

| Frame | Client |
| --- | --- |
| Out of order | A load reads "running" then is sent after the clear, so run state applies only if `run_seq` is newer than the last for that session (`lib/chat/decisions/run-seq.ts` `acceptRunFrame`) |
| Stale load | Still confirms restored steer receipts, but leaves the slot and queue alone |
| No `run_seq` (local placeholder, chat acknowledgement) | Applies as before, guarded by the clear's identity match |

## Late frames

| Frame | Rule |
| --- | --- |
| `running_task` for the cancelled `execution_id` | Cannot revive the task: `run_seq` and the pending cancel guard it |
| Text and row changes after Stop | Not sent. `_broadcast_chat_response` keeps post-stop silence for text frames, and the publisher drops non-terminal changes to rows of a cancelled execution. The terminal `row_upsert` still goes and ends the overlay |
| A rejected cancel | When the rejection's `latest_snapshot` proves the run still goes, the overlay clears, the run slot comes back and later text appears |
| `running_task` after a finished turn's `result` | Clears the composer's running task only. The reply row's status comes from the server's `transcript_update`, so the client writes no row here |

0ms rule: [interaction feedback](https://fzkuji.github.io/OpenProgram/docs/reference/design/ui/interaction-feedback.html). Queue mechanics: [queue and steering](https://fzkuji.github.io/OpenProgram/docs/reference/design/ui/turn-lifecycle/send-queue-reliability.html).

## HTTP abort

| Mechanism | Rule |
| --- | --- |
| `iter_until_cancelled` | In `providers/utils/streams/cancelable_stream.py`: polls the cancel signal every 250ms at most while one `__anext__` stays outstanding, then exits so `async with` closes the stream. Used by the Anthropic and OpenAI Completions adapters. |
| No `wait_for` | Do not `wait_for` the next chunk: the timeout cancels that read and kills httpx and OpenAI SSE iterators. Grok thinking often has no chunk for longer than 250ms, which would finalize an empty reply. |
| `finish_reason` | ends the turn. Grok and xAI often leave SSE open after the last token, so usage drains for `USAGE_DRAIN_S` (1.5 s), then `EventDone`. |

## Four-second grace

`CANCEL_GRACE_S = 4.0` (`run_control/owners.py`) applies when the owner has a subprocess or a terminate hook that kills a child. Token-only chat owners do not wait after cancel intent. Service: `RuntimeControlService.request_cancel` in `runtime/execution/control/`.
