dsh-builtin-browser 0.5.6 → 0.5.8

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.
Files changed (119) hide show
  1. package/CHANGELOG.md +148 -0
  2. package/README.en.md +75 -81
  3. package/README.md +75 -82
  4. package/client.js +831 -384
  5. package/desktop-bridge/install-and-start.cmd +4 -5
  6. package/desktop-bridge/install.mjs +322 -141
  7. package/desktop-bridge/maintenance-progress.ps1 +166 -0
  8. package/desktop-bridge/plugin-browser-bridge.js +157 -19
  9. package/desktop-bridge/request-desktop-quit.ps1 +170 -0
  10. package/docs/tool-reference.md +20 -1
  11. package/docs/user-guide.md +28 -4
  12. package/lib/browser/runtime.d.ts +3 -1
  13. package/lib/browser/runtime.js +9 -0
  14. package/lib/browser/types.d.ts +42 -0
  15. package/lib/browser-electron/authenticated-route.d.ts +27 -0
  16. package/lib/browser-electron/authenticated-route.js +39 -0
  17. package/lib/browser-electron/automatic-maintenance.d.ts +41 -0
  18. package/lib/browser-electron/automatic-maintenance.js +426 -0
  19. package/lib/browser-electron/bridge-auto.d.ts +93 -0
  20. package/lib/browser-electron/bridge-auto.js +113 -0
  21. package/lib/browser-electron/bridge-connection.d.ts +0 -2
  22. package/lib/browser-electron/bridge-connection.js +2 -4
  23. package/lib/browser-electron/bridge-endpoint.js +8 -19
  24. package/lib/browser-electron/bridge-install.d.ts +85 -0
  25. package/lib/browser-electron/bridge-install.js +211 -0
  26. package/lib/browser-electron/bridge-maintenance.d.ts +24 -0
  27. package/lib/browser-electron/bridge-maintenance.js +125 -0
  28. package/lib/browser-electron/bridge-status.d.ts +10 -3
  29. package/lib/browser-electron/bridge-status.js +74 -24
  30. package/lib/browser-electron/desktop-bridge-host.d.ts +11 -5
  31. package/lib/browser-electron/desktop-bridge-host.js +67 -25
  32. package/lib/browser-electron/desktop-identity.js +21 -9
  33. package/lib/browser-electron/electron-provision.d.ts +1 -1
  34. package/lib/browser-electron/electron-provision.js +36 -13
  35. package/lib/browser-electron/entry.js +173 -67
  36. package/lib/browser-electron/ephemeral-profile.js +67 -26
  37. package/lib/browser-electron/history-store.js +2 -2
  38. package/lib/browser-electron/host-main.js +48 -38
  39. package/lib/browser-electron/http-body.d.ts +24 -0
  40. package/lib/browser-electron/http-body.js +33 -0
  41. package/lib/browser-electron/json-reply.d.ts +13 -1
  42. package/lib/browser-electron/json-reply.js +16 -2
  43. package/lib/browser-electron/maintenance-broker.d.ts +35 -0
  44. package/lib/browser-electron/maintenance-broker.js +114 -0
  45. package/lib/browser-electron/maintenance-lifecycle.d.ts +32 -0
  46. package/lib/browser-electron/maintenance-lifecycle.js +67 -0
  47. package/lib/browser-electron/maintenance-route.d.ts +18 -0
  48. package/lib/browser-electron/maintenance-route.js +75 -0
  49. package/lib/browser-electron/paths.d.ts +4 -0
  50. package/lib/browser-electron/paths.js +19 -0
  51. package/lib/browser-electron/process.d.ts +14 -0
  52. package/lib/browser-electron/process.js +24 -0
  53. package/lib/browser-electron/provider.d.ts +16 -9
  54. package/lib/browser-electron/provider.js +87 -18
  55. package/lib/browser-electron/remote-host.js +22 -20
  56. package/lib/browser-electron/runtime-route.d.ts +3 -5
  57. package/lib/browser-electron/runtime-status.d.ts +27 -13
  58. package/lib/browser-electron/runtime-status.js +28 -6
  59. package/lib/browser-electron/settings-route.d.ts +5 -18
  60. package/lib/browser-electron/settings-route.js +4 -14
  61. package/lib/browser-electron/settings-store.d.ts +28 -0
  62. package/lib/browser-electron/settings-store.js +32 -2
  63. package/lib/browser-electron/sidebar-only-host.d.ts +36 -0
  64. package/lib/browser-electron/sidebar-only-host.js +192 -0
  65. package/lib/browser-electron/system-browser.d.ts +6 -11
  66. package/lib/browser-electron/system-browser.js +29 -24
  67. package/lib/browser-electron/timing.d.ts +8 -0
  68. package/lib/browser-electron/timing.js +13 -0
  69. package/lib/browser-electron/windows-system.d.ts +3 -0
  70. package/lib/browser-electron/windows-system.js +19 -0
  71. package/lib/tool-browser/index.js +1045 -7
  72. package/lib/tool-browser/page-probe.d.ts +86 -0
  73. package/lib/tool-browser/page-probe.js +460 -0
  74. package/package.json +5 -3
  75. package/scripts/run-tests.mjs +32 -0
  76. package/scripts/verify-preview-route.mjs +19 -1
  77. package/scripts/verify-runtime-status.mjs +14 -0
  78. package/skills/dsh-builtin-browser/SKILL.md +64 -0
  79. package/skills/dsh-builtin-browser/references/batch.md +23 -0
  80. package/skills/dsh-builtin-browser/references/deliver.md +31 -0
  81. package/skills/dsh-builtin-browser/references/locate.md +11 -0
  82. package/skills/dsh-builtin-browser/references/recover.md +11 -0
  83. package/skills/dsh-builtin-browser/references/verify.md +13 -0
  84. package/src/browser/runtime.ts +11 -0
  85. package/src/browser/types.ts +19 -0
  86. package/src/browser-electron/authenticated-route.ts +56 -0
  87. package/src/browser-electron/automatic-maintenance.ts +414 -0
  88. package/src/browser-electron/bridge-auto.ts +158 -0
  89. package/src/browser-electron/bridge-connection.ts +2 -4
  90. package/src/browser-electron/bridge-endpoint.ts +8 -18
  91. package/src/browser-electron/bridge-install.ts +253 -0
  92. package/src/browser-electron/bridge-maintenance.ts +161 -0
  93. package/src/browser-electron/bridge-status.ts +76 -26
  94. package/src/browser-electron/desktop-bridge-host.ts +60 -26
  95. package/src/browser-electron/desktop-identity.ts +18 -9
  96. package/src/browser-electron/electron-provision.ts +35 -14
  97. package/src/browser-electron/entry.ts +152 -62
  98. package/src/browser-electron/ephemeral-profile.ts +65 -28
  99. package/src/browser-electron/history-store.ts +2 -2
  100. package/src/browser-electron/host-main.ts +40 -34
  101. package/src/browser-electron/http-body.ts +42 -0
  102. package/src/browser-electron/json-reply.ts +18 -3
  103. package/src/browser-electron/maintenance-broker.ts +142 -0
  104. package/src/browser-electron/maintenance-lifecycle.ts +86 -0
  105. package/src/browser-electron/maintenance-route.ts +64 -0
  106. package/src/browser-electron/paths.ts +21 -0
  107. package/src/browser-electron/process.ts +23 -0
  108. package/src/browser-electron/provider.ts +106 -22
  109. package/src/browser-electron/remote-host.ts +23 -23
  110. package/src/browser-electron/runtime-route.ts +3 -5
  111. package/src/browser-electron/runtime-status.ts +56 -19
  112. package/src/browser-electron/settings-route.ts +9 -32
  113. package/src/browser-electron/settings-store.ts +59 -3
  114. package/src/browser-electron/sidebar-only-host.ts +199 -0
  115. package/src/browser-electron/system-browser.ts +26 -23
  116. package/src/browser-electron/timing.ts +16 -0
  117. package/src/browser-electron/windows-system.ts +23 -0
  118. package/src/tool-browser/index.ts +995 -10
  119. package/src/tool-browser/page-probe.ts +474 -0
@@ -0,0 +1,166 @@
1
+ <# A passive, independent progress indicator. Closing it never cancels maintenance. #>
2
+ [CmdletBinding()]
3
+ param(
4
+ [Parameter(Mandatory = $true)]
5
+ [ValidateNotNullOrEmpty()]
6
+ [string]$StatePath,
7
+
8
+ [Parameter(Mandatory = $true)]
9
+ [ValidatePattern('^(install|uninstall)-[A-Za-z0-9]+$')]
10
+ [string]$JobId,
11
+
12
+ [ValidateSet('zh', 'en')]
13
+ [string]$Locale = 'zh'
14
+ )
15
+
16
+ $ErrorActionPreference = 'Stop'
17
+ Set-StrictMode -Version Latest
18
+ [Console]::OutputEncoding = [Text.UTF8Encoding]::new($false)
19
+ $OutputEncoding = [Console]::OutputEncoding
20
+
21
+ function Stop-Progress([string]$Code) {
22
+ Write-Output (@{ ok = $false; code = $Code } | ConvertTo-Json -Compress)
23
+ exit 1
24
+ }
25
+
26
+ function Read-ProgressState {
27
+ try {
28
+ $value = [IO.File]::ReadAllText($script:verifiedStatePath) | ConvertFrom-Json
29
+ if ($null -eq $value -or -not [StringComparer]::Ordinal.Equals([string]$value.id, $JobId) -or
30
+ @('armed', 'closing', 'installing', 'restarting', 'verifying', 'completed', 'complete', 'failed', 'cancelled') -cnotcontains [string]$value.phase -or
31
+ @('install', 'uninstall') -cnotcontains [string]$value.action) { return $null }
32
+ return $value
33
+ } catch { return $null }
34
+ }
35
+
36
+ try {
37
+ if ($env:DSH_BROWSER_TEST -eq '1' -or $null -ne $env:NODE_TEST_CONTEXT) { Stop-Progress 'TEST_CONTEXT_REFUSED' }
38
+ if ($StatePath -notmatch '^(?:[A-Za-z]:[\\/]|\\\\[^\\/]+[\\/][^\\/]+[\\/])') { Stop-Progress 'INVALID_STATE_PATH' }
39
+ $script:verifiedStatePath = [IO.Path]::GetFullPath($StatePath)
40
+ if ([IO.Path]::GetFileName($script:verifiedStatePath) -ine 'state.json' -or
41
+ -not [StringComparer]::Ordinal.Equals([IO.Path]::GetFileName([IO.Path]::GetDirectoryName($script:verifiedStatePath)), $JobId) -or
42
+ -not [IO.File]::Exists($script:verifiedStatePath)) { Stop-Progress 'INVALID_STATE_PATH' }
43
+ $script:lastState = Read-ProgressState
44
+ if ($null -eq $script:lastState) { Stop-Progress 'INVALID_JOB_STATE' }
45
+
46
+ Add-Type -AssemblyName System.Windows.Forms
47
+ Add-Type -AssemblyName System.Drawing
48
+ Add-Type -ReferencedAssemblies System.Windows.Forms, System.Drawing -TypeDefinition @'
49
+ using System;
50
+ using System.Drawing;
51
+ using System.Windows.Forms;
52
+ using Microsoft.Win32;
53
+ namespace DshBridgeMaintenance {
54
+ public sealed class ProgressWindow : Form {
55
+ private readonly Label heading;
56
+ private readonly Label detail;
57
+ private readonly Label elapsed;
58
+ private readonly ProgressBar progress;
59
+ private readonly bool dark;
60
+ public ProgressWindow(string title) {
61
+ try { dark = Convert.ToInt32(Registry.GetValue(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize", "AppsUseLightTheme", 1)) == 0; }
62
+ catch { dark = false; }
63
+ Text = title;
64
+ ShowInTaskbar = false;
65
+ TopMost = false;
66
+ MaximizeBox = false;
67
+ MinimizeBox = false;
68
+ FormBorderStyle = FormBorderStyle.FixedToolWindow;
69
+ StartPosition = FormStartPosition.Manual;
70
+ AutoScaleMode = AutoScaleMode.Dpi;
71
+ ClientSize = new Size(380, 150);
72
+ Font = new Font("Segoe UI", 9F, FontStyle.Regular);
73
+ BackColor = dark ? Color.FromArgb(32, 32, 35) : Color.FromArgb(250, 250, 252);
74
+ ForeColor = dark ? Color.FromArgb(240, 240, 244) : Color.FromArgb(36, 36, 40);
75
+ heading = new Label { Location = new Point(18, 17), Size = new Size(344, 25), Font = new Font("Segoe UI", 11F, FontStyle.Bold), AutoEllipsis = true };
76
+ detail = new Label { Location = new Point(18, 48), Size = new Size(344, 34), ForeColor = dark ? Color.FromArgb(184, 184, 194) : Color.FromArgb(100, 100, 110), AutoEllipsis = true };
77
+ elapsed = new Label { Location = new Point(18, 91), Size = new Size(344, 20), ForeColor = detail.ForeColor };
78
+ progress = new ProgressBar { Location = new Point(18, 121), Size = new Size(344, 5), Style = ProgressBarStyle.Marquee, MarqueeAnimationSpeed = 35 };
79
+ Controls.Add(heading);
80
+ Controls.Add(detail);
81
+ Controls.Add(elapsed);
82
+ Controls.Add(progress);
83
+ Rectangle area = Screen.PrimaryScreen.WorkingArea;
84
+ Location = new Point(Math.Max(area.Left, area.Right - Width - 20), Math.Max(area.Top, area.Bottom - Height - 20));
85
+ }
86
+ protected override bool ShowWithoutActivation { get { return true; } }
87
+ protected override CreateParams CreateParams {
88
+ get {
89
+ CreateParams parameters = base.CreateParams;
90
+ parameters.ExStyle |= 0x08000000 | 0x00000080; // WS_EX_NOACTIVATE | WS_EX_TOOLWINDOW
91
+ return parameters;
92
+ }
93
+ }
94
+ public void UpdateStage(string title, string message, string time, bool running, bool failed) {
95
+ heading.Text = title;
96
+ detail.Text = message;
97
+ elapsed.Text = time;
98
+ heading.ForeColor = failed ? (dark ? Color.FromArgb(255, 150, 150) : Color.FromArgb(182, 51, 51)) : ForeColor;
99
+ progress.Visible = running;
100
+ }
101
+ }
102
+ }
103
+ '@
104
+ [Windows.Forms.Application]::EnableVisualStyles()
105
+ # Escaped source stays valid with Windows PowerShell's ANSI script decoding.
106
+ $copy = if ($Locale -eq 'zh') {
107
+ '{"window":"DSH - \u6d4f\u89c8\u5668\u6865\u63a5","armed":"\u6b63\u5728\u51c6\u5907","closing":"\u6b63\u5728\u9000\u51fa DSH","installing":"\u6b63\u5728\u5b89\u88c5\u6d4f\u89c8\u5668\u6865\u63a5","uninstalling":"\u6b63\u5728\u5378\u8f7d\u6d4f\u89c8\u5668\u6865\u63a5","restarting":"\u6b63\u5728\u542f\u52a8 DSH","verifying":"\u6b63\u5728\u68c0\u67e5\u8fde\u63a5","completed":"\u6865\u63a5\u7ef4\u62a4\u5df2\u5b8c\u6210","failed":"\u6865\u63a5\u7ef4\u62a4\u672a\u5b8c\u6210","cancelled":"\u6865\u63a5\u7ef4\u62a4\u5df2\u53d6\u6d88","working":"\u8bf7\u7a0d\u5019\u3002","finished":"\u64cd\u4f5c\u5df2\u5b8c\u6210\u3002","reopened":"DSH \u5df2\u91cd\u65b0\u542f\u52a8\u3002","retry":"\u53ef\u8fd4\u56de DSH \u8bbe\u7f6e\u67e5\u770b\u7ed3\u679c\u5e76\u91cd\u8bd5\u3002","elapsed":"\u5df2\u7528\u65f6"}' | ConvertFrom-Json
108
+ } else {
109
+ '{"window":"DSH - Browser bridge","armed":"Preparing maintenance","closing":"Closing DSH normally","installing":"Installing the browser bridge","uninstalling":"Removing the browser bridge","restarting":"Starting DSH","verifying":"Checking the connection","completed":"Bridge maintenance completed","failed":"Bridge maintenance did not finish","cancelled":"Bridge maintenance cancelled","working":"Please wait.","finished":"The operation is complete.","reopened":"DSH has restarted.","retry":"Return to DSH settings to review the result and retry.","elapsed":"Elapsed"}' | ConvertFrom-Json
110
+ }
111
+ $script:form = [DshBridgeMaintenance.ProgressWindow]::new($copy.window)
112
+ $script:watch = [Diagnostics.Stopwatch]::StartNew()
113
+ $script:initialElapsedMs = 0
114
+ $script:startedUtc = $null
115
+ $script:frozenElapsedMs = $null
116
+ try {
117
+ if ($script:lastState.PSObject.Properties.Name -contains 'startedAt') {
118
+ $started = [DateTimeOffset]::Parse([string]$script:lastState.startedAt, [Globalization.CultureInfo]::InvariantCulture)
119
+ $script:initialElapsedMs = [Math]::Max(0, ([DateTimeOffset]::UtcNow - $started).TotalMilliseconds)
120
+ $script:startedUtc = $started
121
+ }
122
+ } catch { }
123
+ $script:completionAt = $null
124
+ $script:timer = [Windows.Forms.Timer]::new()
125
+ $script:timer.Interval = 500
126
+ $refresh = {
127
+ try {
128
+ $state = Read-ProgressState
129
+ if ($null -ne $state) { $script:lastState = $state }
130
+ $phase = [string]$script:lastState.phase
131
+ if ($phase -eq 'complete') { $phase = 'completed' }
132
+ $key = if ($phase -eq 'installing' -and $script:lastState.action -eq 'uninstall') { 'uninstalling' } else { $phase }
133
+ $terminal = @('completed', 'failed', 'cancelled') -contains $phase
134
+ $message = if ($phase -eq 'completed') {
135
+ if ($script:lastState.PSObject.Properties.Name -contains 'restarted' -and $script:lastState.restarted -eq $true) { $copy.reopened } else { $copy.finished }
136
+ } elseif ($terminal) { $copy.retry } else { $copy.working }
137
+ $elapsedMs = $script:initialElapsedMs + $script:watch.ElapsedMilliseconds
138
+ if ($terminal -and $null -eq $script:frozenElapsedMs) {
139
+ $script:frozenElapsedMs = $elapsedMs
140
+ try {
141
+ if ($null -ne $script:startedUtc -and $script:lastState.PSObject.Properties.Name -contains 'at') {
142
+ $terminalAt = [DateTimeOffset]::Parse([string]$script:lastState.at, [Globalization.CultureInfo]::InvariantCulture)
143
+ $script:frozenElapsedMs = [Math]::Max(0, [Math]::Min($elapsedMs, ($terminalAt - $script:startedUtc).TotalMilliseconds))
144
+ }
145
+ } catch { }
146
+ }
147
+ if ($null -ne $script:frozenElapsedMs) { $elapsedMs = $script:frozenElapsedMs }
148
+ $span = [TimeSpan]::FromMilliseconds($elapsedMs)
149
+ $time = '{0} {1:00}:{2:00}' -f $copy.elapsed, [Math]::Floor($span.TotalMinutes), $span.Seconds
150
+ $script:form.UpdateStage([string]$copy.$key, [string]$message, $time, -not $terminal, $phase -eq 'failed')
151
+ if ($phase -eq 'completed' -and $null -eq $script:completionAt) { $script:completionAt = $script:watch.ElapsedMilliseconds + 6000 }
152
+ if (($null -ne $script:completionAt -and $script:watch.ElapsedMilliseconds -ge $script:completionAt) -or $script:watch.ElapsedMilliseconds -ge 600000) { $script:form.Close() }
153
+ } catch {
154
+ # State files are atomically replaced during maintenance. Keep the last
155
+ # verified state through a transient read or accessibility repaint failure.
156
+ if ($script:watch.ElapsedMilliseconds -ge 600000) { $script:form.Close() }
157
+ }
158
+ }
159
+ & $refresh
160
+ $script:timer.add_Tick($refresh)
161
+ $script:form.add_FormClosed({ $script:timer.Stop(); $script:timer.Dispose() })
162
+ $script:timer.Start()
163
+ [Windows.Forms.Application]::Run($script:form)
164
+ $script:form.Dispose()
165
+ Write-Output (@{ ok = $true; id = $JobId; action = 'progress-window-closed' } | ConvertTo-Json -Compress)
166
+ } catch { Stop-Progress 'PROGRESS_UNAVAILABLE' }
@@ -23,9 +23,10 @@
23
23
  */
24
24
  import { createServer } from 'node:net'
25
25
  import { randomBytes } from 'node:crypto'
26
- import { writeFileSync, mkdirSync } from 'node:fs'
26
+ import { writeFileSync, mkdirSync, constants } from 'node:fs'
27
+ import { open, mkdir, unlink, link, copyFile } from 'node:fs/promises'
27
28
  import { homedir } from 'node:os'
28
- import { join } from 'node:path'
29
+ import { join, dirname, isAbsolute } from 'node:path'
29
30
  import { app, webContents } from 'electron'
30
31
 
31
32
  /**
@@ -38,6 +39,7 @@ import { app, webContents } from 'electron'
38
39
  * conversation would have brought the page back.
39
40
  */
40
41
  const PANEL_NOT_DISPLAYED = 'panel-not-displayed'
42
+ const PANEL_INITIALIZING = 'panel-initializing'
41
43
 
42
44
  /**
43
45
  * An Error carrying a stable code, so the code survives the socket as a field rather than as text a
@@ -96,7 +98,7 @@ const claims = new Map()
96
98
  * acceptance script compares this against the file's mtime and says so before testing anything.
97
99
  */
98
100
  const LOADED_AT = new Date().toISOString()
99
- const PROTOCOL = 2
101
+ const PROTOCOL = 3
100
102
 
101
103
  /**
102
104
  * The DOM root of THIS conversation's sidebar, as JavaScript to embed in a page script.
@@ -206,6 +208,20 @@ function pruneClaims() {
206
208
  for (const id of [...claims.keys()]) if (!live.has(id)) claims.delete(id)
207
209
  }
208
210
 
211
+ /** The single ownership gate for every op that drives a guest: the ledger is the only proof. */
212
+ async function assertGuestOwner(id, owner) {
213
+ pruneClaims()
214
+ if (claims.get(id) === owner) return
215
+ // A bridge restart, or a host that cached a guest id before the ledger existed, can leave a
216
+ // legitimate guest unclaimed. Ask the renderer once on this cold path and re-register it.
217
+ const shell = webContents.getAllWebContents().find(contents => contents.getType() === 'window')
218
+ if (shell !== undefined && /^session-/.test(owner)) {
219
+ const ids = await panelGuestIds(shell, owner).catch(() => [])
220
+ if (ids.includes(id)) { claims.set(id, owner); return }
221
+ }
222
+ throw new Error(`guest ${id} is not held by this conversation`)
223
+ }
224
+
209
225
  function guestById(id) {
210
226
  for (const contents of webContents.getAllWebContents()) {
211
227
  if (contents.id === id) return contents
@@ -240,6 +256,23 @@ async function sendCdp(id, method, params) {
240
256
  const next = previous.then(async () => {
241
257
  const current = guestById(id)
242
258
  if (current === undefined || current.isDestroyed()) throw new Error(`guest ${id} is not available`)
259
+ // Chromium's CDP keyboard handler can redirect a webview command to the embedder's
260
+ // focused guest. Send text and keys to this exact guest instead, preserving OS focus.
261
+ if (current.getType() === 'webview') {
262
+ if (method === 'Input.insertText') {
263
+ if (typeof params?.text !== 'string') throw new Error('Input.insertText requires text')
264
+ await current.insertText(params.text)
265
+ return {}
266
+ }
267
+ if (method === 'Input.dispatchKeyEvent') {
268
+ const event = nativeKeyEvent(params)
269
+ current.sendInputEvent(event)
270
+ if (params.type === 'keyDown' && typeof params.text === 'string' && params.text !== '') {
271
+ current.sendInputEvent({ ...event, type: 'char', keyCode: params.text })
272
+ }
273
+ return {}
274
+ }
275
+ }
243
276
  if (!current.debugger.isAttached()) current.debugger.attach('1.3')
244
277
  return await current.debugger.sendCommand(method, params ?? {})
245
278
  })
@@ -248,6 +281,77 @@ async function sendCdp(id, method, params) {
248
281
  return await next
249
282
  }
250
283
 
284
+ /** Convert CDP key data for Electron's per-webContents input channel. */
285
+ function nativeKeyEvent(params) {
286
+ const type = params?.type
287
+ if (!['keyDown', 'rawKeyDown', 'keyUp', 'char'].includes(type)) throw new Error('unsupported keyboard event type')
288
+ const aliases = { ArrowLeft: 'Left', ArrowRight: 'Right', ArrowUp: 'Up', ArrowDown: 'Down', ' ': 'Space' }
289
+ const key = type === 'char' ? params.text : params.key
290
+ if (typeof key !== 'string' || key === '') throw new Error('keyboard event requires a key')
291
+ const mask = Number(params.modifiers ?? 0)
292
+ const modifiers = []
293
+ for (const [bit, name] of [[1, 'alt'], [2, 'control'], [4, 'meta'], [8, 'shift']]) {
294
+ if ((mask & bit) !== 0) modifiers.push(name)
295
+ }
296
+ if (params.isKeypad === true || params.location === 3) modifiers.push('isKeypad')
297
+ if (params.autoRepeat === true) modifiers.push('isAutoRepeat')
298
+ return { type: type === 'rawKeyDown' ? 'keyDown' : type, keyCode: type === 'char' ? key : aliases[key] ?? key, modifiers }
299
+ }
300
+
301
+ /** Download with this guest's authenticated session, streaming directly into an exclusive file. */
302
+ async function downloadGuest(guest, url, savePath) {
303
+ let scheme
304
+ try { scheme = new URL(String(url)).protocol } catch { scheme = undefined }
305
+ if (typeof url !== 'string' || !['http:', 'https:'].includes(scheme)) {
306
+ throw new Error('download requires an HTTP(S) URL')
307
+ }
308
+ if (typeof savePath !== 'string' || !isAbsolute(savePath)) throw new Error('download requires an absolute savePath')
309
+ const controller = new AbortController()
310
+ const timer = setTimeout(() => controller.abort(), 55_000)
311
+ let file
312
+ let reader
313
+ let temporary
314
+ const limit = 256 * 1024 * 1024
315
+ try {
316
+ const response = await guest.session.fetch(url, { credentials: 'include', signal: controller.signal })
317
+ if (!response.ok) throw new Error('download HTTP ' + response.status)
318
+ if (Number(response.headers.get('content-length') ?? 0) > limit) throw new Error('download too large (limit ' + limit + ' bytes)')
319
+ await mkdir(dirname(savePath), { recursive: true })
320
+ temporary = join(dirname(savePath), '.dsh-download-' + randomBytes(16).toString('hex') + '.part')
321
+ file = await open(temporary, 'wx', 0o600)
322
+ reader = response.body?.getReader()
323
+ let total = 0
324
+ if (reader !== undefined) {
325
+ for (;;) {
326
+ const chunk = await reader.read()
327
+ if (chunk.done) break
328
+ total += chunk.value.byteLength
329
+ if (total > limit) throw new Error('download too large (limit ' + limit + ' bytes)')
330
+ for (let offset = 0; offset < chunk.value.byteLength;) {
331
+ const { bytesWritten } = await file.write(chunk.value, offset, chunk.value.byteLength - offset)
332
+ if (bytesWritten === 0) throw new Error('download file write made no progress')
333
+ offset += bytesWritten
334
+ }
335
+ }
336
+ }
337
+ await file.close()
338
+ file = undefined
339
+ controller.signal.throwIfAborted()
340
+ try {
341
+ await link(temporary, savePath)
342
+ } catch (error) {
343
+ if (!['ENOTSUP', 'EOPNOTSUPP', 'EPERM', 'EXDEV', 'ENOSYS'].includes(error?.code)) throw error
344
+ await copyFile(temporary, savePath, constants.COPYFILE_EXCL)
345
+ }
346
+ } finally {
347
+ controller.abort()
348
+ await file?.close().catch(() => {})
349
+ await reader?.cancel().catch(() => {})
350
+ if (temporary !== undefined) await unlink(temporary).catch(() => {})
351
+ clearTimeout(timer)
352
+ }
353
+ }
354
+
251
355
  /**
252
356
  * Ask the shell's renderer for THIS conversation's browser panel, and report its guest.
253
357
  *
@@ -265,21 +369,28 @@ async function sendCdp(id, method, params) {
265
369
  * @param url - address to load when a panel has to be opened; `null` to only READ.
266
370
  * @returns the renderer's verdict, normalized so a malformed answer is a named failure.
267
371
  */
268
- async function evaluatePanelService(shellId, sessionId, url) {
372
+ async function evaluatePanelService(shellId, sessionId, url, tabId, viewId, guestId) {
269
373
  // `null` means read-only. This distinction is not cosmetic: `openPanel` CREATES a tab when the
270
374
  // conversation has none, so polling with it turned a 20-second wait into one empty tab every
271
375
  // 250ms — the "it opens a pile of blank pages at once" report. A wait must never be a write.
272
376
  const reading = url === null
377
+ const target = JSON.stringify({
378
+ ...typeof viewId === 'string' && viewId !== '' ? { viewId } : {},
379
+ ...Number.isSafeInteger(guestId) && guestId > 0 ? { guestId } : {},
380
+ })
273
381
  const call = reading
274
382
  // `panelGuest` reports state, not success, so the read form supplies the verdict itself: a
275
383
  // conversation with no panel yet is a legitimate answer to "what do you have", not a failure.
276
- ? `JSON.stringify({ ok: true, ...api.panelGuest(${JSON.stringify(String(sessionId))}) })`
277
- : `JSON.stringify(api.openPanel(${JSON.stringify(String(sessionId))}, ${JSON.stringify(String(url ?? ''))}))`
384
+ ? `JSON.stringify({ ok: true, ...api.panelGuest(${JSON.stringify(String(sessionId))}, ${JSON.stringify(tabId ?? null)}, ${target}) })`
385
+ : `JSON.stringify(api.openPanel(${JSON.stringify(String(sessionId))}, ${JSON.stringify(String(url ?? ''))}, ${target}))`
278
386
  const expression = `(() => {
279
387
  const api = globalThis.__dshBuiltinBrowser;
280
388
  if (api === undefined || api === null || typeof api.openPanel !== 'function') {
281
389
  return JSON.stringify({ ok: false, reason: 'the plugin client half is not loaded in this window' });
282
390
  }
391
+ if (${typeof viewId === 'string' && viewId !== ''} && Number(api.panelProtocol || 0) < 3) {
392
+ return JSON.stringify({ ok: false, reason: 'the browser plugin client needs to reload for separate sidebar tabs; reopen DSH Desktop and retry' });
393
+ }
283
394
  try {
284
395
  return ${call};
285
396
  } catch (error) {
@@ -320,7 +431,9 @@ async function evaluatePanelService(shellId, sessionId, url) {
320
431
  reason: parsed?.reason === undefined ? undefined : String(parsed.reason),
321
432
  panel: parsed?.panel === true,
322
433
  created: parsed?.created === true,
434
+ ...typeof parsed?.displayed === 'boolean' ? { displayed: parsed.displayed } : {},
323
435
  guestId: typeof parsed?.guestId === 'number' && Number.isFinite(parsed.guestId) ? parsed.guestId : null,
436
+ ...typeof parsed?.tabId === 'string' ? { tabId: parsed.tabId } : {},
324
437
  url: typeof parsed?.url === 'string' ? parsed.url : '',
325
438
  // A refusal carries what the renderer found, so the reason is actionable rather than a guess.
326
439
  found: parsed?.found === undefined ? undefined : parsed.found,
@@ -337,7 +450,8 @@ function guestShows(id, url) {
337
450
  if (guest === undefined) return false
338
451
  try {
339
452
  const current = guest.getURL()
340
- return current !== '' && (current === url || current.startsWith(url))
453
+ // A raw prefix match mistakes https://example.com.evil/ for https://example.com.
454
+ return current === url || current.startsWith(`${url}?`) || current.startsWith(`${url}#`)
341
455
  } catch (error) {
342
456
  return false
343
457
  }
@@ -428,6 +542,7 @@ async function handle(request) { const op = String(request?.op ?? '')
428
542
  || (claims.get(g.id) === owner && (!/^session-/.test(owner) || panelIds.includes(g.id))))
429
543
  return {
430
544
  ok: true,
545
+ protocol: PROTOCOL,
431
546
  guests: mineOrFree,
432
547
  sidebar: mineOrFree.filter(g => g.type === 'webview'),
433
548
  frame: await sidebarFrameKind(shell?.id),
@@ -464,10 +579,20 @@ async function handle(request) { const op = String(request?.op ?? '')
464
579
  }
465
580
  if (op === 'cdp') {
466
581
  const id = Number(request.id)
467
- if (!Number.isFinite(id)) throw new Error('cdp requires a numeric id')
582
+ if (!Number.isSafeInteger(id) || id <= 0) throw new Error('cdp requires a positive numeric guest id')
583
+ await assertGuestOwner(id, owner)
468
584
  const result = await sendCdp(id, String(request.method ?? ''), request.params)
469
585
  return { ok: true, result, bridgeRequestId: request.bridgeRequestId }
470
586
  }
587
+ if (op === 'download') {
588
+ const id = Number(request.id)
589
+ if (!Number.isSafeInteger(id) || id <= 0) throw new Error('download requires a positive numeric guest id')
590
+ await assertGuestOwner(id, owner)
591
+ const guest = guestById(id)
592
+ if (guest === undefined || guest.isDestroyed() || guest.getType() !== 'webview') throw new Error('download guest is not available')
593
+ await downloadGuest(guest, request.url, request.savePath)
594
+ return { ok: true, path: request.savePath }
595
+ }
471
596
  if (op === 'ensureSidebar') {
472
597
  // This conversation's OWN panel, opened through the shell's own navigation — never by
473
598
  // simulating input.
@@ -492,10 +617,12 @@ async function handle(request) { const op = String(request?.op ?? '')
492
617
  throw new Error('this host supplied no conversation id, so its own panel cannot be identified')
493
618
  }
494
619
 
620
+ let tabId
495
621
  const ask = async (withUrl) => {
496
622
  // `null` reads, a string places or navigates. Every round of the wait below uses the READ
497
623
  // form, because a wait must never create anything.
498
- const answer = await evaluatePanelService(shell.id, owner, withUrl ? url : null)
624
+ const answer = await evaluatePanelService(shell.id, owner, withUrl ? url : null, tabId,
625
+ typeof request.viewId === 'string' ? request.viewId : undefined, request.guestId)
499
626
  if (answer.ok !== true) {
500
627
  // Carry the renderer's own findings into the failure: it is the side that can see why the
501
628
  // lookup missed, and a bare "not mounted" leaves the next reader guessing between a real
@@ -512,7 +639,11 @@ async function handle(request) { const op = String(request?.op ?? '')
512
639
  // `list` op instead, because this one can drive the shell — that is the difference between "show
513
640
  // me the page" and "let me look at it", and keeping the preview off this path is what stops a
514
641
  // read-only action from moving the reader's layout.
515
- const first = await ask(url !== '')
642
+ const first = await ask(true)
643
+ tabId = first.tabId
644
+ if (first.displayed === false) {
645
+ throw codedError(PANEL_NOT_DISPLAYED, 'the requested conversation is still being displayed; its sidebar will attach after rendering')
646
+ }
516
647
  if (first.guestId !== null) {
517
648
  claims.set(first.guestId, owner)
518
649
  if (!guestShows(first.guestId, url)) {
@@ -555,7 +686,8 @@ async function handle(request) { const op = String(request?.op ?? '')
555
686
  }
556
687
  return { ok: true, created: true, id: polled.guestId, via: 'panel', owner }
557
688
  }
558
- throw new Error(
689
+ throw codedError(
690
+ PANEL_INITIALIZING,
559
691
  'this conversation\'s browser panel produced no page within its budget '
560
692
  + '(the shell placed no guest in this conversation\'s own sidebar)',
561
693
  )
@@ -577,13 +709,17 @@ async function handle(request) { const op = String(request?.op ?? '')
577
709
  if (guest === undefined) throw new Error(`showTab: no guest with id ${viewId}`)
578
710
  // Only a guest this caller holds may be brought forward. Without the check, one session could
579
711
  // switch the sidebar to another session's page — moving the human's view out from under it.
580
- pruneClaims()
581
- if (claims.has(viewId) && claims.get(viewId) !== owner) {
582
- throw new Error(`showTab: guest ${viewId} belongs to another session`)
583
- }
584
- claims.set(viewId, owner)
712
+ await assertGuestOwner(Number(viewId), owner)
585
713
  const shell = webContents.getAllWebContents().find(contents => contents.getType() === 'window')
586
714
  if (shell === undefined) throw new Error('no shell window to drive')
715
+ // Bind by the exact native guest rather than its title: several tabs can have the same title.
716
+ if (typeof request.logicalViewId === 'string' && request.logicalViewId !== '') {
717
+ const shown = await evaluatePanelService(shell.id, owner, '', undefined, request.logicalViewId, viewId)
718
+ if (shown.ok !== true || shown.guestId !== viewId) {
719
+ throw new Error('could not select the requested sidebar tab: ' + String(shown.reason ?? 'the requested guest is not displayed yet'))
720
+ }
721
+ return { ok: true, verdict: 'SELECTED' }
722
+ }
587
723
  const wantTitle = String(guest.getTitle() ?? '').trim()
588
724
  const clicked = await evaluateInPanel(shell.id, owner, 'Runtime.evaluate', {
589
725
  expression: `(() => {
@@ -684,6 +820,8 @@ async function handle(request) { const op = String(request?.op ?? '')
684
820
  return { ok: true, closed: Number(clicked?.result?.value ?? 0) }
685
821
  }
686
822
  if (op === 'collapseSidebar') {
823
+ // An unscoped owner falls back to sendCdp(shell window), whose debugger attachment hangs.
824
+ if (!/^session-/.test(owner)) throw new Error('collapseSidebar requires a conversation id')
687
825
  // Fold the sidebar away so the agent works without occupying the screen. The
688
826
  // guest keeps running — collapsing is presentation, exactly as §3 asks.
689
827
  const shell = webContents.getAllWebContents().find(contents => contents.getType() === 'window')
@@ -797,7 +935,7 @@ export function start() {
797
935
  authenticationDeadline.unref?.()
798
936
  socket.on('close', () => clearTimeout(authenticationDeadline))
799
937
  socket.on('data', chunk => {
800
- if (Buffer.byteLength(buffer, 'utf8') + Buffer.byteLength(chunk, 'utf8') > 128 * 1024 * 1024) {
938
+ if (Buffer.byteLength(buffer, 'utf8') + Buffer.byteLength(chunk, 'utf8') > 32 * 1024 * 1024) {
801
939
  socket.destroy()
802
940
  return
803
941
  }
@@ -805,7 +943,7 @@ export function start() {
805
943
  let newline = buffer.indexOf('\n')
806
944
  while (newline !== -1) {
807
945
  const line = buffer.slice(0, newline).trim()
808
- if (Buffer.byteLength(line, 'utf8') > (authed ? 128 * 1024 * 1024 : 64 * 1024)) {
946
+ if (Buffer.byteLength(line, 'utf8') > (authed ? 32 * 1024 * 1024 : 64 * 1024)) {
809
947
  socket.destroy()
810
948
  return
811
949
  }
@@ -854,7 +992,7 @@ export function start() {
854
992
  }
855
993
  // Authentication may share a TCP chunk with the first real (larger) command. Apply the
856
994
  // unauthenticated cap to that frame, not to bytes belonging to an authenticated successor.
857
- if (Buffer.byteLength(buffer, 'utf8') > (authed ? 128 * 1024 * 1024 : 64 * 1024)) socket.destroy()
995
+ if (Buffer.byteLength(buffer, 'utf8') > (authed ? 32 * 1024 * 1024 : 64 * 1024)) socket.destroy()
858
996
  })
859
997
  socket.on('error', () => { /* client went away */ })
860
998
  })
@@ -0,0 +1,170 @@
1
+ <#
2
+ Requests the verified Desktop process's own native Quit menu action.
3
+ The caller opens the official application menu after starting this helper.
4
+ This helper never dismisses or approves a subsequent task confirmation.
5
+ #>
6
+ [CmdletBinding()]
7
+ param(
8
+ [Parameter(Mandatory = $true)]
9
+ [ValidateRange(1, 2147483647)]
10
+ [int]$TargetPid,
11
+
12
+ [Parameter(Mandatory = $true)]
13
+ [ValidateNotNullOrEmpty()]
14
+ [string]$ExpectedExecutable,
15
+
16
+ [ValidateRange(1, 120)]
17
+ [int]$TimeoutSeconds = 15,
18
+
19
+ # Pass the UTC CreationDate from the coordinator's original Win32_Process
20
+ # snapshot to also detect PID reuse before this helper starts.
21
+ [string]$ExpectedStartTimeUtc
22
+ )
23
+
24
+ $ErrorActionPreference = 'Stop'
25
+ Set-StrictMode -Version Latest
26
+ [Console]::OutputEncoding = [Text.UTF8Encoding]::new($false)
27
+ $OutputEncoding = [Console]::OutputEncoding
28
+
29
+ function Complete-Request([hashtable]$Result, [int]$Code) {
30
+ $Result['pid'] = $TargetPid
31
+ Write-Output ($Result | ConvertTo-Json -Compress -Depth 4)
32
+ exit $Code
33
+ }
34
+
35
+ function Fail-Request([string]$Code, [string]$Message) {
36
+ Complete-Request @{ ok = $false; code = $Code; error = $Message } 1
37
+ }
38
+
39
+ function Read-TargetProcess {
40
+ # Read only this exact PID. Do not collect CommandLine or inspect unrelated
41
+ # Desktop installations, browser guests, or other applications.
42
+ return Get-CimInstance -ClassName Win32_Process -Filter ('ProcessId = ' + $TargetPid.ToString([Globalization.CultureInfo]::InvariantCulture)) -Property ProcessId, ExecutablePath, CreationDate -OperationTimeoutSec 3
43
+ }
44
+
45
+ function Read-CreationTicks($Process) {
46
+ if ($null -eq $Process.CreationDate) {
47
+ Fail-Request 'PROCESS_IDENTITY_UNAVAILABLE' 'The target process creation time is unavailable; no quit action was sent.'
48
+ }
49
+ return $Process.CreationDate.ToUniversalTime().Ticks
50
+ }
51
+
52
+ function Assert-TargetIdentity($Process, [long]$CreationTicks) {
53
+ if ([string]::IsNullOrWhiteSpace($Process.ExecutablePath)) {
54
+ Fail-Request 'PROCESS_IDENTITY_UNAVAILABLE' 'The target executable could not be verified; no quit action was sent.'
55
+ }
56
+ $actualPath = [IO.Path]::GetFullPath($Process.ExecutablePath)
57
+ if (-not [StringComparer]::OrdinalIgnoreCase.Equals($script:verifiedExecutable, $actualPath)) {
58
+ Fail-Request 'PROCESS_IDENTITY_MISMATCH' 'The PID belongs to a different executable; no quit action was sent.'
59
+ }
60
+ if ((Read-CreationTicks $Process) -ne $CreationTicks) {
61
+ Fail-Request 'PID_REUSED' 'The original process has exited and its PID was reused; no quit action was sent.'
62
+ }
63
+ }
64
+
65
+ function Test-NativePopupItem($Element) {
66
+ # Native Electron popup rows have these Views accessibility classes. Requiring
67
+ # the native popup root keeps an HTML role=menuitem out of the candidate set.
68
+ $current = $Element.Current
69
+ if ($current.ClassName -ne 'MenuItemView' -or $current.FrameworkId -ne 'Chrome') { return $false }
70
+ $ancestor = [Windows.Automation.TreeWalker]::RawViewWalker.GetParent($Element)
71
+ $foundMenuRoot = $false
72
+ for ($depth = 0; $depth -lt 32 -and $null -ne $ancestor; $depth++) {
73
+ $information = $ancestor.Current
74
+ if ($information.ProcessId -ne $TargetPid) { return $false }
75
+ if ($information.ControlType -eq [Windows.Automation.ControlType]::Document) { return $false }
76
+ if ($information.ClassName -eq 'MenuHostRootView' -and $information.FrameworkId -eq 'Chrome') { $foundMenuRoot = $true }
77
+ if ($foundMenuRoot -and $information.NativeWindowHandle -ne 0 -and $information.ClassName -match '^Chrome_WidgetWin_') { return $true }
78
+ $ancestor = [Windows.Automation.TreeWalker]::RawViewWalker.GetParent($ancestor)
79
+ }
80
+ return $false
81
+ }
82
+
83
+ try {
84
+ if ($env:DSH_BROWSER_TEST -eq '1' -or $null -ne $env:NODE_TEST_CONTEXT) {
85
+ Fail-Request 'TEST_CONTEXT_REFUSED' 'Native Desktop quit requests are disabled in automated test contexts.'
86
+ }
87
+ if ($ExpectedExecutable -notmatch '^(?:[A-Za-z]:[\\/]|\\\\[^\\/]+[\\/][^\\/]+[\\/])') {
88
+ Fail-Request 'INVALID_EXECUTABLE' 'ExpectedExecutable must be an absolute Windows executable path.'
89
+ }
90
+ $script:verifiedExecutable = [IO.Path]::GetFullPath($ExpectedExecutable)
91
+ $file = Get-Item -LiteralPath $script:verifiedExecutable
92
+ if ($file.PSIsContainer -or $file.Extension -ine '.exe') {
93
+ Fail-Request 'INVALID_EXECUTABLE' 'ExpectedExecutable must identify an existing executable file.'
94
+ }
95
+
96
+ $process = Read-TargetProcess
97
+ if ($null -eq $process) {
98
+ Complete-Request @{ ok = $true; alreadyExited = $true; action = 'already-exited' } 0
99
+ }
100
+ $creationTicks = Read-CreationTicks $process
101
+ if (-not [string]::IsNullOrWhiteSpace($ExpectedStartTimeUtc)) {
102
+ $expectedStart = [DateTimeOffset]::Parse($ExpectedStartTimeUtc, [Globalization.CultureInfo]::InvariantCulture, [Globalization.DateTimeStyles]::RoundtripKind)
103
+ if ($expectedStart.UtcTicks -ne $creationTicks) {
104
+ Fail-Request 'PID_REUSED' 'The PID does not match the coordinator original process creation time; no quit action was sent.'
105
+ }
106
+ }
107
+ Assert-TargetIdentity $process $creationTicks
108
+
109
+ Add-Type -AssemblyName UIAutomationClient
110
+ Add-Type -AssemblyName UIAutomationTypes
111
+ # Official Windows application-menu labels in the shipped Desktop locales.
112
+ # JSON escapes keep the script valid under Windows PowerShell's ANSI default.
113
+ $labels = '["Exit","\u9000\u51fa","\u7d42\u4e86","Salir","Quitter","Beenden","\u0412\u044b\u0445\u043e\u0434","Sair","Quit DeepSeek Harness","\u9000\u51fa DeepSeek Harness"]' | ConvertFrom-Json
114
+ $condition = [Windows.Automation.AndCondition]::new(
115
+ [Windows.Automation.PropertyCondition]::new([Windows.Automation.AutomationElement]::ProcessIdProperty, $TargetPid),
116
+ [Windows.Automation.PropertyCondition]::new([Windows.Automation.AutomationElement]::ControlTypeProperty, [Windows.Automation.ControlType]::MenuItem)
117
+ )
118
+ $watch = [Diagnostics.Stopwatch]::StartNew()
119
+ while ($watch.Elapsed.TotalSeconds -lt $TimeoutSeconds) {
120
+ $process = Read-TargetProcess
121
+ if ($null -eq $process) {
122
+ Complete-Request @{ ok = $true; alreadyExited = $true; action = 'already-exited' } 0
123
+ }
124
+ Assert-TargetIdentity $process $creationTicks
125
+ $candidates = [Collections.Generic.List[object]]::new()
126
+ $elements = [Windows.Automation.AutomationElement]::RootElement.FindAll([Windows.Automation.TreeScope]::Descendants, $condition)
127
+ foreach ($element in $elements) {
128
+ try {
129
+ $current = $element.Current
130
+ if (-not $current.IsEnabled -or $current.IsOffscreen -or $labels -cnotcontains $current.Name -or -not (Test-NativePopupItem $element)) { continue }
131
+ $pattern = $null
132
+ if ($element.TryGetCurrentPattern([Windows.Automation.InvokePattern]::Pattern, [ref]$pattern)) {
133
+ $candidates.Add(@{ element = $element; pattern = $pattern; label = $current.Name })
134
+ }
135
+ } catch [Windows.Automation.ElementNotAvailableException] {
136
+ # An unrelated disappearing menu is a transient view state.
137
+ }
138
+ }
139
+ if ($candidates.Count -gt 1) {
140
+ Fail-Request 'AMBIGUOUS_QUIT_MENU' 'More than one native quit menu item is open; no quit action was sent.'
141
+ }
142
+ if ($candidates.Count -eq 1) {
143
+ $process = Read-TargetProcess
144
+ if ($null -eq $process) {
145
+ Complete-Request @{ ok = $true; alreadyExited = $true; action = 'already-exited' } 0
146
+ }
147
+ Assert-TargetIdentity $process $creationTicks
148
+ $candidate = $candidates[0]
149
+ $current = $candidate.element.Current
150
+ if ($current.ProcessId -ne $TargetPid -or -not $current.IsEnabled -or $current.IsOffscreen -or $labels -cnotcontains $current.Name -or -not (Test-NativePopupItem $candidate.element)) { continue }
151
+ try {
152
+ $candidate.pattern.Invoke()
153
+ } catch {
154
+ $process = Read-TargetProcess
155
+ if ($null -eq $process) {
156
+ Complete-Request @{ ok = $true; alreadyExited = $true; action = 'already-exited' } 0
157
+ }
158
+ Assert-TargetIdentity $process $creationTicks
159
+ Fail-Request 'QUIT_INVOKE_FAILED' 'The native quit menu action could not be invoked; no subsequent dialog was approved.'
160
+ }
161
+ Complete-Request @{ ok = $true; action = 'quit-requested'; method = 'uia-invoke'; label = $candidate.label } 0
162
+ }
163
+ Start-Sleep -Milliseconds 120
164
+ }
165
+ Fail-Request 'QUIT_MENU_TIMEOUT' 'The official native quit menu item was not available before the deadline. Open the Desktop application menu and retry.'
166
+ } catch {
167
+ # Return stable diagnostics without serializing process command lines,
168
+ # environment values, inaccessible executable paths, or UI content.
169
+ Fail-Request 'QUIT_REQUEST_FAILED' 'The Desktop quit request could not be verified or UI Automation was unavailable; no subsequent dialog was approved.'
170
+ }