Files
hapi/cli/src/codex
dff2d99fd6 fix: align Stop with the official agent TUIs (#1992)
* fix(cli): preserve queued user input on plain Stop across flavors

Plain Stop must abort only the active runtime turn and keep unconsumed
queued messages (localIds/order/isolate/mode) for the next drain. Previously
the per-flavor Abort handlers unconditionally called queue.reset(), dropping
pending messages, and an idle loop could collect/ACK a batch that arrived
during abort teardown.

- MessageQueue2.waitForMessagesAndGetAsString checks the abort signal before
  both batch collections, so an in-flight Abort can never collect/ACK (and
  therefore never replay) a pending batch.
- Add a serialized Abort barrier in RemoteLauncherBase with an optional
  synchronous entry callback: onAbortEntry aborts the current signal so an
  idle waiter fails closed, and waitForAbortBarrier holds the loop's next
  dequeue until teardown completes. A rejection during teardown no longer
  spins the loop with a stale aborted signal; it is boxed and propagated to
  the Abort RPC caller, the run loop, and clearAbortHandlers lifecycle.
- Launcher handleAbort resets the queue only on terminal cleanup
  (shouldExit/leavingRemote). BaseLocalLauncher Abort (switch to remote)
  preserves the shared queue. Cursor ACP soft-steer drain handles an already
  aborted signal without deadlock.
- Codex shared root Abort stays a pure turn/interrupt; native queue retained
  (control regression only, no resume-policy change).

Tests: Launcher-level Abort preservation (active/idle/concurrent/rejection),
enqueue-during-cancel, MessageQueue2 idle wake-then-abort and post-await
guard, base-local queue preservation, Codex abort/native-queue control.
Verified with Node22 (.sbx/node22) - full cli suite green; see
.sbx/REPORT.md.

* fix(web): settle Stop state with the abort request

* test(web): cover Stop request settlement without an idle render

* feat(cli): batch compatible Codex queued input

* fix(codex): preserve batch recovery and fork boundaries

* test(cli): cover idle and overlapping Stop teardown

Keep queued input unacknowledged while an idle Stop or a later Stop is still tearing down. Gate cancellation acknowledgements independently from prompt completion to exercise both ordering races.

* fix(codex): keep queue preflight failures retryable

Persist a retryable state during the read-only tail lookup, then journal uncertainty with the native mutation. Preserve released native edits and avoid replay when acceptance arrives during preflight.

* fix(cli): honor exit requests after abort teardown

* test(cli): cover terminal handoff during overlapping stops

* fix(codex): retain uncertain batch append ownership

* fix(dsh): stop queued dispatch during process cleanup

* fix(dsh): stop idle queue waits before process cleanup

* fix(codex): preserve removal intents across native edits

* test(codex): resolve native batch inputs in full-stack checks

* test(copilot): stub session metadata on the abort test client

The ACP session title sync now reads client.getMetadata() when a launcher is
created, so the abort test client needs a getMetadata stub next to its existing
updateMetadata stub. Without it every case built on createAbortSession fails
with "client.getMetadata is not a function".

* fix(opencode): keep the dequeue signal usable after a Stop that only abandons round metadata

The abort barrier aborts the dequeue signal when a Stop arrives so an idle wait
wakes up. A plain Stop during the post-prompt round-summary settle phase only
abandons metadata and returns before performAbort, which is what replaces the
controller. The loop then re-read the aborted signal in a tight microtask loop
and never reached the queued input, pinning a CPU. Recycle the controller on
that early return so the queued input is dequeued on the next iteration.

* fix(cli): keep launchers running when a native cancel is rejected

The abort barrier aborts the dequeue signal when a Stop arrives and, when the
teardown rejected, boxed the failure so the run loop threw it at the next
dequeue. Every launcher that uses the barrier therefore stopped surviving a
rejected native cancel, which it did before the barrier: a rejected cancel left
the controller untouched and only the Abort caller saw the error.

setupAbortHandlers now takes an onAbortRejected callback next to onAbortEntry.
On a teardown rejection the base restores the dequeue signal through it and
rethrows to the Abort RPC caller only; the boxed failure is gone. Each launcher
passes a one-line callback that replaces the controller only when it was
aborted. Queue preservation and the barrier's ordering are unchanged.

* fix(codex): restore the applied batch version after definite rejections

A definite native rejection left the rejected proposal in versions and
rolled batch.current back positionally (length - 2), so a second
consecutive rejection selected the earlier rejected proposal instead of
the applied version; the stale current survived reconciliation and a
later member cancel could submit rejected content for execution.

Capture batch.current before each append and restore that saved index
on definite rejection across nativeUpdate, extendBatch,
cancelBatchMember and steerBatchMember.

Covered by failing-first regression tests: consecutive rejected appends
followed by a member cancel, and consecutive rejected native edits.
See tiann/hapi#1992 review discussion.

* fix(hub): align archive cleanup status assertion with the 503 mapping

tiann/hapi#2423 changed ArchiveCleanupError to return 503 instead of 504
(Cloudflare Tunnel replaces 502/504 bodies; the code field distinguishes
timeouts) and updated one assertion, but the overlapping-archive
singleflight test still expected 504, which the 409 | 503 status union
can never produce.

* fix(opencode): preserve queued input on a plain Stop

tiann/hapi#1992 promises pending input survives a plain Abort on the
queue-backed launchers. Upstream #2424's performAbort reset the queue
unconditionally, dropping not-yet-dispatched input on a plain Stop. Reset
only when leaving the session (switch/exit), and let a terminal request
joining an in-flight plain Stop promote its cleanup intent onto the
operation so the reset still lands exactly once, after the shared
cancellation restore drain.

* fix(opencode): terminal drain ordering, dequeue fence, teardown escalation

Hydrogen pre-review of the preserve-on-plain-Stop round surfaced six
defects in the Stop/terminal paths, all adjudicated valid, and its
re-review surfaced three more:

- A direct switch/exit reset the queue before the v2 cancellation drain,
  so a proven-cancelled steer restored back into the queue after the
  reset and a switch bounced straight back into remote mode. Run the
  terminal reset after the drain, where a terminal joining a plain Stop
  already applied its promoted reset.
- The dequeue loop could dequeue, ACK, and then drop a preserved row on
  the prompt-prep aborted-continue while a plain Stop was still awaiting
  its native cancellation. Park the dequeue on the runtime gate's
  cancellation-idle fence and refuse beforeDequeue while a cancellation
  drain is in flight.
- restoreQueuedReservation ignored shouldExit, re-admitting a steer
  parked before its v2Steers entry after the terminal reset. Leaving
  remote never re-admits.
- performAbort's finally escalated every steer to 'teardown' when the
  teardown threw, stranding a proven-cancelled steer indeterminate on a
  plain Stop that keeps running. Escalate only when leaving remote.
- A terminal joining a plain Stop lost its promoted cleanup intent when
  the owner's performAbort rejected: the queue kept its rows and an idle
  dequeue waiter was never woken. Run the reset and the abort in the
  rejection handler.
- dispatchV2Steer removed its entry only after awaiting the restore, so
  a Stop landing mid-restore ran a second concurrent restore whose
  failed restoreReservation falsely reported the row indeterminate.
  Detach the entry before the restore.
- A plain Stop landing between the dequeue and the prompt (model/effort
  setup, round snapshot, or the native history read) still dropped the
  already-dequeued, hub-ACKed batch on the pre-dispatch bail-outs.
  Requeue the batch there in its original order with each localId
  intact, and echo it at the dispatch commit point so the retry does
  not double-echo; compact keeps its early echo.
- restoreQueuedReservation's leaving-remote path returned false without
  undoing its work: the steer stayed stuck 'dispatching' in the shared
  queue (Cancel answered 'in-flight' forever) and the hub stamp never
  reverted. Persist 'queued' and release the held reservation instead.
- The v1 terminal path had no rejection cleanup: a performAbort(true)
  that threw left the queue unreset and the dequeue signal un-aborted,
  parking the idle loop forever. Mirror the v2 rejection cleanup.

* fix(cli): preserve queued input across pre-prompt Stops in every queue-backed launcher

The whole-PR review surfaced the OpenCode preserve class defect in every
other queue-backed launcher, plus teardown and batching gaps:

- dsh, cursor ACP, copilot, grok and kimi dequeued and hub-ACKed a batch
  and then dropped or dispatched it when a plain Stop landed during the
  pre-prompt setup awaits. Requeue the batch at every pre-dispatch
  bail-out (requeue never fires for terminal switch/exit, whose reset
  already cleared the queue) and defer the cursor ACP hub ACK and user
  echo to the dispatch commit point so a retry never double-ACKs or
  double-echoes. The shared requeue lives in MessageQueue2.unshiftBatch;
  OpenCode's helper delegates to it.
- cursor ACP requeued into the shared queue without a shouldExit check,
  bouncing a switch straight back into remote mode, and its soft-steer
  restoreQueuedReservation re-admitted a 'dispatching' steer after the
  terminal reset. Guard the requeues and release the steer the same way
  OpenCode does: persist 'queued' and release the held reservation.
- A rejected handleAbort(true) skipped the queue reset everywhere and
  the dequeue-signal abort outside DSH, parking an idle runMainLoop
  forever. requestExit now invokes an onTerminalTeardownRejected hook on
  rejection; copilot, grok, kimi and cursor ACP override it with their
  reset+abort, OpenCode and DSH are no-ops (their teardowns guarantee
  the cleanup on every path), and DSH moves its reset into a finally so
  a rejected cancel cannot skip it.
- runAbortUnderBarrier overwrote an in-flight abort barrier instead of
  chaining onto it, letting dsh kill() unblock the loop's dequeue while
  an earlier plain-Stop teardown was still running. The release now
  chains onto the prior barrier.
- codex/shared/root captured the message batch key from this.settings at
  callback arrival, merging queued messages across a settings-changing
  slash command and splitting around cold-start hydration. The key is
  now computed inside the work continuation, after bound and after
  earlier queued commands ran.

* fix(cli): keep origin-indeterminate steers resolvable and skip dead prep on Stop

The round-4 confirm review surfaced three residual steer/teardown gaps:

- restoreQueuedReservation's terminal-exit branch deleted an
  origin-indeterminate reservation and left the hub steerDeliveryState
  stuck at 'dispatching'. An origin-indeterminate row cannot be honestly
  reverted to 'queued': stamp 'indeterminate', emit it, and keep the
  reservation for explicit Cancel/Retry in local mode (opencode and the
  same newly added cursor ACP branch).
- restoreQueuedReservation now returns 'restored' | 'dropped' |
  'indeterminate' so dispatchV2Steer can tell a clean terminal drop from
  an unknown outcome: the rejected-admission branch reports 'Active turn
  changed' instead of a false 'Steer state is indeterminate', and the
  stop-cancellation path treats the drop as definitive removal.
- A plain Stop landing during the inline setModel/setConfigOption awaits
  no longer runs captureOpencodeRoundSnapshot or toggles
  thinking/steeringActive for a prompt that never starts; the already-
  dequeued batch requeues before the round-snapshot setup.

* test(cursor): cover legacy queue preservation across Stop and terminal exits

The PR changed cursorLegacyRemoteLauncher's abort handling (+10: the
leavingRemote queue reset and the rejected-cancel signal restore) without
any behavioral test. Mirror the Cursor ACP coverage: a plain Stop during
an in-flight turn keeps the queued row and drains it after the Stop
settles, a terminal switch/exit resets the queue exactly once with no
further dispatch, and a Stop landing during the dequeue wait preserves
the not-yet-dequeued row. The launcher already behaved correctly on all
three paths; the tests guard them.

* fix(launchers): close abort-window races across teardown and pre-dispatch setup

Four launcher loops (cursorAcp, copilot, grok, kimi) plus dsh and
opencode kept a live dequeue signal and a dequeue-time hub ACK across
their pre-prompt setup awaits, so a batch arriving behind a terminal
switch/exit teardown was dequeued, stamped invoked at the hub, run
through ACP model/mode mutations, and dropped unprompted; and an abort
that landed mid-setup could be erased by a later state reset and still
dispatch the canceled turn.

cursorAcp
- single userAbortRequested reset per turn window: an abort that lands
  during model/mode setup survives to the pre-dispatch gates
- hub ACK moved to the dispatch commit point, after every pre-dispatch
  bail-out: an aborted batch is never stamped invoked nor dropped with
  a false ready
- new requeueAbortedBatch helper: abort-path requeues carry only user
  content, so a Stop-canceled model-error-bridge item is dropped
  instead of resurrecting after the Stop settles
- durable Bridge mutations (user-turn supersede, replay-gate persist)
  deferred to the dispatch commit point with post-persist abort/exit
  guards; guard added after the harness-resume buffer discard
- soft-steer restoreQueuedReservation re-checks shouldExit after the
  'queued' persist and releases the held reservation instead of
  restoring it into the queue, which would bounce a terminal switch
  straight back into remote mode; 'Active turn changed' when the turn
  changed during the restore
