Repository navigation
Description
Part of #1342.
Context
TurnCoordinator exposes all of its turn state as public fields (packages/ui-server/src/ws/turns.ts:405-448): running, bySession, startingBySession, pendingApprovals, the four ask-user maps, pendingLocation, pendingMask, handoffs, askOutcomes, authorizationRegistry, and others. Code outside the class writes to these maps and sets directly at 30 sites across six files:
| File | Direct mutations |
|---|---|
ws/ask-answers.ts |
4 |
ws/bridge.ts |
8 |
ws/dispatch.ts |
6 |
ws/handoff.ts |
4 |
ws/recovery.ts |
2 |
ws/run-session.ts |
6 |
Reproduce the count with:
grep -rnE '(coordinator|turns)\.(running|bySession|startingBySession|unorderedSessions|pending\w+|resolvedApprovals|handoffs|handoffPreparations|askOutcomes|authorizationRegistry)\.(set|delete|clear|add)\(' packages/ui-server/src | grep -v 'src/ws/turns.ts'startingSessions is also incremented from outside the class (ws/run-session.ts:205). Every site re-implements the invariants by hand: delete the entry, then resolve it, then record the outcome. For example, ws/dispatch.ts:342-382 repeats get → match turn → delete → resolve/reject four times.
The copies have already drifted:
- Ask-user collision checks are inconsistent. The four kinds check a new id against pending ones in different ways:
ask_userandask_user_listcallcollidesAcrossTurnson their own map (askUser,ws/bridge.ts:440-447;askUserList,:471-480), which refuses only another turn's entry (collidesAcrossTurns,ws/turns.ts:771-785), whileask_user_rankandask_user_formrefuse any pending id with plain.has()(askUserRank,ws/bridge.ts:504-508;askUserForm,:516-520). Which rule all four should share is a behaviour decision, filed as ui-server: the four ask-user kinds apply different duplicate-id rules #2773 under Epic: Interactive inputs preserve answers and request identity #734. This issue preserves today's per-kind behaviour exactly.- The four maps are checked together at about 10 sites in 6 files (
grep -rn pendingAskUserForm packages/ui-server/src).
- The four maps are checked together at about 10 sites in 6 files (
reset()ships insrcbut only tests call it, and it misses state.reset()(ws/turns.ts:789-816, documented as "Test seam") has 16 call sites in 6 test files (for exampletests/run-session.test.ts:680,tests/ws-handoff.test.ts:219) and none insrc. It clears neitherpendingMask(ws/turns.ts:435) norauthorizationRegistry(ws/turns.ts:448), and it clears the ask maps without settling their promises. A test that resets while a mask request is pending leaves that promise unsettled.WsHostis finished after it is constructed.- The host sets the coordinator hooks
onApprovalSettledandonQueueChangedfrom outside (ws/host.ts:393,:406). createAppsetshost.turnReverts = reverts(app.ts:886), but run-session only reads it as a boolean (ws/run-session.ts:661).createAppsetshost.closing = truedirectly (app.ts:1062).
- The host sets the coordinator hooks
- There is a value-level import cycle:
ws/host.ts:27importsConversationHost,ws/conversation.ts:45importshandleChatMessage, andws/run-session.ts:34-40importsMAX_SESSION_QUEUE,QUEUE_MAX_BYTES,QUEUE_WARN_BYTESandturnLogAttributesback fromhost.ts.
The handler-table split (#1358) and the runRetainedSession split (#1359) would each have to carry these raw map operations into new modules. Encapsulating the state first means each split moves calls to intent methods instead of copies of the invariants.
Scope
- Make the coordinator's collections private. Expose intent methods that own the invariants, for example:
openAsk(kind, id, entry)andsettleAsk(id, outcome)settleApproval(toolUseId, decision)beginStarting/endStartingregisterHandoff/settleHandoffsettleLocation/settleMask
- Replace the four ask-user maps with one
Map<id, PendingAsk>that carries akinddiscriminant. The collision check keeps each kind's current behaviour (same-turn same-kind reuse accepted forask_user/ask_user_list, any pending id refused forask_user_rank/ask_user_form, cross-turn ERROR log only where it exists today), expressed once inside the coordinator. - Pass
onApprovalSettled,onQueueChangedandlogthrough theTurnCoordinatorconstructor. PassturnRevertsthrough theWsHostoptions. Replace thehost.closingassignment with abeginClosing()method. - Move
MAX_SESSION_QUEUE, theQUEUE_*constants andturnLogAttributesinto a leaf module (for examplews/limits.ts) so run-session no longer importshost.tsfor values. - Delete
reset(). Tests tear down throughcancelAll()andhost.close(), which settle every pending entry,pendingMaskincluded.
Out of scope
- Splitting
handleClientMessage,runRetainedSessionormakeBridge(ui-server: replace the 41-case handleClientMessage switch with a per-message handler table #1358, ui-server: split runRetainedSession into lifecycle stages #1359 and themakeBridgeissue in this review). - Moving
nextSendOrderor other module-level state to per-app objects (ui-server: make login buckets, passkey challenges, sync locks and send order per-app #1364). - Fixing the reason logged for a refused "always allow" grant (
ws/dispatch.ts:438-467vsws/bridge.ts:304-305). It touches the same lines but is its own fix. - Unifying the ask-user collision rule or its logging (ui-server: the four ask-user kinds apply different duplicate-id rules #2773,
needs: decision). This issue is behaviour-preserving. - Any change to the wire protocol or to which ids are accepted.
Acceptance criteria
- The grep in Context returns nothing. No file other than
ws/turns.tsmutates coordinator collections. - A characterization test covers the four kinds × same/other turn × same/other kind and asserts today's accept/refuse/log outcome for every cell. It passes on the tree before the change and unchanged after it.
-
grep -n "reset()" packages/ui-server/src/ws/turns.tsreturns nothing. A test that closes a host with a pending mask request asserts that the mask promise rejects. -
run-session.tshas no value import fromhost.ts. A dependency check (for examplemadge --circularor a small import-graph test) shows nohost → conversation → run-session → hostcycle. -
WsHostandTurnCoordinatorhave no fields thatcreateApporWsHostassign after construction (turnReverts,closing,onApprovalSettled,onQueueChanged,log). - Existing ws runtime tests pass. Tests change only in their teardown, from
reset()toclose()/cancelAll().
Verification
bun run test packages/ui-server
bun run typecheck
bun run lintContract impact
None. WsHost is a public export (packages/ui-server/src/index.ts:57), but coordinator and turnReverts are tagged @internal (packages/ui-server/src/ws/host.ts:236-237, :259-260). Confirm in the PR that the api-report/ui-server.txt diff touches no public member. If it does, stop and ask for a ruling.
Found by a repository review on 2026-10-22.
2026-10-24: made the issue behaviour-preserving, as its parent #1342 requires: collision-rule unification moved to #2773 (needs a ruling on the duplicate-id matrix), and the cross-turn rank/form criterion became a characterization test of today's behaviour. Refreshed the collision and reset() anchors to current main. #1358 and #1359 now wait on this issue.
Activity
schlessera commentedon Oct 24, 2026
Split on 2026-10-24: the collision-policy unification is now #2773 under #734, with
needs: decisionon the duplicate-id matrix. This issue stays under #1342 as the behaviour-preserving coordinator encapsulation.schlessera commentedon Nov 2, 2026
Claiming this issue (claim token
claim-2515-622705). Branch:refactor/2515-turn-coordinator-statefromorigin/main@ b228b1f.Collision check on the cited source files: no
pathcollisions; onlyclosureoverlaps (shared test closures) with open drafts #3056, #3059, #3069, #3116, #3277, #3278, #3279.schlessera commentedon Nov 2, 2026
2026-11-02: I checked the citations against
origin/mainbefore implementing. They have drifted, but every claim still holds. Current anchors:host.turnReverts = revertsis atapp.ts:1031andhost.closing = trueatapp.ts:1208.ws/host.ts:448and:461.ws/recovery.tsmutates through a destructuredunorderedSessionsalias, so the grep misses it; the intent-method change covers it.Implementation: #3289. It preserves each ask kind's collision rule exactly (#2773 stays the ruling). A few test fixtures that wrote coordinator collections directly now call the intent methods. That goes beyond teardown-only changes, and the PR names it.
test(ui-server): characterize today's ask-user id collision rules per…
refactor(ui-server): own turn state in TurnCoordinator behind intent …
chore(ui-server): changeset for turn coordinator ownership
refactor(ui-server): own turn state in TurnCoordinator behind intent …
schlessera commentedon Nov 2, 2026
Delivered to the epic integration branch
epic/1342-turn-path-splitat0c3b837622e9179cd76786b65f73ea992409ed1cby #3289 (a squash ontoa62db8f27). Its tree matches the hosted ready-candidate run 41463124246. Every selected job andproofpassed on head6b641c3a3. The checkout wasc7b8cd6be, whose parents are the epic tip and the PR head.This issue stays open. It closes when the epic batch lands on main.
How each acceptance criterion was met:
reset()is gone. Closing a host rejects pending masks, with and without a running turn.host → conversation → run-session → hostvalue cycle. An import-graph test enforces this.One deviation, named in the PR: a few test fixtures that wrote coordinator collections directly now call the intent methods, so test changes are not teardown-only. No behavioural assertion changed.