Skip to content

fix(tui): run new sessions through lifecycle hooks - #100241

Merged
steipete merged 3 commits into
mainfrom
codex/fix-tui-new-session-hooks
Jul 5, 2026
Merged

steipete merged 3 commits into
mainfrom
codex/fix-tui-new-session-hooks

Conversation

@steipete

@steipete steipete commented Jul 5, 2026

Copy link
Copy Markdown
Contributor

What Problem This Solves

TUI /new switched to an empty local key without running the existing Gateway session-creation lifecycle. Command hooks, before_reset, session_end, and session_start therefore missed TUI new-session transitions, so features such as session-memory hooks could not capture the completed parent conversation. Fixes #49918. Builds on the lifecycle-hook direction suggested in BingqingLyu#1006.

Why This Change Was Made

  • Extract the existing sessions.create lifecycle into one shared Gateway-owned service.
  • Route both Gateway and embedded TUI backends through that service; no new protocol field or TUI-specific core policy.
  • Adopt the backend-returned canonical session key and remove the parallel empty-session path.
  • Fence parent rollover against active runs and new work admissions, revalidate the parent under the fence, and serialize TUI input while creation is pending.
  • Reject same-key parent replacement as invalid creation semantics, avoiding lifecycle/admission deadlocks.
  • Preserve Crestodian behavior through the same backend contract.

User Impact

/new now starts a genuinely persisted fresh TUI session and fires the same hook lifecycle in Gateway and --local modes. The parent transcript is complete before hooks run. If a turn is active or finishing, the TUI asks the user to abort or wait instead of racing the rollover.

Evidence

  • node scripts/run-vitest.mjs src/gateway/server.sessions.create.test.ts src/gateway/server.sessions.reset-hooks.test.ts src/tui/embedded-backend.test.ts src/tui/tui-command-handlers.test.ts src/tui/tui-session-actions.test.ts src/tui/tui-pty-harness.e2e.test.ts — 70 Gateway, 172 TUI, and 14 PTY tests passed after rebase.
  • OPENCLAW_TUI_PTY_INCLUDE_LOCAL=1 node scripts/run-vitest.mjs src/tui/tui-pty-local.e2e.test.ts — 5 real-backend PTY scenarios passed; both embedded --local and Gateway modes created/adopted canonical agent:main:tui-* sessions and sent a fresh turn through the mocked Responses endpoint.
  • Blacksmith Testbox tbx_01kwrjhsjn8geh91q5w6rnh5j3 — strict core TypeScript passed; final check:changed is running on the rebased commit.
  • .agents/skills/autoreview/scripts/autoreview --mode local --stream-engine-output — clean, no accepted/actionable findings (overall confidence 0.91).

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime size: XL maintainer Maintainer-authored PR labels Jul 5, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 1836a7ee4a

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

const result = await client.createSession({
key: uniqueKey,
agentId: state.currentAgentId,
...(state.currentSessionId ? { parentSessionKey: state.currentSessionKey } : {}),

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.

P2 Badge Keep parent linkage when /new follows the first run

When a TUI starts on an empty session, the first sendChat creates the backend session but can leave state.currentSessionId null because the send result only carries run id/status and displayable final events intentionally skip loadHistory(). In that normal path, /new reaches this spread without parentSessionKey, so createGatewaySession skips the command/session lifecycle hooks and plugins never receive the completed parent transcript this change is meant to provide. Use the current key, or refresh/record the session id after the first accepted run, instead of gating parent linkage solely on currentSessionId.

Useful? React with 👍 / 👎.

@clawsweeper

clawsweeper Bot commented Jul 5, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed July 5, 2026, 9:33 AM ET / 13:33 UTC.

Summary
The PR replaces TUI /new's local empty-session switch with backend-created sessions, extracts shared Gateway session-create lifecycle handling, updates Gateway/embedded/Crestodian TUI backends, and adds regression/PTy coverage.

PR surface: Source +228, Tests +320. Total +548 across 16 files.

Reproducibility: yes. Source inspection shows current main and v2026.6.11 route TUI /new through setEmptySession, while the documented hook/session-memory contract expects command:new; I did not run a live TUI repro in this read-only review.

Review metrics: 1 noteworthy metric.

  • TUI backend contract: 1 method added. Every TUI backend now participates in /new session creation, so Gateway, embedded local, and Crestodian behavior all need maintainer awareness before merge.

Stored data model
Persistent data-model change detected: serialized state: src/gateway/server-methods/sessions.ts, serialized state: src/gateway/session-create-service.ts, serialized state: src/tui/tui-pty-local.e2e.test.ts, unknown-data-model-change: src/gateway/server-methods/sessions.ts, unknown-data-model-change: src/gateway/session-create-service.ts. Confirm migration or upgrade compatibility proof before merge.

Root-cause cluster
Relationship: fixed_by_candidate
Canonical: #49918
Summary: This PR is the active candidate fix for the canonical TUI /new hook regression tracked by the linked issue.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Merge readiness
Overall: 🐚 platinum hermit
Proof: 🦞 diamond lobster
Patch quality: 🐚 platinum hermit
Result: ready for maintainer review.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Rank-up moves:

  • none.

Risk before merge

  • [P1] Merging intentionally changes TUI /new from a local empty-session switch to a backend-created persisted session and now refuses rollover while parent work is active or admitted; maintainers should accept that stricter session-state behavior before landing.

Maintainer options:

  1. Accept the backend-created TUI session lifecycle (recommended)
    Maintainers can accept the stricter /new behavior because it restores documented hooks and has focused Gateway plus PTY proof.
  2. Ask for a compatibility carve-out
    Require a follow-up patch if active-run /new must preserve the old local-switch behavior while hook emission is restored by a narrower path.

Next step before merge

  • No automated repair is needed; maintainer review should decide whether to accept the stricter backend-created TUI /new lifecycle before merge.

Maintainer decision needed

  • Question: Should TUI /new now create persisted backend sessions through the shared Gateway lifecycle and reject rollover while the parent session is active or admitted?
  • Rationale: The branch is the clean fix for the documented hook regression, but it intentionally changes observable TUI session-state behavior during active or finishing runs.
  • Likely owner: steipete — They authored this repair and are tied to the prior TUI /new isolation landing history, so they are the best available owner for the session-state tradeoff.
  • Options:
    • Accept shared lifecycle behavior (recommended): Land this PR after normal checks because it restores documented hook/session-memory semantics while preserving isolated TUI sessions.
    • Require a compatibility carve-out: Ask for a narrower patch if the old local empty-session rollover must remain available while hooks are restored another way.

Security
Cleared: The diff does not add dependencies, workflows, secret handling, downloaded code, or a concrete security/supply-chain regression.

Review details

Best possible solution:

Land the shared Gateway-owned create lifecycle after maintainer signoff on the stricter TUI /new session-state behavior, while preserving the explicit hook opt-in for programmatic create callers.

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

Yes. Source inspection shows current main and v2026.6.11 route TUI /new through setEmptySession, while the documented hook/session-memory contract expects command:new; I did not run a live TUI repro in this read-only review.

Is this the best way to solve the issue?

Yes, with maintainer signoff. Reusing the shared Gateway session-create lifecycle is cleaner than adding a TUI-only synthetic hook, and the current head removed the earlier changelog defect.

AGENTS.md: found and applied where relevant.

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

Label changes

Label justifications:

  • P2: The PR fixes a bounded TUI session-hook regression without evidence of data loss, security bypass, crash loop, or core runtime outage.
  • merge-risk: 🚨 session-state: The diff changes how TUI /new creates, links, persists, and blocks session rollover, which can affect existing TUI session lifecycle behavior.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): The PR body and follow-up comment include after-fix terminal/Testbox proof for real local and Gateway TUI PTY paths plus focused lifecycle suites.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body and follow-up comment include after-fix terminal/Testbox proof for real local and Gateway TUI PTY paths plus focused lifecycle suites.
Evidence reviewed

PR surface:

Source +228, Tests +320. Total +548 across 16 files.

View PR surface stats
Area Files Added Removed Net
Source 9 650 422 +228
Tests 7 405 85 +320
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 16 1055 507 +548

What I checked:

  • Repository policy read: Root AGENTS.md plus the scoped TUI, Gateway, and Gateway server-methods guides were read; the changelog and session-state review guidance affected this verdict. (AGENTS.md:1, db96218c0562)
  • Maintainer notes check: No .agents/maintainer-notes directory exists in the checkout, so there were no matching maintainer notes to apply.
  • Current main still has the regression: On current main, TUI /new generates a tui-* key and calls setEmptySession, which changes local TUI state instead of running Gateway hook lifecycle code. (src/tui/tui-command-handlers.ts:706, db96218c0562)
  • Latest release still has old behavior: The latest release tag v2026.6.11 still calls setEmptySession(uniqueKey) for TUI /new, so the fix has not already shipped. (src/tui/tui-command-handlers.ts:685, e085fa1a3ffd)
  • Documented hook contract: The hooks documentation defines command:new as firing when /new is issued and documents session-memory as listening to command:new and command:reset. Public docs: docs/automation/hooks.md. (docs/automation/hooks.md:50, db96218c0562)
  • PR TUI path: At the PR head, /new blocks unsafe rollover, calls client.createSession, passes the current agent and parent session when known, then adopts the backend-returned canonical key. (src/tui/tui-command-handlers.ts:713, 5930d6130c53)

Likely related people:

  • steipete: Authored the current shared lifecycle repair and the history shows 46008178d1ba landed the TUI /new isolation behavior that made the hook gap visible. (role: current repair author and prior landing committer; confidence: high; commits: c0212c1920de, 46008178d1ba; files: src/tui/tui-command-handlers.ts, src/gateway/session-create-service.ts, src/gateway/server-methods/sessions.ts)
  • vignesh07: Commit b08146fad6e4 added the TUI/Gateway internal hook behavior for /new and /reset that this PR restores for the TUI path. (role: original hook behavior contributor; confidence: high; commits: b08146fad6e4; files: src/tui/tui-command-handlers.ts, src/gateway/server-methods/sessions.ts)
  • widingmarcus-cyber: The regression-provenance commit says the TUI /new isolation change was landed from contributor PR https://github.com/openclaw/openclaw/pull/39238 by this handle. (role: source behavior contributor; confidence: medium; commits: 46008178d1ba; files: src/tui/tui-command-handlers.ts, src/tui/tui-command-handlers.test.ts)
  • Val Alexander: Commit 49c4a13231a3 restored the sibling Control UI /new hook path with an explicit sessions.create opt-in pattern relevant to this PR's owner boundary. (role: adjacent lifecycle-hook contributor; confidence: medium; commits: 49c4a13231a3; files: src/gateway/server-methods/sessions.ts, src/gateway/server.sessions.reset-hooks.test.ts)
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

How this review workflow works
  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.
Review history (4 earlier review cycles)
  • reviewed 2026-07-05T09:07:22.976Z sha 1836a7e :: needs real behavior proof before merge. :: [P2] Keep parent linkage after the first TUI run
  • reviewed 2026-07-05T09:56:44.576Z sha 3dcf01c :: needs real behavior proof before merge. :: [P2] Keep parent linkage after the first TUI run
  • reviewed 2026-07-05T10:16:55.024Z sha a27b3a1 :: needs changes before merge. :: [P3] Remove the direct changelog entry
  • reviewed 2026-07-05T11:30:35.921Z sha 06df391 :: needs changes before merge. :: [P3] Remove the direct changelog entry

@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. P2 Normal backlog priority with limited blast radius. labels Jul 5, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 3dcf01c4ae

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

break;
}
case "new":
if (hasUnsafeSessionRollover()) {

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.

P2 Badge Block duplicate /new while creation is pending

If the user submits /new again before the first client.createSession() resolves, createEditorSubmitHandler fire-and-forgets handleCommand (src/tui/tui-submit.ts:39), so the second invocation reaches this branch with sessionCreationInFlight already true but no active run and starts another backend session from the same parent. That can emit duplicate command:new/lifecycle hooks for the same parent and leave one created session unadopted; treat sessionCreationInFlight as an unsafe rollover before starting another create.

Useful? React with 👍 / 👎.

@steipete
steipete force-pushed the codex/fix-tui-new-session-hooks branch from 3dcf01c to a27b3a1 Compare July 5, 2026 10:11
@clawsweeper clawsweeper Bot removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Jul 5, 2026
@steipete

steipete commented Jul 5, 2026 •

Copy link
Copy Markdown
Contributor Author

Maintainer verification complete on exact head 2b556a23c091662e10c88dc871c70a0c4bf7617a.

Fixups made after the first CI pass:

  • rebased the implementation onto current main
  • preserved the shared Gateway session-create owner and embedded-mode lifecycle projection
  • made the PTY proof wait for the previous run's terminal idle state before sending /new, matching real TUI behavior instead of racing a final text delta
  • reran fresh Codex autoreview; no actionable findings

Proof:

  • node scripts/run-vitest.mjs run --config test/vitest/vitest.tui-pty.config.ts --configLoader runner src/tui/tui-pty-local.e2e.test.ts -t 'drives the real local backend|creates and adopts a fresh session' --reporter=verbose — 2 passed locally
  • Blacksmith Testbox tbx_01kwrt8e070tznrsj46ysy72by: the same real local + real Gateway PTY proof — 2 passed
  • Blacksmith Testbox tbx_01kwrt8e070tznrsj46ysy72by: OPENCLAW_CHECK_CHANGED_REMOTE_CHILD=1 OPENCLAW_CHANGED_LANES_RAW_SYNC=1 corepack pnpm check:changed — passed in 8m02s
  • prior focused Gateway session-create, reset-hook, TUI command-handler, session-action, and embedded-backend suites — passed
  • exact-head GitHub CI — all meaningful checks green

The live paths prove /new adopts a fresh session only after the active run is terminal, the next prompt reaches the model, and the new request excludes the parent session prompt.

The required changelog entry and issue credit are being aggregated into the final maintainer changelog commit on #91002, avoiding repeated runtime-CI invalidation from unrelated CHANGELOG.md churn on busy main.

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. labels Jul 5, 2026
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation app: android App: android app: web-ui App: web-ui scripts Repository scripts commands Command implementations agents Agent runtime and tooling labels Jul 5, 2026
@steipete
steipete force-pushed the codex/fix-tui-new-session-hooks branch from da09444 to 06df391 Compare July 5, 2026 11:07
@openclaw-barnacle openclaw-barnacle Bot removed docs Improvements or additions to documentation app: android App: android app: web-ui App: web-ui scripts Repository scripts commands Command implementations agents Agent runtime and tooling labels Jul 5, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 06df391c88

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread CHANGELOG.md Outdated

- **Control UI terminal tabs:** vertically center the new-session button in the terminal tab strip.
- **Control UI composer scrollbar:** show the message-field scrollbar only when the draft actually overflows its autosized height.
- **TUI new-session hooks:** create `/new` sessions through the shared Gateway lifecycle so command and session hooks receive the completed parent transcript in both Gateway and embedded modes, while preventing rollover during an active turn. (#49918) Thanks @BingqingLyu.

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.

P2 Badge Remove the manual changelog entry

This change adds a normal PR fix directly to CHANGELOG.md, but the root AGENTS.md says CHANGELOG.md is release-only and normal PRs/direct fixes should put release-note context in the PR body, squash message, or direct commit instead. Leaving this here bypasses the release-generation flow and can make the already-generated release notes drift or duplicate this entry when the release changelog is regenerated.

Useful? React with 👍 / 👎.

@steipete
steipete force-pushed the codex/fix-tui-new-session-hooks branch from 06df391 to 52d3a89 Compare July 5, 2026 13:11
@openclaw-barnacle openclaw-barnacle Bot added channel: voice-call Channel integration: voice-call app: web-ui App: web-ui labels Jul 5, 2026
@steipete
steipete force-pushed the codex/fix-tui-new-session-hooks branch from b6a7974 to 1c52ed1 Compare July 5, 2026 13:22
@openclaw-barnacle openclaw-barnacle Bot removed channel: voice-call Channel integration: voice-call app: web-ui App: web-ui labels Jul 5, 2026
@steipete
steipete force-pushed the codex/fix-tui-new-session-hooks branch from 5930d61 to 2b556a2 Compare July 5, 2026 13:35
@steipete
steipete merged commit cd305b3 into main Jul 5, 2026
97 checks passed
@steipete
steipete deleted the codex/fix-tui-new-session-hooks branch July 5, 2026 13:48
@steipete

steipete commented Jul 5, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

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

Labels

gateway Gateway runtime maintainer Maintainer-authored PR merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: XL status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: TUI /new stopped emitting hook-visible new-session behavior after 46008178d

1 participant