- handleAbort aborts and replaces the dequeue signal at entry when
  leavingRemote, unparking the wait before the teardown's own awaits
- lastUserMessage recorded at the dispatch commit point

copilot/grok/kimi
- handleAbort entry abort-and-replace when leavingRemote
- shouldExit break right after the dequeue resolves, before any state
  mutation
- hub ACK deferred to the dispatch commit point
- intermediate shouldExit/aborted checks after each setup await;
  isClosed guards on every unshiftBatch
- grok: thinking deferred to the commit point, history busy kept early

dsh
- hub ACK deferred to the dispatch commit point
- a failed top-of-loop reconnect requeues the un-ACKed batch when a
  plain Stop landed inside it; isClosed guards on every unshiftBatch
- generation checks after the model/effort switch awaits; thinking
  deferred to the commit point
- kill() batch drop emits the sibling idle 'ready' signal

opencode
- display-mode state applied below the pre-snapshot Stop/exit check

Each loop change is covered by a behavioral regression test that fails
against the pre-fix dequeue-time ACK / live-signal teardown behavior.

* fix(launchers): close bridge supersede, cancel-window, and teardown races

- cursorAcp: markModelErrorSupersededByUserTurn now drops the pending
  bridge row, and the replay gate fails closed once superseded, so a
  manual Bridge enqueued mid-setup can no longer replay after the user
  turn that superseded it
