Skip to content

fix(chat): idle the composer when a turn ends without its _done - #14276

Merged
iamwhatever merged 1 commit into
kirodotdev:mainfrom
rubencu:fix/composer-send-icon-idle
Oct 13, 2026
Merged

iamwhatever merged 1 commit into
kirodotdev:mainfrom
rubencu:fix/composer-send-icon-idle

Conversation

@rubencu

@rubencu rubencu commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Problem / Motivation

Goal: The composer returns to the send arrow as soon as a turn has ended, even when the tab never applied that turn's _done.

After a turn finished, the composer could keep showing the Steer / Queue split button (the target icon) even though no agent was running. The reply above it looked done: its footer showed the duration, the follow-up chips were offered, and the thinking footer was gone. Only a reload brought the normal send arrow back.

Why it matters

The send button is how the user reads whether the agent is busy. Offering "steer" with nothing to steer says the session is working when it is not. It also puts a mode choice (steer or queue) in front of every message until the page is reloaded. It was reported from the phone dashboard, where dropped frames and resumed tabs make it easier to hit.

Not a goal

  • No change to how a turn is started, steered or queued; only how its end is read by the tab.
  • No change to the server's turn ordering: the idle slots row already precedes chat_done, and this PR only names the turn on frames that already exist.
  • No change for an older gateway whose frames carry no turn identity; those keep the previous behavior.
  • No remote-relay changes: that path was removed on main and its hunks were dropped from this PR.
  • No ordering of a genuinely idle completion page against a successor that started after the page was captured: that race already exists on main, and its fix is a dispatch-time epoch in the refresh thunk.
  • No new setting.

What changed (motivation → approach → change)

Before After
A turn whose _done the tab never applied left the composer busy until reload The next live slots row saying the slot is not running settles it, and the composer shows the send arrow

The root cause is two busy signals that can disagree. The transcript and footer follow slotRunning, which the slots sync already clears. selectComposerBusy also reads the active slot's stream state (slotState), which only _done or a history fetch reset. When the _done is not applied (the frame is lost, or a mid-turn history fetch resolves after it and writes back running: true), slotState stays busy.

settleEndedActiveTurn in store/chatSlice.ts now settles the active slot when a live slots row reports it not running, with finalizeActiveTurn, the step _done also uses. The server pushes that idle row before chat_done, so this runs on ordinary turns too, and the _done that follows changes nothing.

Settling early frees the composer before chat_done arrives, so the tab must know which turn each terminal frame belongs to. The server now says so: slots rows, every chat_done (including the remote relay's) and the history reply carry turn (the slot's existing _turn_generation, which counts turn tasks) and turn_gen (the gateway's chunk_generation(), since the counter restarts with the process). chat_done_payload reads them before its store probe can yield to a successor. types/index.ts adds the optional fields to ChatSlot and new ChatDonePayload / ChatSlotDetailResponse types, and api/client.ts returns the history reply as ChatSlotDetailResponse.

The tab keeps, per slot, the newest turn it knows ended. A _done for a turn already known ended is ignored in both the active and background paths, so a late one never finalizes a turn started after it. A pending local send is settled only by a row naming a newer turn than the last one known ended in that gateway generation, or than turn 0 when none is known (a new chat, a restarted gateway). Neither a history reply nor a session-list row (pages/ChatPage.tsx passes the row's identity to syncSlotRunningFromServer, and a late HTTP fetchSlots also writes that list) can restore busy for an ended turn. A history page captured before a turn end this tab already recorded is not applied to the active pane: it is older than what the tab shows, and the refresh that follows the end carries everything it holds. The end without a _done now dispatches that refresh too (hooks/websocket/slotList.ts), so the idle row re-hydrates the pane exactly as _done does, and the _done that follows for the same turn skips its own (the ended turn's identity is recorded per slot in hooks/websocket/idleRowRefresh.ts, shared by the two owners): one refresh per turn end. Background pages captured mid-turn finalize every fetched streaming row of the ended turn and do not vouch as a final reply. A switched page keeps its rows' roles through its merge, which drops the page's streaming rows wherever it re-attaches a reply the tab already finished, and finalizes only the ones it keeps after the merge, so that reply is shown once; its replay floor is seeded from the page's streaming row, so a redelivered chunk of the ended turn is dropped as _done leaves it. A switch whose read a later switch superseded applies nothing, whether it settles before or after the newer one: switchSlot.pending records the newest request, which settling does not clear, and both settlement reducers ignore any other, so an older page cannot finalize the successor turn the pane shows and an older failure cannot empty it. Either way a successor's chunks cannot append to the prior reply. Frames without identity keep the previous behavior. The one chat_done sent mid-turn, the deferred /compact acknowledgement, omits the identity (ends_turn=False), so it cannot mark the live turn ended.

The server order is recorded in docs/system-specs/modules/session.md, commented at _finish_queue_cycle in dashboard/chat_runner.py, and pinned by test/test_finish_queue_cycle_terminal_order.py. No other writer can push an idle row mid-reply: running reads whether the turn's own task is done, every site that clears slot.task does so after that task finished or on a terminal branch, Stop interrupts the provider turn and never clears slot.task (its pushes read running until the turn's own teardown), and regenerate/rewind assign a new task, which advances the turn number.

