Skip to content

fix(gmail): keep forwarding alive across watcher restarts - #130853

Merged
steipete merged 2 commits into
mainfrom
steipete/distracted-hertz-53f9dd
Aug 27, 2026
Merged

steipete merged 2 commits into
mainfrom
steipete/distracted-hertz-53f9dd

Conversation

@steipete

Copy link
Copy Markdown
Contributor

Closes #130852

Additional instructions

This branch is in the main repository and is editable by maintainers.

What Problem This Solves

Fixes an issue where users running openclaw webhooks gmail run would silently lose forwarding after the replacement watcher exited: the command stayed alive and renewed Gmail watches with no serve process left. It also fixes recovery getting stuck when an exited watcher leaves descendants holding its output pipes open.

Why This Change Was Made

The foreground CLI now uses the existing resolved-config Gmail watcher lifecycle shared with Gateway startup and reload. That owner handles every replacement, bounded output drain, bind-error classification, single-flight renewal, and process-tree cleanup; the CLI still owns option resolution, prerequisites, and signals. This removes the duplicate foreground supervisor and redundant cancellation polling/controller rather than maintaining two restart policies. Built-CLI proof also caught the generic startup wrapper terminating this foreground owner after two seconds, before its three-second cleanup finished. Foreground Gmail now stays in the invoking process across ordinary and compile-cache startup, while one-shot setup keeps its existing wrapper behavior.

Unexpected POSIX leader exits clean up only that active watcher's owned process group. Windows does not run taskkill against an already-exited root PID. Normal shutdown retains its three-second grace period, late stderr still classifies bind conflicts, and CLI overrides remain usable with hooks disabled without rewriting config. Setup registration remains fatal on failure; watcher renewal-error policy is unchanged. No new configuration flags, schemas, protocols, or dependencies.

User Impact

Foreground forwarding recovers after repeated unexpected watcher exits using the shared five-second restart delay. Ctrl-C/SIGTERM cancels pending startup, restarts, and renewal work and waits for tree cleanup. Bind conflicts stop restart attempts with an actionable log message. See the webhook CLI reference.

The separate degraded OAuth/renewal-health behavior requested in #96088 is not fixed or closed by this change.

Evidence

The pre-fix regression failed with expected third child, got two, and the same failure reproduced independently from stable tag v2026.7.1. The inherited-pipe fixture recorded originalExited=true, originalClosed=false, spawned=1, and a live resistant helper after seven seconds; no replacement arrived before its twelve-second deadline. The Windows dead-root termination regression also failed before the repair.

Final local proof:

  • 71 focused tests passed across gmail-ops.test.ts, gmail-watcher.test.ts, gmail-watcher-lifecycle.test.ts, cli/webhooks-cli.test.ts, and process/child-process.test.ts using node scripts/run-vitest.mjs with those explicit paths.
  • 11 Gateway cancellation/startup/reload tests passed using node scripts/run-vitest.mjs src/gateway/server-startup-post-attach.test.ts src/gateway/server-reload-handlers.test.ts -t 'Gmail watcher|Gmail restart|post-ready sidecar teardown'; 306 unrelated tests were intentionally unselected.
  • The real fake-gog process-tree integration test passed. Its heavy import now occurs during collection rather than consuming the test's 15-second runtime budget; no timeout increase.
  • An additional 138 launcher/CLI tests passed (one opt-in real-Bun case skipped). Seven new startup-policy and compile-cache shutdown cases failed before the wrapper repair; both source and packaged launcher fixtures now complete their 3.025-second cleanup and exit 0. The fixture-only launcher lane uses its documented OPENCLAW_E2E_SKIP_BUILD=1 because it supplies its own entry files.
  • Core tsgo; plugins-platform, gateway-root, core-other and root test tsgo; scoped oxlint; formatting; assertion safety; import-cycle checks; and git diff --check passed.

pnpm build passed on final head f2db9972eb855f8d14c0286c9476130bb506876b (11m 0.4s). The actual built openclaw.mjs webhooks gmail run then passed offline process proof on macOS with an isolated HOME/config/state, a fake gog first on a minimal PATH, explicit fixture options, and --tailscale off. Kernel sandboxing denied network access to the command and all descendants. Two forced watcher exits produced exactly one replacement each; earlier SIGTERM-resistant pipe-holding helpers were gone before the next watcher became ready. SIGTERM exited the CLI with code 0, all three watchers and all three helpers were already gone before harness cleanup, and config bytes were unchanged. The checked-in launcher fixtures separately cover source and packaged compile-cache startup.

Fresh independent Codex autoreview of the combined final patch, including the built-CLI shutdown correction, completed with no actionable P0 findings. Source review covered the CLI producer, shared owner, Gateway cancellation callers, process output drain/tree cleanup, existing sibling tests, current main, and Node's child-process exit/close ordering. A recursive foreground callback was rejected because it would retain divergent renewal, bind, cancellation, and shutdown behavior; a new supervisor abstraction was unnecessary.

Production LOC: +115/-199 (net -84). Tests: +516/-175 (net +341). Twenty production lines are a pure move of launcher bootstrap execution below its existing argument-parser definitions. Docs: +1/-1. The regression tests exercise observable restart/renewal/termination outcomes and add no test-only production seam.

Provenance: carried forward; original introduction unknown. Blame reaches shallow boundary e357203be5721f55434e7fc9891268e5c6afdd38 (2026-07-12, Vincent Koc), which does not establish introduction. Stable-tag source independently exhibits the defect. Current main's unrelated model-runtime reload changes are in disjoint hunks.

Proof limits: all account/topic/token values are fixtures. No live Gmail account, real gog, Gateway, cloud setup, or email delivery was used or tested, as explicitly required for this task. Windows behavior is modeled in tests, not verified on native Windows. This is process lifecycle proof, not end-to-end email delivery.

AI-assisted; maintainer reviewed and understood the ownership and behavior changes. No release/version/changelog changes.

@steipete
steipete marked this pull request as ready for review August 27, 2026 09:05
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime cli CLI command changes size: XL labels Aug 27, 2026
@clawsweeper

clawsweeper Bot commented Aug 27, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

@openclaw-barnacle openclaw-barnacle Bot added the maintainer Maintainer-authored PR label Aug 27, 2026
@steipete steipete self-assigned this Aug 27, 2026
@clawsweeper clawsweeper Bot added merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. P1 High-priority user-facing bug, regression, or broken workflow. 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. labels Aug 27, 2026
@clawsweeper

clawsweeper Bot commented Aug 27, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 27, 2026, 5:16 AM ET / 09:16 UTC.

ClawSweeper review

What this changes

This PR moves foreground Gmail forwarding onto the shared watcher lifecycle so replacement processes restart and clean up consistently.

Merge readiness

⚠️ Ready for maintainer review - 2 items remain

Keep this maintainer-owned repair open. It removes current main’s separate foreground supervisor, whose replacement child is not itself supervised; no actionable patch defect was found. Exact-head CI is still running, and native Windows process behavior remains the main pre-merge evidence gap.

Priority: P1
Reviewed head: f2db9972eb855f8d14c0286c9476130bb506876b

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A coherent owner-boundary repair with strong lifecycle regression coverage; native Windows behavior and exact-head CI remain pending.
Proof confidence 🐚 platinum hermit (4/6) Not applicable: The maintainer-authored PR documents after-fix offline built-CLI fake-gog process output; no external contributor proof action is required.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The maintainer-authored PR documents after-fix offline built-CLI fake-gog process output; no external contributor proof action is required.
Evidence reviewed 6 items Current-main defect: Current main attaches the foreground exit listener only to the initial child; its restart assigns a replacement without attaching another listener, so a second unexpected exit cannot schedule a further replacement.
Canonical owner-boundary repair: The PR resolves CLI options and delegates foreground operation to the existing shared watcher service, removing the duplicate CLI restart, renewal, and process-tree supervisor.
Shared lifecycle behavior: The shared watcher bounds inherited-pipe draining after process exit, classifies bind failures, and schedules replacement from the per-child lifecycle owner.
Findings None None.
Security None None.

Live Verification

Command: node scripts/run-vitest.mjs src/hooks/gmail-watcher.integration.test.ts

Result: PASS (completed)

[test] starting test/vitest/vitest.hooks.config.ts

 RUN  v4.1.11 /tmp/clawsweeper-live-proof-130853-9mg0zX/target

stdout | src/hooks/gmail-watcher.integration.test.ts › gmail-watcher process-tree shutdown (integration) › stopGmailWatcher removes gog and its credential-helpe
r descendant

gog pid=5601, credential-helper pid=5604
calling stopGmailWatcher...

Assertions:

  • PASS expect_output: gmail-watcher process-tree shutdown

How this fits together

Gmail webhook startup launches a local gog watcher that forwards mail events into OpenClaw. The shared watcher owns process renewal, restart, bind-failure handling, and shutdown for both Gateway and CLI entry points.

flowchart LR
  A[CLI or Gateway startup] --> B[Resolved Gmail watcher config]
  B --> C[Shared watcher lifecycle]
  C --> D[gog serve process]
  D --> E[Webhook forwarding]
  D --> F[Exit and cleanup handling]
  F --> C
Loading

Before merge

  • Resolve merge risk (P1) - Windows inherited-pipe recovery and process-tree cleanup are covered with platform mocks rather than native process proof, so a platform-specific forwarding stall could remain.
  • Complete next step (P2) - This protected maintainer-owned PR needs human merge review, exact-head CI completion, and a decision on whether native Windows proof is required.
Agent review details

Security

None.

PR surface

Source -103, Tests +341, Docs 0, Other +19. Total +257 across 17 files.

View PR surface stats
Area Files Added Removed Net
Source 7 76 179 -103
Tests 8 516 175 +341
Docs 1 1 1 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 39 20 +19
Total 17 632 375 +257

Review metrics

Metric Value Why it matters
Production versus regression coverage production −84 net; tests +341 net The consolidation deletes the duplicate CLI supervisor while adding restart, shutdown, inherited-pipe, and launcher regressions.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #130852
Summary: This PR is the candidate repair for the repeated foreground watcher-exit failure in issue #130852; OAuth health reporting in #96088 is adjacent but distinct.

Members:

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

Merge-risk options

Maintainer options:

  1. Capture native Windows lifecycle proof (recommended)
    Run the fake-gog foreground launcher scenario on Windows to verify replacement and process-tree cleanup before merge.
  2. Accept modeled Windows coverage
    Merge with the existing platform-mocked Windows coverage if maintainers accept the remaining native-process uncertainty.

Technical review

Best possible solution:

Land the shared-lifecycle consolidation after exact-head CI, retaining foreground option resolution and signal ownership; obtain native Windows process proof if that platform is release-gated.

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

Yes. On current main, the exit listener is attached only to the initial foreground child; after its replacement exits, no handler schedules another child.

Is this the best way to solve the issue?

Yes. Reusing the existing watcher lifecycle is the canonical fix; retaining a second CLI supervisor would leave restart, renewal, bind, and cleanup policy divergent.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add P1: Repeated unexpected Gmail watcher exits can leave foreground forwarding stopped while the runner remains alive.
  • add merge-risk: 🚨 message-delivery: The shared process lifecycle controls whether Gmail events continue to be forwarded, while native Windows recovery remains unobserved.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🦞 diamond lobster.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: The maintainer-authored PR documents after-fix offline built-CLI fake-gog process output; no external contributor proof action is required.

Label justifications:

  • P1: Repeated unexpected Gmail watcher exits can leave foreground forwarding stopped while the runner remains alive.
  • merge-risk: 🚨 message-delivery: The shared process lifecycle controls whether Gmail events continue to be forwarded, while native Windows recovery remains unobserved.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: The maintainer-authored PR documents after-fix offline built-CLI fake-gog process output; no external contributor proof action is required.

Evidence

What I checked:

Likely related people:

  • steipete: Recent Gmail CLI, foreground ownership, and launcher changes in the reviewed history are authored by this contributor. (role: recent Gmail CLI and launcher contributor; confidence: high; commits: c1d4e500d2a3, f2db9972eb85; files: src/hooks/gmail-ops.ts, src/cli/respawn-policy.ts, openclaw.mjs)
  • Narahari Raghava: The process-tree shutdown lifecycle repair is directly adjacent to the shared watcher owner used by this PR. (role: recent Gmail watcher lifecycle contributor; confidence: high; commits: 320c3ad8e0d6; files: src/hooks/gmail-watcher.ts)
  • wahaha1223: Recent watcher work covers preserving bind-error classification during lifecycle changes. (role: recent watcher error-classification contributor; confidence: medium; commits: 0e85bfa63217; files: src/hooks/gmail-watcher.ts)

Rank-up moves

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

  • Complete exact-head CI.
  • If Windows is release-gated, capture the equivalent native fake-gog and launcher process proof.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
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.

Workflow

  • 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.

@steipete

Copy link
Copy Markdown
Contributor Author

Verified head: f2db9972eb855f8d14c0286c9476130bb506876b.

The defect is confirmed before the fix: the foreground runner creates only two children after two exits, while its renewal timer stays alive. Stable v2026.7.1 independently reproduces that result. A real fake-gog descendant holding inherited pipes also prevents replacement before the repair. The fix moves foreground ownership into the shared lifecycle and preserves the CLI's shutdown ownership through ordinary and compile-cache startup.

Final local verification passed: 221 focused tests across the Gmail owner, CLI/Gateway callers, process handling, and launcher (one opt-in real-Bun test skipped); the relevant core/test TypeScript programs; scoped lint/format/assertion/import-cycle checks; and pnpm build. Seven launcher regressions failed before the added shutdown repair. Fresh independent Codex autoreview of the combined final patch found no actionable P0 issue; the manual owner-boundary review and native review artifacts have no blocking findings.

The actual built openclaw.mjs webhooks gmail run passed twice, with compile cache disabled and with an inherited compile cache. Both used isolated HOME/config/state, a minimal PATH containing only fixture gog plus system utilities, explicit fixture account/topic/hook/push arguments, and --tailscale off. A kernel sandbox denied all network access to the CLI and descendants. Each run forced two watcher exits and observed exactly one replacement each time, with previous pipe-holding SIGTERM-resistant helpers gone. SIGTERM then exited the CLI with code 0; all three watchers and all three helpers were gone before harness cleanup, and config bytes were unchanged. Recorded source hashes match this head.

Production: +115/-199, net -84; tests: +516/-175; docs: +1/-1. No new configuration keys, schemas, protocols, dependencies, versions, or changelog changes. Current-main reload changes are disjoint and remain untouched. Related #96088 remains outside this repair.

Exact-head CI run 33056951623 completed successfully. node scripts/watch-pr-ci.mjs 130853 f2db9972eb855f8d14c0286c9476130bb506876b exited 0 with GREEN and zero pending checks. Superseded auxiliary cancellations were accounted for by the native watcher; no test-failure retry or CI code change was needed.

The latest ClawSweeper review found no actionable patch or security defect. Both Rank-up moves are accounted for: exact-head CI is complete; native Windows process proof is not run. The authorized landing scope explicitly retains modeled Windows coverage, local macOS proof, and no remote-compute offload. I accept that documented platform uncertainty for this bounded owner repair under the standing landing approval. Windows regressions cover the exited-root PID guard and launcher policy, but are not represented as native process proof. No new Windows release gate or mandatory independent approval is present in the live main rules; the required openclaw/ci-gate is satisfied.

No live Gmail, real gog, Gateway, cloud setup, or email delivery was used, as explicitly required for this task. Windows lifecycle behavior is modeled, not native Windows proof. This is verified process lifecycle behavior, not a claim of end-to-end email delivery.

@steipete
steipete merged commit 1cbcf14 into main Aug 27, 2026
278 of 280 checks passed
@steipete
steipete deleted the steipete/distracted-hertz-53f9dd branch August 27, 2026 09:29
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 28, 2026
…30853)

* fix(gmail): keep forwarding alive across watcher restarts

* fix(gmail): preserve foreground CLI shutdown ownership
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cli CLI command changes docs Improvements or additions to documentation gateway Gateway runtime maintainer Maintainer-authored PR merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. P1 High-priority user-facing bug, regression, or broken workflow. 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]: Foreground Gmail forwarding stops after repeated watcher exits

1 participant