Skip to content

fix(android): order gateway shutdown and credential reuse - #137389

Merged
steipete merged 3 commits into
mainfrom
codex/android-followup-status-20260903
Sep 3, 2026
Merged

steipete merged 3 commits into
mainfrom
codex/android-followup-status-20260903

Conversation

@steipete

@steipete steipete commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Closes #137378. Related: #136934.

What Problem This Solves

Android could start a secondary Gateway after Stop. Forget or authentication reset could then finish before an accepted token write, allowing the cleared credential to reappear. Immediate reconnect or promoting a secondary to the focused connection could also authenticate with stale credentials and let an older write overwrite the newer token.

Intentional Disconnect additionally showed “Not paired” and “Cannot reach gateway” even though pairing was retained.

Why This Change Was Made

Connection admission now uses the existing switch, authentication, and lifecycle owners. Secondary credential reads stay outside the lifecycle monitor; final admission validates the current intent, foreground state, enabled Gateways, registry entry, and discovery route. Stop retains the exact session owning accepted writes. Forget/reset and connection reuse join its ordered disconnect tail before clearing or reading credentials.

Primary direct, cold-start, switch, and stopped-reconnect paths share one admission. Promoting a secondary drains it before either primary role reads credentials. Active-session reconnects and unrelated direct cross-Gateway progress retain their existing behavior. Stop remains nonblocking.

Removes the unused secondary-status flow, captured fleet snapshot, and duplicate primary target-preparation path. No protocol, configuration, database schema, credential format, dependency, or server hot-reload change. Focused node commands and UI state remain owned by the primary connection.

User Impact

Stop retires secondary starts; Forget/reset cannot resurrect cleared credentials; reconnect uses the latest accepted credentials. Ordinary Disconnect retains pairing and displays “Offline”. Actual connection failures retain their error labels.

Production: +120/−123 (net −3). Tests: +375/−31 (net +344). Native string inventory: +1/−2.

Evidence

Six causal regressions use real GatewaySession instances, a local WebSocket server, and synthetic credentials. The original three fail on unchanged base 2074e04c27566a53459662236d35d20ecadb2819: held auth read across Stop, and accepted token writes across Stop→Forget or Stop→auth reset. The late three fail on unchanged b3ff0d5c99b1e13c3e37a9731085bfbea6b6c80b: secondary disable/re-enable, primary Stop/reconnect, and secondary-to-primary promotion.

In each late case, baseline sends the initial stale credential and stores writes in new→old order. Candidate ffe31f51d19bf520f9bbf3494321c3fce06b2475 stores old→new, sends the freshly accepted credential, and retains the newest token. All six regressions pass. These are controlled SharedPreferences interleavings through the real SecurePrefs wrapper, not packaged encrypted-store fault injection.

Final local validation passed 265/265 tests, no skips, across 13 classes: service lifetime, bootstrap auth/TLS, fleet/discovery/registry, direct cross-Gateway session progress, status, chat reconnect recovery, and composer/reader/question layouts. All Android modules passed ktlint; changed-file checks and native string verification passed. Independent Codex P0–P2 review completed both source packs with no actionable findings.

Exact-head CI completed successfully, including Play, third-party, and Wear tests, Android builds, and ktlint. The final packaged APK replay below passed.

Packaged UI evidence

The exact ffe31f51d19bf520f9bbf3494321c3fce06b2475 APK passed 15 asserted lifecycle observations, fresh setup/TLS trust, and a rapid two-tap disable/re-enable sequence (~232ms). A kept its existing connections while B opened one replacement. Switching focus A↔B moved node ownership and kept the other Gateway operator-only.

Stop, Home, and hot reopen kept both routes closed and the service stopped. Explicit Reconnect restored the expected roles. Stop→Forget B→Home/hot reopen→Reconnect restored A only: B stayed absent from the native saved-Gateway list and made no attempts during the recorded 10s window. Remote pairing intentionally remains after local Forget.

The run used an API36 emulator at 320dp width and font scale1, the same app PID throughout, and two isolated real Gateways pinned to 36eb0c1ec3fc1f2ee26152d238be6374b14df41b. APK SHA-256: dae78b167146f87fa57e106a72581a302116649e50af98c44558d2abbe7ad3a0. Its embedded commit and installed digest were independently verified. Native receipt SHA-256: 6f17663ed3c33ea61e718ea396b3ff8336382e61d78831bdc115972fd4043e93.

The lead independently checked all 59 artifact hashes, all 15 settled/final role and service observations, bounded quiet-window connection counters, and both exact raw-trace selections. Prior 19-observation evidence from e5e remains unchanged. All six lab processes were joined; 14 owned PIDs and seven ports were independently verified clear.

The after image is the final APK. Both full captures were inspected and contain only synthetic fixture details. A setup tap affected by a layout shift was explicitly excluded; the successful rapid-toggle receipt is separate. Mixed LAN-discovery viewports were not captured or uploaded. No physical-device, external-provider, indefinite-liveness, or packaged credential-write fault-injection claim is made.

Before: intentional Disconnect After: intentional Disconnect
Baseline incorrectly reports Not paired and Cannot reach gateway Candidate reports Offline without implying pairing loss

Review and CI follow-ups

The late ClawSweeper reconnect-tail finding and rank-up move are addressed by the three new causal cases and shared admission repair, including the primary and focus siblings. Accepted bootstrap persistence is preserved; unrelated GatewaySession connections are not globally serialized.

The initial full Play run failed an existing composer fixture before layout assertions. Controlled replay proved its producer had six commands while the MainViewModel bridge still had zero: Compose polling did not drain Robolectric’s Main queue. Four matching readiness predicates now use existing runOnIdle synchronization. A wider replay reproduced the question sibling before the same fix. All 30 layout cases pass.

The asynchronous admission also exposed three bootstrap tests that observed initial state before completion. They now wait for the existing TLS prompt or desired connection, preserving exact assertions and deadlines; the loose status-poll helper was removed. No retries, longer timeouts, weaker assertions, or runtime test hooks were added.

Final merge-result check

The latest ClawSweeper review found no concrete defect but could not retrieve main’s newer GatewaySession source and had an incomplete CI rollup. Both gaps are resolved. The exact-head CI run is complete and green. Main 951c268db0cb80445264e64796578b6cbe3279b6 merges cleanly with this head (tree 6c4ceea4bbeb1b633f9c826dd4ead286972b3d59).

Reviewed the current-main socket-publication/send change from #137041 and OkHttp 5.5.0 source directly. Its send lock is released before hello processing or accepted-token persistence; close does not acquire it, so it does not introduce a lock cycle with the runtime’s ordered drains. A second independent owner-boundary review reached the same conclusion.

The exact combined Android tree—all 768 tracked blobs—passed 284/284 tests across 15 classes, no skips, plus app ktlint. This includes main’s two socket-publication regressions, updated reader/layout tests, and all six credential-lifecycle cases. This accepts the tested retained-session ordering repair and addresses both latest rank-up moves; no protocol, schema, configuration, or credential-format decision is introduced.

Retain stopped secondary session ownership so Forget and authentication reset join accepted token writes before clearing credentials. Reuse lifecycle admission for fleet starts and show Offline after intentional Disconnect without claiming pairing loss.
@clawsweeper

clawsweeper Bot commented Sep 3, 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 app: android App: android size: M maintainer Maintainer-authored PR labels Sep 3, 2026
@steipete
steipete marked this pull request as ready for review September 3, 2026 15:59
@steipete steipete self-assigned this Sep 3, 2026
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. 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 Sep 3, 2026
@clawsweeper

clawsweeper Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 3, 2026, 1:44 PM ET / 17:44 UTC.

ClawSweeper review

What this changes

The PR serializes Android primary and secondary Gateway shutdown, credential cleanup, and reconnect admission so retired sessions cannot restore stale device tokens, and it corrects intentional-disconnect status text.

Regression provenance

Possible regression — probable (reproduction; reviewed change). No predecessor PR is attributed.

Merge readiness

⛔ Blocked before merge - 4 items remain

No concrete introduced defect was found, and this PR remains necessary because its Android lifecycle repair is not on fetched main or the latest release. Keep it open for maintainer review and refreshed merge-result/CI verification because current main changed the shared GatewaySession file after the pinned base and that promised source blob was unavailable locally.

Priority: P1
Reviewed head: ffe31f51d19bf520f9bbf3494321c3fce06b2475
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The implementation and focused regressions are coherent, but final confidence is limited by the uninspected current-main GatewaySession change and incomplete check rollup.
Proof confidence 🌊 off-meta tidepool Not applicable: The PR is member-authored, so the external-contributor proof gate does not apply; its supplied body nevertheless describes exact-head packaged Android lifecycle evidence. Artifact retrieval was unavailable to this reviewer and does not require contributor action.
Patch quality 🦐 gold shrimp (3/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The PR is member-authored, so the external-contributor proof gate does not apply; its supplied body nevertheless describes exact-head packaged Android lifecycle evidence. Artifact retrieval was unavailable to this reviewer and does not require contributor action.
Evidence reviewed 6 items Lifecycle admission repair: The introduced reconciliation path serializes background starts, reads credentials outside the lifecycle monitor, then revalidates intent, registry, discovery, and enabled state before connecting.
Ordered session-tail contract: GatewaySession exposes disconnectAndJoin for ordered cleanup; accepted device tokens are persisted during successful connection processing, so the new joins cover the writer that cleanup must not race.
Boundary regression coverage: Six introduced scenarios cover Stop→secondary auth read, Stop→Forget/reset during accepted-token persistence, secondary re-enable, primary reconnect, and secondary-to-primary promotion. They use real GatewaySession calls and a local WebSocket fixture while instrumenting SharedPreferences ordering.
Findings None None.
Security None None.

How this fits together

Android’s NodeRuntime owns focused and background Gateway sessions. Registry and lifecycle actions feed connection admission, which starts sessions and persists accepted device credentials.

flowchart LR
  A[Gateway registry] --> B[Android runtime]
  C[Stop Forget or auth reset] --> B
  B --> D[Connection admission]
  D --> E[Gateway sessions]
  E --> F[Credential store]
  E --> G[Gateway server]
Loading

Decision needed

Question Recommendation
Does the Android runtime owner approve this retained-session credential-ordering behavior after reviewing the current-main GatewaySession change? Approve the owner-boundary repair: Confirm the refreshed merge-result and required checks, then accept the tested shared admission and ordered-tail behavior.

Why: The author is a repository member and the PR carries the maintainer label; this auth/session-sensitive lifecycle change requires explicit human ownership rather than automated closure or repair.

Before merge

  • Resolve merge risk (P1) - This changes the ordering of persisted operator device tokens and primary/secondary session handoff; the known interleavings are covered, but a post-base GatewaySession change on main still needs merge-result review.
  • Resolve merge risk (P1) - The available check rollup is incomplete and truncated, so complete exact-head required CI cannot yet be confirmed.
  • Complete next step (P2) - Review the exact merge result with current main’s GatewaySession change and confirm all required checks complete green before merge.
  • Resolve maintainer decision - Resolve the maintainer decision shown above before merge.
Agent review details

Security

None.

PR surface

Tests +344, Other -4. Total +340 across 9 files.

View PR surface stats
Area Files Added Removed Net
Source 0 0 0 0
Tests 5 375 31 +344
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 4 121 125 -4
Total 9 496 156 +340

Review metrics

Metric Value Why it matters
Production versus test delta production +120/-123 (net -3); tests +375/-31 (net +344); native inventory +1/-2 The fix removes net production code while adding targeted race and UI-readiness coverage.

Merge-risk options

Maintainer options:

  1. Refresh merge-result verification (recommended)
    Pause merge until the current-main GatewaySession interaction and complete exact-head required checks are verified.
  2. Accept the covered lifecycle risk
    After owner review, accept the token-ordering and session-handoff change based on the focused regressions and supplied Android evidence.

Technical review

Best possible solution:

Keep the single shared lifecycle-admission path and retained-session tail; merge only after its interaction with current main’s GatewaySession and all required exact-head checks are confirmed.

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

Yes, at source level: the focused regressions establish the controlled Stop, cleanup, re-enable, reconnect, and promotion interleavings against real GatewaySession and local WebSocket boundaries. A fresh current-main replay was not run in this read-only review.

Is this the best way to solve the issue?

Unclear for the final merge result: the repair is the right owner-boundary shape and addresses the prior rank-up path, but current main changed GatewaySession after the PR base and that source could not be inspected locally.

AGENTS.md: found and applied where relevant.

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

Labels

Label justifications:

  • P1: A stale secondary credential or incorrect Gateway handoff affects active Android connection workflows.
  • merge-risk: 🚨 auth-provider: The patch changes when accepted operator device tokens may be read, persisted, and cleared.
  • merge-risk: 🚨 session-state: The patch changes primary and secondary Gateway session retirement and promotion ordering.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🌊 off-meta tidepool and patch quality is 🦐 gold shrimp.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: The PR is member-authored, so the external-contributor proof gate does not apply; its supplied body nevertheless describes exact-head packaged Android lifecycle evidence. Artifact retrieval was unavailable to this reviewer and does not require contributor action.

Evidence

What I checked:

  • Lifecycle admission repair: The introduced reconciliation path serializes background starts, reads credentials outside the lifecycle monitor, then revalidates intent, registry, discovery, and enabled state before connecting. (apps/android/app/src/main/java/ai/openclaw/app/NodeRuntime.kt:3373, ffe31f51d19b)
  • Ordered session-tail contract: GatewaySession exposes disconnectAndJoin for ordered cleanup; accepted device tokens are persisted during successful connection processing, so the new joins cover the writer that cleanup must not race. (apps/android/app/src/main/java/ai/openclaw/app/gateway/GatewaySession.kt:456, ffe31f51d19b)
  • Boundary regression coverage: Six introduced scenarios cover Stop→secondary auth read, Stop→Forget/reset during accepted-token persistence, secondary re-enable, primary reconnect, and secondary-to-primary promotion. They use real GatewaySession calls and a local WebSocket fixture while instrumenting SharedPreferences ordering. (apps/android/app/src/test/java/ai/openclaw/app/NodeForegroundServiceTest.kt:616, ffe31f51d19b)
  • Related lifecycle history: The merged Android ownership refactor is an ancestor of this PR’s pinned base, establishing it as related historical context rather than a replacement for this focused repair. (6031d67aa2d1)
  • Current-main and release check: The PR head is not contained in fetched main or v2026.8.2. Main changed GatewaySession after the pinned base; its promised blob could not be read locally, so the exact merge-result contract was not independently inspected. (apps/android/app/src/main/java/ai/openclaw/app/gateway/GatewaySession.kt, 85d510c13526)
  • Exact-head CI context: The supplied check rollup records success for Android build, ktlint, Play/third-party/Wear tests, and ci-gate on the head, but is marked incomplete and truncated; it does not establish that all required checks have completed. (ffe31f51d19b)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rank-up moves

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

  • Refresh the merge-result review against current main’s GatewaySession change.
  • Confirm all required checks complete green on the exact head.

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.

History

Review history (4 earlier review cycles)
  • reviewed 2026-09-03T16:11:26.118Z sha e5e8a2f :: blocked before merge. :: none
  • reviewed 2026-09-03T16:24:13.710Z sha e5e8a2f :: blocked before merge. :: none
  • reviewed 2026-09-03T16:42:59.353Z sha b3ff0d5 :: blocked before merge. :: [P1] Join the retired secondary session before reusing it
  • reviewed 2026-09-03T17:27:24.520Z sha ffe31f5 :: blocked before merge. :: none

@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Sep 3, 2026
Compose waitUntil advances its clock but does not drain the Robolectric main queue that owns ViewModel state bridges. Evaluate the four bridge predicates through runOnIdle while preserving their deadlines and layout assertions. Controlled composer and natural question readiness failures now pass; all 30 affected layout cases and app ktlint pass.
@steipete

steipete commented Sep 3, 2026

Copy link
Copy Markdown
Contributor Author

The requested packaged Android proof and rank-up evidence are now in the PR body: inspected before/after captures, exact APK/source hashes, and 19 accepted normal two-Gateway observations covering Stop, hot reopen, enablement, and Stop→Forget→Reconnect without restoring the forgotten route. Held local token-write races remain explicitly scoped to the real-session regression tests; they are not claimed as packaged fault injection.

A test-only follow-up also fixes the full Play CI failure. Controlled producer-ready/ViewModel-not-ready reproduction and a natural question-fixture failure both pass after draining Android Main before reading the same readiness predicates. All 30 affected layout tests and independent review pass, with unchanged deadlines/assertions and no production changes from the live-tested APK. The final-head CI run is in progress.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Sep 3, 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 exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed 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 Sep 3, 2026
Join accepted credential writes before secondary reconnect, primary reconnect after Stop, and secondary-to-primary promotion. Reuse the primary switch admission instead of a separate target-preparation path.

Verify real wire credentials and final token ordering in three causal regressions. Preserve bootstrap assertions while waiting for asynchronous connection completion. Validated 265 focused tests, all Android ktlint modules, changed-file checks, and independent review.
@clawsweeper clawsweeper Bot added status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Sep 3, 2026
@steipete steipete changed the title fix(android): secondary connections survive Stop and credential cleanup fix(android): order gateway shutdown and credential reuse Sep 3, 2026
@steipete
steipete merged commit 0bc6bdc into main Sep 3, 2026
153 checks passed
@steipete

steipete commented Sep 3, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

@steipete
steipete deleted the codex/android-followup-status-20260903 branch September 3, 2026 18:04
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 4, 2026
…37389)

* fix(android): stop secondary sessions before clearing credentials

Retain stopped secondary session ownership so Forget and authentication reset join accepted token writes before clearing credentials. Reuse lifecycle admission for fleet starts and show Offline after intentional Disconnect without claiming pairing loss.

* test(android): drain UI state before layout readiness checks

Compose waitUntil advances its clock but does not drain the Robolectric main queue that owns ViewModel state bridges. Evaluate the four bridge predicates through runOnIdle while preserving their deadlines and layout assertions. Controlled composer and natural question readiness failures now pass; all 30 affected layout cases and app ktlint pass.

* fix(android): drain connection owners before gateway reuse

Join accepted credential writes before secondary reconnect, primary reconnect after Stop, and secondary-to-primary promotion. Reuse the primary switch admission instead of a separate target-preparation path.

Verify real wire credentials and final token ordering in three causal regressions. Preserve bootstrap assertions while waiting for asynchronous connection completion. Validated 265 focused tests, all Android ktlint modules, changed-file checks, and independent review.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

app: android App: android maintainer Maintainer-authored PR merge-risk: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. 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. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: L 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.

Android secondary connections outlive Disconnect and credential cleanup

1 participant