hooks/useWebSocket.ts flushes text still buffered for the active slot before dispatching the idle row, so the tail lands in the finished reply. Its identical-frame dedupe still lets a repeat through while the chat reads busy, for history from an older gateway without identity.

Backwards compatibility

Compatible: turn and turn_gen are new fields on existing payloads; nothing is removed or renamed. A frame or reply without them is handled as before this PR.

Tests

  • website/src/test/chatSlice.activeStrandedStream.test.ts (reducer plus selectComposerBusy):
    • A lost _done is healed by the idle row, including a reply whose final frame was also lost; an HTTP fetchSlots reply never settles a live turn.
    • A pending send is not settled by a row already known ended, and is settled by a row naming its newer turn, including a new chat's first turn that ends inside one slots window and the first turn after a gateway restart.
    • Ordinary turn: idle row then matching _done leaves one finished reply; settlement then _done equals _done alone, placeholder row included.
    • A late _done leaves a newer turn streaming, whether started locally or by the server, after switching away, and away and back. A successor's _done finalizes before any running row arrives.
    • Another gateway generation's turn does not suppress a _done; a _done without identity finalizes as before.
    • Stale switchSlot and refreshSlot replies, and a stale session-list row, cannot restore busy for an ended turn. A row naming a newer turn still can. A refresh page captured before a recorded turn end leaves the active transcript and run state exactly as the tab had them. That holds under a live successor opened by a send, a nudge or a subagent row, when the first local row is known only by its sendId, and for a turn the queue dispatched (nothing doubled, nothing lost). The completion refresh that follows lands the text the tab never received. Background and switched history pages captured mid-turn finalize every ended-turn fetched stream before the next send receives chunks. A stale warm keeps a longer identity-less client reply when its fetched page is only partial.
  • website/src/store/chatSlice.switchEndedTurn.test.ts (reducer): a slot whose reply its background chat_done finished, switched to with a page captured mid-turn (running: true, the partial as a streaming row), shows that reply once, idles the composer, seeds the replay floor from the page's row, and drops a redelivered chunk of the ended turn.
  • website/src/store/chatSlice.switchSuperseded.test.ts (reducer): a read of a slot issued mid-turn, superseded by a switch away and a switch back while that turn ended and the next one started streaming, applies nothing when it lands, whether after the newer switch settled or while it is still in flight. The successor's row stays streaming with its text, no extra reply appears, the slot and composer stay busy, the paging cursor and loading flag are the newer switch's, and the successor's next chunk extends the same bubble. The same read failing leaves the pane as it was.
  • website/src/test/useWebSocket.endedTurnFlush.test.ts (hook): buffered text lands before the settlement; identical idle frames are deduped once history is fenced by identity and re-applied for identity-less history; a pending send is left alone. An idle row that ends the active turn without a _done dispatches exactly one refresh and the pane shows its page, including when its flush lands the turn's only text or it ends a pending send. Idle row then _done, and _done then idle row, refresh once per turn, and a record left by a lost _done does not swallow the next turn's _done refresh.
  • test/test_finish_queue_cycle_terminal_order.py (backend, real slot and state): done, idle push with the task cleared, then one chat_done naming the ended turn; synthesis sends no chat_done; rows and history carry the identity; test_the_deferred_compact_acknowledgement_does_not_end_the_turn drives a statusless /compact turn through the behavioral harness and pins its identity-less acknowledgement before the wait plus its identified final chat_done after completion. test/test_remote_crew_execution.py: the relay's chat_done names its turn.
  • Mutation proofs: removing the duplicate-_done guard, suppressing every identified _done, dropping the history or session-list guard, dropping ends_turn=False, or dropping turn from any of the four server emitters each fails its test. So does applying a stale page to the active pane, dropping the idle row's refresh, or deduplicating that refresh by slot alone, and so does finalizing a switched page before its merge or clearing the floor for it. Dropping either settlement reducer's superseded-request check, or the newest-request record in switchSlot.pending, fails the superseded-switch tests.

Manual verification

N/A — unit coverage sufficient: the stranded state comes from frame loss and fetch races that a live session cannot trigger on demand. The tests drive the exact frame sequences through the real reducers and the real WebSocket hook, including the ordinary slots-before-chat_done turn end.

Screenshots / video

Why no screenshot: no component, layout, style or copy changes; the composer renders its existing idle send button in a state where the store previously misreported the slot as busy.

Related Issues

no linked issue: reported directly from the mobile dashboard.

Pattern harvest

Rule candidate: review-prompt
Pattern: two store fields that encode the same fact (slotRunning and slotState for "a turn is running") where a reconciliation path resets only one of them.

