Skip to content

ui-server: TurnCoordinator state is mutated directly from six files, and the copies of its invariants have drifted #2515

Description

@schlessera

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_user and ask_user_list call collidesAcrossTurns on 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), while ask_user_rank and ask_user_form refuse 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).
  • reset() ships in src but 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 example tests/run-session.test.ts:680, tests/ws-handoff.test.ts:219) and none in src. It clears neither pendingMask (ws/turns.ts:435) nor authorizationRegistry (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.
  • WsHost is finished after it is constructed.
    • The host sets the coordinator hooks onApprovalSettled and onQueueChanged from outside (ws/host.ts:393, :406).
    • createApp sets host.turnReverts = reverts (app.ts:886), but run-session only reads it as a boolean (ws/run-session.ts:661).
    • createApp sets host.closing = true directly (app.ts:1062).
  • There is a value-level import cycle: ws/host.ts:27 imports ConversationHost, ws/conversation.ts:45 imports handleChatMessage, and ws/run-session.ts:34-40 imports MAX_SESSION_QUEUE, QUEUE_MAX_BYTES, QUEUE_WARN_BYTES and turnLogAttributes back from host.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) and settleAsk(id, outcome)
    • settleApproval(toolUseId, decision)
    • beginStarting / endStarting
    • registerHandoff / settleHandoff
    • settleLocation / settleMask
  • Replace the four ask-user maps with one Map<id, PendingAsk> that carries a kind discriminant. The collision check keeps each kind's current behaviour (same-turn same-kind reuse accepted for ask_user/ask_user_list, any pending id refused for ask_user_rank/ask_user_form, cross-turn ERROR log only where it exists today), expressed once inside the coordinator.
  • Pass onApprovalSettled, onQueueChanged and log through the TurnCoordinator constructor. Pass turnReverts through the WsHost options. Replace the host.closing assignment with a beginClosing() method.
  • Move MAX_SESSION_QUEUE, the QUEUE_* constants and turnLogAttributes into a leaf module (for example ws/limits.ts) so run-session no longer imports host.ts for values.
  • Delete reset(). Tests tear down through cancelAll() and host.close(), which settle every pending entry, pendingMask included.

Out of scope

Acceptance criteria

  • The grep in Context returns nothing. No file other than ws/turns.ts mutates 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.ts returns nothing. A test that closes a host with a pending mask request asserts that the mask promise rejects.
  • run-session.ts has no value import from host.ts. A dependency check (for example madge --circular or a small import-graph test) shows no host → conversation → run-session → host cycle.
  • WsHost and TurnCoordinator have no fields that createApp or WsHost assign after construction (turnReverts, closing, onApprovalSettled, onQueueChanged, log).
  • Existing ws runtime tests pass. Tests change only in their teardown, from reset() to close()/cancelAll().

Verification

bun run test packages/ui-server
bun run typecheck
bun run lint

Contract 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

  1. added
    type: refactor
    area: ui-server
    priority: p2
    agent-ready
    on Oct 21, 2026
  2. schlessera commented on Oct 24, 2026

    @schlessera
    OwnerAuthor

    Split on 2026-10-24: the collision-policy unification is now #2773 under #734, with needs: decision on the duplicate-id matrix. This issue stays under #1342 as the behaviour-preserving coordinator encapsulation.

  3. self-assigned this
    on Nov 2, 2026
  4. schlessera commented on Nov 2, 2026

    @schlessera
    OwnerAuthor

    Claiming this issue (claim token claim-2515-622705). Branch: refactor/2515-turn-coordinator-state from origin/main @ b228b1f.

    Collision check on the cited source files: no path collisions; only closure overlaps (shared test closures) with open drafts #3056, #3059, #3069, #3116, #3277, #3278, #3279.

  5. added this to the 0.45.0 milestone on Nov 2, 2026
  6. schlessera commented on Nov 2, 2026

    @schlessera
    OwnerAuthor

    2026-11-02: I checked the citations against origin/main before implementing. They have drifted, but every claim still holds. Current anchors:

    • host.turnReverts = reverts is at app.ts:1031 and host.closing = true at app.ts:1208.
    • The coordinator hooks are assigned at ws/host.ts:448 and :461.
    • The mutation grep found 29 sites. ws/recovery.ts mutates through a destructured unorderedSessions alias, 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.

  7. schlessera commented on Nov 2, 2026

    @schlessera
    OwnerAuthor

    Delivered to the epic integration branch epic/1342-turn-path-split at 0c3b837622e9179cd76786b65f73ea992409ed1c by #3289 (a squash onto a62db8f27). Its tree matches the hosted ready-candidate run 41463124246. Every selected job and proof passed on head 6b641c3a3. The checkout was c7b8cd6be, 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:

    • The mutation grep returns nothing.
    • The 32-cell collision characterization passed before and after the change.
    • reset() is gone. Closing a host rejects pending masks, with and without a running turn.
    • There is no host → conversation → run-session → host value cycle. An import-graph test enforces this.
    • There are no post-construction assignments.

    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.

  8. removed their assignment
    on Nov 2, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    agent-readyarea: ui-serverpriority: p2type: refactor

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions