Skip to content

fix(setup): record terminal state when commands are cancelled - #1978

Merged
karkarl merged 1 commit into
openclaw:mainfrom
karkarl:karkarl-setup-cancellation-diagnostics
Nov 4, 2026
Merged

karkarl merged 1 commit into
openclaw:mainfrom
karkarl:karkarl-setup-cancellation-diagnostics

Conversation

@karkarl

@karkarl karkarl commented Nov 2, 2026

Copy link
Copy Markdown
Collaborator

Related: #1952 (fix: native Gateway setup loses startup window to slow validation), #1735 (feat(setup): stream live native Gateway activity log and typed failure diagnosis).

What Problem This Solves

Fixes: setup logs have no terminal command observation when a caller cancels a running command or its post-exit output drain.

User Impact

User impact: developers investigating cancelled setup can distinguish execution from output drain and see the observed direct-child/EOF state, without logging partial command output. No startup or guest-validator stall fix is claimed.

Why This Change Was Made

CommandRunner now records cmd.exit when its direct-child exit wait completes, before output drain, and cmd.cancelled when cancellation interrupts execution or drain. Cancellation records contain only the interrupted phase, direct-child-exit and per-stream EOF observations, elapsed time, and the existing runner-timeout classification.

The original exception/token is rethrown. Existing execution cleanup, post-exit cancellation behavior, deadlines, timeout results, and success output capture are preserved. No retries or new waits are added. Observations are non-atomic and do not prove process-tree cleanup or guest process exit. A caller-linked deadline is still classified as caller cancellation; simultaneous timeout/cancellation does not establish which occurred first.

This is independently applicable to default main, not based on the fork-only #1952 head. Packaging's separate guest invocation ownership repair is outside this diff.

Evidence

Two real-process regression cases failed on the original production source at a4dd026cc5f85a444a0fcd05eef5b86282dbda8c, specifically because cmd.cancelled was absent. Input cancellation is coordinated by the stdin copy callback. Post-exit cancellation is coordinated by the direct-exit observation while a task-owned fixture descendant holds output pipes open, not by a sleep.

The initial focused implementation run passed 39 tests. Final coverage also includes normal/inherited-pipe drain variants and already-observed EOF racing cancellation.

Independent Copilot rubber-duck/source review covered the complete local candidate against the explicit base, P0-P3, and the proof plan. No blocking findings. It noted the existing timeout/caller race, additional intentional debug-log volume, and the existing synchronous logger subscriber exception behavior. The race limitation is documented. Codex CLI is unavailable; model identity is unverified. This narrative review does not provide helper-enforced isolation, frozen-input checks, or structured result validation.

Change Type

  • Bug fix
  • Feature
  • Refactor
  • Docs or instructions
  • Tests or validation
  • Security hardening
  • Chore or infrastructure

Scope

  • Tray or WinUI UX
  • Windows node capability
  • Local MCP or winnode
  • Gateway, connection, or pairing
  • Setup or onboarding
  • Permissions, privacy, or security
  • Tests, CI, or docs

Required proof pools

  • none: The changed contract is setup runner diagnostics, directly exercised by owned process/pipe fixtures without a desktop, WSL, installation, or Gateway. No UI, node dispatch, sandbox, or package contract changes. Live isolated native setup integration remains unverified with the coordinator; WSL proof would not establish native guest-validator behavior.

Validation

Final validation ran after packaging released the serialized validation slot. OPENCLAW_REPO_ROOT was set to this worktree for all test commands. Fresh Shared and Tray test projects were built first with dotnet build <test-project> --verbosity quiet (both passed), so --no-restore did not silently no-op. Tray settings used an isolated task-owned directory.

  • .\build.ps1: PASS. All five projects, Debug win-arm64, on native Windows ARM64. Documentation/proof-pool gate passed.
  • dotnet test .\tests\OpenClaw.Shared.Tests\OpenClaw.Shared.Tests.csproj --no-restore --verbosity minimal: PASS. 4,810 passed, 24 skipped, 0 failed, 4,834 total. Skipped device-identity integration and native MXC opt-in cases are not live proof.
  • dotnet test .\tests\OpenClaw.Tray.Tests\OpenClaw.Tray.Tests.csproj --no-restore --verbosity minimal: PASS. 4,799 passed, 0 skipped, 0 failed.
  • dotnet test .\tests\OpenClaw.SetupEngine.Tests\OpenClaw.SetupEngine.Tests.csproj --no-restore --filter 'FullyQualifiedName~CommandRunnerTests|FullyQualifiedName~SetupLoggerTests|FullyQualifiedName~NativeGatewaySetupTests|FullyQualifiedName~NativeGatewaySetupConnectionTests' --verbosity minimal: PASS. 171 passed, 0 skipped, 0 failed.
  • powershell.exe -NoProfile -NonInteractive -ExecutionPolicy RemoteSigned -Command 'dotnet test .\tests\OpenClaw.SetupEngine.Tests\OpenClaw.SetupEngine.Tests.csproj --no-restore --verbosity minimal; exit $LASTEXITCODE': PASS. Full SetupEngine: 2,529 passed, 4 skipped, 0 failed, 2,533 total. RemoteSigned was process-scoped only, for generated-script fixtures; no persistent machine policy was changed. Skips: two console-visibility cases, the opt-in cleanup proof worker, and cross-volume Local AI compatibility.
  • .\scripts\validate-docs.ps1: PASS. 69 Markdown files and 7 proof pools checked.
  • git diff --check: passed for the source candidate.

.\scripts\Get-CiChangeClassification.ps1 -EventName pull_request -ChangedPaths 'src\OpenClaw.SetupEngine\CommandRunner.cs','src\OpenClaw.SetupEngine\SetupLogger.cs','tests\OpenClaw.SetupEngine.Tests\CommandRunnerTests.cs','docs\SETUP_ENGINE_REDESIGN.md' -Human: PASS, selected targeted tray-tests and setup-e2e hosted lanes. Hosted CI has not yet run. No changes to MXC execution, node commands, WSL setup policy, or packaging are claimed; real WSL/MXC/native Gateway proof was not run.

Baseline command: dotnet test .\tests\OpenClaw.SetupEngine.Tests\OpenClaw.SetupEngine.Tests.csproj --no-restore --filter 'FullyQualifiedName~RunAsync_CancellationDuring' --verbosity minimal: 2 failed, 0 passed, 0 skipped (expected missing-event regressions). A first fresh-worktree invocation omitted --no-restore.

Real Behavior Proof

  • Environment tested: task-owned Windows worktree; owned OpenClaw.Shared.TestHost processes only. No installed Companion, Gateway, WSL, package/profile, credentials or user processes were touched.
  • PR head or commit tested: 6f90b291d38c1525d457863063d47a802e685b47, comparison base a4dd026cc5f85a444a0fcd05eef5b86282dbda8c. Tests ran against uncommitted source manually associated with full candidate diff hash 0c623d8df068b981e784a654f928b4a73d4b7eff before build. This equals the committed parent-relative diff hash; no source changed between final validation and commit.
  • Exact steps or command run: focused setup runner/logger tests listed above.
  • Evidence after fix: cancellation log schema contains only six non-sensitive state fields. For inherited-pipe drain cancellation, direct-child exit is true while both EOF observations are false; the original cancellation token propagates and no cmd.done success/timeout result is manufactured.
  • Observed result: final 171-case focused run and full SetupEngine suite passed. Current-source real process/pipe fixtures observe cancellation instead of losing the terminal record. Existing successful high-volume trailing stdout/stderr and runner-timeout tests remain passing.
  • Screenshot or artifact links verified? (Yes/No/N/A): N/A.
  • Not verified or blocked: no live clawctl collect-logs or Companion/Gateway rerun, by explicit runtime restrictions. The coordinator owns collection and the integrated isolated retest with fix: native Gateway setup loses startup window to slow validation #1952. This patch does not prove startup succeeds, a guest validator exits, its stall cause, process-tree cleanup, or packaging's guest-invocation repair. Synchronous logger subscriber exception behavior is unchanged.

Security Impact

  • New permissions or capabilities? (Yes/No): No.
  • Secrets or tokens handling changed? (Yes/No): No.
  • New or changed network calls? (Yes/No): No.
  • Command or tool execution surface changed? (Yes/No): No.
  • Data access scope changed? (Yes/No): No.
  • If any answer is Yes, explain the risk and mitigation: N/A. New records exclude executable paths, arguments, configuration, identities and raw/partial output.

Compatibility and Migration

  • Backward compatible? (Yes/No): Yes. Existing command results and cancellation semantics retained; additive debug/warning diagnostic records.
  • Config or environment changes? (Yes/No): No.
  • Migration needed? (Yes/No): No.
  • If yes, list the exact upgrade steps: N/A.

Review Conversations

  • I replied to or resolved every bot review conversation addressed by this PR.
  • I left unresolved only conversations that still need maintainer judgment.

@clawsweeper

clawsweeper Bot commented Nov 2, 2026 •

Copy link
Copy Markdown

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@clawsweeper clawsweeper Bot added P3 Low-risk cleanup, docs, polish, ergonomics, or speculative feature. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Nov 2, 2026
@clawsweeper

clawsweeper Bot commented Nov 2, 2026

Copy link
Copy Markdown

Codex review: needs maintainer review before merge.

What this changes

This PR records direct-child exit and cancellation state for setup commands without changing their execution or output-drain policy.

Example: A command exits with code 0, its descendant holds stdout and stderr open, and the caller cancels.

  • Before: The output-drain wait throws cancellation without recording a terminal command observation.
  • After: Logs record cmd.exit followed by cmd.cancelled with phase output-drain, direct-child exit true, and both EOF observations false.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Focused and source-correct with meaningful process-fixture coverage, but no supplied shipped-entry-point result.
Proof confidence 🦐 gold shrimp (3/6) The ordinary contributor-proof gate does not apply to this collaborator-authored PR; supplied Windows process-fixture tests exercise CommandRunner cancellation, while the full body explicitly leaves shipped Companion/Gateway integration unverified.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Developers investigating cancelled setup cannot distinguish command execution from waiting for output EOF.
Reason: The collaborator-authored direction fills a concrete diagnostic gap with state-only records and explicitly preserves execution behavior.

Merge readiness

✅ Ready for maintainer review

Keep this collaborator-authored draft open: main lacks these cancellation diagnostics, and no actionable introduced defect was found.

Priority: P3
Reviewed head: 6f90b291d38c1525d457863063d47a802e685b47

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: No supplied shipped setup run shows execution and post-exit cancellation producing the new diagnostic records.
Agent review details

How this fits together

Setup callers pass commands and cancellation tokens to CommandRunner, which manages processes and redirected streams and sends structured observations to SetupLogger.

flowchart TD
A[Setup callers] --> B[CommandRunner]
B --> C[Direct child process]
C --> D[Redirected output streams]
D --> B
B --> E[SetupLogger]
E --> F[JSONL and diagnostic subscribers]
Loading

Technical review

Best possible solution:

Keep cancellation observations in the existing runner and logger while preserving deadlines, output capture, cleanup, and exception propagation.

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

The pinned main source demonstrates both cancellation paths bypass terminal command logging, and the author reports baseline failures for that exact missing event; no target code was executed during this review.

Is this the best way to solve the issue?

The patch is a small complete diagnostic fix: one phase marker and the existing logger cover execution and drain cancellation without replacing their owners or masking the underlying startup problem.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against a4dd026cc5f8.

Provenance checked

  • Execution cancellation and structured command logging keeps the original intent (cefce39: The SetupEngine redesign established transactional setup, structured sanitized logging, and best-effort command cancellation cleanup.)
  • Direct-child exit separated from stream EOF keeps the original intent (ccd64bb: The process-exit helper avoids conflating direct-child termination with descendants retaining redirected pipe handles.)
  • Normal and inherited-pipe output drain policy keeps the original intent (Preserve normal setup command output drains #1361: Preserve complete normal trailing output and caller cancellation while bounding only timeout cleanup and explicit inherited-pipe inspections.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Scott Hanselman: Raw commit f9bfc87 adds src/OpenClaw.SetupEngine/CommandRunner.cs:330 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: f9bfc871f6d1; files: src/OpenClaw.SetupEngine/CommandRunner.cs)

Review metrics

Metric Value Why it matters
Introduced scope Production +64/-32; tests +135/-10; documentation +18/-1 Growth supports two diagnostic phases and distinct cancellation regressions without adding another execution owner.

Labels

Label changes:

  • add P3: This improves developer diagnostics for cancelled setup commands without claiming to repair setup completion or availability.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P3: This improves developer diagnostics for cancelled setup commands without claiming to repair setup completion or availability.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Optionally capture redacted setup logs showing both cancellation phases through a shipped setup entry point.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

Reviewed November 2, 2026, 12:32 PM ET / 17:32 UTC.

Record direct child exit before output drain and state-only caller cancellation observations without changing deadlines, cleanup or exception semantics.

Co-authored-by: Copilot App <[email protected]>
@karkarl
karkarl force-pushed the karkarl-setup-cancellation-diagnostics branch from 6f90b29 to dc7d172 Compare November 4, 2026 16:57
@karkarl
karkarl marked this pull request as ready for review November 4, 2026 18:13
@karkarl
karkarl merged commit c89cf43 into openclaw:main Nov 4, 2026
28 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P3 Low-risk cleanup, docs, polish, ergonomics, or speculative feature. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. 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.

1 participant