Checklist

  • At most two commits (one is the norm), with a Conventional Commits title (feat|fix|docs|style|refactor|perf|test|chore|ci|build|revert: ...)
  • Existing tests pass and new tests added for new functionality
  • Self-review completed; code follows project style guidelines
  • Documentation updated (if applicable)
  • No secrets, credentials, or internal references in the diff

@rubencu
rubencu requested review from a team and cixuuz September 26, 2026 19:13
@rubencu

rubencu commented Sep 26, 2026

Copy link
Copy Markdown
Contributor Author

Intent: Stop the main chat's composer from offering the Steer/Queue split button after a turn has ended, by letting the live slots frame settle an active-slot stream state that a missed _done (or a stale mid-turn history fetch) left busy.
Not a goal: Changing what Steer or Queue do while a turn or sub-agents are genuinely running, the busy rule for background panes, or how HTTP fetchSlots replies reconcile the slot list.

@github-actions github-actions Bot added fork Pull request from a fork (external contributor) readiness: action required A blocking check or review needs attention labels Sep 26, 2026
@rubencu

rubencu commented Sep 26, 2026

Copy link
Copy Markdown
Contributor Author

Rerun request (infra, not the diff): five checks on head 52f3685d5458 failed before doing any work, all on gh: API rate limit exceeded for installation between 19:21 and 19:22 UTC. None reached a verdict, and a fork contributor cannot rerun them (Must have admin rights to Repository). Could a maintainer rerun the failed jobs once the rate limit resets?

Check Run Failed step
Resolve desktop matrix 36265319059 dorny/paths-filter listFiles
Fork GPT 5.6 Review 36265810875 Resolve and validate PR
Fork Opus 5 Review 36265810917 Resolve and validate PR
Fork Security Scope Review 36265810882 Resolve and validate PR
Fork Internal Content Scan 36265810911 Resolve and validate PR

gh run rerun <id> --failed on each is enough; the diff needs no new push.

@rubencu
rubencu force-pushed the fix/composer-send-icon-idle branch from 52f3685 to f3e9eb7 Compare September 26, 2026 21:36
@rubencu

rubencu commented Sep 26, 2026

Copy link
Copy Markdown
Contributor Author

Re-triggered CI: pushed f3e9eb7, a tree-identical re-commit of 52f3685 (same tree 9d8247c7, no code change), because the five checks stopped by the installation API rate limit at 19:21 UTC were still unrun after two hours. No rerun of the old runs is needed anymore.

@github-actions github-actions Bot added readiness: checking Automated validation is still running and removed readiness: action required A blocking check or review needs attention labels Sep 26, 2026
@github-actions

github-actions Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

UX Review (Opus 5.5, fork) — ✅ PASS

UX-level review of f5b5d1207e26de00d1ebff0103e55e36d054ee81 via the fork AI-review pipeline — updated in place on each push. A BLOCK verdict blocks PR readiness; PASS/CONCERNS are advisory.

UX-Verdict: PASS

Check on the phone dashboard: after a turn whose _done frame is dropped, the send arrow should come back without a reload, and the reply should not be split or shown twice.

[UX-REVIEWED] f5b5d12

Description read

[DESCRIPTION-READ] 881168ad6adf1b598d94bbd8761b452515a7b2ff95fe017c8f957a0d17018b75

That sha256 names everything this verdict read: the PR description, plus the 3 evidence file(s) the workflow collected from it and handed this review. It covers that evidence because the media strip replaces every attachment URL with the same placeholder, so an edit swapping one attachment for another would leave the description's captured text identical while what this review judged changed. Recompute it with .github/scripts/pr-description-capture.sh over the same inputs; if it differs, the description or that evidence changed after this verdict was formed and any finding drawn from either is unproven.

@github-actions

github-actions Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

GPT 6.1 Review (fork) — ✅ no blocking findings

Reviewed f5b5d1207e26de00d1ebff0103e55e36d054ee81 via the fork AI-review pipeline; updated in place on each push.

Review details

No findings.
[GPT-REVIEWED] f5b5d12

@github-actions

github-actions Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

First Principles Review (Opus 5.5, fork) — 🟡 CONCERNS

Premise-level review of f5b5d1207e26de00d1ebff0103e55e36d054ee81 via the fork AI-review pipeline — why this exists and whether the shipped surface is the smallest honest version. Updated in place on each push. A BLOCK verdict blocks PR readiness; PASS/CONCERNS are advisory.

First-Principles-Verdict: CONCERNS

The PR names the cause as "two busy signals that can disagree", then keeps both and adds a third mechanism to reconcile them, without weighing whether one of the reads could simply go.

Not justified as shipped

  • Item 1 — symptom-level: the description says "selectComposerBusy also reads the active slot's stream state (slotState), which only _done or a history fetch reset". The fix keeps that read and has the slots row drive slotState too. This adds turn identity, a per-slot endedTurn, and the idle-row refresh dedupe.
    Subtraction: in website/src/store/chat/selectors.ts:85, stop reading selectSlotStreamState for the active slot and rely on slotRunning, which "the slots sync already clears". Dropping the per-turn fence and its server identity fields follows from that, unless something else needs them.
    Clears when: the description names a busy state that slotRunning misses and slotState catches for the active slot, such as compaction or tool_running.
  • Item 8 — zero consumers: ChatDonePayload in website/src/types/index.ts. Grepping the diff for ChatDonePayload finds only its definition, 1 match and 0 uses.
    Subtraction: delete ChatDonePayload.
    Clears when: the type is deleted or a reader uses it.

What this change ships

Inventory (8 items) — 6 justified

Intent: the send arrow comes back as soon as a turn has ended, even when the tab lost that turn's _done. FIX.

  1. A live idle slots row now idles the composer and finalizes the reply — symptom-level: keeps the second busy signal
  2. Slots rows, terminal chat_done and history replies carry turn/turn_gen — justified
  3. A late _done for an already-ended turn is ignored, active and background — justified
  4. Stale history, switch pages and session-list rows can't restore busy for an ended turn — justified
  5. The idle row dispatches the completion refresh, and the matching _done skips it — justified
  6. A superseded switchSlot reply or failure applies nothing — justified
  7. Buffered text is flushed before the idle row settles the turn — justified
  8. New ChatDonePayload and ChatSlotDetailResponse types — zero consumers: ChatDonePayload unused

[FIRST-PRINCIPLES-REVIEWED] f5b5d12

Description read

[DESCRIPTION-READ] 7af52afb35dfac99705a142bb71a4918ff3766cc9b61252f26f6d25cc3ba9f96

That sha256 names the PR description this verdict read. Recompute it with .github/scripts/pr-description-capture.sh; if it differs, the description changed after this verdict was formed and any finding drawn from the description is unproven.

@github-actions

github-actions Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Design Review (Opus 5.5, fork) — 🟡 CONCERNS

Design-level review of f5b5d1207e26de00d1ebff0103e55e36d054ee81 via the fork AI-review pipeline — updated in place on each push. A BLOCK verdict blocks PR readiness; PASS/CONCERNS are advisory.

Design-Verdict: CONCERNS

Every turn now ends when a running: false slots row arrives, but the test pins only one of the server code paths that can emit that row.

Watch

  • The idle row now ends the turn, on every turn. The diff makes sseSlots call settleEndedActiveTurn, which finalizes the streaming row and idles the composer. It also dispatches the completion refresh. The new test checks this ordering only for _finish_queue_cycle. The other places that clear slot.task or push a slots update are covered by the description's prose ("No other writer can push an idle row mid-reply"), not by a test. If a future change pushes during a brief task = None gap, every reply would split and the composer would go idle too early, and no server test would fail. This trades a rare stuck composer for a possible regression on every turn.
    Clears when: a test lists every slot.task = Noneandpush_slots_updatesite indashboard/and fails when a new one is added without an ordering decision.test_slot_running_readers.pyalready does this forrunning readers.
  • The fix needs a lot of new frontend state. It adds endedTurn, slotSwitchLatestRequestId, a module-level idleRowRefreshes Map kept outside Redux, finalize paths that depend on whether a page reports the turn running, and two dedupe rules for refreshes. These come from settling a turn before its _done arrives. The description explains why each piece is needed but never weighs a smaller fix. For example, the idle row could reset only slotState when no send is pending, leaving _done as the only finalizer and refresh owner.
    Clears when: the description states why that smaller fix does not cure the lost-_done case.

[DESIGN-REVIEWED] f5b5d12

Description read

[DESCRIPTION-READ] 2875e37d9c4c7cec9b19ffa543e9c1d8d1a94e9a30a2d6d3c6587a6b09e594cf

That sha256 names everything this verdict read: the PR description, plus the 1 evidence file(s) the workflow collected from it and handed this review. It covers that evidence because the media strip replaces every attachment URL with the same placeholder, so an edit swapping one attachment for another would leave the description's captured text identical while what this review judged changed. Recompute it with .github/scripts/pr-description-capture.sh over the same inputs; if it differs, the description or that evidence changed after this verdict was formed and any finding drawn from either is unproven.

@github-actions github-actions Bot added readiness: action required A blocking check or review needs attention and removed readiness: checking Automated validation is still running labels Sep 26, 2026
@github-actions

github-actions Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Opus 5.5 Review (fork) — ✅ no blocking findings

Reviewed f5b5d1207e26de00d1ebff0103e55e36d054ee81 via the fork AI-review pipeline; updated in place on each push.

Review details

No findings.

[OPUS-REVIEWED] f5b5d12

@rubencu
rubencu force-pushed the fix/composer-send-icon-idle branch from f3e9eb7 to 819864a Compare September 26, 2026 22:36
@rubencu

rubencu commented Sep 26, 2026

Copy link
Copy Markdown
Contributor Author

Disposition: fixed in 819864a

  • identical idle frames hit break before settlement (website/src/hooks/useWebSocket.ts)

