Skip to content

Fail readiness promptly when the terminal exits - #36457

Merged
brennanb2025 merged 8 commits into
mainfrom
brennanb2025/terminal-wait-known-exit
Oct 30, 2026
Merged

brennanb2025 merged 8 commits into
mainfrom
brennanb2025/terminal-wait-known-exit

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

An agent terminal can exit before or during readiness while a caller still waits until timeout or trusts stale screen output. Idle waits missed an exit recorded before registration; composer readiness observed output without joining the terminal's lifetime. This could strand worker startup or allow readiness to outlive the process.

Readiness now checks the current exact terminal before reading evidence and observes its existing exit/retirement channel while composer readiness is pending. A known exit promptly returns terminal_exited with the recorded neutral cause. The same terminal identity is checked after asynchronous readiness acceptance, and settlement releases its observation and scanner work. Independent readiness sources retain their existing either-source success rule.

Exit waits keep their existing result. Disconnected terminals without confirmed exit remain eligible for reconnect. The change reuses current PTY lifecycle and waiter ownership, with no new timers, saved fields, wire payloads, process control or leaf fallback. Startup-specific explanations remain tracked in #36422.

Bugs tracked in STA-13035 and STA-13036. Review path: full. The common pattern joins readiness with retained completion and current lifecycle. The intended adaptation supports arbitrary late public handles, exact incarnations, recoverable SSH uncertainty and independently updated hosts.

Validation: production-runtime regressions cover exit before and during idle, dual-source and composer-only readiness, cleanup after exit/retirement/cancellation, late asynchronous acceptance, preserved either-source success, and real recorded agent output. Consumer contracts cover actual local/federated worker receipts, launch no-delivery, automation failure, cleanup skip-close and socket shutdown. The real CLI terminal wait command runs through a controlled transport into production runtime. Two SSH inventory/reconnect regressions prove unknown disconnect remains recoverable. A production-trigger N/10N contract checks linear affected-operation work, untouched unrelated terminals and complete observation cleanup.

QA classification: CLI/orchestration and performance, qa=tests. No running-app-only behavior was identified; no real-agent, OS, live SSH performance or rendered UI run is claimed. Logical cancellation prevents late readiness success; it does not forcibly cancel an already-issued host probe. Named focused checks passed, including the 106-test readiness set, 22-test socket-shutdown recheck, 45-test runtime runner with the scaling contract, 14-test inventory suite and 32 federation-consumer tests; these totals overlap. Two test-only CI repairs replace a wall-clock read and unchecked legacy fixture replies without weakening assertions. Final CI on the pushed head is the lint/typecheck gate.

@brennanb2025
brennanb2025 marked this pull request as ready for review October 30, 2026 21:11
@coderabbitai

coderabbitai Bot commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Walkthrough

The change adds a shared error builder that preserves a PTY’s exit cause in non-exit wait errors. It adds a helper for composer waits that manages observation, PTY validation, and cleanup. Tests cover exit timing, waiter cleanup, readiness failures across supported agents, and runtime and automation behavior after terminal exit.

Merge Risk: Moderate · up to 81db8

An unconfirmed SSH disconnect can prematurely fail composer readiness instead of allowing reconnection. Fix this before merging.

Pre-merge checks: Passed 3 · Failed 2

Failed Failed checks: 2 warnings

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentat… Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check Warning The description gives a strong technical summary, rationale, linked issues, testing details, scope, and known limitations. However, it does not follow the repository template headings and omits requir… Reformat the description using the repository template. Add or explicitly mark as not applicable: ELI5, What Changed, Why, Linked Issue with the applicable issue reference, Visual Proof (N/A with a brief reason if there is no UI change), …
Passed Passed checks: 3 passed
Check name Status Explanation
Title check Passed The title clearly and concisely describes the main change: readiness now fails promptly when the terminal exits.
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Docstring Coverage

Explanation

Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 3 functions across 16 files.

Resolution

Write docstrings for the functions missing them to satisfy the coverage threshold.

Full details: Description check

Explanation

The description gives a strong technical summary, rationale, linked issues, testing details, scope, and known limitations. However, it does not follow the repository template headings and omits required sections such as Visual Proof with an explicit N/A rationale, Review, Agent skill upstream boundary, Notes, and the Checklist. It also does not provide the template's Fixes # issue reference format.

Resolution

Reformat the description using the repository template. Add or explicitly mark as not applicable: ELI5, What Changed, Why, Linked Issue with the applicable issue reference, Visual Proof (N/A with a brief reason if there is no UI change), Testing checklist, AI Disclosure if applicable, Review, Agent skill upstream boundary, Notes, and Checklist. Preserve the existing technical details and testing evidence.

Finishing Touches: 💡 1
📝 Generate docstrings: 💡
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai 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.

Actionable comments posted: 1

Nitpick comments: 1
src/main/runtime/terminal-pty-exit-waiter.spec.ts: 1

68-124: Trivial · Functional Correctness · Quick win

Add a readiness-backed exit-wait assertion.

The assertion at agent-status-and-waits-part-02.spec.ts:533 exercises getTerminalAgentStatus, not RuntimeTerminalWait.wait. It does not detect a regression that evaluates ready-strong before the recorded-exit guard.

The current fixture uses data: ''. Add a Pi case with a retained ready OSC title so the exited pane still has strong-ready evidence at waitForTerminal.

Suggested fix
+    it('rejects a strong-ready pane after its recorded exit', async () => {
+      const { runtime, handle } = await createTranscriptPane({
+        paneTitle: 'shell',
+        foregroundProcess: 'bash',
+        launchAgent: 'pi',
+        data: '\x1b]0;ready\x07'
+      })
+      const cause = { kind: 'signaled' as const, signal: 9 }
+
+      runtime.onPtyExit(TRANSCRIPT_PANE_PTY_ID, 137, 'inc-1', {
+        providerExitObserved: true,
+        cause
+      })
+
+      await expect(
+        runtime.waitForTerminal(handle, { condition: 'tui-idle', timeoutMs: 100 })
+      ).rejects.toMatchObject({ message: 'terminal_exited', terminalExitCause: cause })
+    })

Review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: b2a38d4b-4f9b-40df-90f8-d61261f0abc3
Commits

Reviewing files that changed from the base of the PR and between 99fdbcf and 6bbf741.

Files selected for processing: 5
  • src/cli/index-terminal-commands.test.ts
  • src/main/runtime/terminal-pty-exit-waiter.spec.ts
  • src/main/runtime/terminal-wait-results.ts
  • src/main/runtime/terminal/wait/terminal-wait-settlements.ts
  • src/main/runtime/terminal/wait/terminal-wait.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 4 remain after this review.

@brennanb2025 brennanb2025 changed the title Fail idle waits promptly when the terminal already exited Fail readiness promptly when the terminal exits Oct 30, 2026

@coderabbitai coderabbitai 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.

Actionable comments posted: 1


Review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 46b53147-f357-4c71-9a74-783ad36e9796
Commits

Reviewing files that changed from the base of the PR and between 8483ddc and 6e69f54.

Files selected for processing: 1
  • src/main/runtime/terminal/lifecycle/main-pane-liveness.test.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 2 remain after this review.

@coderabbitai coderabbitai 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.

Caution

Some comments are outside the diff and can’t be posted inline due to GitHub limitations.

⚠️ Outside diff range comments (1)

Minor · Do not treat an unconfirmed SSH exit as terminal exit in… · terminal-composer-lifetime.ts:40-49

src/main/runtime/terminal/wait/terminal-composer-lifetime.ts:40-49
Minor · Stability & Availability · Quick win

Do not treat an unconfirmed SSH exit as terminal exit in composer readiness.

Ignoring the observer settlement alone does not preserve the wait. onPtyExit(-1) sets connected to false and records lastExitCode = -1; getPtyTerminalState then returns exited for both composer checks. The post-readiness check can therefore still throw terminal_exited after the readiness scanner succeeds.

Thread the reconnect-eligibility or certified-exit predicate through the observer and both composer state checks. Keep generic terminal state and ordinary exit waits unchanged.


Review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 3c0c4668-dfd9-42eb-a92e-68582f08766e
Commits

Reviewing files that changed from the base of the PR and between 6e69f54 and 81db8eb.

Files selected for processing: 1
  • src/main/runtime/rpc/methods/orchestration/federation/federation-runtime.test-support.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 3 remain after this review.

@brennanb2025

brennanb2025 commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor Author

The terminal could already be gone while an idle or startup-readiness caller still waited for a deadline or trusted stale screen output. The admission check covered only exit waits, and composer readiness did not observe process completion.

This PR now fails readiness promptly for a recorded exit before or during the operation, preserving its neutral cause. It retains recoverable unknown disconnects, exact terminal identity, existing exit-wait results and either-source readiness success. Cleanup retires the operation's existing-registry observation and scanner work. Startup-specific explanations remain in #36422.

The full review completed two rounds and a three-seat design ruling. A later test-size tripwire received its required three-seat re-plan; it retained the same mechanism and whole-class cut, with no further implementation required. Fixed: unknown SSH disconnects being mistaken for death, the pending/composer-only readiness gap, the CLI test's typecheck boundary, and the required scaling contract. No runtime finding remains deferred. The unchanged external-conversation reopen catch-to-refusal path was source-traced; its existing fixture uses unsatisfied readiness rather than a real known-exit rejection. The socket-stop fixture proves abort propagation into actual composer cleanup through a controlled dispatcher; it does not also exercise the real orchestration-check handler during stop.

Verified with production-runtime promptness and lifecycle contracts, captured-output success cases, actual local/federated worker receipts, launch no-delivery, automation/cleanup outcomes, socket abort and the real CLI command through controlled transport. The final focused set passed 106 tests; the shutdown recheck passed 22; after the test-only performance addition, the runtime runner passed 45 including the N/10N contract. The test-only CI repair then passed all 14 tests in its affected file, retaining the same assertions while using a fixed timestamp and actual waiter-registration condition. The federation test-fixture repair passed all 32 tests in its three direct consumers and replaces unchecked replies with complete checked contracts. These totals overlap. The contract counts affected-operation work and cleanup at 2/20 concurrent waits while unrelated terminals remain untouched.

QA is the CLI/orchestration/performance tests row (qa=tests); no app-only behavior was identified. No real-agent, OS, live SSH performance or rendered UI run is claimed. Cancellation prevents late readiness success; it does not forcibly cancel a host probe already issued. Final reference comparison covers the whole mechanism, with intended adaptations for arbitrary late handles, incarnations, uncertain remote contact and independently updated hosts.

The final tested/reviewed head is 81db8eb50bd3e6aa6517aff9e52cca29792ec347. Focused evidence was established at 39c24bee80785f2fd3faba926f61cec0775ab484, with later affected-file checks and full current-head CI. The final clean main merge 8483ddcfc651baa170df4fd653650f0af179e023 leaves all PR-owned files byte-identical; final source/reference review checked that merged head. The later commits 6e69f5494537bf54900cad3c1c9f2572f897cfcd and 81db8eb50bd3e6aa6517aff9e52cca29792ec347 repair test-only CI checks. Continued review accepted both without changing assertions or shipped behavior. Final CI passed on the latter, including static analysis/typecheck, all twelve unit shards, both packages and the three WSL distro checks.

For Brennan's review:

@brennanb2025
brennanb2025 merged commit c8903ea into main Oct 30, 2026
51 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant