Skip to content

fix(agents): pause yielded main-session runs - #75662

Closed
amittell wants to merge 6 commits into
openclaw:mainfrom
amittell:fix/main-session-yield-pause
Closed

amittell wants to merge 6 commits into
openclaw:mainfrom
amittell:fix/main-session-yield-pause

Conversation

@amittell

@amittell amittell commented May 1, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Extend the subagent yield-pause fix from 6f3b5f86 to top-level (non-subagent) sessions.

When a main session ends via the sessions_yield tool, the runner already emits a lifecycle event with yielded: true and livenessState: "paused". The runner's terminal lifecycle metadata, the agent-job snapshot cache, and the agent.wait dedupe entry all propagate those flags generically, so subagent and non-subagent runs benefit equally from those parts of 6f3b5f8.

The gap is in gateway/session-lifecycle-state.ts. deriveGatewaySessionLifecycleSnapshot does not look at the yielded flag, so the session entry is persisted with status: \"done\" even though the runner has queued a post-yield continuation that drains on the next turn. Dashboards, restart recovery, and follow-up turns then treat the session as finished and race the continuation, producing the in-context overflow and out-of-order events the user reports.

Why the same fix needs to apply to the top-level session

The subagent registry tracks active subagent runs in memory and uses pauseReason: \"sessions_yield\" to keep yielded entries in a paused state instead of marking them complete. The main session has no equivalent in-memory registry; its lifecycle state is persisted directly through persistGatewaySessionLifecycleEvent into the on-disk session entry. The gap shows up in three places:

  1. The persisted session entry says status: \"done\", so sessions_list, sessions.changed broadcasts, and dashboard UI all show the session as finished.
  2. main-session-restart-recovery is keyed off entry.abortedLastRun and entry.status === \"running\". With status=done it leaves the entry alone, but on a clean restart-mid-yield the yielded session can also end up abortedLastRun=true (the cleaned-lock path), at which point recovery would force a [System] Your previous turn was interrupted... resume that races the queued continuation.
  3. A new user message arrives at a session that is internally paused but externally "done" — the gateway dispatches a fresh agent.run, and the queued steered yield-interrupt drains alongside the new user input, producing out-of-order assistant text.

Shape of the change

  • Recognize the lifecycle yielded flag in deriveGatewaySessionLifecycleSnapshot and derive status: \"paused\" with pauseReason: \"sessions_yield\" instead of done. Yielded short-circuits before the aborted/stopReason branches so partial classifications cannot mask the paused state.
  • Clear pauseReason on the next lifecycle start event so a fresh run reactivates the session, mirroring how subagent-registry-lifecycle.ts clears pauseReason on completion.
  • Add \"paused\" to SessionRunStatus in both gateway/session-utils.types.ts and agents/tools/sessions-helpers.ts, and add pauseReason?: \"sessions_yield\" to SessionEntry and GatewaySessionRow.
  • Surface pauseReason on the sessions.changed broadcast snapshot and the loadGatewaySessionRow builder so consumers (UI, sessions_list tool) see the paused state.
  • Tighten isTerminalSessionStatus so the type predicate stays accurate after "paused" joins the union (paused is not terminal).
  • Skip main-session-restart-recovery for entries with pauseReason: \"sessions_yield\" so they are not re-prompted with the generic interrupted-turn message.

The runner-level changes (yieldDetected -> livenessState=paused/yielded=true) and the gateway agent-job/agent-wait-dedupe propagation that 6f3b5f8 already added are unchanged. This PR plugs the missing seam between those generic signals and the persisted session entry.

Test coverage

  • src/gateway/session-lifecycle-state.test.ts:
    • marks yielded lifecycle end events as paused with sessions_yield reason (persisted patch).
    • treats yielded as paused even when aborted is set (yield short-circuit).
    • clears pauseReason when a fresh run starts on a paused session (start-phase reactivation).
    • Existing terminal-mapping tests updated to include explicit pauseReason: undefined on non-yield ends.
  • src/agents/main-session-restart-recovery.test.ts:
    • skips sessions paused via sessions_yield instead of forcing a resume.
    • does not mark sessions with sessions_yield pauseReason as restart-aborted from cleaned locks.

Local validation

  • pnpm tsgo:core, pnpm tsgo:core:test, pnpm tsgo:extensions, pnpm tsgo:extensions:test — clean.
  • pnpm test src/gateway/session-lifecycle-state.test.ts src/agents/main-session-restart-recovery.test.ts src/gateway/server-chat.agent-events.test.ts src/config/sessions.test.ts src/agents/tools/sessions-list-tool.test.ts src/gateway/server-methods/agent.test.ts src/gateway/server-methods/agent.create-event.test.ts src/gateway/server-methods/agent-wait-dedupe.test.ts src/agents/subagent-registry.test.ts src/agents/subagent-announce-output.test.ts src/agents/pi-embedded-runner/sessions-yield.orchestration.test.ts — all green (235 tests).
  • pnpm exec oxfmt --check, node scripts/run-oxlint.mjs, pnpm format:docs:check, pnpm check:changelog-attributions — all clean on changed files.

Test plan

  • CI green on `fix(agents): pause yielded main-session runs`.
  • Manual smoke: trigger sessions_yield from a main-session conversation; confirm the session entry persists status: paused and pauseReason: sessions_yield, and that a follow-up turn flips back to running with pauseReason: undefined.
  • Restart-recovery smoke: kill the gateway while a main session is paused via yield; confirm restart-recovery skips it instead of re-prompting with the interrupted-turn message.

Real behavior proof

  • Behavior addressed: Before this PR, when a top-level (non-subagent) embedded openclaw run ended via the sessions_yield tool, the runner emitted yielded=true and livenessState=paused but the gateway treated it as a clean completion and wrote status=done. The session displayed as finished while awaiting a queued post-yield continuation, racing dashboards, restart-recovery, and follow-up turns. After this PR, the lifecycle persistence derives status=paused with pauseReason=sessions_yield, restart-recovery skips paused sessions, and SessionRunStatus adds "paused" so consumers can distinguish a yielded run from a completed one.
  • Real environment tested: live OpenClaw gateway on rh-bot.lan, pid 65734, build SHA 23804e6 (upgrade-v2026.5.28 with this PR cherry-picked). The deployed dist/server-chat-*.js and dist/main-session-restart-recovery-*.js chunks carry the new pauseReason/sessions_yield logic; the proof script imports and executes those exact bundle bytes.
  • Exact steps or command run after this patch:
    # On rh-bot.lan, confirm deployed bundles carry the PR logic:
    grep -c 'sessions_yield\|pauseReason' \
      /Users/alexm/.openclaw/openclaw/dist/main-session-restart-recovery-CirHJY3p.js
    # -> 1 (the new shouldSkipMainRecovery branch)
    
    grep -c 'sessions_yield\|pauseReason' \
      /Users/alexm/.openclaw/openclaw/dist/server-chat-D9hpq-gf.js
    # -> non-zero (new deriveGatewaySessionLifecycleSnapshot branches)
    
    # Drive the deployed code with three scenarios:
    node /tmp/proof-75662-amittell.mjs
    Proof script (/tmp/proof-75662-amittell.mjs) extracts the deployed
    deriveGatewaySessionLifecycleSnapshot from server-chat-D9hpq-gf.js via
    vm.runInContext, dynamically imports main-session-restart-recovery-CirHJY3p.js
    to grab the exported markRestartAbortedMainSessions, seeds a temp
    state-dir with one yielded and one non-yielded running entry, and asserts
    three behaviors:
    1. Lifecycle phase=end with yielded=true -> status=paused,
      pauseReason=sessions_yield, abortedLastRun=false.
    2. Same entry passed to restart-recovery is SKIPPED (no abortedLastRun
      write, updatedAt unchanged).
    3. Sibling running entry without pauseReason is marked
      abortedLastRun=true (existing behavior preserved).
      Plus a guard check: lifecycle phase=error with yielded=true returns
      status=failed with NO pauseReason leak.
  • Evidence after fix:
    === PR #75662 real-behavior proof ===
    host=rh-bot.lan pid=84884 node=v25.8.2
    dist=/Users/alexm/.openclaw/openclaw/dist
    
    [1] lifecycle bundle: /Users/alexm/.openclaw/openclaw/dist/server-chat-D9hpq-gf.js
    [1a] yielded terminal -> {"updatedAt":1780285520789,"status":"paused","startedAt":1780285519789,"endedAt":1780285520789,"runtimeMs":1000,"abortedLastRun":false,"pauseReason":"sessions_yield"}
    [1a] OK: paused status carries pauseReason=sessions_yield
    [1b] non-yielded terminal -> {"updatedAt":1780285520789,"status":"done","startedAt":1780285519789,"endedAt":1780285520789,"runtimeMs":1000,"abortedLastRun":false}
    [1b] OK: non-yielded run preserves status=done with no pauseReason
    [1c] error+yielded -> {"updatedAt":1780285520789,"status":"failed","startedAt":1780285519789,"endedAt":1780285520789,"runtimeMs":1000,"abortedLastRun":false}
    [1c] OK: error phase masks yielded marker, no pauseReason leak
    
    [2] seeded /var/folders/cn/.../state/agents/main/sessions/sessions.json
    [2] recovery bundle: /Users/alexm/.openclaw/openclaw/dist/main-session-restart-recovery-CirHJY3p.js
    [2] exports: i, n, r, t
    [main-session-restart-recovery] marked 1 interrupted main session(s) for restart recovery (pr-75662-proof)
    [2] mark result: {"marked":1,"skipped":1}
    [2] yielded entry after: {"sessionId":"sess-yielded","status":"running","pauseReason":"sessions_yield","startedAt":...,"updatedAt":1780285519789}
    [2] normal entry after:  {"sessionId":"sess-normal","status":"running","startedAt":...,"updatedAt":1780285521266,"abortedLastRun":true}
    [2a] OK: yielded session was skipped (no abortedLastRun, no updatedAt bump)
    [2b] OK: non-yielded running session was marked abortedLastRun=true
    
    === ALL PROOFS PASSED ===
    
  • Observed result after fix: All three scenarios pass on the deployed bundle. A yielded terminal event produces status=paused/pauseReason=sessions_yield and is skipped by restart recovery (no abortedLastRun mutation, no updatedAt bump). A non-yielded terminal event still produces status=done with no pauseReason (existing behavior preserved). An error phase masks the yielded flag and reports status=failed with no pauseReason leak, matching the gating comment in resolveTerminalStatus.
  • Targeted tests: node scripts/run-vitest.mjs run src/agents/main-session-restart-recovery.test.ts src/gateway/session-lifecycle-state.test.ts -> 22 passed + 15 passed (37/37). Broader: node scripts/run-vitest.mjs run src/gateway/session-utils.test.ts src/gateway/sessions-patch.test.ts src/gateway/session-message-events.test.ts -> 172/172 passed. node scripts/run-oxlint-shards.mjs --only=core --threads=4 -> clean.
  • What was not tested: End-to-end live channel trigger (sending a real Telegram message that drives sessions_yield to completion); this is exercised by the existing vitest coverage in pi-embedded-runner/sessions-yield.orchestration.test.ts rather than reproduced live on rh-bot.

Live exact-head capture (2026-06-12): found and fixed an emit-side gap

Running the requested live scenario on an isolated sandbox gateway (loopback :28795, fresh OPENCLAW_STATE_DIR, Control UI webchat, native openai-completions lane with a tool-calling model) surfaced a real defect in this PR's original head: the paused state never persisted in live runs, on any lane. A store probe polling every 0.3s across four real sessions_spawn + sessions_yield turns at head be96a422ff captured the persisted row going running -> killed with abortedLastRun: true at yield time -- the exact pre-PR failure this PR exists to prevent.

Root cause (probe-instrumented): sessions_yield aborts the attempt mid-stream (runAbortController.abort("sessions_yield")), and the terminal lifecycle event can be emitted from the abort teardown before run.ts post-processing writes the yielded meta. The bundle-level instrumentation captured the failing ordering directly:

emitLifecycleTerminal state.yielded = undefined  aborted = false   <- event emitted first
meta.yielded set -> false                                          <- run.ts wrote 551ms later

The event reaches deriveGatewaySessionLifecycleSnapshot carrying aborted without yielded, and resolveTerminalStatus correctly resolves killed. The projection/recovery/UI logic this PR adds was never the problem; the emit side never fed it. The unit tests passed because they fabricate events that already carry yielded: true.

Fix (in a46ba508b8): onYield now records yielded through the subscription's terminal lifecycle meta channel at tool time, before the abort, using the same late-binding pattern the yield abort itself uses (src/agents/embedded-agent-runner/run/attempt.ts). A regression test pins the handler half: an end event with state.yielded set and aborted resolved from the isTerminalAborted fallback still carries yielded (src/agents/embedded-agent-subscribe.handlers.lifecycle.test.ts).

Post-fix live proof, end to end (same sandbox, instrumented bundle):

10:27:40.065  [PROBE] meta.yielded set -> true              (onYield records at tool time)
10:27:40.423  [PROBE] emitLifecycleTerminal state.yielded = true   (event carries it)
10:27:4x      store: status=paused pauseReason=sessions_yield abortedLastRun=false
~10:28        Sessions Control UI: main session "Paused", subagent "Live"
10:28:1x      gateway KILLED while paused -> store unchanged (paused, ab=false)
10:28:3x      gateway restarted -> recovery skips the paused session;
              no "[System] Your previous turn was interrupted" prompt in the chat
10:29:20      subagent (orphan-recovered post-restart) completes -> announce drains
              the queued continuation in order -> running, pauseReason cleared
10:30:48      continuation finishes -> done, abortedLastRun=false

Reproduced again on a second pass (store probe paused/sessions_yield at 15:54-15:56 with closure-identity probes confirming the onYield-time recording). This covers all three asks: visible Paused state, restart skip, and orderly continuation, captured live at the exact head plus the one-commit fix.

Codex lane now covered too (was a sibling-lane gap, now fixed in this PR). The Codex app-server harness lane emits its own terminal lifecycle event (extensions/codex/src/app-server/run-attempt.ts emitLifecycleTerminal) and was dropping the yield meta: the phase:"end" event carried only phase/aborted, never yielded, so the shared projection (resolveYielded) persisted Codex-backed yields as done/killed. The fix forwards {yielded, livenessState:"paused", stopReason:"end_turn"} on that event when result.yieldDetected, exactly as the native runner does, gated on the flag the sessions_yield tool already sets via onYield -> onYieldDetected. The Codex lifecycle event flows through the same onAgentEvent -> server-chat -> persistGatewaySessionLifecycleEvent -> resolveYielded path as the native lane.

Proven live on the Codex lane: a real openai/gpt-5.5 turn through the Codex app-server (ChatGPT OAuth) that calls sessions_yield now persists status=paused, pauseReason=sessions_yield (was done pre-fix), and the subagent then drains the queued continuation in order back to done. An integration test (extensions/codex/src/app-server/run-attempt.yield-lifecycle.test.ts) asserts the Codex lifecycle end event carries yielded:true/livenessState:"paused"/stopReason:"end_turn" on yield and omits them on a normal turn (verified red without the fix).

Codex protocol behavior checked against the sibling ../codex source (HEAD b8aea2340): codex-rs/app-server-protocol/schema/typescript/ServerRequest.ts:19 defines the { "method": "item/tool/call", id, params: DynamicToolCallParams } app-server -> client request, which is how the app-server invokes the OpenClaw sessions_yield dynamic tool (setting yieldDetected); turn lifecycle requests (turn/start/turn/steer/turn/interrupt) are at ClientRequest.ts:90. This change adds no new protocol dependency -- it forwards an OpenClaw-side flag onto OpenClaw's own lifecycle event.

Copilot AI review requested due to automatic review settings May 1, 2026 13:35
@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime agents Agent runtime and tooling size: M labels May 1, 2026
@clawsweeper

clawsweeper Bot commented May 1, 2026 •

Copy link
Copy Markdown
Contributor

Thanks for the context here. I swept through the related work, and this is now duplicate or superseded.

This PR’s central fix is now superseded by the merged canonical yielded-parent lifecycle work in #95996. That implementation keeps a yielded parent nonterminal through the internal lifecycle contract while deliberately retaining the existing public session status shape; this branch’s remaining paused/pauseReason protocol and UI expansion would reintroduce the compatibility decision that the canonical fix avoided.

Canonical path: Keep the merged internal yielded-parent contract from #95996; open a new, narrowly scoped proposal only if maintainers later decide that a public paused session-status API is required.

So I’m closing this here and keeping the remaining discussion on #95996.

Review details

Best possible solution:

Keep the merged internal yielded-parent contract from #95996; open a new, narrowly scoped proposal only if maintainers later decide that a public paused session-status API is required.

Do we have a high-confidence way to reproduce the issue?

No current-main failure remains to reproduce with high confidence: the merged canonical implementation covers the reported yielded-parent nonterminal behavior. The original lifecycle gap was concretely exercised and documented in the PR’s supplied live proof.

Is this the best way to solve the issue?

No; the branch is no longer the best solution because #95996 merged the same core fix using an internal yielded lifecycle contract that avoids this branch’s new public session-status API.

Security review:

Security review cleared: The proposed changes alter lifecycle and protocol state only; the supplied diff adds no dependency, workflow, secret, permission, artifact-download, or code-execution surface.

AGENTS.md: found and applied where relevant.

What I checked:

Likely related people:

  • kklouzal: Authored the merged canonical yielded-parent lifecycle implementation that now owns the central nonterminal-session behavior. (role: canonical implementation author; confidence: high; commits: 2333bd59dbeb; files: src/gateway/session-lifecycle-state.ts, src/agents/agent-lifecycle-parent-state.test.ts)
  • steipete: Authored the merged durable session delivery-state refactor that preserves lifecycle fields while establishing current session-state ownership boundaries. (role: recent adjacent session-state contributor; confidence: medium; commits: 73bba03e4c5a; files: src/config/sessions/types.ts)

Codex review notes: model internal, reasoning high; reviewed against e2fbd3b1ed75.

Copilot AI 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.

Pull request overview

Extends the existing sessions_yield “pause” semantics from subagent runs to top-level (main) sessions by persisting yielded lifecycle ends as status: "paused" with a pauseReason: "sessions_yield", and ensuring downstream consumers (UI/broadcasts/restart-recovery) respect that paused state.

Changes:

  • Add "paused" to session run status unions and introduce pauseReason: "sessions_yield" on persisted session entries + gateway rows.
  • Update gateway lifecycle snapshot derivation to map yielded terminal lifecycle events to status: "paused" and to clear pauseReason on the next start.
  • Update broadcasts/session row building and restart-recovery logic + tests to propagate and honor the paused/yielded state.

Reviewed changes

Copilot reviewed 11 out of 11 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
src/gateway/session-utils.types.ts Adds paused to SessionRunStatus; introduces SessionPauseReason; adds pauseReason to GatewaySessionRow.
src/gateway/session-utils.ts Updates terminal-status predicate for paused; includes pauseReason when building gateway session rows.
src/gateway/session-lifecycle-state.ts Derives status: "paused" + pauseReason for yielded lifecycle ends; clears pauseReason on start; persists pause state.
src/gateway/session-lifecycle-state.test.ts Adds coverage for yielded → paused mapping, yield short-circuiting, and pauseReason clearing on start.
src/gateway/server-chat.ts Includes pauseReason in sessions.changed snapshots.
src/config/sessions/types.ts Persists paused status and adds pauseReason?: "sessions_yield" to SessionEntry.
src/agents/tools/sessions-list-tool.ts Allows "paused" as a readable session status from gateway data.
src/agents/tools/sessions-helpers.ts Extends tool-level SessionRunStatus union to include "paused".
src/agents/main-session-restart-recovery.ts Skips restart recovery for entries paused via sessions_yield.
src/agents/main-session-restart-recovery.test.ts Adds tests ensuring paused/yielded sessions are skipped and not marked restart-aborted by cleaned locks.
CHANGELOG.md Documents the main-session yielded → paused persistence behavior change and recovery skip.

Comment thread src/gateway/session-lifecycle-state.ts Resolved
@amittell
amittell force-pushed the fix/main-session-yield-pause branch 2 times, most recently from c1b4ce4 to fce6130 Compare May 3, 2026 04:09
@amittell
amittell force-pushed the fix/main-session-yield-pause branch from fce6130 to 607eefb Compare May 17, 2026 00:35
@openclaw-barnacle openclaw-barnacle Bot added the triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup. label May 17, 2026
@clawsweeper clawsweeper Bot added the P2 Normal backlog priority with limited blast radius. label May 17, 2026
@amittell
amittell force-pushed the fix/main-session-yield-pause branch from 607eefb to d0f8dfa Compare May 17, 2026 00:54
@openclaw-barnacle openclaw-barnacle Bot added the triage: dirty-candidate Candidate: broad unrelated surfaces; may need splitting or cleanup. label May 17, 2026
amittell added a commit to amittell/openclaw that referenced this pull request May 18, 2026
@amittell
amittell force-pushed the fix/main-session-yield-pause branch from d0f8dfa to b50d7c0 Compare May 18, 2026 02:05
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. impact:message-loss Channel message delivery can be lost, duplicated, or misrouted. impact:session-state Session, memory, transcript, context, or agent state can drift or corrupt. labels May 18, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup. label May 18, 2026
@amittell

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Ran the requested exact-head live scenario tonight on an isolated sandbox gateway built from be96a422ff49 (Control UI webchat, real Codex app-server harness turn with GPT-5.5). Results are in the new PR-body addendum:

  • Proven live: real sessions_spawn + sessions_yield tool calls through the full gateway path, and the orderly-continuation contract -- the subagent announce drained the queued yield continuation in order with a clean finish.
  • Found while capturing: the persisted Paused state cannot engage on Codex-harness-backed sessions at all, because the Codex app-server attempt never wires setTerminalLifecycleMeta (run.ts:1795-1798 optional chaining drops all terminal meta; native attempt wires it at run/attempt.ts:3351, extensions/codex/src has zero references). The lifecycle end event therefore arrives without data.yielded on that lane. This is a pre-existing Codex-lane terminal-meta gap (it also swallows livenessState/stopReason there), not a regression from this PR -- the projection/recovery/UI behavior this PR adds is pinned by its unit tests and the deployed-bundle proof on the event contract.
  • Consequence for the proof ask: a live Paused Control-UI screenshot is only capturable with a native embedded-runner model; on the Codex lane the paused window never persists. Flagging the Codex terminal-meta plumbing as explicit follow-up work per the one-sided-fix policy rather than widening this PR into extensions/codex.

@clawsweeper

clawsweeper Bot commented Jun 12, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

@amittell

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Important update on head a46ba508b8: the live exact-head capture I ran for the proof ask found a real emit-side defect in this PR's previous head, now fixed in this PR.

  • Live repro at be96a422ff: four real sessions_spawn + sessions_yield turns on an isolated sandbox gateway (native lane, Control UI webchat); a 0.3s store probe captured the persisted row going running -> killed with abortedLastRun: true at yield time -- the paused state never persisted on any lane. The sessions_yield abort tears down the stream before run.ts writes the yielded meta, so the lifecycle end event reaches persistence carrying aborted without yielded (bundle instrumentation captured the exact ordering; see the rewritten proof section).
  • Fix: onYield now records yielded through the subscription's terminal-meta channel at tool time, before the abort (one commit, run/attempt.ts + a regression test pinning the handler contract).
  • Post-fix live proof: paused persists (status=paused, pauseReason=sessions_yield), Sessions UI shows Paused while the subagent runs, a full gateway kill+restart mid-pause leaves the row untouched with no interruption prompt, and the orphan-recovered subagent's announce drains the queued continuation in order to a clean done. Full timestamped trace in the PR body.

This replaces my earlier comment's conclusion that the projection was sound and only the Codex lane was gapped -- the native lane was equally broken live, and the unit tests missed it because they fabricate events that already carry yielded: true. The Codex-lane terminal-meta plumbing gap stands as disclosed follow-up. My earlier deployed-bundle proof of the projection/recovery functions remains valid; it just tested downstream of where the break was.

@clawsweeper

clawsweeper Bot commented Jun 13, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

@amittell

Copy link
Copy Markdown
Contributor Author

Update (head 2b717890ba): the codex-lane sibling gap I'd flagged as follow-up is now fixed in this PR, so paused engages on both lanes.

What: the Codex app-server harness emits its own terminal lifecycle event (extensions/codex/src/app-server/run-attempt.ts emitLifecycleTerminal) and was dropping the yield meta -- the phase:"end" event carried only phase/aborted, never yielded, so resolveYielded persisted codex-backed yields as done/killed. Fix forwards {yielded, livenessState:"paused", stopReason:"end_turn"} when result.yieldDetected, mirroring the native runner; the flag is already set by the sessions_yield tool's onYield -> onYieldDetected, and the event flows through the same onAgentEvent -> server-chat -> persistGatewaySessionLifecycleEvent -> resolveYielded path as native.

Proven live (codex lane): a real openai/gpt-5.5 turn through the codex app-server (ChatGPT OAuth) calling sessions_yield now persists status=paused pauseReason=sessions_yield (was done), then drains the queued continuation in order back to done. New integration test run-attempt.yield-lifecycle.test.ts asserts the codex lifecycle end event carries the yield meta on yield and omits it on a normal turn (verified red without the fix). Typecheck/lint/format clean; rebased onto current main, merge-clean.

Codex gate: checked ../codex @ b8aea2340 -- codex-rs/app-server-protocol/schema/typescript/ServerRequest.ts:19 defines the item/tool/call (DynamicToolCallParams) app-server request that invokes the OpenClaw sessions_yield tool (the prerequisite for yieldDetected); turn lifecycle at ClientRequest.ts:90. The change adds no new protocol dependency; it forwards an OpenClaw-side flag onto OpenClaw's lifecycle event.

@amittell

Copy link
Copy Markdown
Contributor Author

CI on head e3a5f6b4ad: 135 passing, 24 skipped, 1 failing (build-artifacts), MERGEABLE.

The one red check is not from this PR — it's a pre-existing i18n raw-copy baseline drift already on main:

$ git show upstream/main:ui/src/ui/views/chat.ts | grep -oE 'Collapse workspace files|Expand workspace files' | sort -u
Collapse workspace files
Expand workspace files
$ git show upstream/main:ui/src/i18n/.i18n/raw-copy-baseline.json | grep -c 'Collapse workspace files\|Expand workspace files'
0

main's chat.ts added those workspace-files aria-label/title strings without updating raw-copy-baseline.json, so ui:i18n:check (the build-artifacts step) fails on main itself. This PR's chat.ts and raw-copy-baseline.json are byte-identical to main (it touches neither), so I'm leaving the baseline for the i18n-bot/maintainer rather than editing a baseline file out of scope. The PR's own i18n delta (the statusPaused string + the 18 .meta.json re-accounting) passes.

The two failures that were mine are fixed: checks-node-core-tooling/test-projects flagged the new run-attempt.yield-lifecycle.test.ts as unregistered — now added to vitest.extension-codex-app-server-attempt-extra.config.ts (folded into the codex commit). Everything else is green.

@amittell

amittell commented Jul 8, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto current main @ 827f2c44225ecb84f881ca47014d5a846b0183fc (2026-07-07). New head: c90af00d0e2ab428c363416aab9969e03745a68e. The PR is MERGEABLE again.

Re-verified the PR is not superseded: resolveTerminalStatus in src/gateway/session-lifecycle-state.ts on current main still has no yielded/paused handling, and src/agents/agent-run-terminal-outcome.ts has no yielded mention.

Adaptations to main refactors made during the rebase (intent unchanged):

  • main consolidated the per-site sessions.changed field lists into buildGatewaySessionEventFields, so the pauseReason broadcast now lives once in src/gateway/session-event-payload.ts:71 instead of the four per-site emits (server-chat.ts kept its snapshot field, which merged cleanly).
  • The Control UI refactor (65e1232) moved the sessions view: the paused badge and statusPaused label now land in ui/src/pages/sessions/view.ts:210 and ui/src/pages/sessions/view.ts:224. The old SESSION_EVENT_ROW_FIELDS allowlist no longer exists on main; ui/src/lib/sessions/reconcile.ts spreads event row fields, so pauseReason flows to UI rows without an allowlist change.
  • Dropped the PR's local isTerminalSessionStatus copy in src/gateway/session-utils.ts; main now imports the canonical guard from src/config/sessions/types.ts:474, which carries this PR's "paused" exclusion.
  • Codex lane: the yield meta forwarding re-applied at main's relocated terminal emit, spread after buildLifecycleTerminalMeta so the yield's end_turn wins stopReason (extensions/codex/src/app-server/run-attempt.ts:3565).
  • src/config/sessions/lifecycle.test.ts updated to current main semantics: done rows now short-circuit as reusable in resolveTerminalMainSessionTranscriptRegistryCheck, so the terminal-check test pins killed and a new test pins done returning undefined.
  • extensions/codex/src/app-server/run-attempt.yield-lifecycle.test.ts now mocks normalizeAgentRuntimeTools as an identity pass-through: since main's registered-tools build pass ignores the runtime plan, the provider-plugin fallback cold-loads the provider registry in a fresh vitest worker (~85s measured) and starves the 120s test timeout. The test pins yield lifecycle meta, not provider schema normalization.
  • i18n regenerated via pnpm ui:i18n:sync (not hand-merged); main's new hi and ru locales take the tracked English fallback for sessionsView.statusPaused, and pnpm ui:i18n:check passes.

Verification on the rebased head (worktree with hydrated modules):

  • node scripts/run-vitest.mjs run src/gateway/session-lifecycle-state.test.ts src/config/sessions/lifecycle.test.ts src/agents/main-session-restart-recovery.test.ts src/agents/embedded-agent-subscribe.handlers.lifecycle.test.ts extensions/codex/src/app-server/run-attempt.yield-lifecycle.test.ts ui/src/lib/session-run-state.test.ts ui/src/pages/sessions/view.test.ts ui/src/lib/sessions/reconcile.test.ts -> 11 files, 224 tests, all passed.
  • scripts/run-oxlint.mjs on all changed files: clean. oxfmt --check: clean. ui:i18n:check: clean.

On vocabulary: the paused-vs-deferred naming question raised alongside the still-open (and itself conflicting) #95996 remains a maintainer call. This PR intentionally does not pre-empt that decision; it keeps the paused/pauseReason: "sessions_yield" shape it shipped with, and renaming can be a mechanical follow-up once the product decision lands.

@amittell

amittell commented Jul 8, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

@amittell

amittell commented Jul 9, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto current main (d3ff48c) and pushed head 0cefba4606a253554f59904dce9340c016c03ca4. The conflicts were confined to the generated i18n meta files, so the stale locale-sync commit was dropped and the locales were regenerated instead of hand-merged.

Review finding fixed ([P2] Workboard linked-card paused handling):

  • ui/src/lib/workboard/index.ts:2686 - getWorkboardLifecycle now routes the linked-card branch through the shared isSessionRunActive predicate, so a status: "paused" session with hasActiveRun: false stays in the running lifecycle (running preset/health filters and execution-status sync no longer resolve the card to idle mid-yield). The raw status === "running" check is kept so a running row without a live-run flag still maps to running until staleness.
  • ui/src/pages/workboard/view.ts:1222-1223 - the card Live badge (getCardActionState) uses the same predicate, so paused cards keep the Live indicator while the queued continuation is pending.
  • ui/src/pages/workboard/data.test.ts:4802-4824 - focused test: status: "paused" + hasActiveRun: false (both recent and 31-minutes-stale updatedAt) maps to { state: "running", targetStatus: "running" }, mirroring the existing lifecycle assertions.

No new user-visible strings were added for this; the paused card renders through the existing running lifecycle. A distinct paused visual can be layered on later if wanted.

CI failure root-caused and fixed: checks-node-compact-small-whole-2 failed test/scripts/control-ui-i18n.test.ts > ships no recorded English fallbacks with ["hi:sessionsView.statusPaused","ru:sessionsView.statusPaused"] - the prior locale sync ran against a provider that returned English fallbacks for hi/ru and recorded them in fallbackKeys. Re-ran pnpm ui:i18n:sync with a working translation provider; hi/ru now carry real translations (hi: "रुका हुआ", ru: "Приостановлено"), all 20 metas report fallbackKeys: [], and a provider-less check (the CI condition) is clean:

control-ui-i18n: [20/20] ru: done changed=true fallbacks=0 elapsed=2.5s wrote
...
zh-CN: clean (fallbacks=0) ... hi: clean (fallbacks=0) ... ru: clean (fallbacks=0)   # `check` with no provider configured

Verification on head 0cefba4606:

node scripts/run-vitest.mjs run src/config/sessions/lifecycle.test.ts src/gateway/session-lifecycle-state.test.ts \
  src/agents/main-session-restart-recovery.test.ts src/agents/embedded-agent-subscribe.handlers.lifecycle.test.ts \
  test/scripts/control-ui-i18n.test.ts
  -> passed 4 Vitest shards (incl. 82 agents/gateway tests, 6 i18n runner tests)
node scripts/run-vitest.mjs run extensions/codex/src/app-server/run-attempt.yield-lifecycle.test.ts
  -> 1 file, 2 tests passed
node scripts/run-vitest.mjs run ui/src/lib/session-run-state.test.ts ui/src/pages/workboard/data.test.ts
  -> 2 files, 184 tests passed
tsgo (tsconfig.core.json: src + ui + packages) -> exit 0
oxlint + oxfmt --check on touched files -> clean

On the remaining review risk (persisted paused status contract): whether this status should keep the paused name or align with the #95996 deferred-style vocabulary remains a maintainer call, per the review's maintainer-decision block; the code here is scoped so a rename stays mechanical.

@amittell

amittell commented Jul 9, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jul 9, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

@amittell

Copy link
Copy Markdown
Contributor Author

Rebased onto current main @ 0d2db46 (#103194). The i18n .i18n/*.meta.json conflicts were resolved by regenerating with pnpm ui:i18n:sync (node --import tsx scripts/control-ui-i18n.ts sync --write), not hand-merged; ui:i18n:check is clean and totalKeys bumped 1769 -> 1770 for the added sessionsView.statusPaused key. Core source files (session-lifecycle-state.ts, attempt.ts, run-attempt.ts, config/sessions, ui workboard) applied cleanly. Round-2 Workboard paused-state fix (keep paused cards in the running lifecycle) is intact. Tests: session-lifecycle-state, workboard/data, and control-ui-i18n suites pass. The paused-vs-#95996 vocabulary choice remains a maintainer call.

@amittell

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

@amittell

Copy link
Copy Markdown
Contributor Author

Re-rebased onto current main (2c622e19); new head 69bb806a31. The prior rebase left the generated i18n .meta.json files conflicting with main's i18n baseline. Resolved cleanly this time by taking main's meta baseline and regenerating via pnpm ui:i18n:sync from the (unchanged) locale translation files, so sessionsView.statusPaused is layered on top of main's current keys. ui:i18n:check passes with no fallbacks. The paused-vs-deferred (#95996) vocabulary is still a maintainer call and this PR does not pre-empt it.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

@amittell

Copy link
Copy Markdown
Contributor Author

Rebased onto current main (94a45bffe90). Notable integration decisions:

  • Two commits were dropped as superseded: main now records yielded through terminal-resolution.ts in the embedded runner and forwards codex yields via run-attempt-lifecycle-terminal.ts, so the pre-abort meta recording and codex forwarding fixes are already structural there.
  • The paused projection now derives from main's canonical isAgentLifecycleYieldedWaiting signature instead of a parallel data.yielded check, so error/aborted ends can never leak sessions_yield (covered in the lifecycle-state table tests). This also resolves the old Copilot thread about pauseReason on error phases.
  • [P2] status parser: sessionRunStatus in ui/src/lib/sessions/reconcile.ts now parses "paused", with reconciliation regression tests.
  • [P2] translations: sessionsView.statusPaused now ships genuine translations for all 20 non-English locales (was English in 18).
  • [P1] vocabulary (session paused vs run deferred): still a maintainer call — happy to rename if deferred (or another term) is preferred; the persisted enum addition is otherwise isolated to SessionEntry.status + pauseReason.

amittell added 6 commits July 25, 2026 16:13
Treats `sessions_yield` as a non-terminal paused state across the
gateway lifecycle, persisted session-state, Control UI projection, and
the new `pauseReason` field. Replaces the silent terminal `done`
mapping that left orphan recovery unable to distinguish a clean yield
from a completed run.

The persisted/Gateway/UI session-status enum gains `"paused"` with a
`pauseReason: "sessions_yield"` so consumers can distinguish the yield
case without ambiguity. Existing consumers of the prior closed-status
enum need maintainer acceptance of the compatibility impact.

`resolveTerminalMainSessionTranscriptRegistryCheck` short-circuits
when the entry status is `"paused"`, even when `endedAt` is positive.
Without this, agent dispatch, auto-reply, and session-command callers
would run terminal transcript freshness/rotation logic on a yielded
paused main session while its queued continuation was still pending,
defeating the nonterminal invariant the paused status preserves.

`pauseReason` now propagates through every `sessions.changed` broadcast
emit site: `server-chat.ts`, `server-session-events.ts`,
`server-methods/session-change-event.ts`, and `server-methods/agent.ts`
all carry the field. The Control UI side wires the field end-to-end:
`GatewaySessionRow` in `ui/src/ui/types.ts` adds an optional
`pauseReason` of type `SessionPauseReason`, and
`SESSION_EVENT_ROW_FIELDS` in `ui/src/ui/controllers/sessions.ts`
includes the field so a paused row delivered by an incremental
`sessions.changed` event preserves the reason instead of dropping it on
reducer merge.

Workboard's `sessionCaptureStatus` projection now uses the shared
`isSessionRunActive` helper instead of duplicating the `status ===
"running" || hasActiveRun === true` check. A paused session has a
queued continuation pending; the helper already treats `paused` as
active, so Workboard now reports `running` for yielded sessions instead
of letting them slip into `done` / `review` while the runner is still
about to drain the continuation.

Adds the Control UI `sessionsView.statusPaused: "Paused"` label and
syncs the 18 locale meta files (`fallbackKeys` + `totalKeys`) so
`pnpm ui:i18n:check` passes.
Route the two remaining linked-card decision points (getWorkboardLifecycle
and the card Live badge) through the shared isSessionRunActive predicate so
a paused (sessions_yield) session with hasActiveRun:false renders as a
pending continuation instead of an idle card.
@amittell

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jul 26, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Command router queued. I will update this comment with the next step.

@clawsweeper

clawsweeper Bot commented Jul 27, 2026

Copy link
Copy Markdown
Contributor

ClawSweeper applied the proposed close for this PR.

  • Action: closed this PR.
  • Close reason: duplicate or superseded.
  • Evidence: durable ClawSweeper review.
  • Coverage proof: PR B is the merged canonical implementation of PR A's material lifecycle behavior. PR A's remaining paused/pauseReason public API and UI expansion is a separate compatibility/product choice deliberately excluded by PR B, not material remaining work required to close the superseded PR. Covering PR: fix: keep yielded parent turns nonterminal #95996.

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

Labels

agents Agent runtime and tooling app: web-ui App: web-ui clawsweeper-recovery-stuck gateway Gateway runtime merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. proof: supplied External PR includes structured after-fix real behavior proof. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: M triage: dirty-candidate Candidate: broad unrelated surfaces; may need splitting or cleanup.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants