@copylee/dsh-computer-use 0.14.2 → 0.16.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/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.
@@ -3993,6 +4131,7 @@ const DEFAULTS = {
3993
4131
  maxLongEdge: 1366,
3994
4132
  maxPixels: 115e4,
3995
4133
  jpegQuality: 70,
4134
+ keepScreenshots: 2,
3996
4135
  blockedApps: [],
3997
4136
  pauseOnUserInput: true,
3998
4137
  reportUserActions: true,
@@ -4035,6 +4174,7 @@ function resolveConfig(raw) {
4035
4174
  maxLongEdge: num("maxLongEdge", 640, 3840),
4036
4175
  maxPixels: num("maxPixels", 3e5, 8e6),
4037
4176
  jpegQuality: num("jpegQuality", 30, 100),
4177
+ keepScreenshots: num("keepScreenshots", 0, 20),
4038
4178
  pauseOnUserInput: bool("pauseOnUserInput"),
4039
4179
  reportUserActions: bool("reportUserActions"),
4040
4180
  userIdleMs: num("userIdleMs", 300, 1e4),
@@ -4428,7 +4568,7 @@ function sessionRoute(gate, settings, parentIdsFor, sync) {
4428
4568
  };
4429
4569
  }
4430
4570
  /** Export a sanitized diagnostic report (plain text by default, or JSON with ?format=json). */
4431
- function diagnosticsRoute(helper, settings, diagnostics, pluginVersion) {
4571
+ function diagnosticsRoute(helper, settings, diagnostics, pluginVersion, phaseTiming) {
4432
4572
  return async (req, res) => {
4433
4573
  const s = settings();
4434
4574
  let displays = [];
@@ -4447,7 +4587,8 @@ function diagnosticsRoute(helper, settings, diagnostics, pluginVersion) {
4447
4587
  helperStatus,
4448
4588
  ...helperError ? { helperError } : {},
4449
4589
  nativeAvailable: helper.available === true,
4450
- recentCalls: diagnostics.recent()
4590
+ recentCalls: diagnostics.recent(),
4591
+ ...phaseTiming ? { phaseTiming: phaseTiming() } : {}
4451
4592
  });
4452
4593
  if (new URL(req.url ?? "/api/dsh-computer-use/diagnostics", "http://127.0.0.1").searchParams.get("format") === "json") {
4453
4594
  json(res, 200, {
@@ -4509,13 +4650,17 @@ function windowsRoute(helper) {
4509
4650
  * DeepSeek Harness's content-addressed store (<DSH_HOME>/attachments/v1/objects/<2>/<sha256>),
4510
4651
  * which has no retention policy yet. Attachments still referenced by a session
4511
4652
  * must stay byte-for-byte (DSH verifies their hash, and a missing one fails the
4512
- * whole turn), so only orphans are removed: screenshots this plugin made that
4513
- * no session, archive or plugin store references any more (e.g. the session
4514
- * was deleted).
4653
+ * whole turn), so only screenshots no request can need any more are removed:
4654
+ * ones this plugin made that no session, archive or plugin store references
4655
+ * (e.g. the session was deleted), and ones whose every occurrence in the
4656
+ * session logs was offloaded (`image/offload`, see retention.ts): an offloaded
4657
+ * image is sent as a text placeholder, so its bytes are never read again.
4515
4658
  */
4516
4659
  const HEX = /^[0-9a-f]{64}$/;
4517
4660
  /** Newly saved screenshots may not be in a session log yet. */
4518
4661
  const GRACE_MS = 864e5;
4662
+ /** A screenshot seen offloaded is still left alone this long after it was (last) saved. */
4663
+ const OFFLOADED_MIN_AGE_MS = 12e4;
4519
4664
  /** Places outside the session logs that can reference attachments. */
4520
4665
  const OTHER_REFERENCE_DIRS = [
4521
4666
  "storages",
@@ -4531,6 +4676,9 @@ var ScreenshotCache = class {
4531
4676
  index;
4532
4677
  saving = Promise.resolve();
4533
4678
  busy = Promise.resolve();
4679
+ /** Parsed session logs keyed by path, reused while their size and mtime stay the same. */
4680
+ files = /* @__PURE__ */ new Map();
4681
+ soon;
4534
4682
  constructor(dshHome = process.env.DSH_HOME || join(homedir(), ".dsh"), indexFile = join(process.env.LOCALAPPDATA || join(homedir(), "AppData", "Local"), "dsh-computer-use", "screenshots.json"), log = () => {}) {
4535
4683
  this.dshHome = dshHome;
4536
4684
  this.indexFile = indexFile;
@@ -4574,7 +4722,20 @@ var ScreenshotCache = class {
4574
4722
  };
4575
4723
  });
4576
4724
  }
4577
- /** Delete orphaned screenshots. */
4725
+ /** Run `clean()` once, `delayMs` after the last call (screenshots were just offloaded). */
4726
+ cleanSoon(delayMs = 18e4) {
4727
+ if (this.soon) clearTimeout(this.soon);
4728
+ this.soon = setTimeout(() => {
4729
+ this.soon = void 0;
4730
+ this.clean().catch((error) => this.log(`screenshot cleanup skipped: ${String(error)}`));
4731
+ }, delayMs);
4732
+ this.soon.unref?.();
4733
+ }
4734
+ dispose() {
4735
+ if (this.soon) clearTimeout(this.soon);
4736
+ this.soon = void 0;
4737
+ }
4738
+ /** Delete screenshots no request can need any more. */
4578
4739
  async clean() {
4579
4740
  return this.exclusive(async () => {
4580
4741
  const { orphans } = await this.classify();
@@ -4596,7 +4757,7 @@ var ScreenshotCache = class {
4596
4757
  }
4597
4758
  this.persist();
4598
4759
  await this.saving;
4599
- if (removed > 0) this.log(`screenshot cleanup: removed ${removed} orphaned screenshots (${(bytes / 1048576).toFixed(1)} MB)`);
4760
+ if (removed > 0) this.log(`screenshot cleanup: removed ${removed} screenshots (${(bytes / 1048576).toFixed(1)} MB)`);
4600
4761
  return {
4601
4762
  removed,
4602
4763
  bytes
@@ -4617,7 +4778,7 @@ var ScreenshotCache = class {
4617
4778
  const orphans = /* @__PURE__ */ new Set();
4618
4779
  for (const [hex, savedAt] of index) {
4619
4780
  if (scan.referenced.has(hex)) continue;
4620
- if (savedAt > 0 && now - savedAt < GRACE_MS) continue;
4781
+ if ((savedAt > 0 ? now - savedAt : Infinity) < (scan.offloaded.has(hex) ? OFFLOADED_MIN_AGE_MS : GRACE_MS)) continue;
4621
4782
  orphans.add(hex);
4622
4783
  }
4623
4784
  return {
@@ -4631,19 +4792,52 @@ var ScreenshotCache = class {
4631
4792
  if (typeof zstd !== "function") throw new Error("This runtime cannot read DeepSeek Harness session logs (no zstd); cleanup skipped.");
4632
4793
  const referenced = /* @__PURE__ */ new Set();
4633
4794
  const ours = /* @__PURE__ */ new Set();
4795
+ const offloaded = /* @__PURE__ */ new Set();
4796
+ const seen = /* @__PURE__ */ new Set();
4797
+ const merge = (part) => {
4798
+ for (const hex of part.referenced) referenced.add(hex);
4799
+ for (const hex of part.ours) ours.add(hex);
4800
+ for (const hex of part.offloaded) offloaded.add(hex);
4801
+ };
4634
4802
  const sessions = join(this.dshHome, "sessions");
4635
4803
  for (const file of await walk(sessions)) {
4804
+ seen.add(file);
4805
+ let info;
4806
+ try {
4807
+ info = await stat(file);
4808
+ } catch {
4809
+ continue;
4810
+ }
4811
+ const cached = this.files.get(file);
4812
+ if (cached && cached.mtimeMs === info.mtimeMs && cached.size === info.size) {
4813
+ merge(cached);
4814
+ continue;
4815
+ }
4636
4816
  const text = await readText(file, zstd);
4637
4817
  if (text === void 0) throw new Error(`Could not read ${file}; cleanup skipped to stay safe.`);
4638
- collect(text, referenced, ours);
4818
+ const part = {
4819
+ referenced: /* @__PURE__ */ new Set(),
4820
+ ours: /* @__PURE__ */ new Set(),
4821
+ offloaded: /* @__PURE__ */ new Set()
4822
+ };
4823
+ collectLog(text, part.referenced, part.ours, part.offloaded);
4824
+ this.files.set(file, {
4825
+ ...part,
4826
+ mtimeMs: info.mtimeMs,
4827
+ size: info.size
4828
+ });
4829
+ merge(part);
4639
4830
  }
4831
+ for (const file of this.files.keys()) if (!seen.has(file)) this.files.delete(file);
4640
4832
  for (const dir of OTHER_REFERENCE_DIRS) for (const file of await walk(join(this.dshHome, dir))) {
4641
4833
  const text = await readText(file, zstd);
4642
4834
  if (text !== void 0) collect(text, referenced, ours);
4643
4835
  }
4836
+ for (const hex of referenced) offloaded.delete(hex);
4644
4837
  return {
4645
4838
  referenced,
4646
- ours
4839
+ ours,
4840
+ offloaded
4647
4841
  };
4648
4842
  }
4649
4843
  async size(hex) {
@@ -4690,6 +4884,72 @@ function collect(text, referenced, ours) {
4690
4884
  for (const match of line.matchAll(/"attachmentId":"sha256:([0-9a-f]{64})"[^{}]*?"name":"screenshot\.jpg"/g)) ours.add(match[1]);
4691
4885
  }
4692
4886
  }
4887
+ const SHA = /sha256:([0-9a-f]{64})/g;
4888
+ function contentOf(event) {
4889
+ const data = event.data;
4890
+ const content = event.type === "tool/result" ? data?.message?.content : event.type === "user/message" ? data?.content : void 0;
4891
+ return Array.isArray(content) ? content : void 0;
4892
+ }
4893
+ /**
4894
+ * Read one session log. An image occurrence (message seq, top-level image
4895
+ * index) named by an `image/offload` event is offloaded; every other mention
4896
+ * of an attachment, in any event, keeps it referenced. Lines that do not parse
4897
+ * keep everything they mention.
4898
+ */
4899
+ function collectLog(text, referenced, ours, offloaded) {
4900
+ const occurrences = /* @__PURE__ */ new Map();
4901
+ const marks = /* @__PURE__ */ new Set();
4902
+ for (const line of text.split("\n")) {
4903
+ const mentionsAttachment = line.includes("sha256:");
4904
+ if (!mentionsAttachment && !line.includes("\"image/offload\"")) continue;
4905
+ let event;
4906
+ try {
4907
+ event = JSON.parse(line);
4908
+ } catch {
4909
+ for (const match of line.matchAll(SHA)) referenced.add(match[1]);
4910
+ continue;
4911
+ }
4912
+ if (event.type === "image/offload") {
4913
+ const targets = event.data?.targets;
4914
+ if (Array.isArray(targets)) for (const target of targets) {
4915
+ if (typeof target?.seq !== "number" || !Array.isArray(target.imageIndexes)) continue;
4916
+ for (const index of target.imageIndexes) if (typeof index === "number") marks.add(`${target.seq}:${index}`);
4917
+ }
4918
+ for (const match of line.matchAll(SHA)) referenced.add(match[1]);
4919
+ continue;
4920
+ }
4921
+ if (!mentionsAttachment) continue;
4922
+ const content = contentOf(event);
4923
+ const images = [];
4924
+ const counted = /* @__PURE__ */ new Map();
4925
+ if (content !== void 0) {
4926
+ const addressable = typeof event.seq === "number";
4927
+ for (const block of content) {
4928
+ if (block?.type !== "image") continue;
4929
+ const id = String(block.attachment?.attachmentId ?? "");
4930
+ const hex = id.startsWith("sha256:") ? id.slice(7) : "";
4931
+ if (!HEX.test(hex)) {
4932
+ images.push("");
4933
+ continue;
4934
+ }
4935
+ if (event.type === "tool/result" && block.attachment?.name === "screenshot.jpg") ours.add(hex);
4936
+ if (!addressable) continue;
4937
+ images.push(block.offloaded === true ? "" : hex);
4938
+ if (block.offloaded === true) offloaded.add(hex);
4939
+ counted.set(hex, (counted.get(hex) ?? 0) + 1);
4940
+ }
4941
+ if (addressable) occurrences.set(event.seq, images);
4942
+ }
4943
+ const mentions = /* @__PURE__ */ new Map();
4944
+ for (const match of line.matchAll(SHA)) mentions.set(match[1], (mentions.get(match[1]) ?? 0) + 1);
4945
+ for (const [hex, n] of mentions) if (n > (counted.get(hex) ?? 0)) referenced.add(hex);
4946
+ }
4947
+ for (const [seq, images] of occurrences) images.forEach((hex, index) => {
4948
+ if (!HEX.test(hex)) return;
4949
+ if (marks.has(`${seq}:${index}`)) offloaded.add(hex);
4950
+ else referenced.add(hex);
4951
+ });
4952
+ }
4693
4953
  async function walk(dir) {
4694
4954
  const out = [];
4695
4955
  let entries;
@@ -4742,6 +5002,87 @@ function decodeFrames(data, zstd) {
4742
5002
  }
4743
5003
  return Buffer.concat(parts).toString("utf8");
4744
5004
  }
5005
+ /** Raw content of a tool result event, read without deriving (cheap pre-filter). */
5006
+ function rawContent(event) {
5007
+ const message = event.data?.message;
5008
+ return Array.isArray(message?.content) ? message.content : void 0;
5009
+ }
5010
+ function isOurs(block) {
5011
+ return block.type === "image" && block.attachment?.name === "screenshot.jpg" && typeof block.attachment.attachmentId === "string";
5012
+ }
5013
+ /**
5014
+ * The image/offload targets that leave only the newest `keep` of this plugin's
5015
+ * retained screenshots. Image indexes count every top-level image block of the
5016
+ * message, offloaded ones included, exactly as the Host's projection does.
5017
+ */
5018
+ function planOffload(session, keep) {
5019
+ const none = {
5020
+ targets: [],
5021
+ attachmentIds: []
5022
+ };
5023
+ if (keep <= 0 || typeof session.eventAt !== "function" || typeof session.deriveEventMessage !== "function") return none;
5024
+ const nodes = session.surface?.nodes;
5025
+ if (nodes === void 0) return none;
5026
+ const retained = [];
5027
+ for (const seq of nodes) {
5028
+ let event;
5029
+ try {
5030
+ event = session.eventAt(seq);
5031
+ } catch {
5032
+ continue;
5033
+ }
5034
+ if (event?.type !== "tool/result") continue;
5035
+ if (!rawContent(event)?.some(isOurs)) continue;
5036
+ let content;
5037
+ try {
5038
+ content = session.deriveEventMessage(event).content;
5039
+ } catch {
5040
+ continue;
5041
+ }
5042
+ if (!Array.isArray(content)) continue;
5043
+ let index = 0;
5044
+ for (const block of content) {
5045
+ if (block?.type !== "image") continue;
5046
+ if (block.offloaded !== true && isOurs(block)) retained.push({
5047
+ seq,
5048
+ index,
5049
+ attachmentId: String(block.attachment.attachmentId)
5050
+ });
5051
+ index++;
5052
+ }
5053
+ }
5054
+ const drop = retained.slice(0, Math.max(0, retained.length - keep));
5055
+ if (drop.length === 0) return none;
5056
+ const bySeq = /* @__PURE__ */ new Map();
5057
+ for (const item of drop) {
5058
+ let list = bySeq.get(item.seq);
5059
+ if (!list) bySeq.set(item.seq, list = []);
5060
+ list.push(item.index);
5061
+ }
5062
+ return {
5063
+ targets: [...bySeq].map(([seq, imageIndexes]) => ({
5064
+ seq,
5065
+ imageIndexes: imageIndexes.sort((a, b) => a - b)
5066
+ })),
5067
+ attachmentIds: drop.map((item) => item.attachmentId)
5068
+ };
5069
+ }
5070
+ /**
5071
+ * Offload this plugin's screenshots older than the newest `keep` in `session`.
5072
+ * Returns the attachment ids offloaded (empty when nothing changed). Never throws.
5073
+ */
5074
+ function offloadOldScreenshots(session, keep, log = () => {}) {
5075
+ if (!session || typeof session.append !== "function") return [];
5076
+ try {
5077
+ const plan = planOffload(session, keep);
5078
+ if (plan.targets.length === 0) return [];
5079
+ session.append("image/offload", { targets: plan.targets });
5080
+ return plan.attachmentIds;
5081
+ } catch (error) {
5082
+ log(`screenshot offload skipped: ${String(error)}`);
5083
+ return [];
5084
+ }
5085
+ }
4745
5086
  //#endregion
4746
5087
  //#region lib/types/sessions.js
4747
5088
  /**
@@ -10904,7 +11245,18 @@ const actionProperties = {
10904
11245
  },
10905
11246
  replace: {
10906
11247
  type: "boolean",
10907
- description: "type: select all (Ctrl+A) and replace existing text in the field."
11248
+ description: "type: select all (Ctrl+A) before entering replacement text."
11249
+ },
11250
+ feedback: {
11251
+ type: "string",
11252
+ enum: [
11253
+ "auto",
11254
+ "state",
11255
+ "diff",
11256
+ "screenshot",
11257
+ "none"
11258
+ ],
11259
+ 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
11260
  }
10909
11261
  };
10910
11262
  const BATCH_ACTIONS = ACTIONS.filter((action) => action !== "screenshot");
@@ -10925,7 +11277,28 @@ function createTools(host) {
10925
11277
  const outcome = await computer.run(input, call);
10926
11278
  if (outcome.image) return withShot(host, outcome.text, outcome.image, call);
10927
11279
  if (input.action === "screenshot" || input.action === "zoom") return { text: outcome.text };
10928
- const shot = await computer.after([input], call);
11280
+ const fb = input.feedback ?? "auto";
11281
+ if (fb === "none" || fb === "state") return { text: outcome.text };
11282
+ if (fb === "auto" && input.action === "ui_action" && outcome.verified === true) return { text: `${outcome.text} (verified via UIA; skipped screenshot)` };
11283
+ if (fb === "diff") {
11284
+ const uiRes = await computer.helper.call("ui", {
11285
+ includeText: false,
11286
+ popups: true,
11287
+ maxNodes: 120
11288
+ }, 1e4).catch(() => void 0);
11289
+ if (uiRes && typeof uiRes.hwnd === "number" && Array.isArray(uiRes.elements)) {
11290
+ const delta = computer.uiDiff.diff({
11291
+ sessionId: call.session,
11292
+ hwnd: uiRes.hwnd,
11293
+ pid: uiRes.pid,
11294
+ queryProfile: "0:120"
11295
+ }, String(uiRes.title ?? ""), uiRes.elements);
11296
+ 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`;
11297
+ return { text: `${outcome.text} [${uiRes.exe}: ${summary}]` };
11298
+ }
11299
+ return { text: outcome.text };
11300
+ }
11301
+ const shot = await computer.after([input], call, input.detail, fb === "screenshot");
10929
11302
  return withShot(host, shot === void 0 && input.action !== "wait" && input.action !== "cursor_position" ? `${outcome.text} ${await computer.describeForeground()}` : outcome.text, shot, call);
10930
11303
  } catch (error) {
10931
11304
  if (call.signal.aborted) await computer.releaseHeld();
@@ -11885,6 +12258,10 @@ const Config = z.object({
11885
12258
  "zh-CN": { $description: "截图 JPEG 质量" },
11886
12259
  "en-US": { $description: "Screenshot JPEG quality" }
11887
12260
  }),
12261
+ keepScreenshots: z.natural().min(0).max(20).default(2).volatile().i18n({
12262
+ "zh-CN": { $description: "对话里保留几张截图给模型看(含最新一张)。更早的截图换成一行文字占位,不再随每次请求重发,几分钟后从磁盘删除。0 = 全部保留(旧行为)" },
12263
+ "en-US": { $description: "Screenshots kept as images in a conversation (including the latest). Older ones become a one-line text placeholder, are no longer resent with every request, and are deleted from disk a few minutes later. 0 keeps all (old behaviour)" }
12264
+ }),
11888
12265
  pauseOnUserInput: z.boolean().default(true).volatile().i18n({
11889
12266
  "zh-CN": { $description: "检测到你在操作时让出控制:你用键盘打字或点击鼠标/滚轮时暂停、停手后继续;你切换或打开了新窗口时,AI 重新看屏幕再决定(纯鼠标移动不会触发)" },
11890
12267
  "en-US": { $description: "Yield to you: pause while you type or click/scroll physically, and re-check the screen when you switch windows (pure mouse movement is ignored)" }
@@ -11994,6 +12371,7 @@ function apply(ctx, config = {}) {
11994
12371
  return () => {
11995
12372
  clearTimeout(first);
11996
12373
  clearInterval(every);
12374
+ screenshots.dispose();
11997
12375
  };
11998
12376
  }, "computer-use: screenshot cleanup");
11999
12377
  const skills = new SkillStore(helperAssetPath("skills"));
@@ -12110,6 +12488,10 @@ function apply(ctx, config = {}) {
12110
12488
  });
12111
12489
  ctx.on("agent/pre-step", ({ agent }, next) => {
12112
12490
  syncAgent(agent);
12491
+ const keep = settings().keepScreenshots;
12492
+ if (keep > 0) {
12493
+ if (offloadOldScreenshots(agent.session, keep, log).length > 0) screenshots.cleanSoon();
12494
+ }
12113
12495
  return next();
12114
12496
  });
12115
12497
  ctx.on("loader/volatile-update", (() => syncAllAgents()));
@@ -12270,7 +12652,7 @@ function apply(ctx, config = {}) {
12270
12652
  route(SCREENSHOTS_CLEAN_ROUTE, screenshotsCleanRoute(screenshots));
12271
12653
  route(SKILLS_ROUTE, skillsRoute(skills));
12272
12654
  route(SESSION_ROUTE, sessionRoute(sessionGate, settings, parentIdsFor, syncAllAgents));
12273
- route(DIAGNOSTICS_ROUTE, diagnosticsRoute(helper, settings, diagnostics, PLUGIN_VERSION));
12655
+ route(DIAGNOSTICS_ROUTE, diagnosticsRoute(helper, settings, diagnostics, PLUGIN_VERSION, () => computer.timingSummary()));
12274
12656
  route(UPDATE_ROUTE, updateRoute(PLUGIN_VERSION));
12275
12657
  route(WINDOWS_ROUTE, windowsRoute(helper));
12276
12658
  });