- cursorAcp/dsh: a batch resolved while the terminal teardown flips
  shouldExit breaks before reconnect or mode/model setup instead of
  mutating ACP state on a closing backend
- MessageQueue2: cancelByLocalId answers 'in-flight' for dequeued-but-
  uncommitted localIds, closing the deferred-ACK window where a cancel
  could double-deliver a message or deliver one after an explicit
  cancel
- MessageQueue2: unshift forwards internal provenance; unshiftBatch and
  the cursorAcp requeue helper keep it on non-isolated requeues
- dsh: a plain Stop racing a failed acpSessionEnded restart requeues
  the dequeued batch instead of dropping it in the recovery catch, and
  the null-model switch path gains the same abort-generation guard as
  its sibling branch
- copilot/kimi: the switched model's effort baseline is captured before
  the plain-Stop bail so the requeued turn takes the new baseline
- tests: failing-first regression tests for each sequence; grok/kimi
  requeue tests drop unused spies, fix stale deferred-ACK comments, and
  assert the commit-time ACK exactly once

* fix(cli): scope in-flight cancel tracking to deferred-ACK launchers

* fix(opencode): commit hub consumption only when the prompt is dispatched

* fix(codex): persist batch uncertainty after an unconfirmed shrink

* fix(codex): journal batch uncertainty before dispatching a shrink

* fix(codex): journal batch uncertainty before every native batch write

Every native RPC that can change the content or existence of a batch's
queued submission now persists the batch as unknown, together with the
proposal that motivated it, before it is dispatched. Only a confirmed
response or a definite rejection settles the batch back, and that
transition is persisted.

Previously the whole native edit (nativeUpdate), the append edit
(extendBatch), the restoration after a rejected steer and the suspend
delete left the batch queued while an unconfirmed proposal was current.
A crash before the edit applied, followed by canceling a member, could
then delete or rewrite the native submission from a version it never held
and silently drop sibling input.

---------

Co-authored-by: sbx <sbx@agent-sandbox.invalid>
2026-11-17 14:58:11 +08:00
..
2025-12-16 15:03:50 +08:00