* refactor(hub): resolve fork and rewind boundaries in one place
Move selectForkTranscriptPrefix into forkBoundary.ts as the single home
for fork and rewind boundary resolution. Fork execution keeps calling
the same function with identical behavior; the forkTranscript module
and its tests move with it, so the next boundary consumers (preview,
token validation) extend one resolver instead of forking the rules.
* feat(shared,hub): read-only fork preview with a boundary token
Add POST /sessions/:id/fork-preview: the hub resolves the preview mode
from the live session (a running Codex with a verified completed turn
previews through it), runs the same admission guards as confirm without
taking the history-action lock, and answers with the kept tail rows,
the excluded rows, counts, and a boundary token.
Confirm accepts the token back on fork and rewind. The public wrappers
re-check it right after the history-action lock: an epoch change, new
invoked rows, or a source that started running since the preview reject
with 409 boundary_moved so the caller re-previews instead of forking a
transcript it never saw. Clients that send no token keep the legacy
behavior, and a latestCompleted preview fails closed on runners that do
not advertise the forkPreview capability, because answering it from hub
rows is the drift this replaces.
* feat(cli): codex shared runtime answers and pins its fork boundary
Add the PreviewForkBoundary RPC: the shared runtime reads its native
history and answers where each fork mode cuts - latestCompleted through
latestCompletedForkCutoff, current through the last turn (falling back
to the completed cut once a turn runs), message through the projected
turn with the steered-cut clientId rule - and names the first excluded
hub row so the hub cuts its preview tail at the same place.
Confirm accepts a preview-pinned lastTurnId: the runtime re-verifies the
turn still exists with a completed native prefix and forks through that
fixed inclusive cutoff instead of re-deriving a moving one, so a turn
that starts between preview and confirm cannot drift the boundary. The
capability is advertised as conversationHistory.forkPreview.
* feat(web): fork preview dialog fed by the hub
Replace the web-side fork boundary mirror with the hub's preview
answer: useForkFlow asks POST /sessions/:id/fork-preview, renders the
returned kept tail and excluded boundary through the regular
normalize/reduce pipeline, and confirms by echoing the boundary token.
A 409 boundary_moved refreshes the preview in place and demands a
re-confirmation, a source that starts running while the dialog is open
re-answers through the hub, and an older hub (404) falls back to the
legacy confirm dialog. forkPreview.ts keeps only the compact text
shaping; its cut rules are gone. SessionChat and SessionList share the
flow, the MessageActions fork button invokes it directly under the
message-fork testid, and the dialog's confirm stays accessible as
Fork. en and zh-CN locales and the e2e fixture/spec come along.
* feat(web): rewind preview dialog
Route rewind through the same hub-fed preview: the MessageActions
rewind button opens the rewind variant of the fork preview dialog,
which emphasizes the region the source would delete (destructive
styling, struck-through rows, and a truncation count) before confirming
with the boundary token. The runner-side fork-safe ambiguity still
offers the fork-at-boundary fallback, an older hub falls back to the
legacy rewind confirm, and the inline rewind confirmation dialog is
removed now that the preview gates the destructive action.
* test(hub): align archive cleanup timeout status with the 503 semantics
* fix(hub): reject the fork preview when the transcript moves during the boundary call
* fix(web): surface fork preview failures in the chat with a connect-error retry
* test(e2e): pin the list fork menu and opencode affordances to the preview flow
* fix(cli): make shared Codex fork previews respect forkable boundaries
The message-mode preview answered boundaries the confirm would refuse: a
historical cut whose completed-turn prefix contains an unfinished turn
only failed after the user confirmed. PreviewForkBoundary now applies
ForkConversation's terminal-status rule on the assertBoundary snapshot it
already fetched, so both sides inspect one history state.
The latestCompleted preview could also name an empty-text userMessage as
the cut row, but the projection never emits a hub row for those, so the
hub resolved a boundary that does not exist and failed with 'Fork
boundary message not found'. firstExcludedUserLocalId now skips items
without hub-visible display text, sharing the projection's rule through
userMessageDisplayText.
* fix(hub): gate the fork preview on the archived-fork admission rules
The inactive-session preview branch answered a boundary without any of
the guards the confirm enforces in forkArchivedCodexSession: an archived
Claude or OpenCode session, a diverged history, queued messages, or an
offline Runner all rendered a preview dialog that could only fail on
confirm. The admission guards now live in assertArchivedForkEligible and
run in both paths.
A latestCompleted token is only minted for a running source, so a runner
exit before the confirm used to fail with the unactionable 'No verified
completed turn' answer instead of refreshing; boundaryMovedReason now
returns boundary_moved when the source went inactive, and the client
re-previews under the archived rules.
* fix(web): replace a stale fork preview with the error dialog and honor the thinking edge
A preview refresh that failed with a non-404 error left the previous
ForkPreviewDialog mounted, so the error dialog — gated on
errorMessage && !preview — never appeared and the stale boundary token
stayed confirmable. The non-404 catch now drops the stale preview first.
The thinking-edge effect also consumed an edge that landed while the
first preview request was still in flight: neither the state nor the
legacy request existed yet, so the stale idle-time answer opened the
dialog after the turn had already started. The in-flight request intent
is now tracked in a ref the effect can re-issue from, and an edge during
a confirm RPC no longer mutates the dialog behind the mutation.
* fix(web): keep the legacy fork confirm locked while the RPC is in flight
confirmLegacy awaited the fork/rewind RPC without any pending flag, and
all three legacy confirm dialogs bind isPending to the preview-loading
state, so the confirm button never showed its confirming label and both
buttons stayed enabled: a double click submitted the fork twice and the
dialog could be dismissed mid-request. A dedicated confirming state now
covers the legacy RPC in useForkFlow and drives the three dialogs.
* fix(web): align the fork error dialogs between the chat and the list
SessionList's error dialog ignored the retry affordance the chat already
had: connect-level preview failures showed only Dismiss with the buttons
unbound to any pending state. Both components now share the same dialog
contract: Retry for connect failures, Dismiss otherwise, one action and
no duplicate Cancel, and the pending state bound to the retry fetch.
The chat's error dialog also introduced every failure as a fork even
when the failed request came from openRewind; useForkFlow now records
the failing intent and the dialog titles itself accordingly. Finally,
HappyThread's historyActionPending was hardcoded false after the preview
flow replaced the direct fork callbacks, so per-message Fork/Rewind
buttons stayed enabled while a preview request was in flight and another
click would supersede it via requestSeq; the loading state now locks them
like the pre-preview flow locked them during its RPCs.
* fix(web): clean up the fork preview dialog's confirm error and rewind footer
A failed confirm quoted the raw ApiError message ('HTTP 409 Conflict:
{...}') inside the dialog while the rest of the flow extracts the hub's
error text; the dialog now shares useForkFlow's apiErrorText. The error
also survived a background view refresh, quoting a stale boundary under
the refreshed one, and a rewind whose excluded rows were all non-text
hid the deletion summary because the section was gated on excludedTurns
being non-empty even though counts.excluded was not zero.
* fix(hub): reject the fork preview when the CLI answers a resolved error envelope
RpcHandlerManager serializes a thrown handler error as a RESOLVED
{error} envelope, so previewForkBoundary's cast answered the preview
with undefined nativeTurnId/cutBeforeLocalId and the runtime failure
was silently swallowed. Unwrap the envelope and throw so the hub
surfaces the failure like any other preview error.
* fix(web): honor the flattened summary capability on the legacy fork fallback
SessionSummary flattens conversationHistory onto metadata while the
full hub Session nests it under metadata.capabilities; the legacy
confirm only read the nested shape, so a 404 fallback from the list
sent a plain current fork for a running session that supports the
latest-completed fork. Accept both shapes.
* fix(web): offer the fork fallback when the legacy rewind is fork-safe
The legacy rewind confirm dropped the ambiguous-native-boundary fork
fallback that the preview confirm and the pre-preview dialog had: a
409 ambiguous_native_boundary_fork_safe surfaced as a dialog error
instead of offering fork-at-boundary. Mirror the preview confirm's
handling on the legacy path.
* fix(hub): catch source active transitions between fork preview and confirm
The boundary token did not record the source's active state, so a
transition between preview and confirm bypassed boundary_moved: a
stopped runner sent the confirm into the archived-fork path (uncoded
admission failure for non-Codex sources, or an archived fork that
silently ignores the previewed live cut), and a reopened session ran
the live fork with a token minted on the archived path. The rewind and
non-Codex message confirms also failed as uncoded 'Session must be
active' / 'Session is busy' on thinking edges.
ForkBoundary now carries sourceActive and boundaryMovedReason rejects
the mismatch across all modes; the rewind and live non-Codex message
cases also reject a thinking edge. latestCompleted keeps its existing
runner-exit guard for tokens minted before this field existed.
* fix(web): keep the preview confirm locked against thinking edges mid-confirm
confirmLegacy set confirmingRef but confirmPreview did not, so a
thinking edge landing while the confirm RPC was in flight re-answered
the preview behind the confirm: the dialog's view was replaced (or
unmounted into the error dialog) under a pending confirm, and the
confirm then navigated over it or threw against a dead dialog. Lock
the confirm the same way the legacy path does, and release it before
the boundary_moved re-preview so the refresh behaves like any other
in-flight preview.
* fix(web): mark the fork boundary on a current preview that excludes a running turn
A shared Codex runtime answers mode 'current' with the last completed
turn while a turn is already running in the CLI (before the hub saw
thinking), so the preview carries an excluded running turn and confirm
pins lastTurnId. The dialog gated the fork-point marker and boundary
box on kind !== 'current' and showed the full-copy footer, hiding the
cut the confirm would apply. Show the boundary section whenever the
preview carries a cut and use the latest-completed footer for a current
preview with exclusions.
* fix(hub): refuse the fork preview when the confirm's pending-fork guards would
forkConversation rejects a confirm outright while a Codex resume is
unconfirmed or an archived-fork child binding is pending on an active
source, but forkPreview ran neither check and opened a dialog whose
confirm always failed. The archived message preview also answered
without the conversationHistoryTurns entry (or pending attempt) that
forkArchivedCodexSession resolves the native turn from. Mirror all
three guards on the fork preview paths; rewind keeps its own, since
the rewind confirm runs different guards.
* fix(cli): answer the idle fork preview with a pin the confirm would accept
The idle current-mode preview pinned the last native turn without
checking its terminal prefix, so a thread holding a non-terminal turn
previewed a 200 whose confirm always failed verifyPinnedTurn with 'The
pinned fork turn no longer has a completed native history prefix'.
Validate the pin before answering and omit it when invalid: preview and
confirm then agree on the unpinned whole-history cut. Message mode also
fetched the thread twice per preview (once up front, once inside
assertBoundary); the up-front read now lives only in the branches that
need it.
* test(hub): pin the rewind route's coded 409 boundary_moved contract
The rewind route tests never sent a boundary token, so the claim that
the route maps a moved rewind boundary to a coded 409 had no coverage.
Mirror the fork route test: the boundary reaches the engine and the
structured code is returned on a 409.
* fix(hub): let a boundary-token rewind confirm reach the engine when the source went inactive
The rewind route answered 409 session_inactive before the engine ran
whenever the source had stopped, so the confirm's sourceActive
re-check was unreachable over HTTP and a confirm after the runner
exited dead-ended instead of refreshing the preview. Every rewind
token is minted on an active source, so an inactive confirm is always
a moved boundary: parse the body first and skip requireActive only
when a token is present, mirroring the fork route. Token-less legacy
rewinds keep the session_inactive 409.
* fix(web): keep the fork preview confirm locked while a refresh replaces the view
A boundary_moved refresh leaves the previous preview mounted until the
fresh answer lands, and the confirm's await only covers the refresh it
started: when a thinking edge fires a second re-preview behind that
refresh, the dialog's local pending resets and Confirm becomes
clickable on a view that is about to be replaced, re-sending the stale
boundary for another refresh. Gate Confirm on the flow's loading state
alongside the pending flag, in both the chat and the list dialogs;
Cancel stays available since closing discards the in-flight refresh.
* fix(web): refuse legacy fork dialog dismissal while the confirm RPC is pending
The legacy confirm dialogs lost the old handlers' pending guard when
they moved onto ConfirmDialog: its Cancel button honors isPending, but
Escape and the dialog's close button reach onClose unconditionally, so
dismissing mid-RPC unmounted the flow while the fork or rewind kept
running, and a later failure had nowhere to surface. Guard the legacy
fork and rewind dismissals with !confirming in the list and the chat;
the preview-route dialog already guards dismissal through its own
pending state.
* fix(hub): refuse archived-fork preview for attached runtimes
* fix(codex): name the original hub message when a fork cut starts at a queued batch
* feat(hub,web,cli): work-scoped liveness — derive in-progress tool work so autonomous rounds stop rendering as waiting
thinking is round-scoped, not work-scoped: a session running an
autonomous loop between turns reports thinking=false while its tool
calls are still open, so the client renders "waiting" for hours. The
hub now sweeps open tool-call rows (getLiveToolWork) and marks the
session with derivedToolWork while any live call exists; the web
session list and status row render it as working. Stale
backgroundTaskCount values are cleared by the same sweep, and the
claude backend re-bumps thinking on autonomous-round assistant frames.
Ported from the fork line; the queued-thinking-grace refinement is
dropped here because that feature does not exist upstream.
Co-Authored-By: Claude Code <noreply@anthropic.com>
* test(web): assert the ticker-era presence badge class, not animate-pulse
The low-rate ticker refactor (#2447) removed animate-pulse from the
presence badge; the derived-work test still expected it. data-presence
plus the badge background class is the visible contract now.
Co-Authored-By: Claude Code <noreply@anthropic.com>
---------
Co-authored-by: miuiadmin <miuiadmin@users.noreply.github.com>
Co-authored-by: Claude Code <noreply@anthropic.com>
* fix(shared): hide and report near-miss AGENT_NOTIFY_SUMMARY footers
A turn whose final line attempts the machine footer but does not parse -
most often truncated before the closing brace - fails twice over: the
status is dropped, and because the strict matcher found nothing to strip,
the raw `AGENT_NOTIFY_SUMMARY {...` line is rendered to the reader. The
second half contradicts the product intent `e2e/notify-summary.spec.ts`
already asserts, and the first half is silent: `extractNotifySummary`
returns null with no log, so the only detector is a human noticing.
Introduce the near-miss notion: the last non-empty line is positionally
eligible to be a footer (the existing glued/indented rules, unchanged) but
yields no summary. On that condition:
- `stripNotifySummaryFooter` removes it, keeping any glued prose prefix
exactly as it does for a valid footer. The machine line is addressed to
the harness, not the reader, and a truncated one is no more readable
than a valid one. `NotifySummaryText` now falls back to the stripped
body instead of re-rendering raw text when there is no summary to show.
- `detectNotifySummaryNearMiss` classifies why it failed - unterminated
JSON, trailing content, invalid JSON, not an object - and the work-graph
ingest logs one warn naming the reason, so a broken emitter is greppable
instead of invisible. Mid-stream snapshots are excluded: a footer still
being written is incomplete by construction, not malformed. The log
carries the payload *length*, not the payload, to keep agent output out
of hub logs.
What is accepted as a *valid* footer is unchanged, and so is what is left
alone: whitespace-delimited prose mentions (`Example: AGENT_NOTIFY_SUMMARY
{...`), mid-body quotes, non-final footers, and a bare token with no
payload all still render as written.
Deliberately not included: repairing a truncated payload by appending the
missing brace. Truncation cuts content, not only syntax, so a repaired
footer would write a silently shortened summary into the append-only
work-graph ledger as though the agent had meant it. The near-miss reason
makes repair a small follow-up if a maintainer wants it.
via [HAPI](https://hapi.run)
Co-Authored-By: HAPI <noreply@hapi.run>
* fix(shared): keep quoted footer examples out of near-miss matching
Review catch: the near-miss path inherited the strict matcher's "glued"
eligibility, which treats any non-whitespace character before the token as
glue - including a backtick or quote. A final line such as
Use `AGENT_NOTIFY_SUMMARY {"status":"done"}` at the end.
therefore matched, the closing backtick read as trailing content, and
stripping left only `Use ` + the opening backtick, deleting the example and
the explanation after it. The Codex commentary path strips before storage
rather than before display, so that text was lost, not merely hidden.
Near-miss matching now skips occurrences inside an inline-code span and
occurrences immediately preceded by a quoting or opening delimiter. The
strict matcher is deliberately left as it was: a payload that parses as an
object through end of line is its own evidence that the line is a real
footer, so a backtick-glued valid footer is almost certainly an agent that
forgot the newline. A near miss has no such evidence, so it has to be more
conservative about what it will delete.
Genuine glued footers are unaffected, including after an earlier inline-code
span on the same line (``Ran `bun test`.AGENT_NOTIFY_SUMMARY {...``), which
is covered by its own regression test alongside the preserved examples.
via [HAPI](https://hapi.run)
Co-Authored-By: HAPI <noreply@hapi.run>
* fix(shared): treat near-miss quoting as a span, not one character
Second review catch, same class as the first: the guard added in 3fbda1e7e
inspected the single character before the token, but quoting is a property
of the *span*. A final line such as
The agent wrote "Done.AGENT_NOTIFY_SUMMARY {"status":"done"}" verbatim.
has ordinary prose punctuation immediately before the token, and the
backtick-parity check only counted backticks, so a double-quoted span read
as unquoted. The line was stripped to `The agent wrote "Done.`, and the same
variant existed for every quote style the local check did not enumerate -
`('Done.AGENT_NOTIFY_SUMMARY {...}')` among them.
Replace both checks with one span test: is the token inside an open quoting
or code span on this line? Symmetric delimiters (backtick, double quote,
single quote) are counted by parity, so a *closed* pair earlier on the line
(`He said "hello".AGENT_NOTIFY_SUMMARY {...`) does not grant immunity;
bracketing delimiters are counted by depth. An apostrophe inside a word is
not treated as a quote, or `didn't` would hide a real footer.
Angle brackets are deliberately absent: `a < b` is far more common in agent
prose than an angle-bracketed footer example, and treating `<` as an opener
would hide real footers. That narrows the previous commit's delimiter set by
one character, by choice.
The strict matcher remains untouched, for the same reason as before: a
payload that parses as an object through end of line is its own evidence of
a real footer.
Regression coverage for the quoted-glue variants, plus three over-correction
guards that pass on both sides of the change - a closed inline-code span, a
closed quote or bracket pair, and an in-word apostrophe must all still strip
a genuine glued footer. The Codex commentary path gets the same cases, since
that path strips before storage rather than before display.
via [HAPI](https://hapi.run)
Co-Authored-By: HAPI <noreply@hapi.run>
* fix(shared): strip a near miss only when its payload runs to end of line
Three review rounds found three quoting constructs the near-miss guard did
not know about - a single-backtick span, a double-quoted span with glued
prose inside it, a double-backtick run - and each fix enumerated one more
piece of syntax. That was not converging, and the reason is visible in the
classifier: *every* reported false positive is `trailing-content`.
The agent wrote "Done.AGENT_NOTIFY_SUMMARY {…}" verbatim. → trailing-content
('Done.AGENT_NOTIFY_SUMMARY {…}') → trailing-content
Use `AGENT_NOTIFY_SUMMARY {…}` at the end. → trailing-content
Use ``Done.AGENT_NOTIFY_SUMMARY {…}`` at the end. → trailing-content
See [Done.AGENT_NOTIFY_SUMMARY {…}] above. → trailing-content
while every shape this feature exists to catch is not:
…,"summary":"ok → unterminated-json {bogus} → invalid-json
{"ver → unterminated-json not-json → not-an-object
So stop enumerating quoting syntax and gate on the payload region instead:
strip a near miss only when it runs to the end of the line. Truncation
terminates the line by definition, so it always qualifies; a quoted example
always closes its delimiter *after* the payload, so it never does. One rule
replaces the whole guard - no quote characters, no backtick runs, no in-word
apostrophe case - and `shared/src/messages.ts` is ~40 lines shorter for it.
`trailing-content` stays classified and logged, so a genuinely stray-text
emitter is still greppable; it simply is not deleted. The cost is one odd
line on screen when an emitter really does append text after a complete
object - and the status was dropped for that shape anyway, since the strict
matcher rejects it too, so the change is purely cosmetic. The alternative is
deleting a reader's example and the prose around it, which the Codex
commentary path does before storage rather than before display. Showing a
strange line beats destroying text.
Every preservation test from the previous two rounds still passes, now for
this one reason rather than per-syntax guards, and the Codex commentary
suite keeps the quoted and double-backtick cases the review asked for.
via [HAPI](https://hapi.run)
Co-Authored-By: HAPI <noreply@hapi.run>
* fix(shared): only delete a near miss when no prose shares its line
Two review points, both about not destroying text.
**The log wording was wrong for the one reason that is no longer stripped.**
`[work-graph] ignored a malformed AGENT_NOTIFY_SUMMARY footer` is untrue of a
`trailing-content` line: a quoted example is correct prose, and it is kept and
shown rather than ignored. Someone grepping that string for lost statuses
would read an example as a dropped one. The message is now
`no AGENT_NOTIFY_SUMMARY status recorded from the final line`, which holds for
every reason, and `removedFromDisplay` carries which of the two outcomes
happened. The reason is still logged - an emitter that appends stray text
after a complete object is genuine signal, and suppressing it to quieten the
noise would trade the wrong way.
**A quoted example of an *incomplete* payload was still being deleted.**
``Use `AGENT_NOTIFY_SUMMARY {"summary":` to reproduce.`` classifies as
`unterminated-json`, so the end-of-line rule could not protect it: an
unterminated payload has no object end to measure against. This was a known
residual of that rule and should have been on the record when it landed.
The fix is a second structural condition rather than a return to parsing
quote syntax: **the token must own the line.** Nothing but whitespace may
precede it. That covers every quoting construct at once, including the ones
earlier rounds enumerated and the ones nobody has thought of, because what it
tests is the presence of prose rather than the shape of quotes.
A *valid* footer still tolerates glued prose - a payload that parses as an
object through end of line is its own evidence that the line is a real footer.
A near miss has no evidence, so it must be sure the line is machine output
before deleting it.
The cost, stated plainly: a truncated footer glued to prose on the same line
now stays visible. That is a real sub-case of the defect this PR fixes, and it
is given up deliberately. The status is lost either way - the strict matcher
rejects that shape too - so the cost is one odd line on screen, against the
risk of deleting a reader's example and the prose around it, which the Codex
commentary path does before storage rather than before display.
The four syntax guards from the previous rounds are replaced by this one rule
and their tests collapse into it, alongside a contrast test that a valid glued
footer is still stripped.
via [HAPI](https://hapi.run)
Co-Authored-By: HAPI <noreply@hapi.run>
* test(shared): pin why line ownership, not payload shape, decides the strip
A payload-shape predicate - "the remainder must be a well-formed JSON prefix
that runs to end of line" - looks like it should separate a truncated footer
from a quoted example, and it does for most shapes. It fails on an open
string, because an unterminated string swallows everything after it:
Use `AGENT_NOTIFY_SUMMARY {"summary":"` to reproduce the failure.
the payload of which is byte-for-byte the shape of a real truncation
(`"summary":"ok`). The signature of the defect and the signature of the
false positive are the same, so no test of the payload can tell them apart -
which is why the decision is made from the line instead.
Pins that case so the next person to reach for a payload-shape rule finds the
counterexample already failing.
via [HAPI](https://hapi.run)
Co-Authored-By: HAPI <noreply@hapi.run>
---------
Co-authored-by: HAPI <noreply@hapi.run>
* 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>
Job wakes interrupted running turns: `deliverJobTerminalWake` only
special-cased inactive sessions, so an opted-in terminal job posted a
user message into whatever the agent was doing. Drop the wake when a
turn is running and settle the claim so a later idle flip cannot re-fire.
Those wakes also impersonated operator input — `sentFrom: 'webapp'`, a
bare user message with a "Verify the outcome and continue" imperative.
Tag them `hapi-system` and render them as a quiet status line in the web
chat instead of a user bubble with fork/retry actions. Drop the default
imperative; a prescription now has to come from `--wake-prompt`.
Agents attached jobs to short work (tests, builds, typechecks) because
the injected prompt was 2.1k chars of REQUIRED / MUST / FORBIDDEN. Replace
it with a decision rule: default is not to attach, never for work that
finishes in this turn, and run `hapi job --help` for the mechanics.
Co-Authored-By: HAPI <noreply@hapi.run>
Cursor ACP sessions can fail mid-turn with a transient model error that the
agent reports inline rather than as an RPC rejection. HAPI treated those turns
as successful, so the session went quiet with no banner, no push, and no way to
resume without retyping the prompt.
This adds the full path:
- detect: classify inline/stderr model errors from the Cursor ACP stream,
requiring strong signatures before typing a failure as a model error
- surface: persist `lastModelError` on session metadata; render a chat banner
and a session-list indicator, with the prompt text kept out of list/SSE
summaries so they never ship up to 32 KB of user prompt
- notify: deliver a push for an unacknowledged error, watermarked on the hub
copy so a restart does not re-page the same eventId
- bridge & retry: offer a one-shot recovery prompt that replays the failed
turn, bound to the originating eventId and gated so a real user turn always
supersedes it. Auto-bridge is opt-in and defaults to OFF, persisted in hub
settings and fanned out to live Cursor CLIs.
Re-cut onto current upstream/main. The branch had accumulated 108 iterative
hardening commits against a 289-commit-older base; replaying them individually
would have re-resolved the same conflicts ~100 times. The pre-re-cut tip was
2c28a1365 if the granular history is ever needed.
Absorbing upstream required adapting to three refactors that landed meanwhile:
- `MessageQueue2` grew an `internal?: boolean` control-message flag upstream
while this branch added richer `internal` provenance. Unified on a tagged
`QueueItemInternal` union (`control` | `model-error-bridge`) so one field
carries one concept. `hasPendingNonBridgeTurn()` now treats *any* internal
item as non-user: otherwise a queued `/auto-review` control slash would have
counted as a user turn and wrongly superseded a live bridge.
- `AcpSdkBackend.prompt()` gained a `timing` callback upstream; merged it with
this branch's `shouldSend` gate into a single options object.
- The hub settings route moved to a unified `updateSettings` transaction.
`autoBridgeTransientModelErrors` is applied outside that transaction because
SyncEngine owns its CLI fan-out and rollback under its own lock.
via [HAPI](https://hapi.run)
Co-authored-by: HAPI <noreply@hapi.run>
* fix(agy): keep empty strings in edit and write tool card inputs
A deletion edit (empty Replacement) or an empty-file write was mapped
without new_string/content, so the web Edit and Write views rendered
nothing. Keep '' for old_string, new_string and content.
* fix(web): take the question card's free-text flag from the pending request
agy's ask_question tool call is shown before its form arrives, so its input
cannot say whether free text is allowed, and the card kept offering Other on
forms without qN_other. Fill allowFreeText on the tool call input from the
pending request's input for questions that carry none. Inputs and requests
without the flag keep showing Other.
agy streams agent_message_chunk as pure deltas, but the backend used the
default overlap-dedupe mode, which dropped a repeated character at a chunk
boundary (73-8 + 800 was shown as 73-800). Set textChunkMode to delta,
as the OpenCode and Grok backends do.
- versionCode is now `git rev-list --count HEAD`; the hapiVersionCode
property is gone. Builds without git fall back to 1.
- Official builds fail fast when git is unavailable or the clone is
shallow, since a shallow history undercounts.
- The official build workflow drops the version_code input, checks out
full history and names the artifact hapi-android-<versionCode>.
- Android and CLI READMEs describe the new rule.
* feat(usage): display CLI account quotas and rate limits across Codex, Antigravity, and Claude
* fix(usage): persist live quota state across processes and normalize agy usage
* fix(cli): isolate Claude quota observations by account and bound probe deadlines
* fix(usage): bind Claude quota events to producing session account and surface quota fetch errors
* fix(usage): preserve OAuth token isolation without email and surface Codex read failures
* fix(usage): skip host claude path lookup when test probe override is active
* fix: keep one stable HAPI session id per Claude conversation
Every terminal `hapi claude -r` minted a new HAPI session id for the same
Claude conversation; the hub then merged the duplicates after the fact and
deleted the older row, so links and peer references to it broke, and two
live duplicates hid one row in the web sidebar.
CLI: resolve identity before Claude starts (HAPI_SESSION_ID is fixed at
bootstrap). `--resume <id>` / `--continue` look up the owning HAPI session
and reopen it with the same id, handing an active remote session over and
refusing one controlled by another terminal; bare `--resume` uses the
`hapi resume` picker filtered to Claude. Rotated Claude ids are kept in
`claudeSessionIdHistory` so older ids still match.
Hub: schema v35 adds `session_redirects`; every merge that deletes a row
records old -> survivor, and client-facing lookups follow it (sockets and
job ownership stay strict). New `GET /cli/sessions/resume-target-by-agent`.
Web: a merged-away URL moves to the survivor instead of bouncing home, and
live Claude duplicates stay visible in the sidebar.
* fix: keep job-key remaps and hub-archived resumes working after redirects
Review follow-up for the stable session identity change.
- Job routes: the session lookup now follows a merged-away id to the
survivor, so `requestedSessionId` must stay the raw URL id. Otherwise a
colliding `<old id>/<key>` remap was bypassed and PATCH/DELETE/late PUT
through the old id hit the survivor's own job.
- Terminal resume of an inactive session now asks the hub to clear a
hub-authored archive first (`POST /cli/sessions/:id/prepare-local-resume`,
same clear as hub reopen), so `hapi claude --resume/--continue` (and
`hapi resume`) no longer exit on the #1911 existing-session guard.
* fix(cli): refuse an explicit Claude resume whose transcript is gone
Reopening the owning HAPI session drops --resume and hands the id to the
local launcher, which silently starts a fresh conversation when the
transcript is missing — under the existing HAPI id, title and history.
Check the transcript before any handoff or archive change and fail
explicitly instead.
* fix: follow merged-session redirects on /api only for clients that rebind
Native clients store a session detail under the requested id and drop SSE
events for any other id, so a merged-away id that resolved to the survivor
loaded history but never showed live messages.
`SyncEngine.resolveSessionAccess` is strict again by default; `/api` routes
follow redirects only with `x-hapi-follow-session-redirects: 1`, which the
web client (that rebinds to the returned id) sends. Native clients keep the
previous 404. CLI REST always follows. Job routes still keep the raw URL id
for key remaps under both modes.
* feat(codex): fill the round footer tok/s from app-server timing
Measure each Codex round's generation window the way agy rounds do: the
live turn span minus tool-execution and wait-for-the-user windows, over
the thread-cumulative output-token delta, emitted on the turn's
turn_duration so the round footer shows tok/s. Tool windows prefer the
app-server's own item timing (startedAtMs/completedAtMs/durationMs).
The token baseline is the last reported cumulative total: the CLI seeds
a thread it created in this process (thread/start) to zero, while
resumed and forked threads receive the app-server's attach-time usage
replay and stay unseeded, so inherited history is never counted as a
turn's output. Only the live root-turn feed reaches the ledger: history
replays re-project old items and must not settle a round. Permission
hooks keep timing waits for the user.
* fix(codex): seed gateway-created threads for the first-turn tok/s baseline
Native /new and /clear create threads through the gateway before/after
hooks, whose after() binds the fresh root without the zero usage seed
the runtime create path applies - so the new thread's first turn
captured a null baseline and never showed tok/s. Seed it there too,
same as create(): thread/start only, since forked threads receive the
app-server's attach-time usage replay instead (tiann/hapi#2379).
* fix(codex): keep the active generation ledger across a hub-only reconnect
SharedCodexRoot's session.onReconnect reset the whole projection, but a
hub reconnect only replays final history: the native turn keeps running
without a new turn/started, so dropping the ledger identity, baseline
and windows made generation.settle() return null at completion and the
round permanently lost its tok/s. Add projection.resetAfterHubReconnect
which replays without touching the ledger; the app-server reconnect
path keeps the full reset, because the resumed turn re-announces itself
and must re-measure from its own start (tiann/hapi#2379).
* fix(codex): seed fresh usage before session-ready releases queued input
The gateway thread/start seed ran in the after() hook, after the bind
wrapper had already activated the root: registerControls and
emitSessionReady open the input gates, so a queued Web prompt (or one
submitted on session-ready while the runner notification is delayed)
could start the thread's first turn before the zero baseline existed,
and seeding afterward could not repair that captured-null turn. Move
the seed into the bind wrapper right after root.bind, guarded by a
freshThread flag the create and gateway paths set for thread/start
only - forks keep their app-server attach-time replay baseline
(tiann/hapi#2379).
Self-hosted hubs are commonly reachable through several origins (an
edge-proxied domain and a direct one); cross-border interference can
randomly break TLS on either for hours. A runner pinned to a single
HAPI_API_URL sat dead through those windows.
When HAPI_API_FALLBACK_URLS is set, the machine client keeps a rotation
ring (primary + fallbacks) and, after HAPI_API_FAILOVER_AFTER (default 5)
consecutive connect failures, tears the socket down and reconnects
through the next entry. A successful connection on a fallback schedules
a return-to-primary attempt after 30 minutes. Without the env, behavior
is byte-for-byte unchanged.