Skip to content

Commit b5d8acb

Browse files
committed
Merge origin/main into Tailscale Serve branch
Preserve strict setup argument parsing and pairing cancellation semantics while integrating the Tailscale CLI options. Co-authored-by: Copilot App <[email protected]> Copilot-Session: 418d0565-a857-47bb-aa72-029b898235dc
2 parents a8b7933 + 6b9e814 commit b5d8acb

59 files changed

Lines changed: 5284 additions & 249 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎docs/ARCHITECTURE.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,9 @@ These are the canonical homes. Do not reintroduce private copies elsewhere.
5454
| Settings test data | `OpenClaw.TestSupport.SettingsDataBuilder` | authoritative |
5555
| JSON `JsonElement` coercion (non-nullable fallback family) | `JsonReadHelpers` | authoritative |
5656
| WSL/POSIX shell quoting | `WslShellQuoting` | authoritative |
57+
| UI-thread marshaling for presentation code | `IUiDispatcher` | authoritative |
58+
| Page view-model activation/deactivation + disposal lifetime | `NavigationScopeManager` | authoritative |
59+
| Presentation-layer DI composition root | `AppServiceRegistration` (root `ServiceProvider`, owned by `App`) | authoritative |
5760
| Capability UI metadata | `NodeCapabilityUiCatalog` (planned) | planned |
5861
| Capability registration/gating | `NodeCapabilityRegistrationPolicy` (planned) | planned |
5962
| Local MCP exposure policy | `McpCapabilityPolicy` (planned) | planned |
@@ -116,6 +119,9 @@ leading and trailing pipe. Columns, in order:
116119
| chat-send-queue | planned | src/OpenClaw.Tray.WinUI/Chat/OpenClawChatDataProvider.cs | send queue/admission/abort state | ChatSendQueue | - | queued send/abort/generation semantics preserved | none | review-only | extracted in Phase 4 |
117120
| gateway-pending-requests | planned | src/OpenClaw.Shared/OpenClawGatewayClient.cs | request-id -> method/completion tracking | PendingRequestRegistry | - | request ids never leak after disconnect; thread-safe | none | review-only | extracted in Phase 4 |
118121
| connect-envelope | planned | src/OpenClaw.Shared/OpenClawGatewayClient.cs + WindowsNodeClient.cs | connect message + auth precedence + signature version | ConnectEnvelopeBuilder | - | credential precedence never downgrades a device token; v3->v2 fallback preserved | none | review-only | extracted in Phase 4 |
122+
| ui-dispatcher | authoritative | src/OpenClaw.Tray.WinUI/App.xaml.cs | UI-thread marshaling abstraction for presentation code | IUiDispatcher | App and existing WinUI code may call DispatcherQueue directly until the view-model migration | presentation view models depend on IUiDispatcher not a concrete DispatcherQueue | UiDispatcherContractTests.PageViewModel_ReceivesRegisteredDispatcher | behavioral | - |
123+
| navigation-scope | authoritative | src/OpenClaw.Tray.WinUI/Windows/HubWindow.xaml.cs | page view-model activation/deactivation and disposal lifetime | NavigationScopeManager | HubWindow keeps frame navigation back-stack and rail selection | transient page view models are activated on navigation and deactivated then disposed on navigate-away | NavigationScopeManagerTests.NavigatingAway_DeactivatesAndDisposesPreviousViewModel | behavioral | - |
124+
| composition-root | authoritative | src/OpenClaw.Tray.WinUI/App.xaml.cs | presentation-layer service construction and wiring | AppServiceRegistration | App remains the composition root and owns non-DI service lifetimes | one validated root ServiceProvider; App-owned singletons registered as instances are never disposed by the container | AppServiceRegistrationTests.Dispose_DoesNotDisposeAppOwnedInstanceSingletons | behavioral | - |
119125
<!-- LEDGER:END -->
120126

121127
## Deferred test builders

‎docs/CONNECTION_ARCHITECTURE.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,14 @@ OpenClaw.Tray.WinUI (net10.0-windows) — UI app, tray icon, pages, windows
1616

1717
**OpenClaw.Shared** owns the low-level gateway clients (`OpenClawGatewayClient`, `WindowsNodeClient`, `WebSocketClientBase`), device identity/signing (`DeviceIdentity`), protocol models, and the `IOperatorGatewayClient` interface.
1818

19+
`WindowsNodeClient` also owns gateway invocation lifetime at the transport
20+
boundary. Active invokes are registered by invoke ID in a focused cancellation
21+
registry, linked to the node connection lifetime, and cancelled individually by
22+
the gateway `node.invoke.cancel` event. Active invocations atomically transition
23+
to cancelled or completed when capability execution returns; whichever
24+
transition wins determines the protocol outcome. Capability implementations
25+
remain responsible for cooperative cancellation of their own underlying work.
26+
1927
**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.
2028

2129
**OpenClaw.Tray.WinUI** consumes the connection layer through interfaces. It never creates gateway clients directly — `GatewayConnectionManager` owns that entirely.

‎docs/MCP_MODE.md‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,9 +66,37 @@ The capability list lives on `NodeService`, *not* on `WindowsNodeClient`. That s
6666
- `tools/list` — flattens `_capabilities` into MCP tools. Tool name = command name (`"screen.snapshot"`); known commands get curated descriptions from `McpToolBridge.CommandDescriptions`; unknown commands fall back to `"{category} capability: {command}"`. `inputSchema` is permissive.
6767
- `tools/call` — finds the capability via `INodeCapability.CanHandle(name)`, builds a `NodeInvokeRequest` (the same struct the gateway path uses), calls `ExecuteAsync`, wraps the result as MCP `content[].text`. Tool failures come back as `result.isError = true`, not JSON-RPC errors (per MCP spec — JSON-RPC errors are reserved for protocol issues).
6868
- `ping`, `notifications/initialized` — protocol housekeeping.
69+
- `notifications/cancelled` — cancels the active request whose JSON-RPC ID is
70+
supplied as `params.requestId`. A cancelled `tools/call` completes with an MCP
71+
tool error containing `cancelled`. If concurrent HTTP scheduling processes
72+
cancellation just before an already-sent call registers, the notification
73+
records a pending cancellation for five seconds. The first matching
74+
registration atomically consumes that tombstone and returns `cancelled` before
75+
capability execution begins, so correctness does not depend on scheduler
76+
timing. Repeated notifications for the same pending ID do not extend its
77+
original five-second lifetime. Pending cancellations and recent-completion
78+
guards are each capped at 1,024 entries;
79+
expired entries are pruned first and the oldest remaining entry is evicted at
80+
capacity. Because JSON-RPC IDs are client-scoped but this stateless HTTP
81+
transport has no client identity, duplicate active IDs are allowed and
82+
cancellation is ignored when more than one active call matches; this prevents
83+
one local client from cancelling another client when the collision is already
84+
observable. Request matching uses the decoded JSON string value or normalized
85+
arbitrary-precision JSON number value, while preserving the distinction
86+
between string and numeric IDs. A tombstone cannot predict a later
87+
cross-client ID collision, so it cancels the first matching registration;
88+
complete isolation would require client identity in the transport. A recent
89+
completion guard also prevents a late notification from poisoning immediate
90+
ID reuse.
6991

7092
The bridge takes a `Func<IReadOnlyList<INodeCapability>>` rather than a snapshot. Every `tools/list` re-reads the live list. This is what guarantees zero-cost capability addition — register a new capability after server start and it appears on the next `tools/list`.
7193

94+
Cancellation is cooperative and uses the same `CancellationToken` capability
95+
contract as the gateway transport. Screen and camera operations propagate the
96+
token through recording consent/countdown, camera admission, capture waits, and
97+
recording shutdown. The HTTP request deadline remains a separate safety bound;
98+
no command-specific transport deadlines are applied.
99+
72100
### HTTP transport
73101

74102
`OpenClaw.Shared/Mcp/McpHttpServer.cs` is `System.Net.HttpListener` bound to `http://127.0.0.1:8765/`. Loopback-only by construction; not reachable from any other machine even with firewall holes. A defensive `IPAddress.IsLoopback` check on each request acts as belt-and-suspenders.

‎docs/SETUP_ENGINE_REDESIGN.md‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,8 @@ src/OpenClaw.SetupEngine.UI/
8080
## Config File (`default-config.json`)
8181

8282
**Config is required.** Neither the headless exe nor the UI will run without one. The bundled `default-config.json` is auto-loaded from `AppContext.BaseDirectory` if no `--config` is specified.
83+
If the setup UI cannot find, read, or deserialize the selected configuration,
84+
it opens on the setup failure page with the load error and does not start setup.
8385

8486
```json
8587
{
@@ -319,6 +321,26 @@ OpenClaw.SetupEngine.Program.Main(["--log-path", "./trace.log"])
319321

320322
Common flags include `--config`, `--headless`, `--dry-run`, `--rollback-on-failure`, `--no-rollback-on-failure`, `--log-path`, `--gateway-port`, and uninstall safety flags such as `--uninstall` plus `--confirm-destructive`.
321323

324+
SetupEngine option names are case-insensitive. Value options accept either separated
325+
syntax (`--config custom.json`) or equals syntax (`--config=custom.json`). Unknown
326+
options, bare `--`, and positional arguments are rejected with exit code 2.
327+
Boolean flags do not accept values, and duplicate value options are rejected;
328+
duplicate bare flags remain idempotent.
329+
330+
Duplicate value rejection is an intentional compatibility break from the legacy
331+
first-value-wins behavior. Scripts that repeat a value option must remove the
332+
duplicate before upgrading.
333+
334+
The same parser enforces the tray-hosted setup window's narrower command-line
335+
contract: `--config` and `--no-rollback-on-failure`. The tray projects recognized
336+
restart and deep-link host arguments out first. A restart PID must be a positive
337+
integer other than the current process, and the post-setup launch target must be
338+
`chat`; malformed host values remain for strict rejection. All remaining unknown options,
339+
positionals, missing values, and duplicates render the setup failure page before
340+
the setup lock is acquired. The tray executable's uninstall arguments are parsed
341+
by `CliUninstallHandler` and currently use separated syntax for values such as
342+
`--json-output <path>`.
343+
322344
Exit codes: 0 = success, 1 = pipeline failure, 2 = bad arguments or setup lock/safety failure, 3 = cancelled
323345

324346
### UI (hosted by tray)

‎docs/WINDOWS_NODE_TESTING.md‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,22 @@ These features need the gateway to send `node.invoke` commands:
9191
| `stt.listen` | Voice-activity microphone transcription | Returns when the user stops speaking or timeout expires |
9292
| `stt.status` | Speech-to-text readiness | Returns Whisper.net model download/readiness state |
9393

94+
### Cancelling an invocation
95+
96+
The gateway may send the `node.invoke.cancel` event with
97+
`payload.invokeId` matching an active `node.invoke.request`. The Windows node
98+
cancels only that invocation and completes its original result with
99+
`ok: false, error: "cancelled"`; unknown or already-completed IDs are ignored.
100+
The legacy `payload.requestId` spelling is also accepted for compatibility.
101+
Operation completion is the linearization point: once capability execution
102+
returns and atomically marks the invocation complete, later cancellation is too
103+
late and the completed result is preserved.
104+
105+
For local MCP, send a JSON-RPC `notifications/cancelled` notification with
106+
`params.requestId` matching the active `tools/call` JSON-RPC ID. Cancellation
107+
must stop queued camera admission, recording delays/frame waits, and active
108+
recording cleanup rather than only abandoning the HTTP waiter.
109+
94110
## Capabilities Advertised
95111

96112
When the node connects, it advertises these capabilities:

‎src/OpenClaw.SetupEngine.UI/SetupWindow.xaml.cs‎

Lines changed: 70 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -52,13 +52,42 @@ public SetupWindow(
5252
string? dataDir = null,
5353
string? localDataDir = null,
5454
string? distroNameOverride = null,
55-
int? gatewayPortOverride = null)
55+
int? gatewayPortOverride = null,
56+
string[]? commandLineArgs = null)
5657
{
5758
_dataDir = dataDir ?? SetupContext.ResolveDataDir();
5859
_localDataDir = localDataDir ?? SetupContext.ResolveLocalDataDir();
5960
InitializeComponent();
6061
Active = this;
6162

63+
Closed += async (_, _) =>
64+
{
65+
_isClosed = true;
66+
_initialContentReady.TrySetResult(true);
67+
try
68+
{
69+
_lifetimeCts.Cancel();
70+
if (_contextApplyTask is { } contextApplyTask)
71+
await contextApplyTask;
72+
}
73+
catch (OperationCanceledException)
74+
{
75+
// Window teardown owns this cancellation; cleanup still must finish.
76+
}
77+
catch (Exception ex)
78+
{
79+
System.Diagnostics.Debug.WriteLine($"Setup cleanup failed: {ex}");
80+
}
81+
finally
82+
{
83+
_setupLock?.Dispose();
84+
_setupLock = null;
85+
if (ReferenceEquals(Active, this))
86+
Active = null;
87+
_cleanupCompleted.TrySetResult(true);
88+
}
89+
};
90+
6291
// Size window accounting for DPI
6392
var hwnd = WinRT.Interop.WindowNative.GetWindowHandle(this);
6493
var dpi = GetDpiForWindow(hwnd);
@@ -73,8 +102,17 @@ public SetupWindow(
73102
SystemBackdrop = new MicaBackdrop();
74103

75104
// Load config: explicit --config arg, or bundled default-config.json (required)
76-
var args = Environment.GetCommandLineArgs();
77-
var explicitConfigPath = configPath ?? GetArg(args, "--config");
105+
commandLineArgs ??= Environment.GetCommandLineArgs().Skip(1).ToArray();
106+
if (!SetupWindowCommandLine.TryParse(
107+
commandLineArgs,
108+
out var setupArguments,
109+
out var argumentError))
110+
{
111+
ShowConfigurationError($"Invalid setup arguments: {argumentError}");
112+
return;
113+
}
114+
115+
var explicitConfigPath = configPath ?? setupArguments.ConfigPath;
78116
configPath = explicitConfigPath;
79117
if (configPath == null)
80118
{
@@ -89,14 +127,23 @@ public SetupWindow(
89127
}
90128
}
91129

92-
if (configPath == null || !File.Exists(configPath))
130+
if (configPath == null)
93131
{
94-
throw new FileNotFoundException(
95-
"No config file found. Place default-config.json next to the executable or pass --config <path>.",
96-
configPath ?? Path.Combine(AppContext.BaseDirectory, "default-config.json"));
132+
var missingPath = Path.Combine(AppContext.BaseDirectory, "default-config.json");
133+
ShowConfigurationError(
134+
$"No setup configuration file was found at '{missingPath}'. " +
135+
"Place default-config.json next to the executable or pass --config <path>.");
136+
return;
137+
}
138+
139+
if (!SetupConfig.TryLoadFromFile(configPath, out var loadedConfig, out var configError))
140+
{
141+
ShowConfigurationError(
142+
$"The setup configuration file '{configPath}' could not be loaded. {configError}");
143+
return;
97144
}
98145

99-
_config = SetupConfig.LoadFromFile(configPath);
146+
_config = loadedConfig;
100147
_config.UsesBundledDefaultConfig = explicitConfigPath == null;
101148
_config = SetupConfig.FromEnvironment(_config);
102149
if (!string.IsNullOrWhiteSpace(distroNameOverride))
@@ -107,41 +154,13 @@ public SetupWindow(
107154
_config.GatewayUrl = null;
108155
}
109156
GatewayLkgVersion.ApplyToConfig(_config);
110-
_config.ApplyUiDefaults(rollbackOnFailure: !HasFlag(args, "--no-rollback-on-failure"));
157+
_config.ApplyUiDefaults(rollbackOnFailure: setupArguments.RollbackOnFailure);
111158
if (startAtGatewayInstalledMilestone)
112159
{
113160
_persistStartupPreferenceOnComplete = false;
114161
_showStartupPreferenceOnComplete = false;
115162
}
116163

117-
Closed += async (_, _) =>
118-
{
119-
_isClosed = true;
120-
_initialContentReady.TrySetResult(true);
121-
try
122-
{
123-
_lifetimeCts.Cancel();
124-
if (_contextApplyTask is { } contextApplyTask)
125-
await contextApplyTask;
126-
}
127-
catch (OperationCanceledException)
128-
{
129-
// Window teardown owns this cancellation; cleanup still must finish.
130-
}
131-
catch (Exception ex)
132-
{
133-
System.Diagnostics.Debug.WriteLine($"Setup cleanup failed: {ex}");
134-
}
135-
finally
136-
{
137-
_setupLock?.Dispose();
138-
_setupLock = null;
139-
if (ReferenceEquals(Active, this))
140-
Active = null;
141-
_cleanupCompleted.TrySetResult(true);
142-
}
143-
};
144-
145164
var previewPage = SetupPreview.RequestedPage;
146165
if (previewPage != null)
147166
{
@@ -250,6 +269,20 @@ public void NavigateToComplete(bool success, TimeSpan elapsed, string? logPath,
250269
ShowStartupPreference: _showStartupPreferenceOnComplete,
251270
ReviewSummary: SetupReviewSummaryBuilder.Build(_config, _dataDir, _localDataDir)));
252271

272+
private void ShowConfigurationError(string errorMessage)
273+
{
274+
_persistStartupPreferenceOnComplete = false;
275+
_showStartupPreferenceOnComplete = false;
276+
NavigateTo(
277+
typeof(CompletePage),
278+
new CompletePageArgs(
279+
Success: false,
280+
Elapsed: TimeSpan.Zero,
281+
LogPath: null,
282+
ErrorMessage: errorMessage,
283+
ShowStartupPreference: false));
284+
}
285+
253286
// Directional page transition: forward steps slide in from the right, Back from the left.
254287
private void NavigateTo(Type page, object? parameter, bool back = false) =>
255288
RootFrame.Navigate(page, parameter, new SlideNavigationTransitionInfo
@@ -381,16 +414,6 @@ private void CompleteInitialContentReady()
381414
() => _initialContentReady.TrySetResult(true));
382415
}
383416

384-
private static string? GetArg(string[] args, string name)
385-
{
386-
for (int i = 0; i < args.Length - 1; i++)
387-
if (args[i].Equals(name, StringComparison.OrdinalIgnoreCase))
388-
return args[i + 1];
389-
return null;
390-
}
391-
392-
private static bool HasFlag(string[] args, string name)
393-
=> args.Any(a => a.Equals(name, StringComparison.OrdinalIgnoreCase));
394417
}
395418

396419
public sealed record CompletePageArgs(

‎src/OpenClaw.SetupEngine/OpenClaw.SetupEngine.csproj‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99

1010
<ItemGroup>
1111
<InternalsVisibleTo Include="OpenClaw.SetupEngine.Tests" />
12+
<InternalsVisibleTo Include="OpenClaw.SetupEngine.UI" />
1213
<ProjectReference Include="..\OpenClaw.Connection\OpenClaw.Connection.csproj" />
1314
<ProjectReference Include="..\OpenClaw.Shared\OpenClaw.Shared.csproj" />
1415
</ItemGroup>

0 commit comments

Comments
 (0)