From cb0f0ffa9ae2a83ea67a9e53b942d1c058688377 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Fri, 20 Nov 2026 13:34:08 +0800 Subject: [PATCH] Track only the Windows CUA helper's own input dispatches --- .../cua-held-inputs/guide.i18n.yaml | 4 +- .../v0.2.2-rc.5/cua-held-inputs/guide.md | 2 +- .../v0.2.2-rc.5/cua-held-inputs/guide.zh.md | 2 +- .../experimental/cua-windows/README.i18n.yaml | 4 +- packages/experimental/cua-windows/README.md | 1 + .../experimental/cua-windows/README.zh.md | 1 + .../native/desktop-tests/Program.cs | 8 +- .../native/entry/DesktopExecutor.cs | 35 +-- .../cua-windows/native/entry/HeldInputs.cs | 212 +++--------------- .../cua-windows/native/entry/Input.cs | 15 +- .../cua-windows/native/entry/Win32.cs | 6 - .../native/tests/HeldInputChecks.cs | 54 ++--- .../tests/desktop-toggle-mouse.spec.ts | 12 +- 13 files changed, 104 insertions(+), 252 deletions(-) diff --git a/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.i18n.yaml index a753c8369d..87f47f507c 100644 --- a/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.i18n.yaml @@ -9,8 +9,8 @@ en: 37252a5d19c7fe09 zh: f1b33b7da3935155 /cua-reports-held-input-after-programs/change: - en: 2812241cf189be50 - zh: ee90f8e5c6c55512 + en: cf9c1397e07dffa5 + zh: f1cce9fadf321d43 /cua-reports-held-input-after-programs/migration: en: 1bd7668cac0efe0d zh: 2122c9d5135283f7 diff --git a/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.md b/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.md index b6c7ff0426..cda4b4f345 100644 --- a/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.md +++ b/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.md @@ -8,7 +8,7 @@ English | [中文](guide.zh.md) ## Change -On macOS and Windows, explicit `sendKeyEvent('down')` and `toggleMouse('down')` remain held across programs and turns until an explicit `up`. Normal completion does not release them. After a successful `run_code` or `cua_run_code`, a system reminder lists any remaining keys and mouse buttons, their application or window and actual input mode. Program failure, user stop, connection closure, environment reset and disposal release owned input in reverse dispatch order. Complete `pressKey`, `typeText`, `click` and `drag` actions keep their operation-local cleanup. DSH and MCP both preserve input after successful programs. A client pause between completed MCP calls is not observable by the server and can leave input held. On Windows, an up after focus changes releases desktop input without reactivating the original window. +On macOS and Windows, explicit `sendKeyEvent('down')` and `toggleMouse('down')` remain held across programs and turns until an explicit `up`. Normal completion does not release them. After a successful `run_code` or `cua_run_code`, a system reminder lists any remaining keys and mouse buttons, their application or window and actual input mode. Program failure, user stop, connection closure, environment reset and disposal release owned input in reverse dispatch order. Complete `pressKey`, `typeText`, `click` and `drag` actions keep their operation-local cleanup. DSH and MCP both preserve input after successful programs. A client pause between completed MCP calls is not observable by the server and can leave input held. On Windows, cleanup sends an up for each input the helper still holds. If you also hold the same key or button, that up may interrupt your press. A focus change sends the up to the desktop without reactivating the original window. ## Migration diff --git a/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.zh.md index a342f3d78a..b9e7025603 100644 --- a/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.zh.md +++ b/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.zh.md @@ -8,7 +8,7 @@ description: macOS 和 Windows 的 CUA 显式输入跨程序和回合保持, ## 变更 -macOS 和 Windows 的显式 `sendKeyEvent('down')` 和 `toggleMouse('down')` 跨程序、跨回合保持,直到显式 `up`。正常结束不释放它们。成功结束的 `run_code` 或 `cua_run_code` 通过 system reminder 列出剩余键盘键和鼠标按钮、所属应用或窗口及实际输入方式。程序失败、用户停止、断连、环境重置和销毁按派发顺序的反序释放所属输入。完整的 `pressKey`、`typeText`、`click` 和 `drag` 保持操作内清理。DSH 和 MCP 都在程序成功后保持输入。客户端在两次 MCP 调用之间暂停时,服务端无法观察到,输入可能继续按住。Windows 失焦后松开会释放桌面输入,不重新激活原窗口。 +macOS 和 Windows 的显式 `sendKeyEvent('down')` 和 `toggleMouse('down')` 跨程序、跨回合保持,直到显式 `up`。正常结束不释放它们。成功结束的 `run_code` 或 `cua_run_code` 通过 system reminder 列出剩余键盘键和鼠标按钮、所属应用或窗口及实际输入方式。程序失败、用户停止、断连、环境重置和销毁按派发顺序的反序释放所属输入。完整的 `pressKey`、`typeText`、`click` 和 `drag` 保持操作内清理。DSH 和 MCP 都在程序成功后保持输入。客户端在两次 MCP 调用之间暂停时,服务端无法观察到,输入可能继续按住。Windows 清理时会为 helper 仍持有的输入发送 up。如果你也按住同一个键或按钮,这次 up 可能打断你的按压。焦点变化后,up 发往当前桌面,原窗口不会被重新激活。 ## 迁移 diff --git a/packages/experimental/cua-windows/README.i18n.yaml b/packages/experimental/cua-windows/README.i18n.yaml index 1ab20bd3f7..01777fdeb8 100644 --- a/packages/experimental/cua-windows/README.i18n.yaml +++ b/packages/experimental/cua-windows/README.i18n.yaml @@ -45,8 +45,8 @@ en: db3e2957041fafbb zh: 34f953887dff37f7 /deepseek-ai-dsh-cua-windows/known-limitations-and-deferred-work: - en: c68454f8d03edabe - zh: f4d41f22838a9eb9 + en: f36d057acb4e9ea3 + zh: a1a94877e51d9d66 /deepseek-ai-dsh-cua-windows/known-limitations-and-deferred-work/dev-note: en: 0a1253c6f7b5e8b9 zh: 9f56528562c7c914 diff --git a/packages/experimental/cua-windows/README.md b/packages/experimental/cua-windows/README.md index 44ffb568ba..7839f0934a 100644 --- a/packages/experimental/cua-windows/README.md +++ b/packages/experimental/cua-windows/README.md @@ -82,6 +82,7 @@ Inspected results append to model history. Retaining an App, Window, or returned - The npm package omits the Windows helper. Use the [standalone ZIP on x64 or a matching build on ARM64](#setup). - Hover, click, scroll and drag use the system pointer. `requireSystemInputApproval` does not prompt separately for Windows pointer operations. - Drag checks the topmost window only at its starting point. An overlay from another application along the path or at the destination can receive the drop even while the selected window stays in the foreground. +- Held-input reminders and cleanup use the helper's own dispatches. If you press the same key or button while the helper holds it, its next up can also interrupt your press. - Windows routes input through the desktop. After focus changes or the original window closes, a confirmed release means the desktop accepted the up. The original window may not receive the event. If the desktop is unavailable or refuses to confirm release, further CUA input for the task is blocked. Inspect the desktop before starting another task. - Cleanup of temporary input inside complete actions does not check each key or button release. If an input remains held after a failure, release it manually before continuing. - Helper identity hashes only the exe. Different DLLs with the same apphost can reuse the old service. Stop Hosts using the same output directory before rebuilding to avoid locked files. diff --git a/packages/experimental/cua-windows/README.zh.md b/packages/experimental/cua-windows/README.zh.md index dbc9067e2a..49c1558534 100644 --- a/packages/experimental/cua-windows/README.zh.md +++ b/packages/experimental/cua-windows/README.zh.md @@ -82,6 +82,7 @@ kind: "package-reference" - 通过 npm 安装的包不含 Windows helper。x64 可使用独立 ZIP,ARM64 需要对应架构的构建产物,见[配置说明](#setup)。 - 悬停、点击、滚动和拖拽使用系统指针。`requireSystemInputApproval` 不会为 Windows 操作弹出单独的指针授权提示。 - 拖拽只检查起点处最上层的窗口。若其他应用遮住路径或终点,即使目标仍在前台,也可能把内容拖到其他应用。 +- 持有提醒和清理只依据 helper 自己派发的输入。如果你也按住同一个键或按钮,helper 之后发送的 up 可能打断你的按压。 - Windows 通过桌面派发输入。焦点变化或原窗口关闭后,确认释放表示桌面接受了 up,原窗口可能收不到该事件。若桌面不可用或无法确认释放,本任务不能继续使用 CUA。请先检查桌面,再开始新任务。 - 清理完整动作内的临时输入时,helper 不检查每个按键或鼠标按钮的释放结果。操作失败后如有按键或按钮仍处于按下状态,请先手动释放。 - helper 的身份摘要只覆盖 exe。同一 apphost 搭配不同 DLL 时可能复用旧服务。重新构建前请先关闭使用同一输出目录的 Host,避免文件被占用。 diff --git a/packages/experimental/cua-windows/native/desktop-tests/Program.cs b/packages/experimental/cua-windows/native/desktop-tests/Program.cs index 5e96f96a96..fabce63383 100644 --- a/packages/experimental/cua-windows/native/desktop-tests/Program.cs +++ b/packages/experimental/cua-windows/native/desktop-tests/Program.cs @@ -12,6 +12,7 @@ internal sealed class FixtureForm : Form private readonly Button button = new() { Name = "submit", Text = "Record click", Bounds = new(20, 140, 180, 40) }; private int clicks; private readonly List inputEvents = []; + private MouseButtons receivedButtons; private int leftDowns, leftUps, rightDowns, rightUps, middleDowns, middleUps; private readonly ToolTip tooltip = new(); @@ -41,6 +42,7 @@ internal sealed class FixtureForm : Form private void Count(MouseButtons pressed, bool down) { + receivedButtons = down ? receivedButtons | pressed : receivedButtons & ~pressed; inputEvents.Add($"{pressed}:{(down ? "down" : "up")}"); switch (pressed) { @@ -84,8 +86,8 @@ internal sealed class FixtureForm : Form ups = new { left = leftUps, right = rightUps, middle = middleUps }, button = new { x = button.Left + button.Width / 2, y = button.Top + button.Height / 2 }, selection = new { start = Editor.SelectionStart, length = Editor.SelectionLength }, - inputEvents = inputEvents.ToArray(), wDown = (GetAsyncKeyState(87) & 0x8000) != 0, - buttons = MouseButtons.ToString(), minimized = WindowState == FormWindowState.Minimized, visible = Visible, + inputEvents = inputEvents.ToArray(), + buttons = receivedButtons.ToString(), minimized = WindowState == FormWindowState.Minimized, visible = Visible, }; protected override void Dispose(bool disposing) @@ -94,7 +96,6 @@ internal sealed class FixtureForm : Form base.Dispose(disposing); } - [DllImport("user32.dll")] private static extern short GetAsyncKeyState(int key); [DllImport("user32.dll")] private static extern nint GetForegroundWindow(); [DllImport("user32.dll")] private static extern nint WindowFromPoint(Point point); [DllImport("user32.dll")] private static extern nint GetAncestor(nint window, uint flags); @@ -141,6 +142,7 @@ internal static class Program { case "sibling": sibling.Show(); sibling.Activate(); sibling.Editor.Focus(); Write(sibling.Inspect()); break; case "inspect": Write(form.Inspect()); break; + case "inspect-sibling": Write(sibling.Inspect()); break; case "focus": form.Activate(); form.Editor.Focus(); Write(form.Inspect()); break; case "pointer": form.PointAtButton(); Write(form.Inspect()); break; case "pointer-outside": form.PointOutside(); Write(form.Inspect()); break; diff --git a/packages/experimental/cua-windows/native/entry/DesktopExecutor.cs b/packages/experimental/cua-windows/native/entry/DesktopExecutor.cs index 0bcad20693..e553283013 100644 --- a/packages/experimental/cua-windows/native/entry/DesktopExecutor.cs +++ b/packages/experimental/cua-windows/native/entry/DesktopExecutor.cs @@ -15,21 +15,9 @@ internal sealed class ClientState internal void Clear() { foreach (var app in Apps.Values) app.Dispose(); Apps.Clear(); } } -internal sealed class DesktopExecutor : IAsyncDisposable +internal sealed class DesktopExecutor(MtaDispatcher mta, StaDispatcher sta) : IAsyncDisposable { - private readonly MtaDispatcher mta; - private readonly StaDispatcher sta; - private readonly HeldInputs inputs = new(control => (Win32.GetAsyncKeyState(control) & 0x8000) != 0, - input => Input.Send(input), DesktopSession.RequireInteractive); - private readonly HeldInputHooks hooks; - - internal DesktopExecutor(MtaDispatcher mta, StaDispatcher sta) - { - this.mta = mta; - this.sta = sta; - hooks = new(inputs); - } - + private readonly HeldInputs inputs = new(input => Input.Send(input), DesktopSession.RequireInteractive); private readonly WindowCapture capture = new(); private readonly ClipboardPaste clipboard = new(); private readonly SemaphoreSlim queue = new(1); @@ -100,7 +88,7 @@ internal sealed class DesktopExecutor : IAsyncDisposable throw new NativeFailure("UNSUPPORTED", "Windows desktop access has no macOS permission switches; inspect the Windows session status"); if (request.Method == "getHeldInputs") return inputs.Get(state.Connection, String(parameters, "taskId")); if (request.Method == "releaseHeldInputs") - return inputs.Release(state.Connection, String(parameters, "taskId"), cancellation, config.GraceMs); + return inputs.Release(state.Connection, String(parameters, "taskId"), cancellation); if (request.Method is "sendKeyEvent" or "toggleMouse" && String(parameters, "direction") == "up") { @@ -108,10 +96,11 @@ internal sealed class DesktopExecutor : IAsyncDisposable var task = String(parameters, "taskId"); var recipient = String(parameters, "appHandle"); var before = Win32.GetForegroundWindow(); - var dispatched = request.Method == "sendKeyEvent" - ? Input.ReleaseKey(state.Connection, task, recipient, window, String(parameters, "key"), context) - : Input.ReleaseButton(state.Connection, task, recipient, window, String(parameters, "mouseButton"), context); - return ActionResult(before, dispatched); + if (request.Method == "sendKeyEvent") + Input.ReleaseKey(state.Connection, task, recipient, window, String(parameters, "key"), context); + else + Input.ReleaseButton(state.Connection, task, recipient, window, String(parameters, "mouseButton"), context); + return ActionResult(before); } DesktopSession.RequireInteractive(); if (request.Method == "listApps") return await DesktopWindows.ListApps(context); @@ -174,7 +163,6 @@ internal sealed class DesktopExecutor : IAsyncDisposable case "sendKeyEvent": { var target = Selected(app, parameters, context); - await sta.Invoke(hooks.Start, cancellation); var dispatched = Input.KeyDown(state.Connection, String(parameters, "taskId"), app, target, String(parameters, "key"), context); return ActionResult(foreground, dispatched); } @@ -206,7 +194,6 @@ internal sealed class DesktopExecutor : IAsyncDisposable case "toggleMouse": { var target = Selected(app, parameters, context); - await sta.Invoke(hooks.Start, cancellation); var dispatched = Input.ButtonDown(state.Connection, String(parameters, "taskId"), app, target, String(parameters, "mouseButton"), context); return ActionResult(foreground, dispatched); } @@ -317,13 +304,13 @@ internal sealed class DesktopExecutor : IAsyncDisposable if (!inputs.HasConnection(state.Connection)) return; using var deadline = new CancellationTokenSource(graceMs); await queue.WaitAsync(deadline.Token); - try { inputs.Release(state.Connection, null, deadline.Token, graceMs); } + try { inputs.Release(state.Connection, null, deadline.Token); } finally { queue.Release(); } } - public async ValueTask DisposeAsync() + public ValueTask DisposeAsync() { - await sta.Invoke(hooks.Dispose, CancellationToken.None); queue.Dispose(); + return ValueTask.CompletedTask; } } diff --git a/packages/experimental/cua-windows/native/entry/HeldInputs.cs b/packages/experimental/cua-windows/native/entry/HeldInputs.cs index 55a133ac05..47267898b5 100644 --- a/packages/experimental/cua-windows/native/entry/HeldInputs.cs +++ b/packages/experimental/cua-windows/native/entry/HeldInputs.cs @@ -1,16 +1,14 @@ -// The shared desktop executor serializes dispatch. Hooks arbitrate external input in the Windows input stream. +// Held keys and buttons share one dispatch order across all connections to this desktop executor. using System.Globalization; -using System.Runtime.InteropServices; using DeepSeek.Cua.Protocol; namespace DeepSeek.Cua.Windows; -internal sealed class HeldInputs(Func isDown, Action send, Action requireInteractive) +internal sealed class HeldInputs(Action send, Action requireInteractive) { internal readonly record struct Target(string AppHandle, nint Window, int ProcessId, long ProcessStarted); private sealed record Press(Guid Connection, string Task, Target Target, ushort Control, string Name, Win32.Input Up) { - internal bool Confirmed { get; set; } internal object Describe() => new { kind = Up.Type == 1 ? "key" : "mouse", key = Up.Type == 1 ? Name : null, @@ -19,70 +17,28 @@ internal sealed class HeldInputs(Func isDown, Action }; } - private sealed record Dispatch(Press Press, nuint Tag, TaskCompletionSource Completion); - private readonly object gate = new(); private readonly List pressed = []; - private readonly nuint prefix = unchecked((nuint)Random.Shared.NextInt64(1, int.MaxValue)) << 32; - private uint sequence; - private Dispatch? pending; - - internal static ushort CanonicalControl(ushort key) => key switch - { - 0xA0 or 0xA1 => 0x10, // Shift - 0xA2 or 0xA3 => 0x11, // Control - 0xA4 or 0xA5 => 0x12, // Alt - _ => key, - }; - - // An accepted external event supersedes an owned hold on the same global Windows input. - internal nint Observe(ushort control, nuint tag, Func next) - { - Dispatch? dispatch; - lock (gate) - { - dispatch = pending?.Tag == tag ? pending : null; - if (dispatch is not null && !pressed.Contains(dispatch.Press)) - { - dispatch.Completion.TrySetResult(false); - return 1; - } - // A delayed synthetic event without an admitted dispatch must not reach the desktop. - if (dispatch is null && tag >> 32 == prefix >> 32) return 1; - } - var outcome = next(); - lock (gate) - { - if (dispatch is not null) dispatch.Completion.TrySetResult(outcome == 0); - else if (outcome == 0) pressed.RemoveAll(press => press.Control == control); - } - return outcome; - } internal void RequireOwner(Guid connection, string? task, string app, nint window) { lock (gate) - { - if (pressed.Exists(press => !press.Confirmed)) - throw new NativeFailure("INPUT_DISPATCH_UNCONFIRMED", "Release unconfirmed held input before sending more desktop input"); if (pressed.Any(press => press.Connection != connection || (task is not null && press.Task != task) || press.Target.AppHandle != app || press.Target.Window != window)) throw new NativeFailure("INPUT_BUSY", "Another task or window owns held desktop input; release it before sending input to this window"); - } } internal void RequireAvailable(ushort control) { lock (gate) - if (pressed.Any(press => press.Control == control) || isDown(control)) + if (pressed.Any(press => press.Control == control)) throw new NativeFailure("INPUT_BUSY", "This key or button is already held; release it before a complete action uses it"); } internal bool Down(Guid connection, string task, Target target, ushort control, string name, Win32.Input down, - Win32.Input up, CancellationToken cancellation, int graceMs) + Win32.Input up, CancellationToken cancellation) { - Press press; lock (gate) { cancellation.ThrowIfCancellationRequested(); @@ -93,47 +49,35 @@ internal sealed class HeldInputs(Func isDown, Action return false; throw new NativeFailure("INPUT_BUSY", "This key or button is already held by another input target"); } - if (isDown(control)) - throw new NativeFailure("INPUT_BUSY", "This key or button is already down outside this task; ask the user to release it before retrying"); - press = new(connection, task, target, control, name, up); + + var press = new Press(connection, task, target, control, name, up); pressed.Add(press); - } - try - { - if (Post(press, down, graceMs)) + try { send(down); } + catch (NativeFailure error) when (error.Code == "INPUT_BLOCKED") { - lock (gate) press.Confirmed = true; - return true; + // SendInput accepted zero events, so there is no corresponding up to send. + pressed.Remove(press); + throw; } + return true; } - catch (NativeFailure error) when (error.Code == "INPUT_BLOCKED") - { - lock (gate) pressed.Remove(press); - throw; - } - lock (gate) pressed.Remove(press); - throw new NativeFailure("INPUT_BLOCKED", "Windows did not deliver the requested press to its input stream"); } - internal bool Up(Guid connection, string task, string app, nint window, string name, bool keyboard, int graceMs) + internal void Up(Guid connection, string task, string app, nint window, string name, bool keyboard) { - Press? press; lock (gate) - press = pressed.Find(press => press.Connection == connection && press.Task == task && press.Target.AppHandle == app + { + var index = pressed.FindIndex(press => press.Connection == connection && press.Task == task && press.Target.AppHandle == app && press.Target.Window == window && press.Name == name && (press.Up.Type == 1) == keyboard); - if (press is null) throw new NativeFailure("INPUT_NOT_HELD", "This task did not hold that input on the selected window"); - return Release(press, graceMs); + if (index < 0) throw new NativeFailure("INPUT_NOT_HELD", "This task did not hold that input on the selected window"); + ReleaseAt(index); + } } internal object[] Get(Guid connection, string task) { lock (gate) - { - var owned = pressed.Where(press => press.Connection == connection && press.Task == task).ToArray(); - if (owned.Any(press => !press.Confirmed)) - throw new NativeFailure("INPUT_DISPATCH_UNCONFIRMED", "Windows did not confirm which inputs are held"); - return owned.Select(press => press.Describe()).ToArray(); - } + return pressed.Where(press => press.Connection == connection && press.Task == task).Select(press => press.Describe()).ToArray(); } internal bool HasConnection(Guid connection) @@ -141,113 +85,29 @@ internal sealed class HeldInputs(Func isDown, Action lock (gate) return pressed.Exists(press => press.Connection == connection); } - internal object[] Release(Guid connection, string? task, CancellationToken cancellation, int graceMs) + internal object[] Release(Guid connection, string? task, CancellationToken cancellation) { - Press[] owned; - lock (gate) owned = pressed.Where(press => press.Connection == connection && (task is null || press.Task == task)).Reverse().ToArray(); - var released = new List(); - var failures = new List(); - foreach (var press in owned) + lock (gate) { - cancellation.ThrowIfCancellationRequested(); - try { if (Release(press, graceMs)) released.Add(press.Describe()); } - catch (NativeFailure error) { failures.Add(error.Message); } + var released = new List(); + var failures = new List(); + for (var index = pressed.Count - 1; index >= 0; index--) + { + var press = pressed[index]; + if (press.Connection != connection || (task is not null && press.Task != task)) continue; + cancellation.ThrowIfCancellationRequested(); + try { ReleaseAt(index); released.Add(press.Describe()); } + catch (NativeFailure error) { failures.Add(error.Message); } + } + if (failures.Count != 0) throw new NativeFailure("INPUT_CLEANUP_FAILED", string.Join("; ", failures)); + return released.ToArray(); } - if (failures.Count != 0) throw new NativeFailure("INPUT_CLEANUP_FAILED", string.Join("; ", failures)); - return released.ToArray(); } - private bool Release(Press press, int graceMs) + private void ReleaseAt(int index) { - lock (gate) if (!pressed.Contains(press)) return false; - // SendInput releases the global input at its current destination; never reactivate an old HWND. requireInteractive(); - var posted = Post(press, press.Up, graceMs); - lock (gate) - { - if (posted) pressed.Remove(press); - else if (pressed.Contains(press)) - throw new NativeFailure("INPUT_BLOCKED", "Windows did not deliver the requested release to its input stream"); - } - return posted; - } - - private bool Post(Press press, Win32.Input input, int graceMs) - { - Dispatch dispatch; - lock (gate) - { - if (!pressed.Contains(press)) return false; - if (pending is not null) throw new NativeFailure("INPUT_BUSY", "Another held input is being dispatched"); - dispatch = new(press, prefix | ++sequence, new(TaskCreationOptions.RunContinuationsAsynchronously)); - pending = dispatch; - } - try - { - if (input.Type == 1) input.Data.Keyboard.Extra = dispatch.Tag; - else input.Data.Mouse.Extra = dispatch.Tag; - send(input); - return dispatch.Completion.Task.WaitAsync(TimeSpan.FromMilliseconds(graceMs)).GetAwaiter().GetResult(); - } - catch (TimeoutException) - { - lock (gate) press.Confirmed = false; - throw new NativeFailure("INPUT_DISPATCH_UNCONFIRMED", "Windows did not confirm the held-input event; inspect the desktop before retrying"); - } - finally - { - lock (gate) pending = null; - } - } - -} - -internal sealed class HeldInputHooks(HeldInputs inputs) : IDisposable -{ - [StructLayout(LayoutKind.Sequential)] - private struct KeyEvent { internal uint Key, Scan, Flags, Time; internal nuint Extra; } - [StructLayout(LayoutKind.Sequential)] - private struct MouseEvent { internal Win32.Point Point; internal uint Data, Flags, Time; internal nuint Extra; } - - private nint keyboard; - private nint mouse; - private readonly Win32.InputHook keyHook = (code, message, value) => - { - if (code < 0) return Win32.CallNextHookEx(0, code, message, value); - var input = Marshal.PtrToStructure(value); - if (input.Key > ushort.MaxValue) return Win32.CallNextHookEx(0, code, message, value); - return inputs.Observe(HeldInputs.CanonicalControl((ushort)input.Key), input.Extra, () => Win32.CallNextHookEx(0, code, message, value)); - }; - private readonly Win32.InputHook mouseHook = (code, message, value) => - { - ushort control = message switch - { - 0x0201 or 0x0202 => 1, // Left down/up - 0x0204 or 0x0205 => 2, // Right down/up - 0x0207 or 0x0208 => 4, // Middle down/up - _ => 0, - }; - if (code < 0 || control == 0) return Win32.CallNextHookEx(0, code, message, value); - var input = Marshal.PtrToStructure(value); - return inputs.Observe(control, input.Extra, () => Win32.CallNextHookEx(0, code, message, value)); - }; - - // Low-level hooks must be installed on a thread that pumps Windows messages. - internal void Start() - { - if (keyboard != 0) return; - var module = Win32.GetModuleHandle(null); - keyboard = Win32.SetWindowsHookEx(13, keyHook, module, 0); - mouse = Win32.SetWindowsHookEx(14, mouseHook, module, 0); - if (keyboard != 0 && mouse != 0) return; - Dispose(); - throw new NativeFailure("INPUT_UNAVAILABLE", "Windows could not observe ownership of held desktop input"); - } - - public void Dispose() - { - if (keyboard != 0) Win32.UnhookWindowsHookEx(keyboard); - if (mouse != 0) Win32.UnhookWindowsHookEx(mouse); - keyboard = mouse = 0; + send(pressed[index].Up); + pressed.RemoveAt(index); } } diff --git a/packages/experimental/cua-windows/native/entry/Input.cs b/packages/experimental/cua-windows/native/entry/Input.cs index f213cd3769..36fc33b79d 100644 --- a/packages/experimental/cua-windows/native/entry/Input.cs +++ b/packages/experimental/cua-windows/native/entry/Input.cs @@ -104,8 +104,8 @@ internal static class Input var key => key, }; - internal static bool ReleaseKey(Guid connection, string task, string app, nint window, string name, RequestContext context) - => context.HeldInputs.Up(connection, task, app, window, HoldKeyName(name), true, context.Config.GraceMs); + internal static void ReleaseKey(Guid connection, string task, string app, nint window, string name, RequestContext context) + => context.HeldInputs.Up(connection, task, app, window, HoldKeyName(name), true); internal static bool KeyDown(Guid connection, string task, AppState app, WindowState window, string name, RequestContext context) { @@ -116,7 +116,7 @@ internal static class Input throw new NativeFailure("UNSUPPORTED", "This key requires modifiers in the target keyboard layout; send each modifier and the base key separately"); var flags = key.Extended ? 1u : 0; return context.HeldInputs.Down(connection, task, new(app.Handle, window.Id, window.ProcessId, window.ProcessStarted), - key.Key, name, Keyboard(key.Key, flags: flags), Keyboard(key.Key, flags: flags | 2), context.Cancellation, context.Config.GraceMs); + key.Key, name, Keyboard(key.Key, flags: flags), Keyboard(key.Key, flags: flags | 2), context.Cancellation); } internal static void Press(AppState app, WindowState window, string key, string[] modifiers, RequestContext context) @@ -187,8 +187,8 @@ internal static class Input return new { dispatched = true, hoverRoute = "system-pointer", systemPointerMoved = before.X != point.X || before.Y != point.Y }; } - internal static bool ReleaseButton(Guid connection, string task, string app, nint window, string button, RequestContext context) - => context.HeldInputs.Up(connection, task, app, window, button, false, context.Config.GraceMs); + internal static void ReleaseButton(Guid connection, string task, string app, nint window, string button, RequestContext context) + => context.HeldInputs.Up(connection, task, app, window, button, false); internal static bool ButtonDown(Guid connection, string task, AppState app, WindowState window, string button, RequestContext context) { @@ -196,7 +196,7 @@ internal static class Input if (!Win32.GetCursorPos(out var point)) throw new NativeFailure("INPUT_UNAVAILABLE", "The current pointer position is unavailable"); Hit(app, window, point, context); return context.HeldInputs.Down(connection, task, new(app.Handle, window.Id, window.ProcessId, window.ProcessStarted), - flags.Control, button, Mouse(flags.Down), Mouse(flags.Up), context.Cancellation, context.Config.GraceMs); + flags.Control, button, Mouse(flags.Down), Mouse(flags.Up), context.Cancellation); } internal static void Click(AppState app, WindowState window, double x, double y, string button, int count, string[] modifiers, RequestContext context) @@ -274,11 +274,12 @@ internal static class Input internal static async Task Drag(AppState app, WindowState window, double fromX, double fromY, double toX, double toY, string button, string[] modifiers, int durationMs, int steps, RequestContext context) { + var flags = Button(button); + context.HeldInputs.RequireAvailable(flags.Control); var geometry = window.RequireObservation(app, context); var from = WindowState.Point(geometry, fromX, fromY); _ = WindowState.Point(geometry, toX, toY); Hit(app, window, from, context); - var flags = Button(button); var keys = modifiers.Select(KeyChord.NormalizeModifier).Select(Modifier).Distinct().ToArray(); var attempted = new List(); var buttonAttempted = false; diff --git a/packages/experimental/cua-windows/native/entry/Win32.cs b/packages/experimental/cua-windows/native/entry/Win32.cs index d19f713cf3..7f15ab66c4 100644 --- a/packages/experimental/cua-windows/native/entry/Win32.cs +++ b/packages/experimental/cua-windows/native/entry/Win32.cs @@ -62,12 +62,6 @@ internal static class Win32 [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool ShowWindowAsync(nint window, int command); [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetGUIThreadInfo(uint thread, ref GuiThreadInfo info); [DllImport("user32.dll", SetLastError = true)] internal static extern uint SendInput(uint count, Input[] inputs, int size); - internal delegate nint InputHook(int code, nuint message, nint value); - [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] internal static extern nint GetModuleHandle(string? module); - [DllImport("user32.dll", CharSet = CharSet.Unicode)] internal static extern nint SetWindowsHookEx(int kind, InputHook hook, nint module, uint thread); - [DllImport("user32.dll")] internal static extern nint CallNextHookEx(nint hook, int code, nuint message, nint value); - [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool UnhookWindowsHookEx(nint hook); - [DllImport("user32.dll")] internal static extern short GetAsyncKeyState(int key); [DllImport("user32.dll")] internal static extern nint GetKeyboardLayout(uint thread); [DllImport("user32.dll", CharSet = CharSet.Unicode)] internal static extern short VkKeyScanEx(char character, nint layout); [DllImport("user32.dll")] internal static extern int GetSystemMetrics(int index); diff --git a/packages/experimental/cua-windows/native/tests/HeldInputChecks.cs b/packages/experimental/cua-windows/native/tests/HeldInputChecks.cs index b29bd1e769..a805c24a81 100644 --- a/packages/experimental/cua-windows/native/tests/HeldInputChecks.cs +++ b/packages/experimental/cua-windows/native/tests/HeldInputChecks.cs @@ -1,4 +1,4 @@ -// The fake input stream drives the same admission and hook callbacks as SendInput. +// The receiver records accepted dispatches and can refuse an individual down or up. using System.Text.Json; using DeepSeek.Cua.Protocol; using DeepSeek.Cua.Windows; @@ -10,22 +10,18 @@ internal static class HeldInputChecks var a = Guid.NewGuid(); var b = Guid.NewGuid(); var target = new HeldInputs.Target("app", 72, 122, 100); - var physical = new HashSet(); var events = new List(); var blocked = false; - var overlap = false; var interactive = true; - HeldInputs inputs = null!; - inputs = new(physical.Contains, input => + void Receive(Win32.Input input) { if (blocked) throw new NativeFailure("INPUT_BLOCKED", "SendInput returned zero"); var isKey = input.Type == 1; var control = isKey ? input.Data.Keyboard.Key : (ushort)1; - var tag = isKey ? input.Data.Keyboard.Extra : input.Data.Mouse.Extra; var up = isKey ? (input.Data.Keyboard.Flags & 2) != 0 : input.Data.Mouse.Flags == 4; - if (overlap) inputs.Observe(control, 0, () => 0); - inputs.Observe(control, tag, () => { events.Add($"{control}:{(up ? "up" : "down")}"); return 0; }); - }, () => + events.Add($"{control}:{(up ? "up" : "down")}"); + } + var inputs = new HeldInputs(Receive, () => { if (!interactive) throw new NativeFailure("SESSION_LOCKED", "The interactive desktop is unavailable"); }); @@ -34,12 +30,10 @@ internal static class HeldInputChecks => inputs.Down(connection, task, target, key, name, new() { Type = 1, Data = new() { Keyboard = new() { Key = key } } }, new() { Type = 1, Data = new() { Keyboard = new() { Key = key, Flags = 2 } } }, - cancellation, 100); + cancellation); - physical.Add(16); - refuses(() => Key(a, "task", 16, "shift"), "INPUT_BUSY"); - check(events.Count == 0, "Physical input cannot become an owned hold"); - physical.Clear(); + refuses(() => inputs.Up(a, "task", "app", 72, "shift", true), "INPUT_NOT_HELD"); + check(events.Count == 0, "No up is sent for a key the helper never pressed"); blocked = true; refuses(() => Key(a, "task", 16, "shift"), "INPUT_BLOCKED"); check(inputs.Get(a, "task").Length == 0, "A refused down does not cause an up"); @@ -47,23 +41,23 @@ internal static class HeldInputChecks check(Key(a, "task", 16, "shift"), "Record the accepted keyboard down"); check(inputs.Down(a, "task", target, 1, "left", new() { Data = new() { Mouse = new() { Flags = 2 } } }, - new() { Data = new() { Mouse = new() { Flags = 4 } } }, default, 100), "Record the accepted mouse down"); + new() { Data = new() { Mouse = new() { Flags = 4 } } }, default), "Record the accepted mouse down"); check(Key(a, "task", 87, "w") && !Key(a, "task", 87, "w"), "A repeated key does not duplicate a hold"); refuses(() => inputs.RequireOwner(b, "task", "app", 72), "INPUT_BUSY"); refuses(() => inputs.RequireOwner(a, "other", "app", 72), "INPUT_BUSY"); refuses(() => inputs.RequireAvailable(1), "INPUT_BUSY"); - refuses(() => inputs.Up(a, "other", "app", 72, "w", true, 100), "INPUT_NOT_HELD"); - refuses(() => inputs.Up(a, "task", "app", 73, "w", true, 100), "INPUT_NOT_HELD"); - check(inputs.Release(b, null, default, 100).Length == 0, "Another connection releases nothing"); + refuses(() => inputs.Up(a, "other", "app", 72, "w", true), "INPUT_NOT_HELD"); + refuses(() => inputs.Up(a, "task", "app", 73, "w", true), "INPUT_NOT_HELD"); + check(inputs.Release(b, null, default).Length == 0, "Another connection releases nothing"); check(inputs.Get(a, "other").Length == 0 && inputs.Get(a, "task").Length == 3, "State query is task-scoped"); var described = JsonSerializer.SerializeToElement(inputs.Get(a, "task"), WireJson.Options); check(described[0].GetProperty("windowId").GetString() == "72" && described[0].GetProperty("mode").GetString() == "system", "Keyboard reminders identify the window and actual desktop mode"); - check(inputs.Up(a, "task", "app", 72, "shift", true, 100) && Key(a, "task", 16, "shift"), - "Explicit up and repress update the dispatch order"); - check(inputs.Release(a, "task", default, 100).Length == 3 + inputs.Up(a, "task", "app", 72, "shift", true); + check(Key(a, "task", 16, "shift"), "Explicit up and repress update the dispatch order"); + check(inputs.Release(a, "task", default).Length == 3 && events.TakeLast(3).SequenceEqual(["16:up", "87:up", "1:up"]), "Release in mixed reverse order, including repress"); - check(inputs.Release(a, null, default, 100).Length == 0, "Duplicate connection cleanup sends no up"); + check(inputs.Release(a, null, default).Length == 0, "Duplicate connection cleanup sends no up"); using (var cancelled = new CancellationTokenSource()) { cancelled.Cancel(); @@ -72,16 +66,22 @@ internal static class HeldInputChecks } Key(a, "task", 87, "w"); interactive = false; - refuses(() => inputs.Release(a, null, default, 100), "INPUT_CLEANUP_FAILED"); + refuses(() => inputs.Release(a, null, default), "INPUT_CLEANUP_FAILED"); check(inputs.Get(a, "task").Length == 1, "A locked desktop leaves the failed release recorded"); interactive = true; blocked = true; - refuses(() => inputs.Release(a, null, default, 100), "INPUT_CLEANUP_FAILED"); + refuses(() => inputs.Release(a, null, default), "INPUT_CLEANUP_FAILED"); check(inputs.Get(a, "task").Length == 1, "A refused release stays recorded for disconnect fallback"); blocked = false; + // Another source releases W and presses D at the same receiver. + Receive(new() { Type = 1, Data = new() { Keyboard = new() { Key = 87, Flags = 2 } } }); + Receive(new() { Type = 1, Data = new() { Keyboard = new() { Key = 68 } } }); + described = JsonSerializer.SerializeToElement(inputs.Get(a, "task"), WireJson.Options); + check(described.GetArrayLength() == 1 && described[0].GetProperty("key").GetString() == "w", + "The reminder still reports only the helper's W down"); var count = events.Count; - overlap = true; - check(inputs.Release(a, null, default, 100).Length == 0 && inputs.Get(a, "task").Length == 0 && events.Count == count, - "An external event at dispatch time wins and the owned event cannot lift user input"); + check(inputs.Release(a, null, default).Length == 1 && events.Skip(count).SequenceEqual(["87:up"]), + "Disconnect retries the helper's W release and leaves D alone"); + check(!inputs.HasConnection(a), "Accepted release removes the connection's last hold"); } } diff --git a/packages/experimental/cua-windows/tests/desktop-toggle-mouse.spec.ts b/packages/experimental/cua-windows/tests/desktop-toggle-mouse.spec.ts index a84b329811..1b2d41a34f 100644 --- a/packages/experimental/cua-windows/tests/desktop-toggle-mouse.spec.ts +++ b/packages/experimental/cua-windows/tests/desktop-toggle-mouse.spec.ts @@ -15,7 +15,7 @@ const Counts = z.object({ left: z.number().int(), right: z.number().int(), middl const FixtureState = z.object({ window: z.string(), foreground: z.string(), cursor: z.object({ x: z.number().int(), y: z.number().int() }), - inputEvents: z.array(z.string()), wDown: z.boolean(), + inputEvents: z.array(z.string()), under: z.string(), buttons: z.string(), clicks: z.number().int(), downs: Counts, ups: Counts, }) const Initial = z.object({ pid: z.number().int(), state: FixtureState }) @@ -153,6 +153,8 @@ it.skipIf(process.platform !== 'win32' || !helperPath || !fixturePath)( const offset = (await inspect()).inputEvents.length await key('shift', 'down') await toggle('left', 'down') + await expect(native.request('drag', { appHandle: app.appHandle, windowId, fromX: 20, fromY: 20, toX: 30, toY: 30, + mouseButton: 'left', durationMs: 100, steps: 2 }, signal)).rejects.toMatchObject({ code: 'INPUT_BUSY' }) await key('w', 'down') expect(released.parse(await holds()).map(input => input.key ?? input.button)).toEqual(['shift', 'left', 'w']) @@ -168,11 +170,15 @@ it.skipIf(process.platform !== 'win32' || !helperPath || !fixturePath)( await expect.poll(async () => (await inspect()).inputEvents.slice(offset)).toEqual( ['ShiftKey:down', 'Left:down', 'W:down', 'W:up', 'Left:up', 'ShiftKey:up']) + const beforeSwitch = (await inspect()).inputEvents.length await key('w', 'down') - await observed({ wDown: true }) + await expect.poll(async () => (await inspect()).inputEvents.slice(beforeSwitch)).toEqual(['W:down']) const switched = await fixture.command('sibling', FixtureState) expect(switched.foreground).toBe(switched.window) await native.dispose() - await observed({ foreground: switched.window, wDown: false }) + await expect.poll(async () => { + const sibling = await fixture.command('inspect-sibling', FixtureState) + return { foreground: sibling.foreground, events: sibling.inputEvents.slice(switched.inputEvents.length) } + }).toEqual({ foreground: switched.window, events: ['W:up'] }) }, 120_000)