Skip to content

refactor(ios): one phase per gateway session with a sticky shared pause - #197212

Merged
obviyus merged 4 commits into
mainfrom
refactor/ios-connection-phases
Nov 11, 2026
Merged

obviyus merged 4 commits into
mainfrom
refactor/ios-connection-phases

Conversation

@obviyus

@obviyus obviyus commented Nov 11, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

The iOS app stored the focused Gateway's connection condition in about ten separately written fields on NodeAppModel (gatewayConnected, operatorConnected, gatewayServerName, gatewayRemoteAddress, node/operator problems, pairing flags, and the pause meaning of gatewayAutoReconnectEnabled). Fields that must agree were written one by one at many sites, so some paths recorded a pause without pausing. Still on main:

  • An operator-side auth pause (rate limit, rejected credentials) recorded the problem but did not stop reconnecting (applyOperatorGatewayConnectionProblem).
  • A node success turned reconnect back on unconditionally, which undid an operator pause.
  • Pause exits differed per loop (break, return, continue), and Talk/Watch inferred "paused" from operatorGatewayTask == nil.

The result: against a locked Gateway the app keeps hitting it, which extends the lockout.

Solution

Stage 1 of a one-owner design for connection state:

  • Each session (node, operator) has one GatewaySessionPhase: idle, connecting, connected, or paused(problem). apply(event, to:route:) is the only live writer. It drops events from a superseded route and ignores live events in fixture mode.
  • A pausing problem (pauseReconnect or pairing approval) moves that session to .paused. The pause is sticky: socket drops, loop exit and the other session connecting don't lift it. Only an explicit user action, a new connect, or disconnect/forget does.
  • canAutoReconnect (user intent, no paused session, no pausing preconnect problem) gates both loops and every automatic reconnect path (lease, restoration, foreground, push wake, Watch, registration refresh). Both loops wait while paused instead of exiting.
  • Connected, server, address, admin scope and per-session problems are now computed from the phases; the stored copies are deleted, along with credentialHandoffFailureGeneration and setOperatorConnected.
  • Background ticks (Talk permission poll, onboarding pairing ticker) resume only what they own; they no longer lift a rate-limit pause.

Unchanged and out of scope (later stages): status text and GatewayStatusBuilder derivation, renaming gatewayAutoReconnectEnabled, the persisted gateway.autoconnect launch toggle, Talk's admission edge.

Impact

When the Gateway locks the device out, or rejects its credentials, the app stops retrying on both connections and keeps the banner until the user taps Retry. Normal connect, reconnect after a Gateway restart, and pairing behave as before.

Evidence

Lockout on a real Gateway (iOS 27 simulator, throwaway password-auth Gateway with the loopback limiter on)

Recipe: pair by manual host + password, lock the address with 11 wrong-password calls (limit is 10/min, 5 min lock), then change the Gateway password so the app's stored credential is also rejected. Count the app's rejected handshakes in the Gateway log for 3 minutes.

Flow Build Node rejections Operator rejections
Onboarding success screen main 1 10 (backoff 2 s → 30 s, never stops)
Onboarding success screen this PR 1 1
Main app (chat) main 2 2
Main app (chat) this PR 2 2

With this PR, both connections stop and the app shows "Too many failed attempts" with Wait and retry. Nothing reached the Gateway while the app was paused. After the lock expired, tapping Wait and retry reconnected both node and operator in about 0.3 s (app diagnostics: gateway connected / operator gateway connected).

An earlier build of this branch also showed the onboarding pairing ticker retrying every 6 s on both roles through a rate limit. Fixed: automatic pairing resume now runs only while a session is paused for pairing approval.

Physical iPhone (iPhone 17, iOS 27.2, Wi-Fi, isolated password-auth Gateway)

Paired by QR, then removed the device's pairing on the Gateway so its stored credential is rejected (password_mismatch).

Bug found on the device with the previous head (b990dd8): the node stopped after one attempt, but the operator kept reconnecting at 1, 2, 4, 8, 16, 30, 30… s. The app's diagnostics showed only operator gateway disconnected … connect failed and never the operator loop's own connect error line. So the retries came from GatewayChannel's internal reconnect, which judges this rejection recoverable and bypassed the app's pause. That same backoff caused the 10 operator rejections on main in the onboarding simulator run.

Fix (fix(ios): a pause stops the socket watchdog of every unconnected session): apply is the single writer. While any session is paused, it disconnects every session that is not connected; a connected session keeps its socket. This replaces the two per-loop disconnects. Test a dropped node stays down while the operator is paused fails without the fix (server.roles == ["node"]: the watchdog reconnected) and passes with it. 456 tests in 5 affected suites pass.

Device run with the fix:

Time Phone handshakes (Gateway log)
21:33:09 app launch node ×1, operator ×1 (password_mismatch)
21:33:09 → 21:36:18, including background → foreground → lock → unlock none
21:36:42 user re-scans a fresh setup QR node client connected, operator client connected

The banner stayed visible throughout, and nothing retried until the user acted.

Tests

  • New GatewaySessionPauseTests:
    • same config connect restarts a paused route: red on base (the paused loop had exited, Still waiting for node connected after retry).
    • node reconnect does not lift an operator pause, resume restarts reconnect attempts after a pause: red on base.
    • operator-only resume keeps a node pause, stale route events are dropped.
    • credential handoff pause survives node loop exit: passes on base too (base used credentialHandoffFailureGeneration, deleted here), so it guards that deletion.
  • Affected suites: ✔ Test run with 461 tests in 6 suites passed (GatewaySessionPause, GatewayConnectionController, NodeAppModelInvoke, TalkModeManager, OnboardingStateStore, GatewayConnectionSecurity) on the final head; an earlier 14-suite run (614 tests) before the last review round. swiftformat --lint clean.
  • Reviews: two headless code-review passes by a second model against the design; all findings applied (preconnect check no longer resumes the old route; Talk poll/cancel resume only the operator; preconnect failures don't write a session phase; QR-scan cancel restores a route whose operator alone was paused; onboarding retry no longer sends two pairing connects).

Not covered

  • The onboarding pairing-ticker guard is private view logic with no test seam; covered by the simulator run above.
  • Talk permission upgrade and target-review restore were not re-driven on a device or simulator; covered by existing GatewayConnectionControllerTests/TalkModeManagerTests.

Size

Production +304/−274 (adds the phase type and its one writer; deletes 9 stored fields, credentialHandoffFailureGeneration, setOperatorConnected, clearOperatorGatewayConnectionProblemIfCurrent and the pairing flags). Tests +273/−137, including the new GatewaySessionPauseTests.swift.

@clawsweeper

clawsweeper Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
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 clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. 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 clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Nov 11, 2026
@clawsweeper

clawsweeper Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR consolidates iOS Gateway connection state into session phases and makes either session’s authentication pause stop automatic reconnects.

Example: An iPhone receives password_mismatch from its Gateway.

  • Before: The operator socket keeps retrying with increasing backoff after the node stops.
  • After: Both disconnected sessions remain paused until the user retries or scans fresh credentials.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) The focused repair has shipped-entry-point evidence, meaningful transport regressions, and no remaining actionable finding; exact-head CI is still pending.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (logs): The real iOS app and Gateway handshake traces exercise credential rejection, sustained pause through lifecycle transitions, and successful user-triggered recovery; simulator evidence additionally covers lockout and Wait and retry, while the unrelated downloaded screenshot contributes no pause proof.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: The iOS client can continue rejected Gateway handshakes after authentication should have paused reconnecting.
Reason: The maintainer-authored direction fixes observed behavior through an existing owner without adding configuration, changing persisted formats, or expanding permissions.

Merge readiness

✅ Ready for maintainer review

Keep this PR open: it addresses a verified iOS reconnect defect, and the current head resolves the previous findings and merge conflict without introducing an actionable defect.

Priority: P2
Reviewed head: c56edfae3727aed36681251f7eb78c90f401b988

Before merge

None.

Findings

None.

Agent review details

How this fits together

The iOS NodeAppModel coordinates node and operator Gateway sessions, translating connection callbacks and user actions into connection state, retry decisions, and presentation.

flowchart TD
  A[User actions and lifecycle events] --> B[NodeAppModel]
  B --> C[Session phases and shared pause]
  C --> D[Node and operator reconnect loops]
  D --> E[GatewayNodeSession transports]
  E --> F[Gateway]
  E --> B
Loading

Technical review

Best possible solution:

Keep connection phases and shared retry policy in NodeAppModel, with explicit recovery actions and transport watchdog shutdown governed by that owner.

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

The current-main pause gap is source-verifiable, and the contributor supplies controlled simulator and physical-device reproductions against a real Gateway; this read-only review executed no target code.

Is this the best way to solve the issue?

The phase representation is a justified consolidation inside the existing lifecycle owner, removes competing stored projections, and addresses both application-loop and socket-watchdog retries.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Shared authentication pause keeps the original intent (0409efb: The earlier repair stopped node retries when its error echoed the operator’s rate limit; this PR preserves that outcome through shared phase-derived admission.)
  • Readable error history and owner-specific pairing keeps the original intent (3261667: Retain the previous error during same-target retries while separating presentation history from live pairing control.)
  • Pairing resume lifecycle keeps the original intent (fc65f70: Pause pairing churn and clear sticky approval state during explicit recovery; the replacement connect now owns clearing the phase to avoid duplicate attempts.)
  • Operator authority invalidation keeps the original intent (ef26537: Privileged native and embedded requests must notice operator authority loss even when observation coalesces a reconnect.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Pinned introduction and complete cutover: The introduced diff replaces independently writable connection fields with session phases, derives existing projections, migrates callers, and centralizes watchdog shutdown in the existing NodeAppModel owner. (apps/ios/Sources/Model/NodeAppModel.swift:3795, c56edfae3727)
  • Current-main defect remains: Current main records operator problems but only applies its shared pairing flag for approval problems; it does not enforce the same pause for rejected credentials. The narrower node-side repair in fix(ios): stop node retries while the Gateway rate-limits auth #196796 does not replace this work. (apps/ios/Sources/Model/NodeAppModel.swift:3808, 56eb6f3fe2e6)
  • Previous behavioral findings resolved: Talk polling resumes only operator pairing pauses, while onboarding automatic retry requires every live pause to concern pairing; a credential or rate-limit pause on either role blocks that retry. (apps/ios/Sources/Onboarding/OnboardingWizardView.swift:1097, c56edfae3727)
  • Real device and Gateway evidence: The contributor’s refactor(ios): one phase per gateway session with a sticky shared pause #197212 (comment) records initial rejected handshakes, no further handshakes through background/foreground and lock/unlock, and successful node/operator connections after scanning a fresh QR code. The body also records simulator lockout and explicit retry recovery. The prepared image was inspected and concerns the separate deep-link change, so it was excluded from pause proof. (c56edfae3727)
  • Conflict resolved; CI still pending: GitHub reports the reviewed head as mergeable, resolving the prior conflict blocker. The exact-head CI gate remains pending, with no failed check observed; security-sensitive review reports no sensitive product changes. (c56edfae3727)
  • Historical intent and review limits: History across Gateway and earlier Bridge paths identifies longstanding pairing, error-retention, scope-upgrade, and reconnect ownership. The earlier reviewed d5a30a2 object is unavailable locally, so no patch-identical comparison or late-finding attribution is claimed; prior findings were checked against current source and discussion. (apps/ios/Sources/Model/NodeAppModel.swift:3941, 56eb6f3fe2e6)

Likely related people:

  • Peter Steinberger: Raw commit 3261667 adds apps/ios/Sources/Model/NodeAppModel.swift:3844 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 3261667b7384; files: apps/ios/Sources/Model/NodeAppModel.swift)
  • joshavant: Raw commit 1746319 adds apps/ios/Sources/Model/NodeAppModel.swift:2056 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 1746319db566; files: apps/ios/Sources/Model/NodeAppModel.swift)
  • Mariano: Raw commit 130e59a adds apps/ios/Sources/Onboarding/OnboardingWizardView.swift:672 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 130e59a9c096; files: apps/ios/Sources/Onboarding/OnboardingWizardView.swift)

PR surface

Source +52, Tests +199. Total +251 across 14 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 4 333 281 +52
Tests 10 337 138 +199
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 14 670 419 +251

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Review metrics

Metric Value Why it matters
Production versus test changes Production +333/−281; tests +337/−138. The production growth replaces independently writable state with one transition owner; test growth covers pause recovery, stale routes, watchdog shutdown, and affected consumer contracts.

Labels

Label changes:

  • add rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove rating: 🐚 platinum hermit: Current PR rating is rating: 🦞 diamond lobster, so this older rating label is no longer current.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P2: This fixes unwanted authentication retries in the iOS client while retaining an explicit in-product recovery action.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

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.

History

Review history (4 earlier review cycles)
  • reviewed 2026-11-11T12:39:11.366Z sha 25d612f :: needs changes before merge. :: [P2] Restrict Talk polling to pairing-approval pauses
  • reviewed 2026-11-11T15:51:25.451Z sha b990dd8 :: needs changes before merge. :: [P2] Preserve non-pairing pauses during automatic onboarding retries
  • reviewed 2026-11-11T16:13:58.370Z sha 72cb104 :: needs changes before merge. :: [P2] Preserve non-pairing pauses during automatic onboarding retries
  • reviewed 2026-11-11T17:39:44.798Z sha d5a30a2 :: needs changes before merge. :: none

Reviewed November 11, 2026, 5:52 PM ET / 22:52 UTC (Revision 5).

@obviyus

obviyus commented Nov 11, 2026

Copy link
Copy Markdown
Collaborator Author

Fixed the Talk polling finding: the poll now resumes the operator only while it is paused for pairing approval. New test Talk approval polling resumes pairing pauses but not rate limits fails without the guard (!appModel.canAutoReconnect at the rate-limit step) and passes with it (269 tests in NodeAppModelInvokeTests + GatewaySessionPauseTests).

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. proof: sufficient ClawSweeper judged the real behavior proof convincing. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Nov 11, 2026
@obviyus

obviyus commented Nov 11, 2026

Copy link
Copy Markdown
Collaborator Author

Physical iPhone proof (iPhone 17, iOS 27.2, Wi-Fi, isolated password-auth Gateway)

Paired by QR, then removed the device's pairing on the Gateway so its stored credential is rejected (password_mismatch).

Bug found on the device with the previous head (b990dd8): the node stopped after one attempt, but the operator kept reconnecting at 1, 2, 4, 8, 16, 30, 30… s. The app's diagnostics showed only operator gateway disconnected … connect failed and never the operator loop's own connect error line. So the retries came from GatewayChannel's internal reconnect, which judges this rejection recoverable and bypassed the app's pause. That same backoff caused the 10 operator rejections on main in the onboarding simulator run.

Fix (fix(ios): a pause stops the socket watchdog of every unconnected session): apply is the single writer. While any session is paused, it disconnects every session that is not connected; a connected session keeps its socket. This replaces the two per-loop disconnects. Test a dropped node stays down while the operator is paused fails without the fix (server.roles == ["node"]: the watchdog reconnected) and passes with it. 456 tests in 5 affected suites pass.

Device run with the fix:

Time Phone handshakes (Gateway log)
21:33:09 app launch node ×1, operator ×1 (password_mismatch)
21:33:09 → 21:36:18, including background → foreground → lock → unlock none
21:36:42 user re-scans a fresh setup QR node client connected, operator client connected

The banner stayed visible throughout, and nothing retried until the user acted.

@obviyus

obviyus commented Nov 11, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Nov 11, 2026
@obviyus

obviyus commented Nov 11, 2026

Copy link
Copy Markdown
Collaborator Author

Fixed the mixed-pause finding. The decision is now one property on the connection state, GatewayConnection.isPausedOnlyForPairing: every live pause must be a pairing approval. The onboarding ticker uses it, so a rate limit or rejected credential on either session blocks the automatic retry. Test automatic pairing retry waits while a credential pause is live covers pairing+connecting, pairing+pairing, pairing+rate limit (blocked), a rate limit alone (blocked), and no pause.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added the clawsweeper:intake:bug Preliminary submission classification; full source review pending. label Nov 11, 2026
@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Nov 11, 2026
@openclaw-barnacle openclaw-barnacle Bot reopened this Nov 11, 2026
@openclaw-barnacle openclaw-barnacle Bot reopened this Nov 11, 2026
@obviyus
obviyus force-pushed the refactor/ios-connection-phases branch from d5a30a2 to c56edfa Compare November 11, 2026 22:46
@obviyus

obviyus commented Nov 11, 2026

Copy link
Copy Markdown
Collaborator Author

Rebased on main to resolve the conflict. The only conflict was the retired-key deep-link test that #197172 added on main; it now marks the node connected through apply(.connected…) instead of the deleted stored field. 463 tests across the 6 affected suites pass on the rebased head.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Nov 11, 2026
@obviyus
obviyus merged commit 20a8d6d into main Nov 11, 2026
81 checks passed
@obviyus
obviyus deleted the refactor/ios-connection-phases branch November 11, 2026 23:19
@obviyus

obviyus commented Nov 11, 2026

Copy link
Copy Markdown
Collaborator Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 12, 2026
…se (openclaw#197212)

* refactor(ios): one phase per gateway session with a sticky shared pause

* fix(ios): Talk approval polling resumes only pairing pauses

* fix(ios): a pause stops the socket watchdog of every unconnected session

* fix(ios): automatic pairing retry waits while a credential pause is live
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

app: ios App: ios P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor 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.

1 participant