Confirmed reachable: an idle slots frame settles the composer, a late switchSlot history reply writes running back, and the next byte-identical frame hit the dedupe break before sseSlots, so nothing re-settled it.
The slots case now skips the dedupe only when the frame reports the active slot running: false while the active chat still reads busy and no local send is pending for it; every other identical repeat is still deduped.
useWebSocket.endedTurnFlush.test.ts covers idle frame -> stale switchSlot.fulfilled -> identical idle frame -> composer idle (fails with the bypass removed), plus dedupe kept when already idle and a pending send left alone.

@rubencu

rubencu commented Sep 26, 2026

Copy link
Copy Markdown
Contributor Author

Disposition: fixed in 819864a

  • Settlement preempts the real _done on every ordinary turn (Watch)

Confirmed: _finish_queue_cycle clears the task, calls push_slots_update(), then broadcasts chat_done, and the leading-edge push usually goes out at once, so the settlement runs first on most turns. It also removed placeholder streaming rows that _done keeps, a transcript change on the common path.
settleEndedActiveTurn and the _done branch now call one shared idempotent step, finalizeActiveTurn, so the following _done changes nothing and the result equals _done alone. The doc comment states it runs on the common path, and why chat_done is the only frame of the turn that can follow.
chatSlice.activeStrandedStream.test.ts adds chunks -> idle slots -> _done (one finished reply, idle composer, _done returns the settled state unchanged), the reverse order as a no-op, and settle-then-_done deep-equal to _done alone including a placeholder row (fails against the previous settlement).

@github-actions github-actions Bot added readiness: checking Automated validation is still running readiness: action required A blocking check or review needs attention and removed readiness: action required A blocking check or review needs attention readiness: checking Automated validation is still running labels Sep 26, 2026
@rubencu
rubencu force-pushed the fix/composer-send-icon-idle branch from 819864a to 3dc7ba4 Compare September 27, 2026 00:06
@rubencu

rubencu commented Sep 27, 2026

Copy link
Copy Markdown
Contributor Author

Disposition: fixed in 3dc7ba4

  • Early settlement lets the prior chat_done terminate a new turn (website/src/store/chatSlice.ts)

Confirmed reachable: the idle slots frame frees the composer while the server still awaits chat_done_payload, and chat_done carries no turn id, so a send in that gap had its new turn finalized and its pendingTurnSlot cleared by the old _done.
settleEndedActiveTurn now records a one-shot settledAwaitingDone token with the slot's run epoch (the existing per-slot count of turn starts). The _done branch consumes it and, when a newer epoch has started, leaves that turn's stream state and pending-send guard untouched. Slot switches, resets, new-chat activation, resume and eviction clear the token.
The one ambiguous wire case (the settled turn's _done lost, then the next turn's _done ahead of its idle frame) fails busy and recovers on that idle frame.
chatSlice.activeStrandedStream.test.ts covers the race with a locally started and a server-started newer turn, and the lost-_done recovery; all three fail with the epoch check removed.

@rubencu

rubencu commented Sep 27, 2026

Copy link
Copy Markdown
Contributor Author

Disposition: fixed in 3dc7ba4

  • Every turn's finalization now hangs on a backend emission-order invariant that no backend test pins (Watch)

test/test_finish_queue_cycle_terminal_order.py drives a real slot and state through _finish_queue_cycle and pins the order: done appended, then slot.task = None with turn_running false and the projected row reading running: false when push_slots_update runs, then exactly one chat_done. It also pins that a synthesis dispatch keeps the slot running and sends no chat_done, and that the projection's running is turn_running. Swapping the push and chat_done, clearing the task after the push, or projecting slot.running each fails it.
A comment at that terminal step in chat_runner.py names the frontend dependency and the test, and the chatSlice.ts comments cite the test.
A read of _run_chat found every content frame emitted before its finally reaches _finish_queue_cycle, and slot.task cleared only there.

@github-actions github-actions Bot added readiness: checking Automated validation is still running and removed readiness: action required A blocking check or review needs attention labels Sep 27, 2026
@github-actions github-actions Bot added the readiness: action required A blocking check or review needs attention label Oct 9, 2026
@github-actions github-actions Bot added the merge conflict Branch has merge conflicts with its base — author must resolve before merge label Oct 9, 2026
@rubencu
rubencu force-pushed the fix/composer-send-icon-idle branch from 0034ff3 to 06a0edc Compare October 9, 2026 20:14
@github-actions github-actions Bot removed the merge conflict Branch has merge conflicts with its base — author must resolve before merge label Oct 9, 2026
@rubencu

rubencu commented Oct 9, 2026

Copy link
Copy Markdown
Contributor Author

Pushed 06a0edc (rebased onto current main) to answer the GPT 6.1 finding on 0034ff3, "an ended-turn history page splices the next answer into the previous reply". The finding was reproduced in the store tests: a history page captured mid-turn T and applied after this tab had already recorded T's end kept T's streaming row under an idle composer, so T+1's chunks appended to it.

