@copylee/dsh-computer-use 0.14.2 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/helper/Native.cs CHANGED
@@ -50,7 +50,13 @@ namespace DshComputerUse
50
50
  [DllImport("user32.dll", SetLastError = true)] public static extern bool DestroyIcon(IntPtr hIcon);
51
51
  [DllImport("user32.dll", SetLastError = true)] public static extern bool SetSystemCursor(IntPtr hcur, uint id);
52
52
  [DllImport("user32.dll", SetLastError = true)] public static extern bool SystemParametersInfo(uint uiAction, uint uiParam, IntPtr pvParam, uint fWinIni);
53
- public const uint SPI_SETCURSORS = 0x0057;
53
+ [DllImport("user32.dll", SetLastError = true)] public static extern bool SystemParametersInfo(uint uiAction, uint uiParam, out bool pvParam, uint fWinIni);
54
+ [DllImport("winmm.dll")] public static extern uint timeBeginPeriod(uint uPeriod);
55
+ [DllImport("winmm.dll")] public static extern uint timeEndPeriod(uint uPeriod);
56
+ [StructLayout(LayoutKind.Sequential)]
57
+ public struct BITMAPINFOHEADER { public uint biSize; public int biWidth; public int biHeight; public ushort biPlanes; public ushort biBitCount; public uint biCompression; public uint biSizeImage; public int biXPelsPerMeter; public int biYPelsPerMeter; public uint biClrUsed; public uint biClrImportant; }
58
+ [DllImport("gdi32.dll")] public static extern IntPtr CreateDIBSection(IntPtr hdc, ref BITMAPINFOHEADER pbmi, uint iUsage, out IntPtr ppvBits, IntPtr hSection, uint dwOffset);
59
+ public const uint SPI_SETCURSORS = 0x0057, SPI_GETMOUSEVANISH = 0x1020, SPI_SETMOUSEVANISH = 0x1021;
54
60
  public const uint OCR_NORMAL = 32512, OCR_IBEAM = 32513, OCR_WAIT = 32514, OCR_HAND = 32649, OCR_APPSTARTING = 32650;
55
61
 
56
62
  public delegate bool MonitorEnumProc(IntPtr hMonitor, IntPtr hdc, ref RECT rect, IntPtr data);
package/helper/Overlay.cs CHANGED
@@ -389,11 +389,14 @@ namespace DshComputerUse
389
389
  public static volatile bool SkipWaitRequested;
390
390
  static volatile bool clickTargetEnabled = true;
391
391
  static volatile bool customCursorActive;
392
+ static volatile bool disabledMouseVanish;
392
393
  static string cursorBadge = "DSH";
393
394
  static LayeredForm markForm;
394
395
  static DateTime markExpiresAt = DateTime.MinValue;
395
396
  static bool markActive;
396
397
  static bool markIsResting;
398
+ static LayeredForm clickRippleForm;
399
+ static DateTime clickRippleExpiresAt = DateTime.MinValue;
397
400
  static float cachedMarkScale;
398
401
  static bool cachedMarkFlipX, cachedMarkFlipY, cachedMarkRipple, cachedMarkArrow;
399
402
  static string cachedMarkText = "";
@@ -402,7 +405,6 @@ namespace DshComputerUse
402
405
  static bool hasCachedMarkBitmap;
403
406
  static volatile int latestMouseX, latestMouseY;
404
407
  static int mouseMovePending;
405
- static int lastMouseMoveTick = int.MinValue / 2;
406
408
  static int lastTyping = int.MinValue / 2;
407
409
  static int lastEmit;
408
410
  static readonly object RectLock = new object();
@@ -656,14 +658,39 @@ namespace DshComputerUse
656
658
  g.DrawPolygon(outline, arrow);
657
659
  }
658
660
  }
659
- // Build a clean 32-bit ARGB cursor with an all-zero monochrome AND mask
661
+ // Build a clean 32-bit premultiplied ARGB DIB cursor + all-zero monochrome AND mask
660
662
  // so Windows DWM composites it purely on the hardware cursor plane without flicker.
661
- IntPtr hbmColor = bmp.GetHbitmap(Color.FromArgb(0));
662
- IntPtr hbmMask = Native.CreateBitmap(size, size, 1, 1, IntPtr.Zero);
663
+ IntPtr hbmColor = IntPtr.Zero;
664
+ IntPtr hbmMask = IntPtr.Zero;
663
665
  try
664
666
  {
665
- if (hbmColor != IntPtr.Zero && hbmMask != IntPtr.Zero)
667
+ var bmi = new Native.BITMAPINFOHEADER();
668
+ bmi.biSize = (uint)Marshal.SizeOf(typeof(Native.BITMAPINFOHEADER));
669
+ bmi.biWidth = size;
670
+ bmi.biHeight = -size; // top-down DIB
671
+ bmi.biPlanes = 1;
672
+ bmi.biBitCount = 32;
673
+ bmi.biCompression = 0; // BI_RGB
674
+ IntPtr bits = IntPtr.Zero;
675
+ IntPtr screenDc = Native.GetDC(IntPtr.Zero);
676
+ try { hbmColor = Native.CreateDIBSection(screenDc, ref bmi, 0, out bits, IntPtr.Zero, 0); }
677
+ finally { Native.ReleaseDC(IntPtr.Zero, screenDc); }
678
+ hbmMask = Native.CreateBitmap(size, size, 1, 1, IntPtr.Zero);
679
+ if (hbmColor != IntPtr.Zero && hbmMask != IntPtr.Zero && bits != IntPtr.Zero)
666
680
  {
681
+ var rect = new Rectangle(0, 0, size, size);
682
+ BitmapData data = bmp.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format32bppPArgb);
683
+ try
684
+ {
685
+ int totalBytes = size * size * 4;
686
+ byte[] buf = new byte[totalBytes];
687
+ for (int row = 0; row < size; row++)
688
+ {
689
+ Marshal.Copy(new IntPtr(data.Scan0.ToInt64() + (long)row * data.Stride), buf, row * size * 4, size * 4);
690
+ }
691
+ Marshal.Copy(buf, 0, bits, totalBytes);
692
+ }
693
+ finally { bmp.UnlockBits(data); }
667
694
  var ii = new Native.ICONINFO();
668
695
  ii.fIcon = false;
669
696
  ii.xHotspot = tipX;
@@ -680,6 +707,17 @@ namespace DshComputerUse
680
707
  }
681
708
  }
682
709
  if (hCursor == IntPtr.Zero) return;
710
+ // Disable Windows' "Hide pointer while typing" (SPI_SETMOUSEVANISH) temporarily so
711
+ // synthetic keyboard typing never makes our hardware cursor vanish for 1-2 seconds.
712
+ if (!disabledMouseVanish)
713
+ {
714
+ bool vanishOn = false;
715
+ if (Native.SystemParametersInfo(Native.SPI_GETMOUSEVANISH, 0, out vanishOn, 0) && vanishOn)
716
+ {
717
+ if (Native.SystemParametersInfo(Native.SPI_SETMOUSEVANISH, 0, IntPtr.Zero, 0))
718
+ disabledMouseVanish = true;
719
+ }
720
+ }
683
721
  uint[] ids = new uint[] { Native.OCR_NORMAL, Native.OCR_IBEAM, Native.OCR_HAND, Native.OCR_APPSTARTING, Native.OCR_WAIT };
684
722
  bool anyApplied = false;
685
723
  for (int i = 0; i < ids.Length; i++)
@@ -698,9 +736,14 @@ namespace DshComputerUse
698
736
  }
699
737
  }
700
738
 
701
- /** Reload the user's native Windows cursor scheme (idempotent & crash-safe). */
739
+ /** Reload the user's native Windows cursor scheme and mouse-vanish setting (idempotent & crash-safe). */
702
740
  public static void RestoreSystemCursor(bool force)
703
741
  {
742
+ if (disabledMouseVanish)
743
+ {
744
+ try { Native.SystemParametersInfo(Native.SPI_SETMOUSEVANISH, 0, new IntPtr(1), 0); } catch (Exception) { }
745
+ disabledMouseVanish = false;
746
+ }
704
747
  if (!force && !customCursorActive) return;
705
748
  try { Native.SystemParametersInfo(Native.SPI_SETCURSORS, 0, IntPtr.Zero, 0); } catch (Exception) { }
706
749
  customCursorActive = false;
@@ -1068,7 +1111,7 @@ namespace DshComputerUse
1068
1111
  PlaceMarkOnUi(latestMouseX, latestMouseY, cursorBadge, Accent, 0, false, false, true);
1069
1112
  }
1070
1113
 
1071
- /** Smooth EaseOutCubic glide (~150ms @ ~60-90Hz) moving both OS cursor and cached badge in lockstep. */
1114
+ /** Smooth true-120Hz EaseOutCubic glide (~140ms) moving OS cursor and cached DSH badge in lockstep. */
1072
1115
  public static void GlideMark(int x, int y, string text, Color color, int holdMs, bool capturable, bool ripple)
1073
1116
  {
1074
1117
  int startX, startY;
@@ -1077,22 +1120,34 @@ namespace DshComputerUse
1077
1120
  else if (hasLastMark) { startX = lastMarkX; startY = lastMarkY; }
1078
1121
  else { startX = x; startY = y; }
1079
1122
  double dist = Math.Sqrt((double)(x - startX) * (x - startX) + (double)(y - startY) * (y - startY));
1080
- if (dist >= 30.0)
1123
+ if (dist >= 24.0)
1081
1124
  {
1082
- int steps = Math.Max(8, Math.Min(16, (int)(dist / 65.0) + 8));
1083
- for (int i = 1; i < steps; i++)
1125
+ double durationMs = Math.Max(95.0, Math.Min(190.0, 85.0 + dist * 0.085));
1126
+ bool highRes = false;
1127
+ try
1084
1128
  {
1085
- double t = (double)i / steps;
1086
- double ease = 1.0 - Math.Pow(1.0 - t, 3.0); // EaseOutCubic
1087
- int ix = startX + (int)Math.Round((x - startX) * ease);
1088
- int iy = startY + (int)Math.Round((y - startY) * ease);
1089
- try { Native.SetCursorPos(ix, iy); } catch (Exception) { }
1090
- Mark(ix, iy, text, color, holdMs, capturable, false);
1091
- Thread.Sleep(10);
1129
+ highRes = Native.timeBeginPeriod(1) == 0;
1130
+ var sw = Stopwatch.StartNew();
1131
+ while (true)
1132
+ {
1133
+ double elapsed = sw.Elapsed.TotalMilliseconds;
1134
+ if (elapsed >= durationMs) break;
1135
+ double t = elapsed / durationMs;
1136
+ double ease = 1.0 - Math.Pow(1.0 - t, 3.0); // EaseOutCubic
1137
+ int ix = startX + (int)Math.Round((x - startX) * ease);
1138
+ int iy = startY + (int)Math.Round((y - startY) * ease);
1139
+ try { Native.SetCursorPos(ix, iy); } catch (Exception) { }
1140
+ Mark(ix, iy, text, color, holdMs, false, false);
1141
+ Thread.Sleep(7);
1142
+ }
1143
+ }
1144
+ finally
1145
+ {
1146
+ if (highRes) { try { Native.timeEndPeriod(1); } catch (Exception) { } }
1092
1147
  }
1093
1148
  }
1094
1149
  try { Native.SetCursorPos(x, y); } catch (Exception) { }
1095
- Mark(x, y, text, color, holdMs, capturable, ripple);
1150
+ Mark(x, y, text, color, holdMs, false, false);
1096
1151
  }
1097
1152
 
1098
1153
  static void ShowRestingMarkOnUi(int x, int y)
@@ -1106,6 +1161,42 @@ namespace DshComputerUse
1106
1161
  Ui(delegate { PlaceMarkOnUi(x, y, text, color, holdMs, capturable, ripple, false); });
1107
1162
  }
1108
1163
 
1164
+ /** Render post-click ripple on a separate capturable form so the live DSH badge never toggles affinity or blinks. */
1165
+ static void ShowClickRippleOnUi(int x, int y, string text, Color color, int holdMs)
1166
+ {
1167
+ if (clickRippleForm == null)
1168
+ {
1169
+ clickRippleForm = new LayeredForm(true);
1170
+ clickRippleForm.SetCapturable(true);
1171
+ clickRippleForm.Show();
1172
+ }
1173
+ float scale; Rectangle mon;
1174
+ MonitorAt(x, y, out scale, out mon);
1175
+ float s = Math.Max(0.75f, Math.Min(3f, scale));
1176
+ string labelText = text ?? "";
1177
+ int estW = (int)((Math.Max(6, labelText.Length) * 11 + 36) * s);
1178
+ bool flipX = !mon.IsEmpty && x + estW > mon.Right;
1179
+ bool flipY = !mon.IsEmpty && y + (int)(52 * s) > mon.Bottom;
1180
+ int cx, cy;
1181
+ using (var bmp = DrawMark(labelText, color, scale, flipX, flipY, true, false, out cx, out cy))
1182
+ {
1183
+ clickRippleForm.SetBitmap(bmp, new Rectangle(x - cx, y - cy, bmp.Width, bmp.Height), 255);
1184
+ }
1185
+ clickRippleForm.KeepOnTop();
1186
+ clickRippleExpiresAt = DateTime.UtcNow.AddMilliseconds(holdMs);
1187
+ if (!timer.Enabled) timer.Start();
1188
+ }
1189
+
1190
+ static void HideClickRipple()
1191
+ {
1192
+ clickRippleExpiresAt = DateTime.MinValue;
1193
+ if (clickRippleForm != null)
1194
+ {
1195
+ clickRippleForm.Close();
1196
+ clickRippleForm = null;
1197
+ }
1198
+ }
1199
+
1109
1200
  public static void MarkResult(int x, int y, string button, int count, string coordLabel)
1110
1201
  {
1111
1202
  Color color;
@@ -1115,11 +1206,23 @@ namespace DshComputerUse
1115
1206
  else if (button == "right") { color = Color.FromArgb(16, 185, 129); verb = "已右键"; }
1116
1207
  else if (button == "middle") { color = Color.FromArgb(6, 182, 212); verb = "已中键"; }
1117
1208
  else { color = Color.FromArgb(59, 130, 246); verb = "已单击"; }
1118
- Mark(x, y, verb + " " + coordLabel, color, 900, true, true);
1209
+ Ensure();
1210
+ Ui(delegate
1211
+ {
1212
+ ShowClickRippleOnUi(x, y, verb + " " + coordLabel, color, 750);
1213
+ // Keep the live DSH badge immediately tracking the pointer without freezing at the click spot.
1214
+ if (visible && clickTargetEnabled && !petFinished && !paused)
1215
+ {
1216
+ Native.POINT cp;
1217
+ if (Native.GetCursorPos(out cp)) ShowRestingMarkOnUi(cp.X, cp.Y);
1218
+ else ShowRestingMarkOnUi(x, y);
1219
+ }
1220
+ });
1119
1221
  }
1120
1222
 
1121
1223
  static void HideMark()
1122
1224
  {
1225
+ HideClickRipple();
1123
1226
  markActive = false;
1124
1227
  markIsResting = false;
1125
1228
  hasCachedMarkBitmap = false;
@@ -1221,6 +1324,10 @@ namespace DshComputerUse
1221
1324
 
1222
1325
  static void Tick()
1223
1326
  {
1327
+ if (clickRippleForm != null && DateTime.UtcNow >= clickRippleExpiresAt)
1328
+ {
1329
+ HideClickRipple();
1330
+ }
1224
1331
  if (markActive && DateTime.UtcNow >= markExpiresAt)
1225
1332
  {
1226
1333
  if (visible && clickTargetEnabled && !petFinished && !paused)
@@ -1234,7 +1341,7 @@ namespace DshComputerUse
1234
1341
  }
1235
1342
  if (!visible)
1236
1343
  {
1237
- if (!markActive) timer.Stop();
1344
+ if (!markActive && clickRippleForm == null) timer.Stop();
1238
1345
  return;
1239
1346
  }
1240
1347
  if (visible && clickTargetEnabled && !petFinished && !paused && !markActive)
@@ -1886,8 +1993,8 @@ namespace DshComputerUse
1886
1993
  if (nCode >= 0 && visible)
1887
1994
  {
1888
1995
  int msg = wParam.ToInt32();
1889
- // Hardware-rate cursor tracking on WM_MOUSEMOVE (throttled to ~60Hz so 1000Hz mice
1890
- // never flood the UI thread): never triggers takeover, only moves the cached badge.
1996
+ // Native-rate cursor tracking on WM_MOUSEMOVE: Interlocked.Exchange coalesces bursts
1997
+ // directly to the UI message loop rate (60Hz/120Hz/144Hz+) with zero 15.6ms TickCount lag.
1891
1998
  if (msg == 0x0200)
1892
1999
  {
1893
2000
  if (clickTargetEnabled && !petFinished && !paused && markActive && markIsResting && invoker != null)
@@ -1895,10 +2002,8 @@ namespace DshComputerUse
1895
2002
  var mm = (Native.MSLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(Native.MSLLHOOKSTRUCT));
1896
2003
  latestMouseX = mm.pt.X;
1897
2004
  latestMouseY = mm.pt.Y;
1898
- int tick = Environment.TickCount;
1899
- if (unchecked(tick - lastMouseMoveTick) >= 16 && Interlocked.Exchange(ref mouseMovePending, 1) == 0)
2005
+ if (Interlocked.Exchange(ref mouseMovePending, 1) == 0)
1900
2006
  {
1901
- lastMouseMoveTick = tick;
1902
2007
  try { invoker.BeginInvoke((MethodInvoker)SyncRestingCursorOnUi); }
1903
2008
  catch (Exception) { Interlocked.Exchange(ref mouseMovePending, 0); }
1904
2009
  }
package/helper/Uia.cs CHANGED
@@ -158,11 +158,22 @@ namespace DshComputerUse
158
158
  else if (action == "set_checked")
159
159
  {
160
160
  bool want = Args.Bool(r, "checked", true);
161
+ ToggleState desired = want ? ToggleState.On : ToggleState.Off;
161
162
  var tp = (TogglePattern)pattern;
162
- bool isOn = tp.Current.ToggleState == ToggleState.On;
163
- if (isOn != want) tp.Toggle();
164
- result["changed"] = isOn != want;
165
- result["checked"] = want;
163
+ ToggleState initial = tp.Current.ToggleState;
164
+ bool changed = false;
165
+ // Handle tri-state checkboxes (Indeterminate -> On -> Off) with up to 2 toggles.
166
+ for (int attempt = 0; attempt < 2 && tp.Current.ToggleState != desired; attempt++)
167
+ {
168
+ tp.Toggle();
169
+ changed = true;
170
+ Thread.Sleep(20);
171
+ }
172
+ ToggleState actual = tp.Current.ToggleState;
173
+ result["changed"] = changed || actual != initial;
174
+ result["checked"] = actual == ToggleState.On;
175
+ result["toggleState"] = actual.ToString();
176
+ result["verified"] = actual == desired;
166
177
  }
167
178
  else if (action == "expand" || action == "collapse")
168
179
  {
@@ -174,21 +185,41 @@ namespace DshComputerUse
174
185
  {
175
186
  if (wantExpand) ec.Expand();
176
187
  else ec.Collapse();
188
+ Thread.Sleep(25);
177
189
  }
190
+ var actual = ec.Current.ExpandCollapseState;
191
+ bool verified = wantExpand
192
+ ? (actual == ExpandCollapseState.Expanded || actual == ExpandCollapseState.PartiallyExpanded)
193
+ : (actual == ExpandCollapseState.Collapsed);
178
194
  result["changed"] = !already;
195
+ result["state"] = actual.ToString();
196
+ result["verified"] = verified;
179
197
  }
180
198
  else if (action == "select")
181
199
  {
182
200
  var sp = (SelectionItemPattern)pattern;
183
201
  bool already = sp.Current.IsSelected;
184
- if (!already) sp.Select();
202
+ if (!already)
203
+ {
204
+ sp.Select();
205
+ Thread.Sleep(20);
206
+ }
207
+ bool actual = sp.Current.IsSelected;
185
208
  result["changed"] = !already;
209
+ result["selected"] = actual;
210
+ result["verified"] = actual;
186
211
  }
187
212
  else if (action == "set_value")
188
213
  {
189
214
  string val = Args.Str(r, "value", "");
190
- ((ValuePattern)pattern).SetValue(val);
215
+ var vp = (ValuePattern)pattern;
216
+ vp.SetValue(val);
217
+ Thread.Sleep(20);
218
+ string actual = "";
219
+ try { actual = vp.Current.Value ?? ""; } catch (Exception) { actual = ""; }
191
220
  result["changed"] = true;
221
+ result["verified"] = actual == val;
222
+ result["actualLength"] = actual.Length;
192
223
  }
193
224
  result["performed"] = true;
194
225
  return result;
@@ -229,6 +260,7 @@ namespace DshComputerUse
229
260
  string query = Args.Str(r, "query", "").Trim();
230
261
  int maxMatches = Math.Max(1, Math.Min(120, Args.Int(r, "maxMatches", 24)));
231
262
  List<object> result = null;
263
+ bool truncated = false;
232
264
  Exception error = null;
233
265
 
234
266
  var worker = new Thread(delegate ()
@@ -268,7 +300,6 @@ namespace DshComputerUse
268
300
  string qLower = query.ToLowerInvariant();
269
301
  foreach (AutomationElement el in found)
270
302
  {
271
- if (list.Count >= maxMatches) break;
272
303
  var rect = (System.Windows.Rect)el.GetCachedPropertyValue(AutomationElement.BoundingRectangleProperty);
273
304
  if (rect.IsEmpty || rect.Width < 2 || rect.Height < 2) continue;
274
305
  var type = (ControlType)el.GetCachedPropertyValue(AutomationElement.ControlTypeProperty);
@@ -278,6 +309,7 @@ namespace DshComputerUse
278
309
  && elName.ToLowerInvariant().IndexOf(qLower, StringComparison.Ordinal) < 0
279
310
  && elAid.ToLowerInvariant().IndexOf(qLower, StringComparison.Ordinal) < 0)
280
311
  continue;
312
+ if (list.Count >= maxMatches) { truncated = true; break; }
281
313
 
282
314
  bool isPwd = false;
283
315
  try
@@ -321,6 +353,7 @@ namespace DshComputerUse
321
353
  if (error != null) throw error;
322
354
  var outMap = Windows.Describe(hwnd);
323
355
  outMap["elements"] = result ?? new List<object>();
356
+ outMap["truncated"] = truncated;
324
357
  return outMap;
325
358
  }
326
359
 
package/lib/index.js CHANGED
@@ -1749,6 +1749,8 @@ const ACTIONS = [
1749
1749
  "cursor_position",
1750
1750
  "ui_action"
1751
1751
  ];
1752
+ /** Controls whose labels indicate non-idempotent/destructive actions: never auto-retry via physical click after UIA invoke. */
1753
+ const NON_IDEMPOTENT_CONTROL = /\b(submit|delete|remove|pay|checkout|purchase|send|confirm|transfer|order)\b|提交|删除|移除|支付|付款|下单|转账|确认删除|清空|发送/i;
1752
1754
  /** Actions that change something on screen and deserve a fresh screenshot. */
1753
1755
  const MUTATING = /* @__PURE__ */ new Set([
1754
1756
  "left_click",
@@ -1798,8 +1800,10 @@ var Computer = class Computer {
1798
1800
  heldButton = false;
1799
1801
  /** Dimensions of the latest full-display screenshot shown to the model (keeps coordinate conversion exact across detail modes). */
1800
1802
  lastShot;
1801
- /** Recent click locations (repeat counter + auto physical-click fallback if a UIA invoke had no effect). */
1803
+ /** Recent click locations (repeat counter + scoped auto physical-click fallback if a UIA invoke had no effect). */
1802
1804
  clickHistory = [];
1805
+ /** Rolling per-phase timing samples (settle + screenshot) for diagnostics & performance profiling. */
1806
+ phaseSamples = [];
1803
1807
  /** The agent that last wrote the clipboard; when it goes idle the user's clipboard comes back. */
1804
1808
  clipboardAgent;
1805
1809
  /** Single-machine desktop control lease preventing concurrent sessions from colliding. */
@@ -2022,7 +2026,7 @@ var Computer = class Computer {
2022
2026
  }) ?? "unchanged";
2023
2027
  }
2024
2028
  /** Record a click position and return how many times this spot (±24 px) was clicked in the last 2 minutes. */
2025
- noteClick(point, helperRepeat, via = "physical") {
2029
+ noteClick(point, helperRepeat, via = "physical", meta) {
2026
2030
  const now = Date.now();
2027
2031
  while (this.clickHistory.length > 0 && now - this.clickHistory[0].at > REPEAT_WINDOW_MS) this.clickHistory.shift();
2028
2032
  let local = 0;
@@ -2031,23 +2035,55 @@ var Computer = class Computer {
2031
2035
  x: point.x,
2032
2036
  y: point.y,
2033
2037
  at: now,
2034
- via
2038
+ via,
2039
+ ...meta?.session ? { session: meta.session } : {},
2040
+ ...meta?.hwnd !== void 0 ? { hwnd: meta.hwnd } : {},
2041
+ ...meta?.name ? { name: meta.name } : {}
2035
2042
  });
2036
2043
  for (const entry of this.clickHistory) if (Math.abs(entry.x - point.x) <= REPEAT_RADIUS_PX && Math.abs(entry.y - point.y) <= REPEAT_RADIUS_PX) local++;
2037
2044
  }
2038
2045
  return typeof helperRepeat === "number" && Number.isFinite(helperRepeat) && helperRepeat > 0 ? helperRepeat : local;
2039
2046
  }
2040
- /** Whether this spot (±24 px) was already clicked via background UIA invoke recently (so a retry should use a real physical click). */
2041
- hadRecentUiaClickAt(point, windowMs = 3e4) {
2047
+ /**
2048
+ * Whether this spot (±24 px) in the same session & window was recently invoked via UIA
2049
+ * (and is NOT a non-idempotent submit/delete/pay button), so a retry upgrades to physical click.
2050
+ */
2051
+ hadRecentUiaClickAt(point, session, hwnd, windowMs = 3e4) {
2042
2052
  if (!point) return false;
2043
2053
  const now = Date.now();
2044
2054
  for (let i = this.clickHistory.length - 1; i >= 0; i--) {
2045
2055
  const entry = this.clickHistory[i];
2046
2056
  if (now - entry.at > windowMs) break;
2047
- if (Math.abs(entry.x - point.x) <= REPEAT_RADIUS_PX && Math.abs(entry.y - point.y) <= REPEAT_RADIUS_PX) return entry.via === "uia";
2057
+ if (session && entry.session && entry.session !== session) continue;
2058
+ if (hwnd !== void 0 && entry.hwnd !== void 0 && entry.hwnd !== hwnd) continue;
2059
+ if (Math.abs(entry.x - point.x) <= REPEAT_RADIUS_PX && Math.abs(entry.y - point.y) <= REPEAT_RADIUS_PX) {
2060
+ if (entry.via !== "uia") return false;
2061
+ if (entry.name && NON_IDEMPOTENT_CONTROL.test(entry.name)) return false;
2062
+ return true;
2063
+ }
2048
2064
  }
2049
2065
  return false;
2050
2066
  }
2067
+ /** Rolling average settle/screenshot phase timings for diagnostics. */
2068
+ timingSummary() {
2069
+ const n = this.phaseSamples.length;
2070
+ if (n === 0) return {
2071
+ samples: 0,
2072
+ avgSettleMs: 0,
2073
+ avgShotMs: 0
2074
+ };
2075
+ let settleSum = 0;
2076
+ let shotSum = 0;
2077
+ for (const s of this.phaseSamples) {
2078
+ settleSum += s.settleMs;
2079
+ shotSum += s.shotMs;
2080
+ }
2081
+ return {
2082
+ samples: n,
2083
+ avgSettleMs: Math.round(settleSum / n),
2084
+ avgShotMs: Math.round(shotSum / n)
2085
+ };
2086
+ }
2051
2087
  async foreground() {
2052
2088
  const win = await this.helper.call("foreground");
2053
2089
  if (!win || typeof win.hwnd !== "number") return void 0;
@@ -2065,6 +2101,29 @@ var Computer = class Computer {
2065
2101
  if (!fg || !(isHostWindow(fg) || isTransientShell(fg)) || !target || target.hwnd === fg.hwnd) return;
2066
2102
  if ((await this.focus(target).catch(() => void 0))?.focused) await setTimeout$1(80);
2067
2103
  }
2104
+ /** Prefer sampling the visible foreground target window (clamped to current display) so taskbar/side-app animations never disrupt settle detection. */
2105
+ async settleRect() {
2106
+ const display = await this.display();
2107
+ const fg = await this.foreground().catch(() => void 0);
2108
+ if (fg && !isHostWindow(fg) && !isTransientShell(fg) && !fg.minimized && fg.width >= 120 && fg.height >= 80) {
2109
+ const x1 = Math.max(display.x, fg.x);
2110
+ const y1 = Math.max(display.y, fg.y);
2111
+ const x2 = Math.min(display.x + display.width, fg.x + fg.width);
2112
+ const y2 = Math.min(display.y + display.height, fg.y + fg.height);
2113
+ if (x2 - x1 >= 120 && y2 - y1 >= 80) return {
2114
+ x: x1,
2115
+ y: y1,
2116
+ width: x2 - x1,
2117
+ height: y2 - y1
2118
+ };
2119
+ }
2120
+ return {
2121
+ x: display.x,
2122
+ y: display.y,
2123
+ width: display.width,
2124
+ height: display.height
2125
+ };
2126
+ }
2068
2127
  /** Wait at most `maxMs`, returning once the screen settles (for waits ≥ 4s, waits for a real visual update first and emits progress checkpoints if still changing so AI can act early or wait again). */
2069
2128
  async waitForQuiet(maxMs, signal, wait) {
2070
2129
  const started = Date.now();
@@ -2090,13 +2149,13 @@ var Computer = class Computer {
2090
2149
  skipped: false
2091
2150
  };
2092
2151
  }
2093
- const display = await this.display();
2152
+ const rect = await this.settleRect();
2094
2153
  const waitForChange = maxMs >= 4e3;
2095
2154
  const settlePromise = this.helper.call("settle", {
2096
- x: display.x,
2097
- y: display.y,
2098
- width: display.width,
2099
- height: display.height,
2155
+ x: rect.x,
2156
+ y: rect.y,
2157
+ width: rect.width,
2158
+ height: rect.height,
2100
2159
  minMs: 300,
2101
2160
  maxMs,
2102
2161
  quietMs: waitForChange ? 800 : 600,
@@ -2144,12 +2203,12 @@ var Computer = class Computer {
2144
2203
  /** Wait until the screen stops changing (bounded), instead of a fixed delay. */
2145
2204
  async settle(signal) {
2146
2205
  const s = this.settings();
2147
- const display = await this.display();
2206
+ const rect = await this.settleRect();
2148
2207
  if (await this.helper.call("settle", {
2149
- x: display.x,
2150
- y: display.y,
2151
- width: display.width,
2152
- height: display.height,
2208
+ x: rect.x,
2209
+ y: rect.y,
2210
+ width: rect.width,
2211
+ height: rect.height,
2153
2212
  minMs: s.settleMs,
2154
2213
  maxMs: Math.max(s.settleMs, 2500)
2155
2214
  }, 15e3).catch(() => null) === null) await setTimeout$1(s.settleMs, void 0, { signal });
@@ -2370,29 +2429,55 @@ var Computer = class Computer {
2370
2429
  if (!res || !Array.isArray(res.elements)) return void 0;
2371
2430
  return {
2372
2431
  ...res,
2373
- elements: res.elements
2432
+ elements: res.elements,
2433
+ ...res.truncated !== void 0 ? { truncated: res.truncated } : {}
2374
2434
  };
2375
2435
  }
2376
2436
  /**
2377
- * Look for a named control via fast C#-side targeted UIA query when possible,
2378
- * then full window UIA, then popups, and finally built-in Windows OCR when
2379
- * the UIA tree is empty or sparse (<= 20 controls).
2437
+ * Look for a named control via tiered C#-side targeted UIA lookup:
2438
+ * 1. Exact AutomationId native PropertyCondition
2439
+ * 2. Exact Name (+ optional Role) native PropertyCondition
2440
+ * 3. Role + fuzzy query (accepting unique results only when not truncated)
2441
+ * 4. Full window UIA -> popup UIA -> Windows OCR fallback.
2380
2442
  */
2381
2443
  async find(target, hwnd) {
2382
2444
  const parsed = parseTarget(target);
2383
- if (parsed.automationId || parsed.role) {
2445
+ if (parsed.automationId) {
2384
2446
  const fast = await this.findElements({
2385
2447
  ...hwnd === void 0 ? {} : { hwnd },
2386
- ...parsed.automationId ? { automationId: parsed.automationId } : {},
2448
+ automationId: parsed.automationId,
2387
2449
  ...parsed.role ? { role: parsed.role } : {},
2388
- ...parsed.name && !parsed.automationId ? { query: parsed.name } : {},
2389
2450
  maxMatches: 24
2390
2451
  });
2391
- if (fast && fast.elements.length > 0) {
2452
+ if (fast && fast.elements.length > 0 && !fast.truncated) {
2392
2453
  const fastMatch = matchTarget(fast.elements, target);
2393
2454
  if (fastMatch.kind !== "missing") return fastMatch;
2394
2455
  }
2395
2456
  }
2457
+ if (parsed.name && !parsed.automationId) {
2458
+ const exact = await this.findElements({
2459
+ ...hwnd === void 0 ? {} : { hwnd },
2460
+ name: parsed.name,
2461
+ ...parsed.role ? { role: parsed.role } : {},
2462
+ maxMatches: 24
2463
+ });
2464
+ if (exact && exact.elements.length > 0 && !exact.truncated) {
2465
+ const exactMatch = matchTarget(exact.elements, target);
2466
+ if (exactMatch.kind !== "missing") return exactMatch;
2467
+ }
2468
+ }
2469
+ if (parsed.role && !parsed.automationId) {
2470
+ const fuzzy = await this.findElements({
2471
+ ...hwnd === void 0 ? {} : { hwnd },
2472
+ role: parsed.role,
2473
+ ...parsed.name ? { query: parsed.name } : {},
2474
+ maxMatches: 24
2475
+ });
2476
+ if (fuzzy && fuzzy.elements.length > 0 && !fuzzy.truncated) {
2477
+ const fuzzyMatch = matchTarget(fuzzy.elements, target);
2478
+ if (fuzzyMatch.kind !== "missing") return fuzzyMatch;
2479
+ }
2480
+ }
2396
2481
  const inWindow = await this.elements("window", hwnd).catch(() => []);
2397
2482
  const match = matchTarget(inWindow, target);
2398
2483
  if (match.kind !== "missing") return match;
@@ -2764,11 +2849,16 @@ var Computer = class Computer {
2764
2849
  const button = action === "right_click" ? "right" : action === "middle_click" ? "middle" : "left";
2765
2850
  const count = action === "double_click" ? 2 : action === "triple_click" ? 3 : 1;
2766
2851
  const modifiers = parseModifiers(input.modifiers ?? input.text);
2767
- const retryAfterUia = action === "left_click" && modifiers.length === 0 && this.hadRecentUiaClickAt(p);
2852
+ const clickHwnd = named?.window.hwnd ?? hitWin?.hwnd;
2853
+ const retryAfterUia = action === "left_click" && modifiers.length === 0 && this.hadRecentUiaClickAt(p, call.session, clickHwnd);
2768
2854
  if (action === "left_click" && named && modifiers.length === 0 && !retryAfterUia) {
2769
2855
  const semantic = named.element.role === "Edit" || named.element.editable ? "focus" : "invoke";
2770
2856
  if (await this.semanticAction(call, named, semantic)) {
2771
- this.noteClick(p, void 0, "uia");
2857
+ this.noteClick(p, void 0, "uia", {
2858
+ session: call.session,
2859
+ hwnd: named.window.hwnd,
2860
+ name: named.element.name
2861
+ });
2772
2862
  return { text: `${semantic === "focus" ? "Focused" : "Invoked"}${label}.` };
2773
2863
  }
2774
2864
  }
@@ -2786,7 +2876,11 @@ var Computer = class Computer {
2786
2876
  }
2787
2877
  if (hit?.ok === true) {
2788
2878
  this.invalidateMarks();
2789
- const repeat = this.noteClick(p, void 0, "uia");
2879
+ const repeat = this.noteClick(p, void 0, "uia", {
2880
+ session: call.session,
2881
+ ...hitWin ? { hwnd: hitWin.hwnd } : {},
2882
+ ...hit.name ? { name: hit.name } : {}
2883
+ });
2790
2884
  const repeatHint = repeat >= 3 ? ` (same spot clicked ${repeat} times — screenshot before clicking again)` : "";
2791
2885
  return { text: `Invoked ${hit.name ? `${hit.role || "control"} "${hit.name.slice(0, 40)}"` : hit.role || "control"}${label} in background (${hit.mechanism || "uia"}).${repeatHint}` };
2792
2886
  }
@@ -2819,7 +2913,10 @@ var Computer = class Computer {
2819
2913
  x: clickRes.x,
2820
2914
  y: clickRes.y
2821
2915
  } : void 0);
2822
- const repeat = this.noteClick(clickedAt, clickRes?.repeat, "physical");
2916
+ const repeat = this.noteClick(clickedAt, clickRes?.repeat, "physical", {
2917
+ session: call.session,
2918
+ ...clickHwnd !== void 0 ? { hwnd: clickHwnd } : {}
2919
+ });
2823
2920
  const repeatHint = repeat >= 3 ? ` (same spot clicked ${repeat} times — screenshot before clicking again)` : "";
2824
2921
  const fallbackNote = retryAfterUia ? " (physical click after prior UIA invoke at same spot)" : "";
2825
2922
  return { text: `${action.replace("_", " ")}${label}${modifiers.length ? ` holding ${input.modifiers ?? input.text}` : ""}.${fallbackNote}${repeatHint}` };
@@ -2934,11 +3031,40 @@ var Computer = class Computer {
2934
3031
  }, 4e3);
2935
3032
  if (res?.performed !== true) throw new Error(`UI Automation could not perform "${op}" on ${element.role} "${element.name.slice(0, 50)}" (control may not support this pattern).`);
2936
3033
  const desc = `${element.role} "${element.name.slice(0, 50)}"`;
2937
- if (op === "set_checked") return { text: `${res.changed === false ? "Already" : "Set"} ${desiredChecked ? "checked" : "unchecked"} on ${desc}.` };
2938
- if (op === "expand" || op === "collapse") return { text: `${res.changed === false ? "Already " : ""}${op === "expand" ? "Expanded" : "Collapsed"} ${desc}.` };
2939
- if (op === "select") return { text: `${res.changed === false ? "Already selected" : "Selected"} ${desc}.` };
2940
- if (op === "set_value") return { text: `Set value (${desiredValue.length} chars) on ${desc} via UIA ValuePattern.` };
2941
- return { text: `${op === "focus" ? "Focused" : "Invoked"} ${desc}.` };
3034
+ const verified = res.verified === true;
3035
+ if (op === "set_checked") {
3036
+ const actualState = res.toggleState ?? (res.checked === true ? "On" : res.checked === false ? "Off" : desiredChecked ? "On" : "Off");
3037
+ const suffix = res.verified === false ? ` (unverified: actual state is ${actualState})` : "";
3038
+ return {
3039
+ text: `${res.changed === false ? "Already" : "Set"} ${desiredChecked ? "checked" : "unchecked"} on ${desc}.${suffix}`,
3040
+ verified
3041
+ };
3042
+ }
3043
+ if (op === "expand" || op === "collapse") {
3044
+ const suffix = res.verified === false ? ` (unverified: actual state is ${res.state ?? "unknown"})` : "";
3045
+ return {
3046
+ text: `${res.changed === false ? "Already " : ""}${op === "expand" ? "Expanded" : "Collapsed"} ${desc}.${suffix}`,
3047
+ verified
3048
+ };
3049
+ }
3050
+ if (op === "select") {
3051
+ const suffix = res.verified === false ? " (unverified: control did not report IsSelected=true)" : "";
3052
+ return {
3053
+ text: `${res.changed === false ? "Already selected" : "Selected"} ${desc}.${suffix}`,
3054
+ verified
3055
+ };
3056
+ }
3057
+ if (op === "set_value") {
3058
+ const suffix = res.verified === false ? ` (unverified: read back ${res.actualLength ?? 0} chars)` : "";
3059
+ return {
3060
+ text: `Set value (${desiredValue.length} chars) on ${desc} via UIA ValuePattern.${suffix}`,
3061
+ verified
3062
+ };
3063
+ }
3064
+ return {
3065
+ text: `${op === "focus" ? "Focused" : "Invoked"} ${desc}.`,
3066
+ ...op === "focus" ? { verified: true } : {}
3067
+ };
2942
3068
  }
2943
3069
  default: throw new Error(`Unknown action: ${String(action)}`);
2944
3070
  }
@@ -3014,12 +3140,22 @@ var Computer = class Computer {
3014
3140
  * (vision models only). A wait already waited, so it is captured at once:
3015
3141
  * "wait, then look" should be one step, not two.
3016
3142
  */
3017
- async after(inputs, call, detail) {
3018
- if (!this.settings().autoScreenshot || !call.vision) return void 0;
3143
+ async after(inputs, call, detail, forceScreenshot = false) {
3144
+ if (!this.settings().autoScreenshot && !forceScreenshot || !call.vision) return void 0;
3019
3145
  const mutating = inputs.some((input) => MUTATING.has(input.action));
3020
- if (!mutating && !inputs.some((input) => input.action === "wait")) return void 0;
3146
+ if (!forceScreenshot && !mutating && !inputs.some((input) => input.action === "wait")) return void 0;
3147
+ const t0 = Date.now();
3021
3148
  if (mutating) await this.settle(call.signal);
3022
- return this.freshShot(detail ?? inputs.at(-1)?.detail);
3149
+ const settleMs = Date.now() - t0;
3150
+ const t1 = Date.now();
3151
+ const shot = await this.freshShot(detail ?? inputs.at(-1)?.detail);
3152
+ const shotMs = Date.now() - t1;
3153
+ this.phaseSamples.push({
3154
+ settleMs,
3155
+ shotMs
3156
+ });
3157
+ if (this.phaseSamples.length > 40) this.phaseSamples.shift();
3158
+ return shot;
3023
3159
  }
3024
3160
  /** Bring a window forward and verify it is the foreground window. */
3025
3161
  async focus(win) {
@@ -3145,7 +3281,8 @@ function buildDiagnosticSnapshot(options) {
3145
3281
  blockedAppsCount: s.blockedApps.length,
3146
3282
  hasCustomHarnessUrl: Boolean(s.harnessUrl)
3147
3283
  },
3148
- recentCalls: options.recentCalls
3284
+ recentCalls: options.recentCalls,
3285
+ ...options.phaseTiming ? { phaseTiming: options.phaseTiming } : {}
3149
3286
  };
3150
3287
  }
3151
3288
  function formatDiagnosticText(snap) {
@@ -3154,6 +3291,7 @@ function formatDiagnosticText(snap) {
3154
3291
  `Generated: ${snap.generatedAt}`,
3155
3292
  `Plugin: ${snap.pluginVersion} | Node: ${snap.nodeVersion} | OS: ${snap.os}`,
3156
3293
  `Helper: ${snap.helper.status} | Native koffi available: ${snap.helper.nativeAvailable}${snap.helper.error ? ` | Error: ${snap.helper.error}` : ""}`,
3294
+ ...snap.phaseTiming && snap.phaseTiming.samples > 0 ? [`Phase timing (${snap.phaseTiming.samples} samples): avg settle=${snap.phaseTiming.avgSettleMs}ms | avg screenshot=${snap.phaseTiming.avgShotMs}ms`] : [],
3157
3295
  "",
3158
3296
  "--- Displays ---",
3159
3297
  ...snap.displays.length === 0 ? ["(none)"] : snap.displays.map((d) => `#${d.index}${d.primary ? " (primary)" : ""}: ${d.width}x${d.height} @ ${Math.round(d.dpi / 96 * 100)}% DPI | shot=${d.shot.width}x${d.shot.height} (${d.shot.megapixels}MP, ${d.shot.limitedBy}) | compact=${d.compactShot.width}x${d.compactShot.height}`),
@@ -3759,7 +3897,7 @@ ${mode === "per-app" ? "- Before acting on an app, call request_access once with
3759
3897
  - Prefer reliable keyboard shortcuts (ctrl+l for a browser address bar, ctrl+s, alt+F4, ctrl+t). Click the center of targets. When text is too small to read, zoom once on a generous region that contains everything you need (zooming step by step wastes calls).
3760
3898
  - Actions return a fresh screenshot taken once the screen stops changing (page loads included, up to a few seconds), so you rarely need wait. If something is still loading, use wait: it also returns a screenshot, so never follow it with a separate screenshot call. Explicit screenshot and zoom skip sending duplicate pixels when nothing changed (pass force: true to capture anyway); pass detail: "low" when you only need a quick visual confirmation rather than reading small text.
3761
3899
  - When the overlay is enabled, a colored pointer cursor with a subtle click ripple briefly stays visible in the next screenshot at the click position (blue = left click, purple = double click, green = right click, cyan = middle click, orange = triple click) so you can verify exactly where your click landed. If you see a repeat-click warning on the same spot, inspect the screen before clicking again.
3762
- - For windows with sparse or empty UI Automation trees (canvas UIs, games, custom-drawn apps), use ui_elements with ocr: true to read visible text and clickable center coordinates via built-in Windows OCR; target lookups and ui_elements with text: true also fall back to Windows OCR automatically when UIA finds nothing. To look up specific controls without dumping the whole tree, pass query and/or role to ui_elements (e.g. query: "保存", role: "Button"). For idempotent native UIA operations (checking/unchecking checkboxes, expanding trees/menus, selecting list items, or setting values directly), use computer action "ui_action" with target and operation ("set_checked" | "expand" | "collapse" | "select" | "set_value" | "invoke" | "focus"). On repeated inspections of the same window, pass diff: true to ui_elements to receive only added/changed/removed controls and save tokens. On dense UIs with duplicate button labels, use ui_elements with marks: true to get a Set-of-Marks numbered screenshot and click or type by target "#12" (marks expire automatically after any action or window change). When CDP is enabled in settings, ui_elements with cdp: true reads visible DOM elements of the active matched browser tab.
3900
+ - For windows with sparse or empty UI Automation trees (canvas UIs, games, custom-drawn apps), use ui_elements with ocr: true to read visible text and clickable center coordinates via built-in Windows OCR; target lookups and ui_elements with text: true also fall back to Windows OCR automatically when UIA finds nothing. To look up specific controls without dumping the whole tree, pass query and/or role to ui_elements (e.g. query: "保存", role: "Button"). For idempotent native UIA operations (checking/unchecking checkboxes, expanding trees/menus, selecting list items, or setting values directly), use computer action "ui_action" with target and operation ("set_checked" | "expand" | "collapse" | "select" | "set_value" | "invoke" | "focus") — verified ui_action calls return their read-back state automatically without taking a redundant screenshot (pass feedback: "screenshot" when visual inspection is needed, or feedback: "none"/"diff" on other actions to save time and tokens). On repeated inspections of the same window, pass diff: true to ui_elements to receive only added/changed/removed controls and save tokens. On dense UIs with duplicate button labels, use ui_elements with marks: true to get a Set-of-Marks numbered screenshot and click or type by target "#12" (marks expire automatically after any action or window change). When CDP is enabled in settings, ui_elements with cdp: true reads visible DOM elements of the active matched browser tab.
3763
3901
  - When replacing text in an existing field, pass replace: true to type so it selects all and replaces in one step. Password fields are protected by default: never attempt to type passwords; stop and ask the user.
3764
3902
  - When the user asks you to write something in an app, enter it there with type, even long or multi-line Markdown: the user watches it appear (long text is streamed in paragraph by paragraph, literally, without the editor's auto-formatting getting in the way). Do not write the file from a shell and reopen it instead, and do not put text on the clipboard with shell commands (Set-Clipboard, clip): that clutters the user's clipboard history.
3765
3903
  - App skills & macros: open_application returns your saved notes for the app it opens; follow them instead of rediscovering how the app behaves. After working out an unfamiliar app (or finding a note wrong), record the reusable part with app_skill rather than in general memory. For repeatable multi-step routines, save parameterized sequences via app_skill save_macro and replay them with computer_batch macro.
@@ -4428,7 +4566,7 @@ function sessionRoute(gate, settings, parentIdsFor, sync) {
4428
4566
  };
4429
4567
  }
4430
4568
  /** Export a sanitized diagnostic report (plain text by default, or JSON with ?format=json). */
4431
- function diagnosticsRoute(helper, settings, diagnostics, pluginVersion) {
4569
+ function diagnosticsRoute(helper, settings, diagnostics, pluginVersion, phaseTiming) {
4432
4570
  return async (req, res) => {
4433
4571
  const s = settings();
4434
4572
  let displays = [];
@@ -4447,7 +4585,8 @@ function diagnosticsRoute(helper, settings, diagnostics, pluginVersion) {
4447
4585
  helperStatus,
4448
4586
  ...helperError ? { helperError } : {},
4449
4587
  nativeAvailable: helper.available === true,
4450
- recentCalls: diagnostics.recent()
4588
+ recentCalls: diagnostics.recent(),
4589
+ ...phaseTiming ? { phaseTiming: phaseTiming() } : {}
4451
4590
  });
4452
4591
  if (new URL(req.url ?? "/api/dsh-computer-use/diagnostics", "http://127.0.0.1").searchParams.get("format") === "json") {
4453
4592
  json(res, 200, {
@@ -10904,7 +11043,18 @@ const actionProperties = {
10904
11043
  },
10905
11044
  replace: {
10906
11045
  type: "boolean",
10907
- description: "type: select all (Ctrl+A) and replace existing text in the field."
11046
+ description: "type: select all (Ctrl+A) before entering replacement text."
11047
+ },
11048
+ feedback: {
11049
+ type: "string",
11050
+ enum: [
11051
+ "auto",
11052
+ "state",
11053
+ "diff",
11054
+ "screenshot",
11055
+ "none"
11056
+ ],
11057
+ description: "Post-action feedback: \"auto\" (default: skips settle/screenshot for verified ui_action, returns screenshot otherwise), \"state\"/\"none\" (skip screenshot), \"diff\" (UIA delta instead of screenshot), \"screenshot\" (force visual screenshot)."
10908
11058
  }
10909
11059
  };
10910
11060
  const BATCH_ACTIONS = ACTIONS.filter((action) => action !== "screenshot");
@@ -10925,7 +11075,28 @@ function createTools(host) {
10925
11075
  const outcome = await computer.run(input, call);
10926
11076
  if (outcome.image) return withShot(host, outcome.text, outcome.image, call);
10927
11077
  if (input.action === "screenshot" || input.action === "zoom") return { text: outcome.text };
10928
- const shot = await computer.after([input], call);
11078
+ const fb = input.feedback ?? "auto";
11079
+ if (fb === "none" || fb === "state") return { text: outcome.text };
11080
+ if (fb === "auto" && input.action === "ui_action" && outcome.verified === true) return { text: `${outcome.text} (verified via UIA; skipped screenshot)` };
11081
+ if (fb === "diff") {
11082
+ const uiRes = await computer.helper.call("ui", {
11083
+ includeText: false,
11084
+ popups: true,
11085
+ maxNodes: 120
11086
+ }, 1e4).catch(() => void 0);
11087
+ if (uiRes && typeof uiRes.hwnd === "number" && Array.isArray(uiRes.elements)) {
11088
+ const delta = computer.uiDiff.diff({
11089
+ sessionId: call.session,
11090
+ hwnd: uiRes.hwnd,
11091
+ pid: uiRes.pid,
11092
+ queryProfile: "0:120"
11093
+ }, String(uiRes.title ?? ""), uiRes.elements);
11094
+ const summary = delta.isBaseline ? `${uiRes.elements.length} UI elements` : delta.added.length === 0 && delta.changed.length === 0 && delta.removed.length === 0 ? "UI tree unchanged" : `+${delta.added.length} added, ~${delta.changed.length} changed, -${delta.removed.length} removed`;
11095
+ return { text: `${outcome.text} [${uiRes.exe}: ${summary}]` };
11096
+ }
11097
+ return { text: outcome.text };
11098
+ }
11099
+ const shot = await computer.after([input], call, input.detail, fb === "screenshot");
10929
11100
  return withShot(host, shot === void 0 && input.action !== "wait" && input.action !== "cursor_position" ? `${outcome.text} ${await computer.describeForeground()}` : outcome.text, shot, call);
10930
11101
  } catch (error) {
10931
11102
  if (call.signal.aborted) await computer.releaseHeld();
@@ -12270,7 +12441,7 @@ function apply(ctx, config = {}) {
12270
12441
  route(SCREENSHOTS_CLEAN_ROUTE, screenshotsCleanRoute(screenshots));
12271
12442
  route(SKILLS_ROUTE, skillsRoute(skills));
12272
12443
  route(SESSION_ROUTE, sessionRoute(sessionGate, settings, parentIdsFor, syncAllAgents));
12273
- route(DIAGNOSTICS_ROUTE, diagnosticsRoute(helper, settings, diagnostics, PLUGIN_VERSION));
12444
+ route(DIAGNOSTICS_ROUTE, diagnosticsRoute(helper, settings, diagnostics, PLUGIN_VERSION, () => computer.timingSummary()));
12274
12445
  route(UPDATE_ROUTE, updateRoute(PLUGIN_VERSION));
12275
12446
  route(WINDOWS_ROUTE, windowsRoute(helper));
12276
12447
  });
@@ -88,6 +88,7 @@ export interface CallContext {
88
88
  export declare const ACTIONS: readonly ["screenshot", "left_click", "right_click", "middle_click", "double_click", "triple_click", "mouse_move", "left_click_drag", "left_mouse_down", "left_mouse_up", "scroll", "type", "key", "hold_key", "wait", "zoom", "cursor_position", "ui_action"];
89
89
  export type Action = typeof ACTIONS[number];
90
90
  export type UiSemanticOperation = 'invoke' | 'focus' | 'set_checked' | 'expand' | 'collapse' | 'select' | 'set_value';
91
+ export type ActionFeedback = 'auto' | 'state' | 'diff' | 'screenshot' | 'none';
91
92
  export interface ActionInput {
92
93
  action: Action;
93
94
  coordinate?: number[];
@@ -116,6 +117,8 @@ export interface ActionInput {
116
117
  detail?: ScreenshotDetail;
117
118
  /** type: select all (Ctrl+A) before entering replacement text. */
118
119
  replace?: boolean;
120
+ /** Post-action feedback mode: 'auto' skips screenshots for verified deterministic ui_action, 'state'/'none' skips screenshot, 'diff' returns UIA delta, 'screenshot' forces visual capture. */
121
+ feedback?: ActionFeedback;
119
122
  }
120
123
  export interface ActionOutcome {
121
124
  text: string;
@@ -123,6 +126,8 @@ export interface ActionOutcome {
123
126
  image?: Shot | 'unchanged';
124
127
  /** The action was not performed because the user took over the keyboard. */
125
128
  skipped?: boolean;
129
+ /** True when a deterministic UIA Control Pattern read back and verified the desired post-state. */
130
+ verified?: boolean;
126
131
  }
127
132
  export interface ClickResult {
128
133
  x?: number;
@@ -164,8 +169,10 @@ export declare class Computer {
164
169
  private heldButton;
165
170
  /** Dimensions of the latest full-display screenshot shown to the model (keeps coordinate conversion exact across detail modes). */
166
171
  private lastShot;
167
- /** Recent click locations (repeat counter + auto physical-click fallback if a UIA invoke had no effect). */
172
+ /** Recent click locations (repeat counter + scoped auto physical-click fallback if a UIA invoke had no effect). */
168
173
  private readonly clickHistory;
174
+ /** Rolling per-phase timing samples (settle + screenshot) for diagnostics & performance profiling. */
175
+ private readonly phaseSamples;
169
176
  /** The agent that last wrote the clipboard; when it goes idle the user's clipboard comes back. */
170
177
  clipboardAgent: CancellableAgent | undefined;
171
178
  /** Single-machine desktop control lease preventing concurrent sessions from colliding. */
@@ -227,8 +234,17 @@ export declare class Computer {
227
234
  }): Promise<Shot | 'unchanged'>;
228
235
  /** Record a click position and return how many times this spot (±24 px) was clicked in the last 2 minutes. */
229
236
  private noteClick;
230
- /** Whether this spot (±24 px) was already clicked via background UIA invoke recently (so a retry should use a real physical click). */
237
+ /**
238
+ * Whether this spot (±24 px) in the same session & window was recently invoked via UIA
239
+ * (and is NOT a non-idempotent submit/delete/pay button), so a retry upgrades to physical click.
240
+ */
231
241
  private hadRecentUiaClickAt;
242
+ /** Rolling average settle/screenshot phase timings for diagnostics. */
243
+ timingSummary(): {
244
+ samples: number;
245
+ avgSettleMs: number;
246
+ avgShotMs: number;
247
+ };
232
248
  foreground(): Promise<WindowInfo | undefined>;
233
249
  /**
234
250
  * The user clicked into the DeepSeek Harness card (to read or scroll the
@@ -236,6 +252,8 @@ export declare class Computer {
236
252
  * in front instead of refusing.
237
253
  */
238
254
  private refocusFromHost;
255
+ /** Prefer sampling the visible foreground target window (clamped to current display) so taskbar/side-app animations never disrupt settle detection. */
256
+ private settleRect;
239
257
  /** Wait at most `maxMs`, returning once the screen settles (for waits ≥ 4s, waits for a real visual update first and emits progress checkpoints if still changing so AI can act early or wait again). */
240
258
  waitForQuiet(maxMs: number, signal: AbortSignal, wait?: WaitHandle): Promise<{
241
259
  ms: number;
@@ -296,11 +314,14 @@ export declare class Computer {
296
314
  maxMatches?: number;
297
315
  }): Promise<(Partial<WindowInfo> & {
298
316
  elements: UiElement[];
317
+ truncated?: boolean;
299
318
  }) | undefined>;
300
319
  /**
301
- * Look for a named control via fast C#-side targeted UIA query when possible,
302
- * then full window UIA, then popups, and finally built-in Windows OCR when
303
- * the UIA tree is empty or sparse (<= 20 controls).
320
+ * Look for a named control via tiered C#-side targeted UIA lookup:
321
+ * 1. Exact AutomationId native PropertyCondition
322
+ * 2. Exact Name (+ optional Role) native PropertyCondition
323
+ * 3. Role + fuzzy query (accepting unique results only when not truncated)
324
+ * 4. Full window UIA -> popup UIA -> Windows OCR fallback.
304
325
  */
305
326
  private find;
306
327
  /**
@@ -343,7 +364,7 @@ export declare class Computer {
343
364
  * (vision models only). A wait already waited, so it is captured at once:
344
365
  * "wait, then look" should be one step, not two.
345
366
  */
346
- after(inputs: readonly ActionInput[], call: CallContext, detail?: ScreenshotDetail): Promise<Shot | 'unchanged' | undefined>;
367
+ after(inputs: readonly ActionInput[], call: CallContext, detail?: ScreenshotDetail, forceScreenshot?: boolean): Promise<Shot | 'unchanged' | undefined>;
347
368
  /** Bring a window forward and verify it is the foreground window. */
348
369
  focus(win: WindowInfo): Promise<WindowInfo & {
349
370
  focused: boolean;
@@ -57,6 +57,11 @@ export interface DiagnosticSnapshot {
57
57
  hasCustomHarnessUrl: boolean;
58
58
  };
59
59
  recentCalls: readonly DiagnosticCall[];
60
+ phaseTiming?: {
61
+ samples: number;
62
+ avgSettleMs: number;
63
+ avgShotMs: number;
64
+ };
60
65
  }
61
66
  export declare class DiagnosticsLog {
62
67
  private readonly calls;
@@ -75,5 +80,10 @@ export declare function buildDiagnosticSnapshot(options: {
75
80
  helperError?: string;
76
81
  nativeAvailable: boolean;
77
82
  recentCalls: readonly DiagnosticCall[];
83
+ phaseTiming?: {
84
+ samples: number;
85
+ avgSettleMs: number;
86
+ avgShotMs: number;
87
+ };
78
88
  }): DiagnosticSnapshot;
79
89
  export declare function formatDiagnosticText(snap: DiagnosticSnapshot): string;
@@ -47,7 +47,11 @@ export declare function sessionRoute(gate: SessionGate, settings: () => Settings
47
47
  /** Export a sanitized diagnostic report (plain text by default, or JSON with ?format=json). */
48
48
  export declare function diagnosticsRoute(helper: HelperLike & {
49
49
  available?: boolean;
50
- }, settings: () => Settings, diagnostics: DiagnosticsLog, pluginVersion: string): Handler;
50
+ }, settings: () => Settings, diagnostics: DiagnosticsLog, pluginVersion: string, phaseTiming?: () => {
51
+ samples: number;
52
+ avgSettleMs: number;
53
+ avgShotMs: number;
54
+ }): Handler;
51
55
  /** Check npmjs & npmmirror concurrently for a newer plugin version. */
52
56
  export declare function updateRoute(pluginVersion: string): Handler;
53
57
  /** Passive read-only window list for `@窗口` composer references (never triggers overlay or focus). */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@copylee/dsh-computer-use",
3
- "version": "0.14.2",
3
+ "version": "0.15.0",
4
4
  "description": "DeepSeek Harness Computer Use 插件(Windows):让 AI 看屏幕、点鼠标、敲键盘操控电脑;控制时屏幕泛起橙色光晕并显示“DeepSeek Harness 正在操控你的电脑”,按 Esc 暂停 / 继续。",
5
5
  "icon": "assets/icon.svg",
6
6
  "type": "module",