Skip to content

Commit 6b9e814

Browse files
authored
fix: screen and camera capture continue after cancellation (#1007)
* fix: stop cancelled screen and camera captures Propagate per-invocation cancellation through gateway, MCP, consent, countdown, and native capture paths while preserving bounded concurrent dispatch. Co-authored-by: Copilot App <[email protected]> Copilot-Session: 4ba999dd-6583-43ea-ac04-fcbe3c881113 * fix: make MCP pre-cancellation deterministic Replace the scheduler-dependent cancellation probe with bounded tombstones and preserve cancellation outcome semantics across registration races. Co-authored-by: Copilot App <[email protected]> Copilot-Session: 4ba999dd-6583-43ea-ac04-fcbe3c881113 * test: assert node cancellation response Capture the real Windows node send path and verify request-form node.invoke.cancel returns a successful cancelled payload. Co-authored-by: Copilot App <[email protected]> Copilot-Session: 4ba999dd-6583-43ea-ac04-fcbe3c881113 * fix: preserve camera capture failures Keep a primary preview capture exception when cancellation races cleanup, while retaining cancellation when no capture failure exists. Co-authored-by: Copilot App <[email protected]> Copilot-Session: 4ba999dd-6583-43ea-ac04-fcbe3c881113 * fix: harden cancellation response handling Co-authored-by: Copilot App <[email protected]> Copilot-Session: 4ba999dd-6583-43ea-ac04-fcbe3c881113
1 parent a286e43 commit 6b9e814

23 files changed

Lines changed: 2372 additions & 167 deletions

‎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/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.Shared/Capabilities/CameraCapability.cs‎

Lines changed: 43 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
using System;
22
using System.Collections.Generic;
3+
using System.Threading;
34
using System.Threading.Tasks;
45

56
namespace OpenClaw.Shared.Capabilities;
@@ -21,9 +22,9 @@ public class CameraCapability : NodeCapabilityBase
2122
public override IReadOnlyList<string> Commands => _commands;
2223

2324
// Events for platform-specific implementation
24-
public event Func<Task<CameraInfo[]>>? ListRequested;
25-
public event Func<CameraSnapArgs, Task<CameraSnapResult>>? SnapRequested;
26-
public event Func<CameraClipArgs, Task<CameraClipResult>>? ClipRequested;
25+
public event Func<CancellationToken, Task<CameraInfo[]>>? ListRequested;
26+
public event Func<CameraSnapArgs, CancellationToken, Task<CameraSnapResult>>? SnapRequested;
27+
public event Func<CameraClipArgs, CancellationToken, Task<CameraClipResult>>? ClipRequested;
2728

2829
public CameraCapability(IOpenClawLogger logger) : base(logger)
2930
{
@@ -32,18 +33,25 @@ public CameraCapability(IOpenClawLogger logger) : base(logger)
3233
private static int Clamp(int value, int min, int max)
3334
=> value < min ? min : (value > max ? max : value);
3435

35-
public override async Task<NodeInvokeResponse> ExecuteAsync(NodeInvokeRequest request)
36+
public override Task<NodeInvokeResponse> ExecuteAsync(NodeInvokeRequest request)
37+
=> ExecuteAsync(request, CancellationToken.None);
38+
39+
public override async Task<NodeInvokeResponse> ExecuteAsync(
40+
NodeInvokeRequest request,
41+
CancellationToken cancellationToken)
3642
{
3743
return request.Command switch
3844
{
39-
"camera.list" => await HandleListAsync(request),
40-
"camera.snap" => await HandleSnapAsync(request),
41-
"camera.clip" => await HandleClipAsync(request),
45+
"camera.list" => await HandleListAsync(request, cancellationToken),
46+
"camera.snap" => await HandleSnapAsync(request, cancellationToken),
47+
"camera.clip" => await HandleClipAsync(request, cancellationToken),
4248
_ => Error($"Unknown command: {request.Command}")
4349
};
4450
}
4551

46-
private async Task<NodeInvokeResponse> HandleListAsync(NodeInvokeRequest request)
52+
private async Task<NodeInvokeResponse> HandleListAsync(
53+
NodeInvokeRequest request,
54+
CancellationToken cancellationToken)
4755
{
4856
Logger.Info("camera.list");
4957

@@ -54,9 +62,15 @@ private async Task<NodeInvokeResponse> HandleListAsync(NodeInvokeRequest request
5462

5563
try
5664
{
57-
var cameras = await ListRequested();
65+
cancellationToken.ThrowIfCancellationRequested();
66+
var cameras = await ListRequested(cancellationToken);
67+
cancellationToken.ThrowIfCancellationRequested();
5868
return Success(new { cameras });
5969
}
70+
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
71+
{
72+
return Error("cancelled");
73+
}
6074
catch (Exception ex)
6175
{
6276
Logger.Error("Camera list failed", ex);
@@ -71,7 +85,9 @@ private async Task<NodeInvokeResponse> HandleListAsync(NodeInvokeRequest request
7185
private const int MaxQuality = 100;
7286
private const int MaxClipDurationMs = 60_000;
7387

74-
private async Task<NodeInvokeResponse> HandleSnapAsync(NodeInvokeRequest request)
88+
private async Task<NodeInvokeResponse> HandleSnapAsync(
89+
NodeInvokeRequest request,
90+
CancellationToken cancellationToken)
7591
{
7692
var deviceId = GetStringArg(request.Args, "deviceId");
7793
var format = GetStringArg(request.Args, "format", "jpeg");
@@ -87,13 +103,15 @@ private async Task<NodeInvokeResponse> HandleSnapAsync(NodeInvokeRequest request
87103

88104
try
89105
{
106+
cancellationToken.ThrowIfCancellationRequested();
90107
var result = await SnapRequested(new CameraSnapArgs
91108
{
92109
DeviceId = deviceId,
93110
Format = format ?? "jpeg",
94111
MaxWidth = maxWidth,
95112
Quality = quality
96-
});
113+
}, cancellationToken);
114+
cancellationToken.ThrowIfCancellationRequested();
97115

98116
return Success(new
99117
{
@@ -103,14 +121,20 @@ private async Task<NodeInvokeResponse> HandleSnapAsync(NodeInvokeRequest request
103121
base64 = result.Base64
104122
});
105123
}
124+
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
125+
{
126+
return Error("cancelled");
127+
}
106128
catch (Exception ex)
107129
{
108130
Logger.Error("Camera snap failed", ex);
109131
return Error("Snap failed");
110132
}
111133
}
112134

113-
private async Task<NodeInvokeResponse> HandleClipAsync(NodeInvokeRequest request)
135+
private async Task<NodeInvokeResponse> HandleClipAsync(
136+
NodeInvokeRequest request,
137+
CancellationToken cancellationToken)
114138
{
115139
var deviceId = GetStringArg(request.Args, "deviceId");
116140
// Floor at 100ms — anything shorter is meaningless and a 0/negative
@@ -128,13 +152,15 @@ private async Task<NodeInvokeResponse> HandleClipAsync(NodeInvokeRequest request
128152

129153
try
130154
{
155+
cancellationToken.ThrowIfCancellationRequested();
131156
var result = await ClipRequested(new CameraClipArgs
132157
{
133158
DeviceId = deviceId,
134159
DurationMs = durationMs,
135160
IncludeAudio = includeAudio,
136161
Format = format
137-
});
162+
}, cancellationToken);
163+
cancellationToken.ThrowIfCancellationRequested();
138164

139165
return Success(new
140166
{
@@ -144,6 +170,10 @@ private async Task<NodeInvokeResponse> HandleClipAsync(NodeInvokeRequest request
144170
hasAudio = result.HasAudio
145171
});
146172
}
173+
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
174+
{
175+
return Error("cancelled");
176+
}
147177
catch (Exception ex)
148178
{
149179
Logger.Error("Camera clip failed", ex);

‎src/OpenClaw.Shared/Capabilities/ScreenCapability.cs‎

Lines changed: 31 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
using System;
22
using System.Collections.Generic;
3+
using System.Threading;
34
using System.Threading.Tasks;
45

56
namespace OpenClaw.Shared.Capabilities;
@@ -20,19 +21,24 @@ public class ScreenCapability : NodeCapabilityBase
2021
public override IReadOnlyList<string> Commands => _commands;
2122

2223
// Events for UI/platform-specific implementation
23-
public event Func<ScreenCaptureArgs, Task<ScreenCaptureResult>>? CaptureRequested;
24-
public event Func<ScreenRecordArgs, Task<ScreenRecordResult>>? RecordRequested;
24+
public event Func<ScreenCaptureArgs, CancellationToken, Task<ScreenCaptureResult>>? CaptureRequested;
25+
public event Func<ScreenRecordArgs, CancellationToken, Task<ScreenRecordResult>>? RecordRequested;
2526

2627
public ScreenCapability(IOpenClawLogger logger) : base(logger)
2728
{
2829
}
2930

30-
public override async Task<NodeInvokeResponse> ExecuteAsync(NodeInvokeRequest request)
31+
public override Task<NodeInvokeResponse> ExecuteAsync(NodeInvokeRequest request)
32+
=> ExecuteAsync(request, CancellationToken.None);
33+
34+
public override async Task<NodeInvokeResponse> ExecuteAsync(
35+
NodeInvokeRequest request,
36+
CancellationToken cancellationToken)
3137
{
3238
return request.Command switch
3339
{
34-
"screen.snapshot" => await HandleCaptureAsync(request),
35-
"screen.record" => await HandleRecordAsync(request),
40+
"screen.snapshot" => await HandleCaptureAsync(request, cancellationToken),
41+
"screen.record" => await HandleRecordAsync(request, cancellationToken),
3642
_ => Error($"Unknown command: {request.Command}")
3743
};
3844
}
@@ -44,7 +50,9 @@ public override async Task<NodeInvokeResponse> ExecuteAsync(NodeInvokeRequest re
4450
private const int MaxQuality = 100;
4551
private const int MaxScreenIndex = 32; // far above any plausible monitor count
4652

47-
private async Task<NodeInvokeResponse> HandleCaptureAsync(NodeInvokeRequest request)
53+
private async Task<NodeInvokeResponse> HandleCaptureAsync(
54+
NodeInvokeRequest request,
55+
CancellationToken cancellationToken)
4856
{
4957
// The format is interpolated into the data URI, so validate it before
5058
// invoking the capture backend.
@@ -69,14 +77,16 @@ private async Task<NodeInvokeResponse> HandleCaptureAsync(NodeInvokeRequest requ
6977

7078
try
7179
{
80+
cancellationToken.ThrowIfCancellationRequested();
7281
var result = await CaptureRequested(new ScreenCaptureArgs
7382
{
7483
Format = format,
7584
MaxWidth = maxWidth,
7685
Quality = quality,
7786
MonitorIndex = screenIndex,
7887
IncludePointer = includePointer
79-
});
88+
}, cancellationToken);
89+
cancellationToken.ThrowIfCancellationRequested();
8090

8191
// Use the validated format for the MIME type instead of the backend echo.
8292
var image = $"data:image/{format};base64,{result.Base64}";
@@ -89,6 +99,10 @@ private async Task<NodeInvokeResponse> HandleCaptureAsync(NodeInvokeRequest requ
8999
image
90100
});
91101
}
102+
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
103+
{
104+
return Error("cancelled");
105+
}
92106
catch (Exception ex)
93107
{
94108
Logger.Error("Screen capture failed", ex);
@@ -120,7 +134,9 @@ internal static bool TryNormalizeSnapshotFormat(string? requested, out string no
120134
}
121135
}
122136

123-
private async Task<NodeInvokeResponse> HandleRecordAsync(NodeInvokeRequest request)
137+
private async Task<NodeInvokeResponse> HandleRecordAsync(
138+
NodeInvokeRequest request,
139+
CancellationToken cancellationToken)
124140
{
125141
var format = GetStringArg(request.Args, "format", "mp4");
126142
if (!string.IsNullOrWhiteSpace(format) &&
@@ -144,14 +160,16 @@ private async Task<NodeInvokeResponse> HandleRecordAsync(NodeInvokeRequest reque
144160

145161
try
146162
{
163+
cancellationToken.ThrowIfCancellationRequested();
147164
var result = await RecordRequested(new ScreenRecordArgs
148165
{
149166
DurationMs = durationMs,
150167
Fps = fps,
151168
ScreenIndex = screenIndex,
152169
Format = "mp4",
153170
IncludeAudio = includeAudio
154-
});
171+
}, cancellationToken);
172+
cancellationToken.ThrowIfCancellationRequested();
155173

156174
return Success(new
157175
{
@@ -163,6 +181,10 @@ private async Task<NodeInvokeResponse> HandleRecordAsync(NodeInvokeRequest reque
163181
hasAudio = result.HasAudio
164182
});
165183
}
184+
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
185+
{
186+
return Error("cancelled");
187+
}
166188
catch (Exception ex)
167189
{
168190
Logger.Error("Screen recording failed", ex);

0 commit comments

Comments
 (0)