You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Commit d67ef51
Browse filesBrowse the repository at this point in the historyBrowse files
* refactor(connection): extract domain coordinators
Co-authored-by: Copilot App <[email protected]>
* fix(connection): detach node token recovery callback
NodeConnector raises ConnectionFailure while holding _clientLifecycleLock
and requires subscribers to return promptly. HandleConnectionFailure called
TrackBackground(HandleDeviceTokenMismatchAsync(attempt)), which evaluated the
recovery's synchronous prefix (attempt-lease acquire, endpoint trust check,
DeviceIdentity node-token clearing) on the lock-holding callback stack when
awaits completed synchronously, risking blocked lifecycle and deadlock.
Wrap the dispatch in Task.Run so the whole recovery runs off the callback
stack. The unwrapped proxy task is still tracked in _backgroundTasks and
drained on shutdown; generation and credential fencing are unchanged.
Adds a deterministic barrier test plus superseded-generation, recovery
success, untrusted-endpoint, and after-stop regressions.
Co-authored-by: Copilot App <[email protected]>
* fix(connection): preserve parent recovery and fencing semantics
Co-authored-by: Copilot App <[email protected]>
Copilot-Session: 59c9cc10-f388-47ba-a6a0-2afd21dff031
---------
Co-authored-by: Copilot App <[email protected]>
Co-authored-by: Karen Lai <[email protected]>
Copilot-Session: 59c9cc10-f388-47ba-a6a0-2afd21dff031
|`src/OpenClaw.SetupEngine/SetupSteps.cs`| one file per step; `WslShellClient`, `GatewayConfigScriptBuilder`, `KeepaliveProcessManager`. WSL/POSIX quoting is done - use `WslShellQuoting`, never a local `ShellEscape`. |
109
+
|`src/OpenClaw.Connection/GatewayConnectionManager.cs`| The three connection-domain owners are authoritative. Keep only the public lifecycle facade, manager-owned operator/state/tunnel orchestration, typed source/sink/security ports, and event forwarding. |
107
110
| Any test hand-rolling a temp dir / env save-restore / CLI capture |`OpenClaw.TestSupport` fixtures |
108
111
109
112
## Ledger
@@ -191,6 +194,12 @@ leading and trailing pipe. Columns, in order:
191
194
| app-notification-infobar-presentation | authoritative | src/OpenClaw.Tray.WinUI/Windows/HubWindow.xaml.cs | banner severity filtering, selected-banner fallback, notification action versus Show more, and action enabled state | AppNotificationInfoBarPresenter | HubWindow keeps notification subscription, bell reconciliation, WinUI control assignment, navigation, and dismissal side effects | Warning and Error banners retain priority and hiding semantics while action projection stays WinUI-free | AppNotificationInfoBarPresenterTests.Present_ActionableNotificationWinsOverShowMore | behavioral | - |
192
195
| tray-menu-presentation | authoritative | TrayMenuStateBuilder and src/OpenClaw.Tray.WinUI/App.xaml.cs | tray row and flyout presence, ordering, text, formatting, icon identity, action, checked and enabled state, accelerator, accessibility names, and connection-toggle projection | TrayMenuPresenter + ConnectionTogglePresenter | App captures immutable input and owns semantic callbacks, persistence, and reconnect policy; TrayController applies live projection; TrayMenuRenderer builds WinUI controls; TrayMenuWindow owns popup mechanics | equal immutable snapshots project equal complete menus; connected and disconnected compositions, all nine permission toggles, and transient connection states preserve behavior | TrayMenuPresenterTests.Connected_ProjectsExactTopLevelAndNestedOrder | behavioral | - |
193
196
| tray-menu-state-builder-closed | closed | TrayMenuStateBuilder and src/OpenClaw.Tray.WinUI/App.xaml.cs | snapshot interpretation, semantic menu construction, and duplicated connection-toggle decisions | TrayMenuPresenter + ConnectionTogglePresenter | mechanical rendering, immutable snapshot capture, action dispatch, persistence callbacks, TrayController weak control references, and TrayMenuWindow native popup behavior | presentation owners stay WinUI/App/concrete-settings free and the renderer and controller do not interpret runtime snapshots | TrayMenuPresentationContractTests.PresentationFiles_AreWinUiAppAndConcreteSettingsFree | source-shape | when the tray menu no longer uses WinUI rendering |
197
+
| node-connection-coordinator | authoritative | src/OpenClaw.Connection/GatewayConnectionManager.cs | node generation, cancellation, start guard, connect ordering, classified token recovery, connector events, and node telemetry | NodeConnectionCoordinator | manager public node façade; node-only operator/lifecycle/tunnel preparation; typed lifecycle/state/security ports; one event-forwarding subscription set | a superseded lifecycle or node generation cannot write node snapshot state | NodeConnectionCoordinatorTests.SupersededGeneration_DoesNotWriteSnapshot | behavioral | - |
198
+
| gateway-manager-node-owner-closed | closed | src/OpenClaw.Connection/GatewayConnectionManager.cs | private node generation/CTS/start workflow/recovery/telemetry implementation | NodeConnectionCoordinator | public node façade; node-only operator/lifecycle/tunnel preparation; typed lifecycle/state/security ports; one event-forwarding subscription set | the manager has no node generation, node CTS, combined node-attempt predicate, node connect core, or node telemetry names | ConnectionDomainOwnerClosureTests.GatewayConnectionManager_DoesNotReintroduceNodeGenerationOrTelemetryOwnership | source-shape | when GatewayConnectionManager no longer composes NodeConnectionCoordinator directly |
199
+
| bootstrap-token-lifecycle | authoritative | src/OpenClaw.Connection/GatewayConnectionManager.cs | bootstrap selection and durable clear timing, device-token persistence handoff, post-bootstrap reconnect, and operator token recovery | BootstrapTokenLifecycle | manager public setup/shared-token façade and save-failure rollback; operator event forwarding; typed lifecycle lease, endpoint-security, reconnect, and v2 persistence ports | bootstrap clears only after canonical operator and node role tokens are both durably readable | BootstrapTokenLifecycleTests.ClearsBootstrap_OnlyWhenBothRoleTokensDurable | behavioral | - |
200
+
| gateway-manager-bootstrap-owner-closed | closed | src/OpenClaw.Connection/GatewayConnectionManager.cs | bootstrap timing flags, durable-token clear helper, post-bootstrap scheduling, and operator mismatch recovery | BootstrapTokenLifecycle | public setup/shared-token façade and save-failure rollback; one-shot shared-token validation; operator event forwarding; typed lifecycle/reconnect/v2 ports | stale token events cannot restore timing flags, clear a newer record, or schedule an untyped reconnect callback | ConnectionDomainOwnerClosureTests.GatewayConnectionManager_DoesNotReintroduceBootstrapTimingOwnership | source-shape | when GatewayConnectionManager no longer composes BootstrapTokenLifecycle directly |
201
+
| device-pair-approval-coordinator | authoritative | src/OpenClaw.Connection/GatewayConnectionManager.cs | device role-upgrade approval, confirmation, dedupe, and one-in-flight plus one-queued bounded reconnect | DevicePairApprovalCoordinator | manager pairing-event forwarding and generation-bound operator gateway lease source | post-approval node reconnect is bounded to two attempts per request and reacquires the current operator gateway | DevicePairApprovalCoordinatorTests.PostApproveReconnect_IsBounded | behavioral | - |
202
+
| gateway-manager-device-pair-owner-closed | closed | src/OpenClaw.Connection/GatewayConnectionManager.cs | device-pair approve RPC, success dedupe, reconnect attempts, and queued retry state | DevicePairApprovalCoordinator | pairing-event forwarding, node snapshot application, and generation-bound operator gateway lease source | manager cannot regain device-pair workflow fields or approve/reconnect methods | ConnectionDomainOwnerClosureTests.GatewayConnectionManager_DoesNotReintroduceDevicePairWorkflowOwnership | source-shape | when GatewayConnectionManager no longer composes DevicePairApprovalCoordinator directly |
Copy file name to clipboardExpand all lines: docs/CONNECTION_ARCHITECTURE.md
+34-4Lines changed: 34 additions & 4 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -24,7 +24,22 @@ to cancelled or completed when capability execution returns; whichever
24
24
transition wins determines the protocol outcome. Capability implementations
25
25
remain responsible for cooperative cancellation of their own underlying work.
26
26
27
-
**OpenClaw.Connection** owns all connection management: `GatewayConnectionManager`, `GatewayRegistry`, `CredentialResolver`, `ConnectionStateMachine`, `NodeConnector`, `SshTunnelService/Manager`, `SetupCodeDecoder`, and all connection interfaces/DTOs/enums. This project has zero WinUI dependencies and is independently testable.
27
+
**OpenClaw.Connection** owns all connection management. `GatewayConnectionManager`
28
+
is the public lifecycle façade and sole writer of the overall state machine,
29
+
operator lifecycle, active gateway context, tunnel, and operator reconnect
30
+
orchestration. Three narrower owners sit behind it:
`NodeConnector`, `SshTunnelService/Manager`, `SetupCodeDecoder`, and connection
41
+
interfaces/DTOs/enums remain separate. This project has zero WinUI dependencies
42
+
and is independently testable.
28
43
29
44
**OpenClaw.Tray.WinUI** consumes the connection layer through interfaces. It never creates gateway clients directly - `GatewayConnectionManager` owns that entirely.
30
45
@@ -204,7 +219,17 @@ Two orthogonal self-healing behaviors keep the connection reliable without dead-
204
219
205
220
The gateway may reject a stored device token with the structured code `AUTH_DEVICE_TOKEN_MISMATCH` (a rotated/revoked/replaced device token) - distinct from a wrong *shared* token. `GatewayErrorClassifier` is the single classifier for this: `ClassifyWithCode(message, ...codes)` inspects the structured `error.code`/`error.details.code`**before** the textual heuristic and returns the exact `GatewayErrorKind.DeviceTokenMismatch`, keeping a stale *device* token (auto-recoverable) separate from a wrong *shared* token (`Auth`, not device-recoverable). Broad `GatewayErrorKind.TokenDrift` remains a manual re-pair signal for UI copy.
206
221
207
-
On a device-token mismatch, the manager clears **only the rejected role's** device token and reconnects, letting `CredentialResolver` fall back to the same record's `SharedGatewayToken` (preferred) or `BootstrapToken`. This kills the post-setup "need a new token" dead end (setup clears the bootstrap token once pairing is durable, but the shared token remains). Operator recovery runs in `TryScheduleOperatorTokenRecovery`; node recovery is driven off the node client's classified `INodeConnectorTelemetryEvents.ConnectionFailure(GatewayErrorKind)` - the manager's `OnNodeConnectionFailure` queues `HandleNodeDeviceTokenMismatchAsync` off the connector's dispatch lock (capturing lifecycle+node generations at fire time and re-checking `IsCurrentNodeAttempt` before/after the transition semaphore). A per-gateway, per-role attempt guard (reset on handshake success / node pairing) prevents clear→reconnect→mismatch loops.
222
+
On a device-token mismatch, the applicable credential owner clears **only the
223
+
rejected role's** device token and reconnects, letting `CredentialResolver` fall
224
+
back to the same record's `SharedGatewayToken` (preferred) or
`NodeConnectionCoordinator` owns node recovery from the connector's classified
227
+
`INodeConnectorTelemetryEvents.ConnectionFailure(GatewayErrorKind)`. The
228
+
manager subscribes once and forwards typed connector events. The node owner
229
+
captures lifecycle plus node generation and is the only implementation of the
230
+
combined current-node-attempt check. A per-gateway, per-role attempt guard
231
+
(reset on handshake success / node pairing) prevents
232
+
clear→reconnect→mismatch loops.
208
233
209
234
**Security - trust gate and endpoint provenance.** Clearing a device token downgrades to the more powerful shared/bootstrap credential, so `IsRecoverySafeEndpoint` restricts recovery to trusted endpoints: an owned SSH tunnel, a validated TLS (`wss`/`https`) endpoint, or a setup-managed WSL loopback gateway proven by `ManagedLocalGatewayPortProvenanceService`. The managed-local proof accepts either the existing verified Windows WSL relay identity or a relayless mirrored-networking endpoint with a complete empty Windows listener snapshot, positive expected-distro systemd MainPID ownership, and an immediate second complete empty snapshot. Strong credentials repeat that relayless proof immediately before use. Loopback is not treated as identity by itself: incomplete capture or any unknown, conflicting, or changed Windows listener blocks fallback, so a wrong local process cannot return a device-token mismatch to induce disclosure of the shared credential. A plain `ws://` remote endpoint is never eligible.
210
235
@@ -233,10 +258,12 @@ Setup codes (from QR scan or paste) decode to `{ url, bootstrapToken }` via `Set
233
258
1.`ApplySetupCodeAsync(code)` decodes and validates the gateway URL and bootstrap token
234
259
2. Creates/updates and persists the active `GatewayRecord`, preserving any shared token and durable per-role device tokens
235
260
3. Disconnects the previous connection only after the record is durable
236
-
4.Forces`auth.bootstrapToken` for this connection attempt without clearing stored device tokens; the record-scoped force flag is consumed or cleared even when identity loading fails
237
-
5. After successful pairing, the gateway returns `hello-ok.auth.deviceToken` and the connection manager persists the replacement role token
261
+
4.`BootstrapTokenLifecycle` forces`auth.bootstrapToken` for this connection attempt without clearing stored device tokens; the record-scoped force flag is consumed or cleared even when identity loading fails
262
+
5. After successful pairing, the gateway returns `hello-ok.auth.deviceToken` and `BootstrapTokenLifecycle` persists the replacement role token
238
263
6. If pairing or connection fails, the previously stored device tokens remain intact, so retrying or returning to the prior pairing does not require an unintended full re-pair
239
264
265
+
The bootstrap token is cleared only after operator and node role tokens are both durably readable.
266
+
240
267
**Approval boundaries**: `GatewayConnectionManager` leaves node-pair command-trust requests and reapproval pending for explicit operator approval. It may automatically approve and reconnect only an explicitly typed device-pair request used for a device role upgrade.
241
268
242
269
## Inbound pairing approval (operator)
@@ -310,5 +337,8 @@ Connection tests live in `tests/OpenClaw.Connection.Tests/`:
The heaviest remaining gap is Windows shell UI behavior (tray clicks, tooltip visibility, WinUI menu routing). Cover pure decision logic in unit tests; use manual or integration smoke tests for shell behavior.
0 commit comments