The fix stops applying such a page to the active pane at all: in refreshSlot.fulfilled a page that still reports the turn running after the tab recorded that turn's end is older than what the tab shows, the same case the existing refreshAppliedSeq guard already drops, so it writes nothing (no transcript merge, no run state, no replay floor). Loss-freeness then rests on the refresh that follows a turn end: chat_done already dispatches one, and the _done-less end this PR settles now dispatches the same refresh from the idle slots row (hooks/websocket/slotList.ts); the _done that usually follows for the same turn skips its own, deduplicated by the turn's wire identity in hooks/websocket/idleRowRefresh.ts (never by slot alone, so a record left by a lost _done cannot swallow the next turn's refresh). Background and switched pages captured mid-turn finalize every fetched streaming row before merging, since the viewed thread's refresh does not cover them. One Not a goal bullet names the pre-existing inverse (a genuinely idle completion page ordered against a successor that started after it was captured), which main has and this PR does not change.

Tests: the store regressions cover a live successor opened by a send, a nudge or a subagent row, a first local row known only by its sendId, and a queue-drained turn (nothing doubled, nothing lost), plus the completion page landing; the hook tests pin exactly one refresh per turn end in both orderings and the identity dedupe. Removing the early return, the idle row's refresh, or the identity check each fails its tests by name. Two main pins were extended for the new surface: useWebSocket.ownership.test.ts lists idleRowRefresh.ts and its two edges, and chatSlice.ownership.test.ts accounts for the facade's wireTurnIdentity re-export. Locally: 10,529 frontend tests across the chat store, websocket hook and chat page suites, typecheck and ESLint clean; the only reds are ten ArtifactDetailPage/ChatInput.approval tests that fail identically on a pristine main checkout on this host. Backend: the PR's five test files plus the source-pin budget and flake ratchet, 496 passed. The rebase itself met one conflict, main's new restoredQuestionNotices per-slot map beside this PR's endedTurn in slotResidue.ts, resolved as both.

@github-actions github-actions Bot added readiness: checking Automated validation is still running readiness: action required A blocking check or review needs attention and removed readiness: action required A blocking check or review needs attention readiness: checking Automated validation is still running labels Oct 9, 2026
@rubencu
rubencu force-pushed the fix/composer-send-icon-idle branch from 06a0edc to 1d5fc0d Compare October 9, 2026 23:29
@rubencu

rubencu commented Oct 9, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto main (bad04199fca0), one commit, head 1d5fc0d5e509. Answers the three AI reviews on 06a0edcb.

GPT 6.1, "Finalizing stale history before merging duplicates the completed reply" (slotSwitch.ts): accepted, fixed. switchSlot.fulfilled no longer finalizes the fetched page before the merge. The page's rows keep their roles through mergePreservedPastes and the three merge branches, so the branches that re-attach the tab's finished reply still drop the page's streaming partial. Afterwards, finalizePageStreaming (store/chat/transcript.ts) finalizes, on copies, only the streaming rows that came from the page and survived the merge. The replay floor is now seeded from the pure fetched page whenever the page reports running, including an ended-turn page. That keeps the floor _done leaves, so a redelivered chunk of the ended turn cannot reopen the reply or the busy composer. Test: store/chatSlice.switchEndedTurn.test.ts, "a mid-turn switch page does not render the reply its background chat_done finished twice". It asserts exactly one assistant reply ("partial answer") with no stale "partial " row, an idle composer, a floor of seq 1 from the page's row, and a dropped redelivered chunk. Mutation evidence on archive copies: restoring the pre-merge finalize fails that test by name (two replies), and so does seeding the floor only for a page believed running (lastChunkSeq undefined). The sibling sites need no change. refreshSlot.fulfilled returns before any merge for an ended-turn page. warmSlotCache.fulfilled finalizes before its merge, but that merge filters nothing by role (tailNotInPage and the coverage checks read row identity and the pure fetched page), so its kept-copy rule already holds and is pinned by "keeps a longer identity-less cached reply when stale warm history is partial".

First Principles, delete idleRowRefresh.ts for turnAlreadyEnded: declined, because the two records answer different questions. ChatState.endedTurn records that a turn ended. Every live idle row writes it, including a row that found the pane already idle and dispatched no refresh, and the _done reducer writes it before turnCompletion.afterDone runs. idleRowRefresh records that the idle row dispatched the completion refresh. Probes on archive copies: the suggested read in afterDone sees the _done's own record and skips the refresh in two orderings ("a _done then the idle row for the same turn refreshes once, from the _done" and "a lost _done's record does not swallow the next turn's _done refresh", 0 refreshes against 1). The same read taken before the _done reducer passes those two but loses the refresh when Stop's "not running" reply idled the pane before the idle row: the row then records the end and dispatches no refresh, and the _done skips its own. The module record passes all three. idleRowRefresh.ts now says this in its docstring.

Design review, a walk over every slot.task = None site: not added, answered. An AST scan of src/kiro_crew finds 11 sites that set a .task attribute to None. One clears a chat turn and is followed by chat_done: _finish_queue_cycle, pinned by test/test_finish_queue_cycle_terminal_order.py. It is also the only function that emits chat_done at a turn end (the read-only relay refusal sends one without touching slot.task, and the deferred /compact acknowledgement sends one with ends_turn=False). The other ten emit no chat_done: a dead task dropped on a failed archive restore (which pushes slots), the spec builder's reservation release and handoff, the Slack injection's done callback, and non-turn tasks (the side panel, the catalog cache, tailnet recovery, a workflow handle). A walk asserting "push before chat_done" would therefore pin one function, which the behavioural test already pins through a real slot. The rule stays in docs/system-specs/modules/session.md and at _finish_queue_cycle.

Frontend Tests (1) red on 06a0edcb: base-owned, cured by the rebase. focusRingContrast.test.ts flagged AskAnswersCard.tsx, which this PR does not touch. The old base sat between the commit that added that test and the one that fixed the card. On the new base it passes.

Validation on this head: the store, WebSocket-hook and ChatPage selection is 146 files and 1,991 tests, all passing. The full frontend suite is 46,403 passed and 66 failed in 20 files (Pierre, DiffBlock, highlighting, ArtifactDetailPage, ChatInput.approval, SchedulePage.secrets and others), and the same 20 files fail with the same 66 tests on a pristine main checkout on this host. Typecheck, ESLint on the 24 changed TS files and git diff --check are clean. Backend test_slot_running_readers.py and test_finish_queue_cycle_terminal_order.py: 11 passed.

@github-actions github-actions Bot added readiness: checking Automated validation is still running readiness: action required A blocking check or review needs attention and removed readiness: action required A blocking check or review needs attention readiness: checking Automated validation is still running labels Oct 9, 2026
@rubencu
rubencu force-pushed the fix/composer-send-icon-idle branch from 1d5fc0d to c20c0b9 Compare October 10, 2026 01:29
@rubencu

rubencu commented Oct 10, 2026

Copy link
Copy Markdown
Contributor Author

Accepted: a superseded switchSlot read could finalize the live turn that followed it. The thunk never aborts an earlier read of the same slot, and switchSlot.fulfilled checked only the key once the newer switch had settled and nulled the claim. A read issued mid-turn N could land after a switch away and back, by when N had ended and N+1 was streaming. historyReportsRunning then read it as an ended-turn page, and the re-attach branch finalized N+1's live row and idled the slot.

Fix in c20c0b9 (one commit, rebased onto adfd71b): switchSlot.pending records the newest requestId in slotSwitchLatestRequestId, which settling does not clear. switchSlot.fulfilled returns before any write when the action carries a different requestId, so the newer switch owns the pane. A hand-rolled dispatch without a requestId keeps the previous behavior. switchSlot.rejected takes the same check: its transient-failure branch is the one write the claimed gate does not cover, and an older failure there emptied the transcript and cleared slotRunning under the live turn (that half is pre-existing on main).

Tests in website/src/store/chatSlice.switchSuperseded.test.ts:

  • "a superseded switch page cannot finalize the live turn that followed it": the reviewed sequence (R1 for A mid-turn N, R2 for B, N's background chat_done and N+1's chunks on A, R3 for A settles, then R1 lands).
  • "a superseded switch page landing while the newer switch is in flight applies nothing": R1 lands while R3 holds the claim, then R3 applies normally.
  • "a superseded switch failure cannot empty the live turn that followed it".

On an archive copy of the published head 1d5fc0d all three fail. In the first, R1 leaves the transcript as [request, assistant "second "], the slot idle and the composer free, the cursor R1's, and N+1's next chunk opens a second bubble. Mutations on archive copies of c20c0b9, each anchor matched once: removing the check in fulfilled fails the first two tests, removing it in rejected fails the third, and removing the record in pending fails all three. Round 8's chatSlice.switchEndedTurn test passes throughout.

Siblings, unchanged: refreshSlot.fulfilled carries no switch claim, and round 7's ended-turn early return declines the same stale page before it writes the pane (on main that page replaces the transcript). warmSlotCache.fulfilled never writes the active pane, writes run state only while the receipt tick is unchanged, and finalizes only its own copy of the page, so N+1's cached row and run entry stay streaming.

@github-actions github-actions Bot added readiness: checking Automated validation is still running and removed readiness: action required A blocking check or review needs attention readiness: checking Automated validation is still running labels Oct 10, 2026
@rubencu

rubencu commented Oct 10, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto d3f462f23b after #18658 touched slotSwitch.ts: 84fad32594. The one conflict was the ./transcript import line, resolved as the union (finalizePageStreaming from this PR, tailNotInPage from #18658); every other hunk merged cleanly, and the two changes compose: #18658's liveSends rows go in front of the trailing reply, this PR's finalizePageStreaming then finalizes only the page's own surviving streaming rows. Typecheck and ESLint clean; 72 chat-store test files (1,241 tests, including #18658's chatSlice.switchSlotLiveSend.test.ts and this PR's three new files) green; backend pins, source-pin budget and flake ratchet 496 green; diff --check and push_guard green.

@rubencu

rubencu commented Oct 12, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto main at d866dd2607 (84fad32594 -> 9e6110e4bf, same single commit). One slotSwitch.ts hunk met #19263: the chunk-floor seed keeps this change's reportedRunning gate (the floor survives a turn end, as _done leaves it) and carries main's sentence about a page that predates a live send, whose else if (!pagePredatesLiveSend) arm stands as main wrote it. tsc --noEmit 0 errors, ESLint 0 on the 25 changed TypeScript files, the 8 changed test files plus the two ownership pins: 111 passed. git diff --check and push_guard pass.

@rubencu

rubencu commented Oct 12, 2026

Copy link
Copy Markdown
Contributor Author

Rebased 9e6110e4bf -> 5bcdf72a2e on main 10350b7294: main added the instance-version and remote-update interfaces above ChatSlot in website/src/types/index.ts, beside this change's TurnIdentityFields and ChatDonePayload. Both blocks kept, ChatSlot extends TurnIdentityFields as before. tsc and ESLint clean, 111 vitest tests in the eight touched files and 404 backend tests in the five touched test files pass, docs-lint and diff-check clean. MERGEABLE.

A turn whose _done the tab never applied left the active slot's
slotState busy: the frame was lost, or a history fetch served mid-turn
resolved after it and wrote its stale running=true back. A later slots
snapshot cleared slotRunning, so the transcript and footer read idle,
but selectComposerBusy also reads the stream state and kept offering
the Steer/Queue split button with no agent running.

The live sseSlots frame now settles it: the server projects running
from the turn task, so a frame reporting it false follows every frame
of that turn on the ordered socket. HTTP fetchSlots replies never
settle, since they can predate a turn already streaming. The slots WS
handler flushes text still buffered for the active slot before such a
frame, as chat_done does, so the tail lands in the finished reply.

A switch page captured before a turn the tab already recorded as
ended keeps its streaming rows through the merge, which drops them
beside a reply the tab finished, and only the rows it keeps are
finalized after it: finalized first, the page's partial passed the
streaming filter and the finished reply rendered twice. That page also
seeds the chunk replay floor from its streaming row, as _done leaves
the floor, so a redelivered chunk of the ended turn cannot reopen the
reply or the busy composer.

A switch settlement whose read a later switch superseded applies
nothing. The thunk never aborts an earlier read of the same slot, so a
page captured mid-turn could land after the user left and came back,
by when the tab had recorded that turn ended and a successor was
streaming. Merged as an ended-turn page, it finalized the successor's
live row and idled the slot. The pending reducer records the newest
requestId, which settling does not clear, and the fulfilled and
rejected reducers ignore any other.
@rubencu

rubencu commented Oct 13, 2026

Copy link
Copy Markdown
Contributor Author

Rebased 5bcdf72a2e -> f5b5d1207e on main 2598f22518: main added the wake_starting field to the slot projection and its facade key list where this change adds turn and turn_gen; both kept in each. 414 backend tests in the five touched files, tsc and 111 vitest tests pass; docs-lint and diff-check clean. MERGEABLE.

@iamwhatever iamwhatever left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This fixes a composer stuck on Steer/Queue after a turn whose _done the tab never applied. The cause is that slotState was reset only by _done or a history fetch. Now the live idle slots row settles the active turn (settleEndedActiveTurn in store/chat/runState.ts), and the server stamps slots rows, terminal chat_done and the history reply with {turn, turn_gen}, so a late _done, a stale history or switch page, or a late fetchSlots row can no longer finalize or re-busy a successor turn. Our change request at 81d9e2e asked to drop the relay hunks; the current head f5b5d12 contains no remote_relay.py or test_remote_crew_execution.py changes, so it is met. I read all ~1,180 production lines and skimmed the tests, and tried to break the early settle four ways. (1) An idle row mid-turn: _finish_queue_cycle clears slot.task then pushes then sends chat_done, a queue-drained successor returns before that, and both compacting frames are sent inside the turn task, so running stays true. (2) A pending send settled by the previous turn's idle row: refused, because the row must name a turn newer than the known baseline (turn 0 when none is known, which no real turn carries). (3) The mid-turn /compact acknowledgement fencing the live turn: it passes ends_turn=False and carries no identity. (4) A superseded switchSlot read: dropped by slotSwitchLatestRequestId. The one residual race the author disclosed (a pre-restart history reply landing after a restart, then a late _done) needs three unlikely events and is never worse than main, which has no fence at all. Non-blocking points. The description still mentions the removed relay's chat_done, test_remote_crew_execution.py, and settleEndedActiveTurn in store/chatSlice.ts; please refresh it. ChatDonePayload in types/index.ts has no reader (First Principles). PR Scope was cancelled at 15 min on this head with no newer run, so please rerun it before merge. The needs-author-decision label looks stale. — crew-pr-reviewer (deep re-check)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

fork Pull request from a fork (external contributor) needs-author-decision PR blocked on author input

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants