Skip to content

fix(macos): keep gateway windows on their selected connections - #137089

Merged
steipete merged 6 commits into
mainfrom
codex/mac-gateway-window-ownership
Sep 3, 2026
Merged

steipete merged 6 commits into
mainfrom
codex/mac-gateway-window-ownership

Conversation

@steipete

@steipete steipete commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Closes #136940

What Problem This Solves

Fixes an issue where users working with several Gateways in the macOS app could keep a dashboard on an obsolete Primary route, send native commands to the wrong window, or render another Gateway’s widget inside a chat. Changing Primary could retain the previous password, while secondary chats could overwrite the primary session and activity state. Closing or switching windows also left pending opens, transport work, and observers alive. Intentional control-channel disconnect scheduled automatic recovery, allowing retired work to restart a local Gateway.

Why This Change Was Made

Gateway ownership now stays with the connection and native window that admitted the work. Every dashboard targeting Primary follows the current primary route; saved-profile windows remain independent, including a second window for a profile that another window promotes to Primary. Profile existence comes from the profile store, independently of picker deduplication.

Each native window owns its pending selection and ordered commands across document replacement. Explicit selection, profile removal, and close retire obsolete actions; reconnect and credential refresh preserve current actions. Recovery cannot overwrite a pending picker selection, and an obsolete Primary presentation cannot blank the newly selected dashboard with a late error.

Primary replacement commits the complete URL/token/TLS configuration and clears the previous password before publishing the selection. Native chat closes its old transcript owner before accepting a different primary route, uses the existing shared detachTransport lifetime operation, and retires profile observers when their connection ends. Widgets use their own operator connection. The control channel cancels its event listener and recovery work on intentional disconnect; delayed endpoint and tunnel work retain their admitted generation. The endpoint store owns SSH tunnel completion and publication independently of any individual waiting task, so cancelling a retired waiter cannot strand an otherwise successful replacement tunnel. Unexpected endpoint failure still recovers. Only the primary control-channel consumer updates global session activity. Each admitted connection adopts its activity once, so delayed duplicate hello notifications cannot erase work already received from that connection.

Queued events now retain their physical Gateway connection and endpoint revision through consumer execution. A selection change immediately invalidates old payloads; exact-source retirement receipts clear only the old connection’s state. Delayed appearance responses cannot repaint the new Gateway. Approval rows, modal decisions, pairing cards, list replies, and automatic pairing probes retain the same source ownership, so a retained A action cannot resolve a same-ID request on B. Pending command and system-agent approvals automatically reload after each admitted connection through their existing advertised list APIs; intervening approval events trigger a fresh authoritative list pass so unresolved cards cannot disappear; a temporary failure preserves a still-current unresolved card. Voice Wake reloads settings after a new Primary handshake or reconnect and rejects retired read results. Pairing SSH checks use the active SSH target or discovery matching the connected Gateway, never a dormant target from another Gateway.

User Impact

Operators can keep several Gateways open, switch and promote them, and refresh their credentials without mixing connections, sessions, widgets, queued commands, or approval decisions. No configuration keys, database schemas, protocol versions, or dependencies change.

Evidence

Regression-first macOS VM runs reproduced stale Primary dashboards, credential replacement, close/open races, late chat history, retained profile observers, secondary activity contamination, and the picker/reconnect/command cases. The failing scenarios also showed a removed profile’s queued command running on Primary, a superseded Primary open blanking the selected profile, and menu/bridge opens surviving a close before task execution.

  • Final application source at b2438071c0d3: 2,007 native tests across 205 suites passed at CI's parallelization width 8, in the original execution order (65.171 seconds). The separate named-profile lane passed both tests. SwiftFormat, strict SwiftLint, docs checks, and strict macOS Periphery passed.
  • Shared chat siblings: 653 Swift Testing cases across 16 suites plus 20 attachment XCTest cases passed on the rebased baseline; the shared source is unchanged since that run.
  • Independent review of the full production candidate completed in six passes without accepted/actionable P0–P2 findings. The final Control/tunnel correction passed a separate two-pass review. The iOS-shared fixture correction passed another independent review and changes no application code.

The full native run exposed test isolation problems as well as the recovery bug. A buffered event fixture inherited Local process ownership and started a real recovery operation that contaminated a later readiness assertion. That fixture now owns and retires its process context explicitly; dedicated recovery tests and readiness assertions remain intact. A notification test now admits its action in the same MainActor operation that chooses focus. Hosted iOS compilation also caught a Mac-only helper in the shared WebSocket fixture; the unchanged helper moved to its Mac test owner.

Hosted macOS CI exposed an existing onboarding retry fixture that checked completion after a fixed 100 ms sleep. Holding the second response reproduced five premature assertions across the failed-verification and successful-retry cases; releasing it produced the expected results. Both cases now control that response and await the existing observable terminal state. Their exact outcome, busy-state, activation-lease and request-count assertions remain intact. The two repaired tests passed in 0.028 seconds with no production change. The signed de0ce19450f8 live proof above covers the same application source; the later change affects only this test fixture.

Additional failing-before cases reproduced queued A events reaching B’s activity, duplicate hello clearing current work, A appearance success/failure overwriting B, retained node/device pairing decisions reaching B, cross-kind pairing ID suppression, and direct B checking A’s dormant SSH target. Both real Gateway processes advertised and successfully served the existing system-agent approval-list API. Mock event/decision regressions and real-server live checks are recorded separately.

A Developer ID-signed Cocoa host exercised the actual native approval presenter over deterministic A/B WebSocket fixtures. The retained A dialog was denied after source replacement; the B dialog was allowed once. Throwing assertions confirmed exactly one resolution RPC, addressed to B with allow-once, and no redirected A decision. The host completed successfully. Separate failure-first regressions cover automatic reconnection with the menu kept open and approval events arriving during the initial list.

The signed baseline visibly reproduced Gateway B’s chat rendering Gateway A’s widget. The ordered synthetic traffic was A node admission, B chat history, then A widget HTTP retrieval. The final Developer ID-signed app at de0ce19450f8 rendered B’s widget through B’s operator connection while A’s node remained active. The fixture recorded A node admission, B chat history, and then B widget HTTP retrieval, with no A widget request.

The same signed app connected to two real, authenticated Gateway processes through native Settings, opened independent native chats and four dashboards, then promoted A followed by B. All three Primary dashboards followed B. The saved A dashboard stayed on A and read A’s task-owned automation; a Primary B window read B’s distinct automation. A’s saved dashboard kept its original WebSocket throughout promotion. The original A/B native chat sockets and green connected indicators remained intact. No provider/model turn was invoked.

An actual SSH recovery check then terminated only the app-owned forwarding process. The unchanged app created a new forward in the next wall-clock second and returned from degraded to connected in 588 ms, without Test remote, manual reconnect, a selection change, or an external Gateway probe. Logs show the replacement tunnel becoming ready, the retired recovery waiter cancelling, and the endpoint-change consumer connecting successfully. The real Gateway processes remained running. Task-only SSH keys, host trust, listener, and forwarding processes were cleaned up afterwards. The expected cancelled waiter still emits an error-level diagnostic; the adjacent Control-channel owner follow-up will remove that misleading line.

Before: Gateway B chat incorrectly renders Gateway A widget

After: final signed app renders Gateway B’s own widget

Saved Gateway A remains selected after Gateway B becomes Primary

Production +1630/−1120 (net +510); tests/test support +2727/−381 (net +2346); docs +18/−6. The raw production churn includes an unchanged 52-line Cron API move; discounting that move does not change the net growth. The production growth records native-window selection lifetime, primary transcript retirement, and the physical connection ownership required for buffered events, approval decisions, pairing checks, and settings publication. These facts must survive queued UI work and asynchronous replies; checking only the current selection at dispatch cannot preserve their origin. It replaces duplicate command queues, configuration rollback, per-waiter tunnel publication, and the primary-node widget fallback. The final Control/tunnel correction removes 13 production lines. The shared model change is five cancellation lines on top of #136702's existing detach operation.

ClawSweeper rank-up work is covered by the preserved current-main stale-read cancellation and revision-aware endpoint admission, combined native and dead-code checks, the final signed-app widget/A–B/SSH proofs above, and production-growth accounting that discounts the unchanged Cron API move. Exact-head CI remains the merge gate.

Adjacent repairs are tracked separately: native Cron row/editor/read ownership (including a signed-app A-editor save dispatched to B), Skills/ClawHub retained actions and catalog ownership, shared Health/Instances/Nodes and usage/cost publication, and Channels/config draft/login ownership. These legacy panes are reachable through the existing Settings > Debug > Show native settings panes option; the default dashboard flow is tested separately. This PR only adapts their event subscriptions where required by the shared delivery contract.

@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 docs Improvements or additions to documentation app: macos App: macos size: XL maintainer Maintainer-authored PR labels Sep 3, 2026
@steipete
steipete marked this pull request as ready for review September 3, 2026 06:27
@steipete steipete self-assigned this Sep 3, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. 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, 9:25 AM ET / 13:25 UTC.

ClawSweeper review

What this changes

This PR makes each macOS dashboard, chat window, queued action, and recovery path retain its selected Gateway ownership while Primary windows follow Primary changes and saved-profile windows remain isolated.

Merge readiness

⛔ Blocked before merge - 3 items remain

No actionable introduced P0–P2 defect was found in the reviewed macOS ownership, recovery, approval, and window-lifetime paths. The PR remains necessary for the linked stale-Primary-dashboard bug, but exact-head macOS checks must finish successfully before merge.

Priority: P2
Reviewed head: 958297dff60d4f068c32ec5ffecda5e6eafef9ff

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The patch uses coherent owner-boundary fencing and substantial focused coverage, with remaining merge readiness limited to the unfinished exact-head native checks.
Proof confidence 🌊 off-meta tidepool Not applicable: This is a maintainer-authored PR; supplied review context reports signed-app A/B Gateway, saved-profile isolation, and SSH-recovery evidence, so no contributor proof action is required.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: This is a maintainer-authored PR; supplied review context reports signed-app A/B Gateway, saved-profile isolation, and SSH-recovery evidence, so no contributor proof action is required.
Evidence reviewed 9 items Primary dashboard reconciliation: The changed owner selects every open controller targeting Primary, updates or replaces it when route or credentials change, and deliberately excludes saved-profile targets.
Prior behavior and introduced repair: The merge-base implementation returned when the main dashboard displayed a saved profile and reconciled only its single controller; the PR changes that introduced behavior to reconcile all Primary-targeted windows.
Lease-bound delivery and retirement: Gateway deliveries carry a physical server lease and current-owner predicate; retirement emits source-bound cleanup that a replacement connection invalidates.
Findings None None.
Security None None.

How this fits together

The macOS app maintains a Primary Gateway plus optional saved Gateway profiles for native dashboards and chats. Endpoint updates feed window reconciliation, connection lifecycle, approvals, activity state, and operator widgets without allowing a stale connection to affect a replacement route.

flowchart LR
  A[Gateway endpoint update] --> B[Primary route reconciliation]
  B --> C[Primary dashboard windows]
  B --> D[Primary chat and activity state]
  E[Saved Gateway profile] --> F[Independent dashboard and chat]
  D --> G[Lease-bound control events]
  G --> H[Recovery and approval actions]
  F --> H
Loading

Before merge

  • Resolve merge risk (P1) - Exact-head macOS checks are still running or queued; the broad asynchronous lifecycle change should not merge until those checks succeed.
  • Resolve merge risk (P1) - The bug-fix diff adds 1,630 and removes 1,120 production lines (net +510); its ownership-boundary rationale is plausible, but this material growth warrants maintainer visibility before landing.
  • Complete next step (P2) - Wait for the required exact-head macOS checks to complete successfully before merging.
Agent review details

Security

None.

PR surface

Docs +12, Other +2856. Total +2868 across 58 files.

View PR surface stats
Area Files Added Removed Net
Source 0 0 0 0
Tests 0 0 0 0
Docs 2 18 6 +12
Config 0 0 0 0
Generated 0 0 0 0
Other 56 4357 1501 +2856
Total 58 4375 1507 +2868

Review metrics

Metric Value Why it matters
Production versus test delta production +1,630/-1,120 (net +510); tests/support +2,727/-381; docs +18/-6 The repair is a material owner-boundary refactor, so its production growth needs deliberate merge review despite extensive regression coverage.
Affected files 58 files changed The change spans dashboards, shared Gateway lifecycle, approvals, chat windows, activity state, tests, and macOS documentation.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #136940
Summary: This PR is the candidate owner-boundary repair for the stale Primary-dashboard route issue.

Members:

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

Merge-risk options

Maintainer options:

  1. Complete exact-head native verification (recommended)
    Wait for the queued and running exact-head macOS checks to pass before merging this route, credential, and lifecycle refactor.

Technical review

Best possible solution:

Land the lease- and generation-owned model only after exact-head macOS verification succeeds, preserving Primary followers and saved-profile isolation.

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

Yes—source comparison identifies the former single-main-window guard, and focused native tests encode deterministic endpoint replacement, stale-push, and independent-profile scenarios; this read-only review did not execute them.

Is this the best way to solve the issue?

Yes—the per-window and per-server-lease ownership model repairs the producer boundary; dispatch-time checks against the currently selected Gateway would leave queued work and stale deliveries able to cross a route replacement.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • remove rating: 🦐 gold shrimp: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.

Label justifications:

  • P2: This fixes incorrect multi-window macOS Gateway routing with a bounded but meaningful operator impact.
  • merge-risk: 🚨 compatibility: Replacing Primary credentials and routes changes how existing dashboard windows reconnect and authenticate.
  • merge-risk: 🚨 session-state: The PR deliberately retires Primary chat and activity state while preserving independent saved-profile state across route changes.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: This is a maintainer-authored PR; supplied review context reports signed-app A/B Gateway, saved-profile isolation, and SSH-recovery evidence, so no contributor proof action is required.

Evidence

Acceptance criteria:

  • [P1] Await successful exact-head macOS CI for 958297d.

What I checked:

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.

  • Wait for exact-head macOS checks to complete successfully.

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 (6 earlier review cycles)
  • reviewed 2026-09-03T06:57:05.578Z sha 903c360 :: blocked before merge. :: none
  • reviewed September 3, 2026, 3:38 AM ET / 07:38 UTC sha unknown :: blocked before merge. :: none
  • reviewed 2026-09-03T10:31:07.378Z sha db1a3cc :: blocked before merge. :: none
  • reviewed 2026-09-03T11:13:01.506Z sha 9f6643f :: blocked before merge. :: none
  • reviewed 2026-09-03T12:10:20.309Z sha b243807 :: blocked before merge. :: none
  • reviewed 2026-09-03T12:30:03.291Z sha de0ce19 :: blocked before merge. :: none

@clawsweeper clawsweeper Bot added merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. labels Sep 3, 2026
Keep every Primary dashboard on the current primary route while saved-profile
windows retain independent connections. Bind selections and queued commands
to their native window, and retire stale presentations, opens, transports,
and observers when their owner changes or closes.

Replace the primary credential bundle atomically, isolate session/activity
state from secondary connections, and load native chat widgets through the
window's own operator connection. Preserve the canonical shared chat detach
operation and revision-aware endpoint admission.

Bind pushed state, approval decisions, pairing prompts, and voice-wake reads
to their admitted physical connection. Reconcile pending lists after source
changes without resurrecting resolved requests or hiding untouched requests.
Document the resulting multi-Gateway behavior.

Validated with regression-first native tests, shared chat tests, canonical
lint/format checks, and independent Codex review. Signed app A/B switching,
widget routing, and real native approval modal evidence are tracked in the PR.

Refs #136940.
Replace timing-dependent scheduled-task assertions with the old relay close, replacement create, successful microphone start, and final cleanup. Consolidate audio failure, input selection, and unpause cases while preserving stale-owner and retry-budget coverage.

Observed the original assertion fail under parallel native load after recovery consumed its task handle. All 28 focused native tests pass at width 8; independent Codex review is clean. No production behavior changes.
@steipete
steipete force-pushed the codex/mac-gateway-window-ownership branch from 903c360 to db1a3cc Compare September 3, 2026 10:22
Cancel control events and recovery on intentional disconnect, and fence queued endpoint work by its admitted generation. Let the shared SSH ensure operation own completion publication so canceled waiters cannot strand a replacement tunnel.

Keep native fixture process ownership explicit and admit notification focus before yielding. Regression-first endpoint and control cases pass; the full macOS VM default run passed 2007 tests, with both named-profile checks passing separately. Independent review found no remaining P0-P2 issues.
@clawsweeper clawsweeper Bot added rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Sep 3, 2026
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. labels Sep 3, 2026
@steipete

steipete commented Sep 3, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

The control/tunnel follow-up now makes intentional disconnect retire recovery, while the endpoint store owns replacement-tunnel publication independently of cancelled waiters. Full native proof passed 2,007 tests at CI width 8, with independent P0–P2 review clean.

The final signed app passed widget isolation, three Primary followers plus a retained saved A window against real A/B Gateways, and actual SSH-forward termination/recovery in 588 ms without manual reconnect. The PR body includes inspected screenshots and the observed behavior. The latest commit changes only two onboarding retry fixtures exposed by CI; controlled before/after proof and independent review passed, and application source is byte-identical to the signed live-tested commit.

@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: 🐚 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
@steipete

steipete commented Sep 3, 2026

Copy link
Copy Markdown
Contributor Author

Ready to land the window and connection ownership repair at 958297dff60d4f068c32ec5ffecda5e6eafef9ff.

Exact-head CI is green on attempt 2, including the required gate. The only first-attempt failure was an existing Android coroutine test timeout; rerunning that job passed without a source change. macOS, iOS, and shared-kit dead-code checks are also green. The latest ClawSweeper review found no actionable P0–P2 code issue; its remaining exact-head native-check requirement is satisfied.

The isolated signed app passed real A/B Gateway switching with three Primary followers, a retained saved-A window and native A/B chats, a B-owned widget while the Mac node stayed on A, and automatic SSH tunnel recovery after its forward was terminated. Application source is identical between that signed de0ce19450f81b746e2a8f6f317cabdd6ee45275 build and the final head; only the reviewed onboarding test synchronization changed. The complete native run passed 2,007 tests across 205 suites, plus the named-profile lane. Commands and inspected synthetic before/after captures are in the PR evidence.

The repair records ownership at the native window, physical connection, and endpoint-operation boundaries. That is why its net +510 production lines are justified: queued actions and buffered delivery cannot be repaired by checking only the currently selected Gateway downstream. Duplicate queues, stale intent state, and waiter-owned tunnel publication were removed. Current main at 79f0df31c8eb99ae4f93b2a03cba9ee1c76efc7d has no macOS/shared-app source changes since the reviewed main baseline. No new configuration, schema, protocol version, or dependency is introduced.

@steipete
steipete merged commit 2074e04 into main Sep 3, 2026
115 of 117 checks passed
@steipete
steipete deleted the codex/mac-gateway-window-ownership branch September 3, 2026 14:30
@steipete

steipete commented Sep 3, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

steipete added a commit that referenced this pull request Sep 4, 2026
Retire selected Gateway state before a replacement handshake, and carry
source ownership through status panes, config documents, Cron drafts and
skill actions. Same-Gateway reconnects retain valid durable intent; a
replacement cannot inherit it. Keep Config lookup failures actionable and
show independent ClawHub install acknowledgements and read failures.

Regression proof covers unavailable replacements, retained and reopened
panes, stale async work, cold Config acquisition, and source-scoped edits.
The final candidate passes 2,073 native tests plus the named isolation
suite, pinned lint/format gates, and independent correction review.

Follow-up to #137089. Release-note context: Mac Gateway switching now
clears stale settings/status immediately and prevents retained controls
from acting on another Gateway.
steipete added a commit that referenced this pull request Sep 4, 2026
* fix(macos): keep settings and edits on their selected gateway

Retire selected Gateway state before a replacement handshake, and carry
source ownership through status panes, config documents, Cron drafts and
skill actions. Same-Gateway reconnects retain valid durable intent; a
replacement cannot inherit it. Keep Config lookup failures actionable and
show independent ClawHub install acknowledgements and read failures.

Regression proof covers unavailable replacements, retained and reopened
panes, stale async work, cold Config acquisition, and source-scoped edits.
The final candidate passes 2,073 native tests plus the named isolation
suite, pinned lint/format gates, and independent correction review.

Follow-up to #137089. Release-note context: Mac Gateway switching now
clears stale settings/status immediately and prevents retained controls
from acting on another Gateway.

* fix(macos): distinguish gateway loading failures and redact diagnostics

Show Cron loading, errors, and confirmed empty results from the store owner.
Use one credential-safe endpoint formatter for Dashboard errors and logs.
Regenerate the native text inventory and preserve localized empty results.

Validation: failing-before/passing-after owner regressions, combined native
2077 tests plus named-profile checks, lint/format/docs, and independent review.

* fix(macos): keep config reads alive across view cancellation

Own shared config and schema reads in ChannelsStore so Source-driven SwiftUI task replacement cannot cancel the read used by other callers. Preserve queued Reload and dirty-draft semantics while removing unused schema reload state. Regression proof covers cancellation before dispatch, joining callers, and source retirement; full native validation passes 2078 tests.

* fix(macos): preserve cold gateway retry ownership
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 4, 2026
…law#137089)

* fix(macos): preserve gateway ownership across window switches

Keep every Primary dashboard on the current primary route while saved-profile
windows retain independent connections. Bind selections and queued commands
to their native window, and retire stale presentations, opens, transports,
and observers when their owner changes or closes.

Replace the primary credential bundle atomically, isolate session/activity
state from secondary connections, and load native chat widgets through the
window's own operator connection. Preserve the canonical shared chat detach
operation and revision-aware endpoint admission.

Bind pushed state, approval decisions, pairing prompts, and voice-wake reads
to their admitted physical connection. Reconcile pending lists after source
changes without resurrecting resolved requests or hiding untouched requests.
Document the resulting multi-Gateway behavior.

Validated with regression-first native tests, shared chat tests, canonical
lint/format checks, and independent Codex review. Signed app A/B switching,
widget routing, and real native approval modal evidence are tracked in the PR.

Refs openclaw#136940.

* test(macos): observe Talk recovery through its relay lifecycle

Replace timing-dependent scheduled-task assertions with the old relay close, replacement create, successful microphone start, and final cleanup. Consolidate audio failure, input selection, and unpause cases while preserving stale-owner and retry-budget coverage.

Observed the original assertion fail under parallel native load after recovery consumed its task handle. All 28 focused native tests pass at width 8; independent Codex review is clean. No production behavior changes.

* fix(macos): clean up gateway ownership and native validation

* fix(macos): retire control recovery with its gateway owner

Cancel control events and recovery on intentional disconnect, and fence queued endpoint work by its admitted generation. Let the shared SSH ensure operation own completion publication so canceled waiters cannot strand a replacement tunnel.

Keep native fixture process ownership explicit and admit notification focus before yielding. Regression-first endpoint and control cases pass; the full macOS VM default run passed 2007 tests, with both named-profile checks passing separately. Independent review found no remaining P0-P2 issues.

* test(macos): keep activity fixtures out of the iOS target

* test(macos): await onboarding retry completion
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 4, 2026
…7502)

* fix(macos): keep settings and edits on their selected gateway

Retire selected Gateway state before a replacement handshake, and carry
source ownership through status panes, config documents, Cron drafts and
skill actions. Same-Gateway reconnects retain valid durable intent; a
replacement cannot inherit it. Keep Config lookup failures actionable and
show independent ClawHub install acknowledgements and read failures.

Regression proof covers unavailable replacements, retained and reopened
panes, stale async work, cold Config acquisition, and source-scoped edits.
The final candidate passes 2,073 native tests plus the named isolation
suite, pinned lint/format gates, and independent correction review.

Follow-up to openclaw#137089. Release-note context: Mac Gateway switching now
clears stale settings/status immediately and prevents retained controls
from acting on another Gateway.

* fix(macos): distinguish gateway loading failures and redact diagnostics

Show Cron loading, errors, and confirmed empty results from the store owner.
Use one credential-safe endpoint formatter for Dashboard errors and logs.
Regenerate the native text inventory and preserve localized empty results.

Validation: failing-before/passing-after owner regressions, combined native
2077 tests plus named-profile checks, lint/format/docs, and independent review.

* fix(macos): keep config reads alive across view cancellation

Own shared config and schema reads in ChannelsStore so Source-driven SwiftUI task replacement cannot cancel the read used by other callers. Preserve queued Reload and dirty-draft semantics while removing unused schema reload state. Regression proof covers cancellation before dispatch, joining callers, and source retirement; full native validation passes 2078 tests.

* fix(macos): preserve cold gateway retry ownership
steipete added a commit that referenced this pull request Oct 13, 2026
* refactor(apple): simplify old shared and macOS bookkeeping

Replace redundant generations with existing cancellation or actual owner
identity, consolidate parallel fallback/policy paths, and remove test-only
forwarding layers. Preserve authority, FIFO, durable state, resource bounds,
public protocol/config shapes, signing, permissions, and visible rendering.

Reuse canonical session-key normalization for Voice Wake delivery selection:
opaque Signal group IDs remain case-sensitive and main aliases are not added.
Use canonical IP-literal policy for discovery labels and remote CLI validation.

Best-effort tradeoffs accepted

- Palette generation (#159350): synthetic direct completions bypassed the sole cancellation-owning caller; unsupported future callers can show stale results until the next search. Current cancellation/request/agent checks remain.
- Link preview generation (#160710): synthetic URL replacement without caller cancellation is outside the SwiftUI task lifecycle; a late cosmetic result can remain until the next refresh. Network/SSRF checks and bounded caches remain.
- Sidebar preview generation (#147197): same-request overlapping cache reads can finish out of order; no linked human failure report, and a later refresh replaces the cosmetic projection. Owner/request checks remain.
- Source-preview producer revision (#148906): duplicate of exact task cancellation, with no human failure report. Consumer revision and authenticated resource authority remain.
- Mermaid generations (#135470/#135746): feature stress fixtures, no linked human race report. Exact subscriber cancellation and job/WebView identity retain the same admission; no extra failure accepted.
- Camera JPEG UUID (#107879): duplicates exact task cancellation; #107804 was a human feature request, not a generation-specific incident. Captured session/agent/route and attachment admission remain.
- Discovery generation (#145435): speculative queued callbacks, no linked human incident. A stopped browser may publish one late discovery projection; next discovery/refresh repairs it. Connection authority remains separate.
- FSEvents generation (#145453): synthetic stop/restart fixtures, no linked human incident. An old callback after restart may cause one extra refresh; serial lifecycle ownership and pending-work cancellation remain.
- Menu generations (#139688): feature-local late-result fixtures, no linked human incident. Exact task cancellation replaces duplicate tokens; drain-before-disconnect and real consumer/window authority remain.
- Cron generation (#131466/#137502): #138209 cut every load over to one cancel-and-drain chain. No direct concurrent load caller remains; cancellation and physical source leases stay checked after awaits.
- WebChat visibility acknowledgement/retry (#113634/#137089): synthetic timeout/reconnect interleavings, no linked human incident. A timed-out visibility update is best effort until the next transition/reconnect; FIFO and live socket leases remain.
- WebChat cleanup UUID (#113634/#137089): retain one bounded completed Task handle per live connection instead of matching cleanup tokens. Completion releases captures; replacement/retirement removes the handle.
- Child-exit polling (#145437): synthetic missed-notification coverage, no linked human report. A lost OS exit notification may wait for the existing deadline; final non-reaping liveness/status checks and cleanup remain.
- Realtime iterator borrowing trap (#156772): every real consumer awaits its own iterator sequentially. Unsupported concurrent next calls no longer get a custom custody protocol; bounded stream/cancellation/socket checks remain.
- Receipt projection admission (#161745): both real callers already match receipt and row identity immediately before synchronous projection. Those effect checks remain; no unsupported internal caller is defended twice.
- Recap attribution heuristics (#112188/#113084): synthetic guard matrix, no linked human race report. Missing initial rows or very late unrelated completion may supply a cosmetic footer; per-session freshness, failed-turn handling and settled results remain.
- PortGuardian per-write schema scans (#110527): synthetic live-handle version advance, no linked human incident. Concurrent external schema upgrades are best effort until reopen; initial admission, migration locks, receipts, transactions and durability remain.
- Unread queue counter (#110019): actual Task equality replaces the duplicate integer token. Exact-tail reclamation, bounded bookkeeping, FIFO and route authority remain unchanged.

Review dispositions: the claimed Task compilation failure is disproved by the
selected SDK's Equatable conformance and native builds. Repeated receipt
identity admission is unnecessary at its internal projector because both real
callers retain it immediately before projection. Per-write schema revalidation
was declined under the explicit best-effort policy above.

Proof and scope

Net production reduction: 369 lines (148 added, 517 deleted), excluding tests.
Fresh seven-day census permits all substantive production edits; the only
recent caller change is the unavoidable one-line fallback-to-parse rename.

Shared Swift build passed. Final focused shared tests passed 396 cases in six
suites (6.683s execution), Watch decoder tests passed five cases (0.003s), and
isolated whole-owner native tests passed 16 cases. macOS SwiftPM compiled all
products and the test bundle. Final macOS and iOS/Watch xcodebuild builds passed
(89.60s and 120.87s wall), without signing changes or app launches.

Canonical Apple lint/format checks passed; the initial iOS format failure in
WatchCommands was ours and corrected, with no gate weakened. Lint-suppression
tests passed 3/3 (14.09s wall). Earlier runtime cycles and Madge each reported 0;
the TypeScript graph is unchanged. Native localization stayed at 4476 entries.
The 45 original packaging/elevation timeout cases passed one focused retry
(94.79s wall), with no assertion/budget change and no claim of a diagnosed fix.

Known gaps: seven issues remained in the earlier ChatStreamReplayTests
narration=false package cases; causality/current-main attribution is unproven.
App-hosted macOS tests were not executed on the operator desktop. No hosted CI
or PR was started: the explicit BELOW-500 rule requires a branch-only handoff.

* refactor(ui): consolidate old UI owners and validation

Share route decoding, attachment retention, gallery preparation, transient
identity encoding, override copying, and extension classification. Remove
duplicate admission/schema mirrors and obsolete supported-browser fallbacks.
Both Lit and Solid paths remain; no rendering change is intended. No config,
protocol, persisted shape, dependency, or public SDK change.

Best-effort tradeoffs accepted

- Malformed internal native requests (#140988): all callers are typed and
  native hosts validate at the effect; their error replaces the renderer mirror.
- Worker replacement during an identity query (#140484): added for synthetic
  autoreview interleavings, not a human incident. Return false; normal worker
  announcements and foreground recovery observe the next active worker.
- Native readiness changing between synchronous checks (#140484/#109719):
  rely on queued events. A broken native event can require another worker event
  or reload; camera readiness retains its existing five-second error deadline.
- Overlapping application-root health reporters (#152638): startup mounts one
  root. Unsupported overlapping roots are last-publication-wins; the actual
  reported health/status feature and native trusted-document checks remain.
- Polling after stop (#139704): its sole owner retires eligibility first.
  Scheduling now uses that owner admission, not a separate read-only generation.
- Resetting an observer without retiring its connection (#116887): no production
  caller does this. Canonical connection epochs remain the sole retirement owner;
  unsupported direct live-scope reset no longer fences an old response separately.
- Upload policy changing during local reads (#158567): decoded/hash work can
  finish. Draft publication and every upload request retain live policy checks.
- Missing supported browser primitives (#105240/#151388/#100024/#102745):
  unsupported runtimes error instead of code-point initials, skipped input yield,
  wall-clock timing, or approximate microtask paint. The human progress-card fix
  in #151386 keeps its browser yield and durable FIFO handoff unchanged.
- URL APIs disappearing after URL creation (#100024/#149330): supported browsers
  keep paired APIs. An unsupported replaced global can throw during cleanup;
  undefined URLs, creation fallback, cancellation and release ordering remain.
- Malformed internal MCP calls bypassing AppBridge (#161747): may throw. The SDK
  still rejects malformed wire blocks before dispatch, proved over real in-memory
  App/AppBridge transport. UI content, authority, confirmation and custody policy
  remain. The introducing PR cites no human incident for the second mirror.

Production: +176/-394, net -218 lines across 21 eligible old files. Tests: +30.
Focused owner/sibling tests, targeted types/lint/format, lint-suppression and
independent P0-P2 review pass. Import edges are unchanged; runtime/Madge cycle
proof remains zero. Whole-tree Knip timed out at existing limits; heavy gallery
renderer runs did not reach assertions, while its owning controller suite passed.

* refactor(ui): remove obsolete Fetch capability branch

The supported Control UI browser floor includes Fetch. Start attachment
metadata reads directly rather than leaving an unsupported runtime in a
permanent checking state.

Best-effort tradeoffs accepted

- Missing global Fetch: the guard originated in #64104, whose feature report
  cites no human missing-Fetch incident. An unsupported runtime that replaces
  Fetch now reaches the existing rejected-request/unavailable path. Metadata
  validation, auth/tickets, allow POST, cancellation, resource admission,
  expiry and bounded retry remain unchanged. No intended rendering change.

Unchanged lifecycle baseline: 21/21, 25.09 s. Final lifecycle and attachment
siblings: 50/50, 14.77 s. UI types, typed lint, formatting and lint-suppression
checks pass. This cut removes five production lines including formatter
reflow, bringing the lane to 223 net production lines removed.
Fresh independent P0-P2 review is scoped-clean with no actionable findings.

* fix(ui): use global frame scheduling APIs

Preserve double-frame paint timing and cancellation without requiring a Window object in renderer-free hosts that supply the standard global APIs. The existing access suite reproduces seven unhandled errors before this fix and passes on main; all 130 affected cases plus 262 timing/state/send sibling cases now pass without test changes.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 14, 2026
…#170823)

* refactor(apple): simplify old shared and macOS bookkeeping

Replace redundant generations with existing cancellation or actual owner
identity, consolidate parallel fallback/policy paths, and remove test-only
forwarding layers. Preserve authority, FIFO, durable state, resource bounds,
public protocol/config shapes, signing, permissions, and visible rendering.

Reuse canonical session-key normalization for Voice Wake delivery selection:
opaque Signal group IDs remain case-sensitive and main aliases are not added.
Use canonical IP-literal policy for discovery labels and remote CLI validation.

Best-effort tradeoffs accepted

- Palette generation (openclaw#159350): synthetic direct completions bypassed the sole cancellation-owning caller; unsupported future callers can show stale results until the next search. Current cancellation/request/agent checks remain.
- Link preview generation (openclaw#160710): synthetic URL replacement without caller cancellation is outside the SwiftUI task lifecycle; a late cosmetic result can remain until the next refresh. Network/SSRF checks and bounded caches remain.
- Sidebar preview generation (openclaw#147197): same-request overlapping cache reads can finish out of order; no linked human failure report, and a later refresh replaces the cosmetic projection. Owner/request checks remain.
- Source-preview producer revision (openclaw#148906): duplicate of exact task cancellation, with no human failure report. Consumer revision and authenticated resource authority remain.
- Mermaid generations (openclaw#135470/openclaw#135746): feature stress fixtures, no linked human race report. Exact subscriber cancellation and job/WebView identity retain the same admission; no extra failure accepted.
- Camera JPEG UUID (openclaw#107879): duplicates exact task cancellation; openclaw#107804 was a human feature request, not a generation-specific incident. Captured session/agent/route and attachment admission remain.
- Discovery generation (openclaw#145435): speculative queued callbacks, no linked human incident. A stopped browser may publish one late discovery projection; next discovery/refresh repairs it. Connection authority remains separate.
- FSEvents generation (openclaw#145453): synthetic stop/restart fixtures, no linked human incident. An old callback after restart may cause one extra refresh; serial lifecycle ownership and pending-work cancellation remain.
- Menu generations (openclaw#139688): feature-local late-result fixtures, no linked human incident. Exact task cancellation replaces duplicate tokens; drain-before-disconnect and real consumer/window authority remain.
- Cron generation (openclaw#131466/openclaw#137502): openclaw#138209 cut every load over to one cancel-and-drain chain. No direct concurrent load caller remains; cancellation and physical source leases stay checked after awaits.
- WebChat visibility acknowledgement/retry (openclaw#113634/openclaw#137089): synthetic timeout/reconnect interleavings, no linked human incident. A timed-out visibility update is best effort until the next transition/reconnect; FIFO and live socket leases remain.
- WebChat cleanup UUID (openclaw#113634/openclaw#137089): retain one bounded completed Task handle per live connection instead of matching cleanup tokens. Completion releases captures; replacement/retirement removes the handle.
- Child-exit polling (openclaw#145437): synthetic missed-notification coverage, no linked human report. A lost OS exit notification may wait for the existing deadline; final non-reaping liveness/status checks and cleanup remain.
- Realtime iterator borrowing trap (openclaw#156772): every real consumer awaits its own iterator sequentially. Unsupported concurrent next calls no longer get a custom custody protocol; bounded stream/cancellation/socket checks remain.
- Receipt projection admission (openclaw#161745): both real callers already match receipt and row identity immediately before synchronous projection. Those effect checks remain; no unsupported internal caller is defended twice.
- Recap attribution heuristics (openclaw#112188/openclaw#113084): synthetic guard matrix, no linked human race report. Missing initial rows or very late unrelated completion may supply a cosmetic footer; per-session freshness, failed-turn handling and settled results remain.
- PortGuardian per-write schema scans (openclaw#110527): synthetic live-handle version advance, no linked human incident. Concurrent external schema upgrades are best effort until reopen; initial admission, migration locks, receipts, transactions and durability remain.
- Unread queue counter (openclaw#110019): actual Task equality replaces the duplicate integer token. Exact-tail reclamation, bounded bookkeeping, FIFO and route authority remain unchanged.

Review dispositions: the claimed Task compilation failure is disproved by the
selected SDK's Equatable conformance and native builds. Repeated receipt
identity admission is unnecessary at its internal projector because both real
callers retain it immediately before projection. Per-write schema revalidation
was declined under the explicit best-effort policy above.

Proof and scope

Net production reduction: 369 lines (148 added, 517 deleted), excluding tests.
Fresh seven-day census permits all substantive production edits; the only
recent caller change is the unavoidable one-line fallback-to-parse rename.

Shared Swift build passed. Final focused shared tests passed 396 cases in six
suites (6.683s execution), Watch decoder tests passed five cases (0.003s), and
isolated whole-owner native tests passed 16 cases. macOS SwiftPM compiled all
products and the test bundle. Final macOS and iOS/Watch xcodebuild builds passed
(89.60s and 120.87s wall), without signing changes or app launches.

Canonical Apple lint/format checks passed; the initial iOS format failure in
WatchCommands was ours and corrected, with no gate weakened. Lint-suppression
tests passed 3/3 (14.09s wall). Earlier runtime cycles and Madge each reported 0;
the TypeScript graph is unchanged. Native localization stayed at 4476 entries.
The 45 original packaging/elevation timeout cases passed one focused retry
(94.79s wall), with no assertion/budget change and no claim of a diagnosed fix.

Known gaps: seven issues remained in the earlier ChatStreamReplayTests
narration=false package cases; causality/current-main attribution is unproven.
App-hosted macOS tests were not executed on the operator desktop. No hosted CI
or PR was started: the explicit BELOW-500 rule requires a branch-only handoff.

* refactor(ui): consolidate old UI owners and validation

Share route decoding, attachment retention, gallery preparation, transient
identity encoding, override copying, and extension classification. Remove
duplicate admission/schema mirrors and obsolete supported-browser fallbacks.
Both Lit and Solid paths remain; no rendering change is intended. No config,
protocol, persisted shape, dependency, or public SDK change.

Best-effort tradeoffs accepted

- Malformed internal native requests (openclaw#140988): all callers are typed and
  native hosts validate at the effect; their error replaces the renderer mirror.
- Worker replacement during an identity query (openclaw#140484): added for synthetic
  autoreview interleavings, not a human incident. Return false; normal worker
  announcements and foreground recovery observe the next active worker.
- Native readiness changing between synchronous checks (openclaw#140484/openclaw#109719):
  rely on queued events. A broken native event can require another worker event
  or reload; camera readiness retains its existing five-second error deadline.
- Overlapping application-root health reporters (openclaw#152638): startup mounts one
  root. Unsupported overlapping roots are last-publication-wins; the actual
  reported health/status feature and native trusted-document checks remain.
- Polling after stop (openclaw#139704): its sole owner retires eligibility first.
  Scheduling now uses that owner admission, not a separate read-only generation.
- Resetting an observer without retiring its connection (openclaw#116887): no production
  caller does this. Canonical connection epochs remain the sole retirement owner;
  unsupported direct live-scope reset no longer fences an old response separately.
- Upload policy changing during local reads (openclaw#158567): decoded/hash work can
  finish. Draft publication and every upload request retain live policy checks.
- Missing supported browser primitives (openclaw#105240/openclaw#151388/openclaw#100024/openclaw#102745):
  unsupported runtimes error instead of code-point initials, skipped input yield,
  wall-clock timing, or approximate microtask paint. The human progress-card fix
  in openclaw#151386 keeps its browser yield and durable FIFO handoff unchanged.
- URL APIs disappearing after URL creation (openclaw#100024/openclaw#149330): supported browsers
  keep paired APIs. An unsupported replaced global can throw during cleanup;
  undefined URLs, creation fallback, cancellation and release ordering remain.
- Malformed internal MCP calls bypassing AppBridge (openclaw#161747): may throw. The SDK
  still rejects malformed wire blocks before dispatch, proved over real in-memory
  App/AppBridge transport. UI content, authority, confirmation and custody policy
  remain. The introducing PR cites no human incident for the second mirror.

Production: +176/-394, net -218 lines across 21 eligible old files. Tests: +30.
Focused owner/sibling tests, targeted types/lint/format, lint-suppression and
independent P0-P2 review pass. Import edges are unchanged; runtime/Madge cycle
proof remains zero. Whole-tree Knip timed out at existing limits; heavy gallery
renderer runs did not reach assertions, while its owning controller suite passed.

* refactor(ui): remove obsolete Fetch capability branch

The supported Control UI browser floor includes Fetch. Start attachment
metadata reads directly rather than leaving an unsupported runtime in a
permanent checking state.

Best-effort tradeoffs accepted

- Missing global Fetch: the guard originated in openclaw#64104, whose feature report
  cites no human missing-Fetch incident. An unsupported runtime that replaces
  Fetch now reaches the existing rejected-request/unavailable path. Metadata
  validation, auth/tickets, allow POST, cancellation, resource admission,
  expiry and bounded retry remain unchanged. No intended rendering change.

Unchanged lifecycle baseline: 21/21, 25.09 s. Final lifecycle and attachment
siblings: 50/50, 14.77 s. UI types, typed lint, formatting and lint-suppression
checks pass. This cut removes five production lines including formatter
reflow, bringing the lane to 223 net production lines removed.
Fresh independent P0-P2 review is scoped-clean with no actionable findings.

* fix(ui): use global frame scheduling APIs

Preserve double-frame paint timing and cancellation without requiring a Window object in renderer-free hosts that supply the standard global APIs. The existing access suite reproduces seven unhandled errors before this fix and passes on main; all 130 affected cases plus 262 timing/state/send sibling cases now pass without test changes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

app: macos App: macos docs Improvements or additions to documentation maintainer Maintainer-authored PR merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P2 Normal backlog priority with limited blast radius. 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]: macOS primary gateway changes leave secondary dashboards on stale routes

1 participant