@copylee/dsh-computer-use 0.1.4 → 0.1.6

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/README.md CHANGED
@@ -7,14 +7,14 @@
7
7
  | 功能 | 说明 |
8
8
  |---|---|
9
9
  | 截图即坐标系 | 模型只用最近一张截图的像素坐标,DPI、缩放、多显示器偏移全部由插件换算,高分屏(200% 缩放)也点得准 |
10
- | 动作后自动回传截图 | 点击 / 输入 / 按键后自动等界面稳定再截图,少一轮调用 |
10
+ | 动作后自动回传截图 | 点击 / 输入 / 按键 / 滚动后,**等画面不再变化**(页面加载、动画结束,最多约 2.5 秒)再截图;`wait` 也直接带回截图,“等一下再看”只需一步 |
11
11
  | 批量动作 | `computer_batch` 一次执行“点输入框 → 输入 → 回车”等多步,最后只截一张图 |
12
12
  | 按应用授权 | 先 `request_access` 列出要操控的应用,经 DSH 原生审批后才能操作;也可改为“全部允许” |
13
13
  | 不会操作自己 | 永远拒绝向 DeepSeek Harness 自身窗口输入;常见密码管理器默认禁止,可再自定义禁用列表 |
14
14
  | 正在控制的提示 | 橙色光晕 + 胶囊提示条(显示当前动作),**不会出现在截图里** |
15
- | 悬浮卡片 | 操控期间 DeepSeek Harness 窗口缩成右下角置顶卡片,结束后自动恢复原尺寸、位置和最大化 / 最小化状态(也可选最小化或不动) |
15
+ | 悬浮卡片 | 操控期间 DeepSeek Harness 窗口缩成右下角置顶卡片,结束后自动恢复原尺寸、位置和最大化 / 最小化状态(也可选最小化或不动)。AI 要点击 / 滚动 / 查看卡片下面的内容时,卡片自动躲到另一侧角落 |
16
16
  | 暂停与停止 | 你亲手按 **Esc** 暂停(AI 停在下一步之前),再按 Esc 或点“继续”恢复,对话不会被中断;点“停止”才结束本轮。插件自己发出的 Esc 不会误触发 |
17
- | 你随时可以插手 | 你用键盘打字时 AI 自动暂停,停手 1.5 秒后继续;你切换或打开了别的窗口,AI 下一步不会盲目执行,而是先看新截图再决定。鼠标移动不会触发,避免误触 |
17
+ | 你随时可以插手 | 你用键盘打字时 AI 自动暂停,停手 1.5 秒后继续(单按 Shift / Ctrl 等修饰键不算);你切换或打开了别的窗口,AI 下一步不会盲目执行,而是先看新截图再决定。你只是点进 DSH 卡片看对话时不算切换,AI 的按键会自动回到它正在操作的窗口。鼠标移动不会触发,避免误触 |
18
18
  | 中文输入 | Unicode 直接输入,不受输入法状态影响;长文本走剪贴板并自动恢复原剪贴板;剪贴板文本统一为 CRLF,粘贴到 Obsidian 等应用不丢换行 |
19
19
  | 打开应用 | `open_application` 同时搜索开始菜单和桌面快捷方式(含公共桌面),便携软件也能按名字打开 |
20
20
  | 看不见图的模型 | `ui_elements` 用 Windows UI Automation 列出可点击元素和坐标,纯文本模型也能用 |
@@ -70,7 +70,7 @@ dsh plugin --profile web add @copylee/dsh-computer-use@latest
70
70
  | 提示条名称 | DeepSeek Harness | 显示为“<名称> 正在操控你的电脑” |
71
71
  | 操控期间 DSH 窗口 | 悬浮卡片 | 悬浮卡片 / 最小化 / 保持不变,结束后自动恢复 |
72
72
  | 操作后自动截图 | 开 | 关闭可省 token,但模型需要自己截图 |
73
- | 等待稳定 | 400 ms | 动作后多久再截图 |
73
+ | 等待稳定 | 400 ms | 动作后至少等这么久,之后画面静止即截图(最多约 2.5 秒) |
74
74
  | 截图最长边 / 总像素 / JPEG 质量 | 1366 / 1.15MP / 80 | 越大越清晰、越费 token |
75
75
  | 检测到你在操作时让出控制 | 开 | 键盘输入暂停、窗口被切换时重新看屏幕 |
76
76
  | 键盘静止多久后恢复 | 1500 ms | |
@@ -250,6 +250,7 @@ namespace DshComputerUse
250
250
  case "ping": { var d = new Dictionary<string, object>(); d["version"] = Program.Version; return d; }
251
251
  case "displays": return Screen2.Displays();
252
252
  case "screenshot": return Screen2.Capture(r);
253
+ case "settle": return Screen2.Settle(r);
253
254
  case "cursor": { Native.POINT p; Native.GetCursorPos(out p); return Pt(p.X, p.Y); }
254
255
  case "move": Overlay.Dodge(Args.Int(r, "x", 0), Args.Int(r, "y", 0)); Input.Move(Args.Int(r, "x", 0), Args.Int(r, "y", 0)); return null;
255
256
  case "click": return Input.Click(r);
@@ -311,6 +312,75 @@ namespace DshComputerUse
311
312
  return list;
312
313
  }
313
314
 
315
+ /** Sample every 8th pixel of a screen rectangle (BGR bytes). */
316
+ static byte[] Sample(int x, int y, int w, int h)
317
+ {
318
+ using (var bmp = new Bitmap(w, h, PixelFormat.Format24bppRgb))
319
+ {
320
+ using (var g = Graphics.FromImage(bmp))
321
+ {
322
+ IntPtr dst = g.GetHdc();
323
+ IntPtr src = Native.GetDC(IntPtr.Zero);
324
+ try { Native.BitBlt(dst, 0, 0, w, h, src, x, y, 0x00CC0020 | 0x40000000); }
325
+ finally { Native.ReleaseDC(IntPtr.Zero, src); g.ReleaseHdc(dst); }
326
+ }
327
+ var data = bmp.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
328
+ try
329
+ {
330
+ int sx = (w + 7) / 8, sy = (h + 7) / 8;
331
+ var row = new byte[data.Stride];
332
+ var outp = new byte[sx * sy * 3];
333
+ int k = 0;
334
+ for (int j = 0; j < sy; j++)
335
+ {
336
+ Marshal.Copy(new IntPtr(data.Scan0.ToInt64() + (long)j * 8 * data.Stride), row, 0, data.Stride);
337
+ for (int i = 0; i < sx; i++) { int o = i * 8 * 3; outp[k++] = row[o]; outp[k++] = row[o + 1]; outp[k++] = row[o + 2]; }
338
+ }
339
+ return outp;
340
+ }
341
+ finally { bmp.UnlockBits(data); }
342
+ }
343
+ }
344
+
345
+ static double Changed(byte[] a, byte[] b)
346
+ {
347
+ int n = a.Length / 3, diff = 0;
348
+ for (int i = 0; i < a.Length; i += 3)
349
+ if (Math.Abs(a[i] - b[i]) + Math.Abs(a[i + 1] - b[i + 1]) + Math.Abs(a[i + 2] - b[i + 2]) > 30) diff++;
350
+ return n == 0 ? 0 : (double)diff / n;
351
+ }
352
+
353
+ /**
354
+ * Wait until the screen stops changing: at least minMs, then until two
355
+ * consecutive samples (quietMs apart in total) differ in under 0.2% of
356
+ * the sampled pixels, or maxMs passes (videos, spinners).
357
+ */
358
+ public static Dictionary<string, object> Settle(Dictionary<string, object> r)
359
+ {
360
+ int x = Args.Int(r, "x", 0), y = Args.Int(r, "y", 0), w = Args.Int(r, "width", 0), h = Args.Int(r, "height", 0);
361
+ int minMs = Args.Int(r, "minMs", 300), maxMs = Args.Int(r, "maxMs", 2500), interval = Args.Int(r, "intervalMs", 120), quietMs = Args.Int(r, "quietMs", 240);
362
+ if (w <= 0 || h <= 0) throw new Exception("invalid settle rect");
363
+ var watch = System.Diagnostics.Stopwatch.StartNew();
364
+ byte[] prev = Sample(x, y, w, h);
365
+ long quietSince = -1;
366
+ bool stable = false;
367
+ while (true)
368
+ {
369
+ Thread.Sleep(interval);
370
+ byte[] cur = Sample(x, y, w, h);
371
+ long now = watch.ElapsedMilliseconds;
372
+ if (Changed(prev, cur) < 0.002) { if (quietSince < 0) quietSince = now - interval; }
373
+ else quietSince = -1;
374
+ prev = cur;
375
+ if (now >= minMs && quietSince >= 0 && now - quietSince >= quietMs) { stable = true; break; }
376
+ if (now >= maxMs) break;
377
+ }
378
+ var d = new Dictionary<string, object>();
379
+ d["ms"] = (int)watch.ElapsedMilliseconds;
380
+ d["stable"] = stable;
381
+ return d;
382
+ }
383
+
314
384
  static ImageCodecInfo jpegCodec;
315
385
 
316
386
  public static Dictionary<string, object> Capture(Dictionary<string, object> r)
@@ -1366,13 +1436,17 @@ namespace DshComputerUse
1366
1436
  if (down) invoker.BeginInvoke((MethodInvoker)delegate { Press(paused ? "resume" : "pause"); });
1367
1437
  return new IntPtr(1);
1368
1438
  }
1369
- if (down)
1439
+ // Modifier-only presses (Shift to switch the IME, Ctrl, Alt, Win)
1440
+ // and synthetic packets are not typing.
1441
+ int vk = (int)kb.vkCode;
1442
+ bool modifier = vk == 0x10 || vk == 0x11 || vk == 0x12 || (vk >= 0xA0 && vk <= 0xA5) || vk == 0x5B || vk == 0x5C || vk == 0x14 || vk == 0xE7 || vk == 0xFF;
1443
+ if (down && !modifier)
1370
1444
  {
1371
1445
  // The user is typing: the host waits. Mouse movement is
1372
1446
  // deliberately ignored (too easy to nudge).
1373
1447
  int now = Environment.TickCount;
1374
1448
  lastTyping = now;
1375
- if (unchecked(now - lastEmit) > 250) { lastEmit = now; Program.EmitEvent("user_input", "keyboard"); }
1449
+ if (unchecked(now - lastEmit) > 250) { lastEmit = now; Program.EmitEvent("user_input", "vk=0x" + vk.ToString("X2")); }
1376
1450
  }
1377
1451
  }
1378
1452
  }
package/lib/client.js CHANGED
@@ -70,6 +70,60 @@ window.__ModuleLoader__.load({
70
70
  };
71
71
  }
72
72
  //#endregion
73
+ //#region lib/types/client/nav-icon.js
74
+ /**
75
+ * Give the "电脑控制" row in the DSH settings navigation a mouse-pointer icon
76
+ * instead of the shell's fallback gear.
77
+ *
78
+ * `settings.section` registrations only carry `id`, `order` and `label`; the
79
+ * shell picks icons for built-in ids only. So, like dsh-better-sidebar, we mark
80
+ * our own row by its label and let CSS swap the glyph (Lucide mouse-pointer-2,
81
+ * drawn as a currentColor mask so hover / active colors still apply).
82
+ */
83
+ const MARKER = "data-dsh-computer-use-settings-nav";
84
+ const POINTER_SVG = "%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M4.037 4.688a.495.495 0 0 1 .651-.651l16 6.5a.5.5 0 0 1-.063.947l-6.124 1.58a2 2 0 0 0-1.438 1.435l-1.579 6.126a.5.5 0 0 1-.947.063z'/%3E%3C/svg%3E";
85
+ const navIconCss = `
86
+ [${MARKER}] > svg:first-child { display: none; }
87
+ [${MARKER}]::before {
88
+ content: '';
89
+ flex: none;
90
+ width: 16px;
91
+ height: 16px;
92
+ background: currentColor;
93
+ -webkit-mask: url("data:image/svg+xml,${POINTER_SVG}") center / contain no-repeat;
94
+ mask: url("data:image/svg+xml,${POINTER_SVG}") center / contain no-repeat;
95
+ }
96
+ `;
97
+ /** Keep the marker on the settings-nav button labelled `label`; returns a disposer. */
98
+ function registerNavIcon(label) {
99
+ const style = document.createElement("style");
100
+ style.setAttribute("data-dsh-computer-use", "nav-icon");
101
+ style.textContent = navIconCss;
102
+ document.head.appendChild(style);
103
+ let disposed = false;
104
+ const sync = () => {
105
+ if (disposed) return;
106
+ for (const button of document.querySelectorAll("[role=\"dialog\"] nav button")) {
107
+ const mine = button.textContent?.trim() === label;
108
+ if (mine && !button.hasAttribute(MARKER)) button.setAttribute(MARKER, "");
109
+ else if (!mine && button.hasAttribute(MARKER)) button.removeAttribute(MARKER);
110
+ }
111
+ };
112
+ sync();
113
+ const observer = new MutationObserver(sync);
114
+ observer.observe(document.body, {
115
+ childList: true,
116
+ subtree: true,
117
+ characterData: true
118
+ });
119
+ return () => {
120
+ disposed = true;
121
+ observer.disconnect();
122
+ style.remove();
123
+ document.querySelectorAll(`[${MARKER}]`).forEach((element) => element.removeAttribute(MARKER));
124
+ };
125
+ }
126
+ //#endregion
73
127
  //#region lib/types/client/select.js
74
128
  const h$1 = react.createElement;
75
129
  /** Menu appearance and fixed-position behavior follow dsh-free-search / dsh-proxy. */
@@ -680,7 +734,7 @@ window.__ModuleLoader__.load({
680
734
  disabled,
681
735
  onChange: (value) => edit("autoScreenshot", value)
682
736
  }), h("div", { style: S.grid2 }, h(NumberField, {
683
- label: "操作后等待界面稳定",
737
+ label: "操作后至少等待(之后画面静止即截图,最多约 2.5 秒)",
684
738
  unit: "毫秒",
685
739
  value: draft.settleMs,
686
740
  error: errors.settleMs,
@@ -743,6 +797,7 @@ window.__ModuleLoader__.load({
743
797
  "remote.settings"
744
798
  ];
745
799
  function apply(ctx) {
800
+ ctx.effect(() => registerNavIcon("电脑控制"), "computer-use: settings nav icon");
746
801
  ctx.slots.inject("settings.section", () => ctx.slots.register({
747
802
  name: "settings.section",
748
803
  id: ENTRY_ID,
package/lib/index.js CHANGED
@@ -107,6 +107,17 @@ function normalizeApp(name) {
107
107
  function exeBase(win) {
108
108
  return normalizeApp(win.exe.split(/[\\/]/).pop() ?? "");
109
109
  }
110
+ /** Executable names an app name stands for (UWP's shared frame host excluded). */
111
+ function exeNames(name) {
112
+ const n = normalizeApp(name);
113
+ return new Set([n.replace(/\s/g, ""), ...ALIASES[n] ?? []].filter((exe) => exe !== "applicationframehost"));
114
+ }
115
+ /** Do two app names refer to the same program ("explorer" and "文件资源管理器")? */
116
+ function sameApp(a, b) {
117
+ const x = exeNames(a);
118
+ for (const exe of exeNames(b)) if (x.has(exe)) return true;
119
+ return false;
120
+ }
110
121
  function isHostWindow(win) {
111
122
  return HOST_EXES.includes(win.exe.toLowerCase());
112
123
  }
@@ -148,10 +159,10 @@ var AccessControl = class {
148
159
  isGranted(session, win) {
149
160
  return this.granted(session).some((name) => appMatches(name, win));
150
161
  }
151
- /** Names from `names` the session has not been granted yet. */
162
+ /** Names from `names` the session has not been granted yet (aliases count). */
152
163
  missing(session, names) {
153
164
  const set = this.grants.get(session) ?? /* @__PURE__ */ new Set();
154
- return names.filter((name) => !set.has(normalizeApp(name)));
165
+ return names.filter((name) => !set.has(normalizeApp(name)) && ![...set].some((granted) => sameApp(granted, name)));
155
166
  }
156
167
  forget(session) {
157
168
  this.grants.delete(session);
@@ -467,6 +478,12 @@ const MUTATING = /* @__PURE__ */ new Set([
467
478
  ]);
468
479
  /** Actions that wait for the user to stop typing before they run. */
469
480
  const INPUT = new Set([...MUTATING].filter((action) => action !== "mouse_move"));
481
+ /** Actions whose input goes to the foreground window. */
482
+ const KEYBOARD = /* @__PURE__ */ new Set([
483
+ "type",
484
+ "key",
485
+ "hold_key"
486
+ ]);
470
487
  var Computer = class Computer {
471
488
  helper;
472
489
  access;
@@ -511,10 +528,12 @@ var Computer = class Computer {
511
528
  async point(coordinate, field = "coordinate") {
512
529
  if (!Array.isArray(coordinate) || coordinate.length !== 2) throw new Error(`${field} must be [x, y] in screenshot pixels.`);
513
530
  const display = await this.display();
514
- return toPhysical({
531
+ const p = toPhysical({
515
532
  x: coordinate[0],
516
533
  y: coordinate[1]
517
534
  }, display, this.shotSize(display));
535
+ await this.overlay.dodgeCard(p);
536
+ return p;
518
537
  }
519
538
  async toModel(point) {
520
539
  const display = await this.display();
@@ -533,6 +552,12 @@ var Computer = class Computer {
533
552
  }
534
553
  /** The foreground window as of the model's latest look at the screen. */
535
554
  seen;
555
+ /** The latest foreground window that was not DeepSeek Harness itself. */
556
+ lastTarget;
557
+ /** A new turn starts: the user may have rearranged things while chatting. */
558
+ resetLook() {
559
+ this.seen = void 0;
560
+ }
536
561
  async remember() {
537
562
  this.seen = await this.foreground().catch(() => void 0);
538
563
  }
@@ -575,7 +600,34 @@ var Computer = class Computer {
575
600
  }
576
601
  async foreground() {
577
602
  const win = await this.helper.call("foreground");
578
- return typeof win.hwnd === "number" ? win : void 0;
603
+ if (!win || typeof win.hwnd !== "number") return void 0;
604
+ if (!isHostWindow(win)) this.lastTarget = win;
605
+ return win;
606
+ }
607
+ /**
608
+ * The user clicked into the DeepSeek Harness card (to read or scroll the
609
+ * chat): keys would go there. Put the window the agent was working in back
610
+ * in front instead of refusing.
611
+ */
612
+ async refocusFromHost() {
613
+ const target = this.lastTarget;
614
+ const fg = await this.foreground().catch(() => void 0);
615
+ if (!fg || !isHostWindow(fg) || !target || target.hwnd === fg.hwnd) return;
616
+ if ((await this.focus(target).catch(() => void 0))?.focused) await setTimeout$1(80);
617
+ }
618
+ /** Wait until the screen stops changing (bounded), instead of a fixed delay. */
619
+ async settle(signal) {
620
+ const s = this.settings();
621
+ const display = await this.display();
622
+ if (await this.helper.call("settle", {
623
+ x: display.x,
624
+ y: display.y,
625
+ width: display.width,
626
+ height: display.height,
627
+ minMs: s.settleMs,
628
+ maxMs: Math.max(s.settleMs, 2500)
629
+ }, 15e3).catch(() => null) === null) await setTimeout$1(s.settleMs, void 0, { signal });
630
+ if (signal.aborted) throw new Error("Cancelled.");
579
631
  }
580
632
  async windowAt(point) {
581
633
  const win = await this.helper.call("window_at", { ...point });
@@ -646,7 +698,7 @@ var Computer = class Computer {
646
698
  }
647
699
  if (s.pauseOnUserInput && INPUT.has(action)) {
648
700
  const changed = await this.foregroundChanged();
649
- if (changed) {
701
+ if (changed && !isHostWindow(changed)) {
650
702
  await this.overlay.status("检测到窗口切换,重新查看屏幕");
651
703
  const image = call.vision ? await this.screenshot() : void 0;
652
704
  if (!image) this.seen = changed;
@@ -658,6 +710,7 @@ var Computer = class Computer {
658
710
  }
659
711
  }
660
712
  if (INPUT.has(action)) this.seen = void 0;
713
+ if (KEYBOARD.has(action)) await this.refocusFromHost();
661
714
  switch (action) {
662
715
  case "screenshot": {
663
716
  const shot = await this.screenshot();
@@ -783,12 +836,16 @@ var Computer = class Computer {
783
836
  up: true
784
837
  }).catch(() => {});
785
838
  }
786
- /** After a mutating action: settle, then capture (vision models only). */
839
+ /**
840
+ * After a mutating action: wait for the screen to settle, then capture
841
+ * (vision models only). A wait already waited, so it is captured at once:
842
+ * "wait, then look" should be one step, not two.
843
+ */
787
844
  async after(inputs, call) {
788
- const s = this.settings();
789
- if (!s.autoScreenshot || !call.vision) return void 0;
790
- if (!inputs.some((input) => MUTATING.has(input.action))) return void 0;
791
- await setTimeout$1(s.settleMs, void 0, { signal: call.signal });
845
+ if (!this.settings().autoScreenshot || !call.vision) return void 0;
846
+ const mutating = inputs.some((input) => MUTATING.has(input.action));
847
+ if (!mutating && !inputs.some((input) => input.action === "wait")) return void 0;
848
+ if (mutating) await this.settle(call.signal);
792
849
  return this.screenshot();
793
850
  }
794
851
  /** Bring a window forward and verify it is the foreground window. */
@@ -1062,11 +1119,15 @@ var OverlayController = class {
1062
1119
  visible = false;
1063
1120
  idleTimer;
1064
1121
  hostWindows = [];
1122
+ /** The floating card and the display it lives on, while carded. */
1123
+ card;
1065
1124
  stopping = false;
1066
1125
  /** Paused by Esc or the pill; actions wait until resumed. */
1067
1126
  paused = false;
1068
1127
  /** When the user last typed on the physical keyboard while the overlay was up (ms epoch). */
1069
1128
  lastUserInput = 0;
1129
+ /** Which physical key that was (helper reason, e.g. "vk=0x41"), for the log. */
1130
+ lastUserKey = "";
1070
1131
  constructor(helper, settings, log, iconPath = "") {
1071
1132
  this.helper = helper;
1072
1133
  this.settings = settings;
@@ -1076,7 +1137,10 @@ var OverlayController = class {
1076
1137
  if (event.event === "stop") this.stop(event.reason ?? "user");
1077
1138
  else if (event.event === "pause") this.paused = true;
1078
1139
  else if (event.event === "resume") this.paused = false;
1079
- else if (event.event === "user_input") this.lastUserInput = Date.now();
1140
+ else if (event.event === "user_input") {
1141
+ this.lastUserInput = Date.now();
1142
+ this.lastUserKey = event.reason ?? "";
1143
+ }
1080
1144
  });
1081
1145
  }
1082
1146
  /** The agent currently driving the computer, if any. */
@@ -1095,6 +1159,7 @@ var OverlayController = class {
1095
1159
  const idleMs = this.settings().userIdleMs;
1096
1160
  const typing = () => waitForTyping && Date.now() - this.lastUserInput < idleMs;
1097
1161
  if (!this.paused && !typing()) return false;
1162
+ if (!this.paused) this.log(`computer use waits: the user is typing (${this.lastUserKey})`);
1098
1163
  const started = Date.now();
1099
1164
  while (this.paused || typing()) {
1100
1165
  if (signal.aborted) throw new Error("Cancelled.");
@@ -1189,13 +1254,46 @@ var OverlayController = class {
1189
1254
  hwnd: main.hwnd,
1190
1255
  mode: "card"
1191
1256
  }];
1257
+ this.card = {
1258
+ hwnd: main.hwnd,
1259
+ display
1260
+ };
1192
1261
  } catch (error) {
1193
1262
  this.log(`host window ${mode}: ${String(error)}`);
1194
1263
  }
1195
1264
  }
1265
+ /**
1266
+ * The agent is about to point at something under the card: move the card to
1267
+ * the opposite bottom corner so the target is visible and clickable.
1268
+ * Returns whether it moved.
1269
+ */
1270
+ async dodgeCard(point) {
1271
+ const card = this.card;
1272
+ if (!card) return false;
1273
+ try {
1274
+ const win = await this.helper.call("window_at", { ...point });
1275
+ if (!win || win.hwnd !== card.hwnd) return false;
1276
+ const d = card.display;
1277
+ const margin = Math.round(16 * d.dpi / 96);
1278
+ const x = win.x + win.width / 2 > d.workX + d.workWidth / 2 ? d.workX + margin : d.workX + d.workWidth - win.width - margin;
1279
+ await this.helper.call("window_card", {
1280
+ hwnd: card.hwnd,
1281
+ x,
1282
+ y: win.y,
1283
+ width: win.width,
1284
+ height: win.height
1285
+ });
1286
+ await new Promise((resolve) => setTimeout(resolve, 120));
1287
+ return true;
1288
+ } catch (error) {
1289
+ this.log(`card dodge: ${String(error)}`);
1290
+ return false;
1291
+ }
1292
+ }
1196
1293
  async restoreHost() {
1197
1294
  const windows = this.hostWindows;
1198
1295
  this.hostWindows = [];
1296
+ this.card = void 0;
1199
1297
  for (const win of windows) if (win.mode === "card") await this.helper.call("window_uncard", { hwnd: win.hwnd }).catch(() => {});
1200
1298
  else await this.helper.call("window_cmd", {
1201
1299
  hwnd: win.hwnd,
@@ -1210,10 +1308,12 @@ function promptText(mode) {
1210
1308
  You can see and operate the user's Windows computer with the computer, computer_batch, open_application, windows, ui_elements and clipboard tools.
1211
1309
  ${mode === "per-app" ? "- Before acting on an app, call request_access once with every app the task needs; the user approves it. Input to apps that are not granted is refused.\n" : ""}- Start with a screenshot (computer action "screenshot") unless you just received one. All coordinates are pixels of the latest screenshot; the plugin converts them for DPI and scaling.
1212
1310
  - Open or switch apps with open_application (by name; it also finds desktop shortcuts) rather than hunting through the taskbar or Start menu or starting GUI apps from a shell. Use windows to see which windows exist; each line shows the process .exe.
1213
- - The "DeepSeek Harness.exe" window is your own chat interface; while you control the computer it may float as a small card in a corner. Never click or type into it; bring the target window to the front first, and work around the card.
1311
+ - The "DeepSeek Harness.exe" window is your own chat interface; while you control the computer it floats as a card in a bottom corner. Never type into it. If the card hides something you need, point at that spot (mouse_move, or just click/scroll there): the card jumps to the other corner. Keys go to the window you were working in even if the user clicked the card.
1214
1312
  - Prefer reliable keyboard shortcuts (ctrl+l for a browser address bar, ctrl+s, alt+F4, ctrl+t). Click the center of targets; zoom in when text is small.
1215
- - Actions return a fresh screenshot. Check it before continuing and verify the result instead of assuming success. Use computer_batch for several confident steps in a row.
1216
- - If the user has a dedicated tool for a website or service (browser automation, an API tool), prefer it over driving the desktop.
1313
+ - 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.
1314
+ - Be efficient: every tool call costs the user several seconds. Put predictable sequences (click a field, type, press Return; open a menu and pick an item you can already see) into one computer_batch. Avoid shell commands for things you can see on screen.
1315
+ - To see more of a page or list, scroll (action "scroll" with coordinate over the area, scroll_direction, scroll_amount 5-10) instead of hunting with zoom; for long web pages Page Down / End keys also work.
1316
+ - If a dedicated tool fits the whole task better (an API, or browser automation attached to the user's own browser), choose it at the start; do not switch tools halfway through a task that is going fine on screen.
1217
1317
  - Do not enter passwords, payment details or solve CAPTCHAs: stop and ask the user to do that step. Ask before irreversible actions (sending messages, deleting, purchasing) unless the user clearly asked for them.
1218
1318
  - The user sees an orange border and can press Esc to pause you at any time. If they pause, type on the keyboard or switch windows, you wait; when an action reports it was not performed, re-check the screen instead of repeating it blindly.`;
1219
1319
  }
@@ -7067,7 +7167,7 @@ function createTools(host) {
7067
7167
  const tools = [];
7068
7168
  tools.push(defineTool({
7069
7169
  name: "computer",
7070
- description: "Control the Windows desktop with the mouse and keyboard, like a person. Coordinates are pixels of the latest screenshot (the plugin handles DPI and scaling). Clicks, typing, keys and scrolls return a fresh screenshot automatically, so do not call screenshot again right after. Prefer keyboard shortcuts when they are reliable. zoom shows a region at full resolution for small text.",
7170
+ description: "Control the Windows desktop with the mouse and keyboard, like a person. Coordinates are pixels of the latest screenshot (the plugin handles DPI and scaling). Clicks, typing, keys, scrolls and wait return a fresh screenshot automatically (taken once the screen settles), so do not call screenshot again right after. Prefer keyboard shortcuts when they are reliable. zoom shows a region at full resolution for small text.",
7071
7171
  parameters: actionProperties,
7072
7172
  output,
7073
7173
  timeoutMs: 18e5,
@@ -7142,7 +7242,7 @@ function createTools(host) {
7142
7242
  }
7143
7243
  }
7144
7244
  const done = lines.join("\n");
7145
- const shot = call.vision && computer.settings().autoScreenshot ? await setTimeout$1(computer.settings().settleMs, void 0, { signal: call.signal }).then(() => computer.screenshot()) : void 0;
7245
+ const shot = call.vision && computer.settings().autoScreenshot ? await computer.settle(call.signal).then(() => computer.screenshot()) : void 0;
7146
7246
  const summary = failure === void 0 ? `All ${actions.length} actions done.\n${done}` : `Stopped: ${failure}${done ? `\nCompleted before it:\n${done}` : ""}\nRemaining actions were skipped.`;
7147
7247
  return withShot(host, shot === void 0 ? `${summary}\n${await computer.describeForeground()}` : summary, shot, call);
7148
7248
  },
@@ -7164,18 +7264,20 @@ function createTools(host) {
7164
7264
  if (name === "") throw new Error("name is required.");
7165
7265
  const settings = computer.settings();
7166
7266
  const isUrl = /^https?:\/\//i.test(name);
7167
- if (settings.accessMode === "per-app" && !isUrl && computer.access.missing(call.session, [name]).length > 0) {
7168
- const running = (await computer.windows()).find((win) => appMatches(name, win));
7169
- if (!running || !computer.access.isGranted(call.session, running)) throw new Error(`"${name}" is not granted for this session. Call request_access with ["${name}"] first.`);
7267
+ const appName = /^ms-settings:/i.test(name) ? "设置" : name;
7268
+ if (settings.accessMode === "per-app" && !isUrl && computer.access.missing(call.session, [appName]).length > 0) {
7269
+ const running = (await computer.windows()).find((win) => appMatches(appName, win));
7270
+ if (!running || !computer.access.isGranted(call.session, running)) throw new Error(`"${appName}" is not granted for this session. Call request_access with ["${appName}"] first.`);
7170
7271
  }
7171
7272
  await computer.overlay.begin(call.agent, `打开 ${name}`);
7172
7273
  await computer.overlay.yieldToUser(call.signal, false);
7173
7274
  const before = await computer.foreground();
7174
7275
  let how;
7175
- const running = isUrl ? void 0 : (await computer.windows()).find((win) => !isHostWindow(win) && appMatches(name, win));
7276
+ const isUri = isUrl || /^[a-z][a-z0-9+.-]+:(?![\/])/i.test(name);
7277
+ const running = isUri ? void 0 : (await computer.windows()).find((win) => !isHostWindow(win) && appMatches(name, win));
7176
7278
  if (running) how = (await computer.focus(running)).focused ? `Brought ${running.exe} ("${running.title.slice(0, 60)}") to the front.` : `Tried to bring ${running.exe} to the front, but Windows kept another window focused.`;
7177
7279
  else {
7178
- const app = (isUrl ? [] : await computer.helper.call("apps", {
7280
+ const app = (isUri ? [] : await computer.helper.call("apps", {
7179
7281
  query: name,
7180
7282
  limit: 5
7181
7283
  }, 3e4))[0];
@@ -7185,12 +7287,12 @@ function createTools(host) {
7185
7287
  for (let i = 0; i < 32; i++) {
7186
7288
  await setTimeout$1(250, void 0, { signal: call.signal });
7187
7289
  const now = await computer.foreground();
7188
- if (now && now.hwnd !== before?.hwnd && !isHostWindow(now) && now.exe.toLowerCase() !== "explorer.exe") break;
7290
+ if (now && now.hwnd !== before?.hwnd && !isHostWindow(now) && (now.exe.toLowerCase() !== "explorer.exe" || now.className === "CabinetWClass")) break;
7189
7291
  }
7190
7292
  }
7191
7293
  const fg = await computer.foreground();
7192
- if (fg && !isHostWindow(fg) && settings.accessMode === "per-app" && (computer.access.missing(call.session, [name]).length === 0 || isUrl)) computer.access.grant(call.session, [fg.exe]);
7193
- await setTimeout$1(settings.settleMs, void 0, { signal: call.signal });
7294
+ if (fg && !isHostWindow(fg) && settings.accessMode === "per-app" && (computer.access.missing(call.session, [appName]).length === 0 || isUrl)) computer.access.grant(call.session, [fg.exe]);
7295
+ await computer.settle(call.signal);
7194
7296
  const shot = call.vision ? await computer.screenshot() : void 0;
7195
7297
  return withShot(host, `${how} ${await computer.describeForeground()}`, shot, call);
7196
7298
  },
@@ -7427,8 +7529,8 @@ const Config = z.object({
7427
7529
  "en-US": { $description: "Return a screenshot after every action (saves a round trip)" }
7428
7530
  }),
7429
7531
  settleMs: z.natural().max(5e3).default(400).volatile().i18n({
7430
- "zh-CN": { $description: "操作后等待界面稳定的毫秒数,再截图" },
7431
- "en-US": { $description: "Milliseconds to wait after an action before the screenshot" }
7532
+ "zh-CN": { $description: "操作后至少等待的毫秒数;之后画面静止即截图(最多约 2.5 秒)" },
7533
+ "en-US": { $description: "Minimum wait after an action; then the screenshot is taken once the screen stops changing (up to ~2.5 s)" }
7432
7534
  }),
7433
7535
  maxLongEdge: z.natural().min(640).max(3840).default(1366).volatile().i18n({
7434
7536
  "zh-CN": { $description: "截图最长边像素(越大越清晰、越费 token)" },
@@ -7527,6 +7629,7 @@ function apply(ctx, config = {}) {
7527
7629
  };
7528
7630
  });
7529
7631
  ctx.on("agent/status", ({ agent, status }) => {
7632
+ if (status === "running") computer.resetLook();
7530
7633
  if (status === "idle" && overlay.controller === agent) overlay.end(agent);
7531
7634
  });
7532
7635
  ctx.on("agent/disposed", ({ agent }) => {
@@ -12,6 +12,8 @@ export interface WindowLike {
12
12
  /** The DSH desktop host: the agent must never type into its own chat. */
13
13
  export declare const HOST_EXES: string[];
14
14
  export declare function normalizeApp(name: string): string;
15
+ /** Do two app names refer to the same program ("explorer" and "文件资源管理器")? */
16
+ export declare function sameApp(a: string, b: string): boolean;
15
17
  export declare function isHostWindow(win: WindowLike): boolean;
16
18
  /** Does a granted (or requested) app name refer to this window? */
17
19
  export declare function appMatches(name: string, win: WindowLike): boolean;
@@ -20,7 +22,7 @@ export declare class AccessControl {
20
22
  grant(session: string, names: readonly string[]): string[];
21
23
  granted(session: string): string[];
22
24
  isGranted(session: string, win: WindowLike): boolean;
23
- /** Names from `names` the session has not been granted yet. */
25
+ /** Names from `names` the session has not been granted yet (aliases count). */
24
26
  missing(session: string, names: readonly string[]): string[];
25
27
  forget(session: string): void;
26
28
  /**
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Give the "电脑控制" row in the DSH settings navigation a mouse-pointer icon
3
+ * instead of the shell's fallback gear.
4
+ *
5
+ * `settings.section` registrations only carry `id`, `order` and `label`; the
6
+ * shell picks icons for built-in ids only. So, like dsh-better-sidebar, we mark
7
+ * our own row by its label and let CSS swap the glyph (Lucide mouse-pointer-2,
8
+ * drawn as a currentColor mask so hover / active colors still apply).
9
+ */
10
+ export declare const navIconCss = "\n[data-dsh-computer-use-settings-nav] > svg:first-child { display: none; }\n[data-dsh-computer-use-settings-nav]::before {\n content: '';\n flex: none;\n width: 16px;\n height: 16px;\n background: currentColor;\n -webkit-mask: url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M4.037 4.688a.495.495 0 0 1 .651-.651l16 6.5a.5.5 0 0 1-.063.947l-6.124 1.58a2 2 0 0 0-1.438 1.435l-1.579 6.126a.5.5 0 0 1-.947.063z'/%3E%3C/svg%3E\") center / contain no-repeat;\n mask: url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M4.037 4.688a.495.495 0 0 1 .651-.651l16 6.5a.5.5 0 0 1-.063.947l-6.124 1.58a2 2 0 0 0-1.438 1.435l-1.579 6.126a.5.5 0 0 1-.947.063z'/%3E%3C/svg%3E\") center / contain no-repeat;\n}\n";
11
+ /** Keep the marker on the settings-nav button labelled `label`; returns a disposer. */
12
+ export declare function registerNavIcon(label: string): () => void;
@@ -1,4 +1,4 @@
1
- import type { AccessControl, AccessMode, WindowLike } from './access.js';
1
+ import { type AccessControl, type AccessMode, type WindowLike } from './access.js';
2
2
  import { type Display, type Point, type Size } from './coords.js';
3
3
  import type { HelperLike } from './helper-client.js';
4
4
  import type { CancellableAgent, HostWindowMode, OverlayController } from './overlay.js';
@@ -64,6 +64,8 @@ export interface ActionOutcome {
64
64
  /** The action was not performed because the user took over the keyboard. */
65
65
  skipped?: boolean;
66
66
  }
67
+ /** Longest adaptive wait for the screen to settle after an action. */
68
+ export declare const MAX_SETTLE_MS = 2500;
67
69
  export declare class Computer {
68
70
  readonly helper: HelperLike;
69
71
  readonly access: AccessControl;
@@ -85,6 +87,10 @@ export declare class Computer {
85
87
  screenshot(): Promise<Shot>;
86
88
  /** The foreground window as of the model's latest look at the screen. */
87
89
  private seen;
90
+ /** The latest foreground window that was not DeepSeek Harness itself. */
91
+ private lastTarget;
92
+ /** A new turn starts: the user may have rearranged things while chatting. */
93
+ resetLook(): void;
88
94
  private remember;
89
95
  /**
90
96
  * Did another window come to the front since the model last looked, without
@@ -94,6 +100,14 @@ export declare class Computer {
94
100
  private capture;
95
101
  zoom(region: number[] | undefined): Promise<Shot>;
96
102
  foreground(): Promise<WindowInfo | undefined>;
103
+ /**
104
+ * The user clicked into the DeepSeek Harness card (to read or scroll the
105
+ * chat): keys would go there. Put the window the agent was working in back
106
+ * in front instead of refusing.
107
+ */
108
+ private refocusFromHost;
109
+ /** Wait until the screen stops changing (bounded), instead of a fixed delay. */
110
+ settle(signal: AbortSignal): Promise<void>;
97
111
  windowAt(point: Point): Promise<WindowInfo | undefined>;
98
112
  windows(): Promise<WindowInfo[]>;
99
113
  cursor(): Promise<Point>;
@@ -108,7 +122,11 @@ export declare class Computer {
108
122
  run(input: ActionInput, call: CallContext): Promise<ActionOutcome>;
109
123
  /** Release a mouse button left down by an aborted run. */
110
124
  releaseHeld(): Promise<void>;
111
- /** After a mutating action: settle, then capture (vision models only). */
125
+ /**
126
+ * After a mutating action: wait for the screen to settle, then capture
127
+ * (vision models only). A wait already waited, so it is captured at once:
128
+ * "wait, then look" should be one step, not two.
129
+ */
112
130
  after(inputs: readonly ActionInput[], call: CallContext): Promise<Shot | undefined>;
113
131
  /** Bring a window forward and verify it is the foreground window. */
114
132
  focus(win: WindowInfo): Promise<WindowInfo & {
@@ -40,11 +40,15 @@ export declare class OverlayController {
40
40
  private visible;
41
41
  private idleTimer;
42
42
  private hostWindows;
43
+ /** The floating card and the display it lives on, while carded. */
44
+ private card;
43
45
  private stopping;
44
46
  /** Paused by Esc or the pill; actions wait until resumed. */
45
47
  paused: boolean;
46
48
  /** When the user last typed on the physical keyboard while the overlay was up (ms epoch). */
47
49
  lastUserInput: number;
50
+ /** Which physical key that was (helper reason, e.g. "vk=0x41"), for the log. */
51
+ private lastUserKey;
48
52
  constructor(helper: HelperLike, settings: () => OverlaySettings, log: (message: string) => void,
49
53
  /** Absolute path of the pill icon (PNG). */
50
54
  iconPath?: string);
@@ -66,6 +70,15 @@ export declare class OverlayController {
66
70
  private armIdle;
67
71
  /** Card: shrink the DSH window to an always-on-top corner card; minimize: get it out of the way. */
68
72
  private shrinkHost;
73
+ /**
74
+ * The agent is about to point at something under the card: move the card to
75
+ * the opposite bottom corner so the target is visible and clickable.
76
+ * Returns whether it moved.
77
+ */
78
+ dodgeCard(point: {
79
+ x: number;
80
+ y: number;
81
+ }): Promise<boolean>;
69
82
  private restoreHost;
70
83
  }
71
84
  export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@copylee/dsh-computer-use",
3
- "version": "0.1.4",
3
+ "version": "0.1.6",
4
4
  "description": "DeepSeek Harness Computer Use 插件(Windows):让 AI 看屏幕、点鼠标、敲键盘操控电脑;控制时屏幕泛起橙色光晕并显示“DeepSeek Harness 正在操控你的电脑”,按 Esc 暂停 / 继续。",
5
5
  "type": "module",
6
6
  "author": "copylee",