dsh-builtin-browser 0.5.7 → 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.
- package/CHANGELOG.md +66 -0
- package/README.en.md +48 -22
- package/README.md +48 -22
- package/client.js +469 -81
- package/desktop-bridge/install-and-start.cmd +4 -5
- package/desktop-bridge/install.mjs +251 -159
- package/desktop-bridge/maintenance-progress.ps1 +166 -0
- package/desktop-bridge/plugin-browser-bridge.js +151 -18
- package/desktop-bridge/request-desktop-quit.ps1 +170 -0
- package/docs/user-guide.md +28 -4
- package/lib/browser-electron/automatic-maintenance.d.ts +41 -0
- package/lib/browser-electron/automatic-maintenance.js +426 -0
- package/lib/browser-electron/bridge-auto.d.ts +93 -0
- package/lib/browser-electron/bridge-auto.js +113 -0
- package/lib/browser-electron/bridge-connection.d.ts +0 -2
- package/lib/browser-electron/bridge-connection.js +2 -4
- package/lib/browser-electron/bridge-endpoint.js +1 -19
- package/lib/browser-electron/bridge-install.d.ts +41 -4
- package/lib/browser-electron/bridge-install.js +131 -18
- package/lib/browser-electron/bridge-maintenance.d.ts +24 -0
- package/lib/browser-electron/bridge-maintenance.js +125 -0
- package/lib/browser-electron/bridge-status.d.ts +10 -3
- package/lib/browser-electron/bridge-status.js +76 -45
- package/lib/browser-electron/desktop-bridge-host.d.ts +5 -2
- package/lib/browser-electron/desktop-bridge-host.js +54 -33
- package/lib/browser-electron/desktop-identity.js +21 -9
- package/lib/browser-electron/electron-provision.js +5 -2
- package/lib/browser-electron/entry.js +104 -74
- package/lib/browser-electron/ephemeral-profile.js +67 -26
- package/lib/browser-electron/history-store.js +2 -2
- package/lib/browser-electron/host-main.js +26 -37
- package/lib/browser-electron/http-body.d.ts +24 -0
- package/lib/browser-electron/http-body.js +33 -0
- package/lib/browser-electron/json-reply.d.ts +13 -1
- package/lib/browser-electron/json-reply.js +16 -2
- package/lib/browser-electron/maintenance-broker.d.ts +35 -0
- package/lib/browser-electron/maintenance-broker.js +114 -0
- package/lib/browser-electron/maintenance-lifecycle.d.ts +32 -0
- package/lib/browser-electron/maintenance-lifecycle.js +67 -0
- package/lib/browser-electron/maintenance-route.d.ts +18 -0
- package/lib/browser-electron/maintenance-route.js +75 -0
- package/lib/browser-electron/paths.d.ts +4 -0
- package/lib/browser-electron/paths.js +19 -0
- package/lib/browser-electron/process.d.ts +14 -0
- package/lib/browser-electron/process.js +24 -0
- package/lib/browser-electron/provider.d.ts +7 -7
- package/lib/browser-electron/provider.js +13 -14
- package/lib/browser-electron/remote-host.js +18 -16
- package/lib/browser-electron/runtime-status.d.ts +27 -13
- package/lib/browser-electron/runtime-status.js +24 -4
- package/lib/browser-electron/settings-store.d.ts +11 -0
- package/lib/browser-electron/settings-store.js +8 -2
- package/lib/browser-electron/sidebar-only-host.d.ts +36 -0
- package/lib/browser-electron/sidebar-only-host.js +192 -0
- package/lib/browser-electron/system-browser.d.ts +1 -9
- package/lib/browser-electron/system-browser.js +19 -22
- package/lib/browser-electron/timing.d.ts +8 -0
- package/lib/browser-electron/timing.js +13 -0
- package/lib/browser-electron/windows-system.d.ts +3 -0
- package/lib/browser-electron/windows-system.js +19 -0
- package/lib/tool-browser/index.js +5 -4
- package/package.json +2 -2
- package/scripts/run-tests.mjs +32 -0
- package/scripts/verify-preview-route.mjs +19 -1
- package/src/browser-electron/automatic-maintenance.ts +414 -0
- package/src/browser-electron/bridge-auto.ts +158 -0
- package/src/browser-electron/bridge-connection.ts +2 -4
- package/src/browser-electron/bridge-endpoint.ts +1 -18
- package/src/browser-electron/bridge-install.ts +151 -20
- package/src/browser-electron/bridge-maintenance.ts +161 -0
- package/src/browser-electron/bridge-status.ts +78 -48
- package/src/browser-electron/desktop-bridge-host.ts +48 -32
- package/src/browser-electron/desktop-identity.ts +18 -9
- package/src/browser-electron/electron-provision.ts +5 -2
- package/src/browser-electron/entry.ts +91 -69
- package/src/browser-electron/ephemeral-profile.ts +65 -28
- package/src/browser-electron/history-store.ts +2 -2
- package/src/browser-electron/host-main.ts +23 -36
- package/src/browser-electron/http-body.ts +42 -0
- package/src/browser-electron/json-reply.ts +18 -3
- package/src/browser-electron/maintenance-broker.ts +142 -0
- package/src/browser-electron/maintenance-lifecycle.ts +86 -0
- package/src/browser-electron/maintenance-route.ts +64 -0
- package/src/browser-electron/paths.ts +21 -0
- package/src/browser-electron/process.ts +23 -0
- package/src/browser-electron/provider.ts +18 -18
- package/src/browser-electron/remote-host.ts +19 -19
- package/src/browser-electron/runtime-status.ts +52 -17
- package/src/browser-electron/settings-store.ts +20 -3
- package/src/browser-electron/sidebar-only-host.ts +199 -0
- package/src/browser-electron/system-browser.ts +19 -22
- package/src/browser-electron/timing.ts +16 -0
- package/src/browser-electron/windows-system.ts +23 -0
- package/src/tool-browser/index.ts +5 -4
|
@@ -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
|
/**
|
|
@@ -97,7 +98,7 @@ const claims = new Map()
|
|
|
97
98
|
* acceptance script compares this against the file's mtime and says so before testing anything.
|
|
98
99
|
*/
|
|
99
100
|
const LOADED_AT = new Date().toISOString()
|
|
100
|
-
const PROTOCOL =
|
|
101
|
+
const PROTOCOL = 3
|
|
101
102
|
|
|
102
103
|
/**
|
|
103
104
|
* The DOM root of THIS conversation's sidebar, as JavaScript to embed in a page script.
|
|
@@ -207,6 +208,20 @@ function pruneClaims() {
|
|
|
207
208
|
for (const id of [...claims.keys()]) if (!live.has(id)) claims.delete(id)
|
|
208
209
|
}
|
|
209
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
|
+
|
|
210
225
|
function guestById(id) {
|
|
211
226
|
for (const contents of webContents.getAllWebContents()) {
|
|
212
227
|
if (contents.id === id) return contents
|
|
@@ -241,6 +256,23 @@ async function sendCdp(id, method, params) {
|
|
|
241
256
|
const next = previous.then(async () => {
|
|
242
257
|
const current = guestById(id)
|
|
243
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
|
+
}
|
|
244
276
|
if (!current.debugger.isAttached()) current.debugger.attach('1.3')
|
|
245
277
|
return await current.debugger.sendCommand(method, params ?? {})
|
|
246
278
|
})
|
|
@@ -249,6 +281,77 @@ async function sendCdp(id, method, params) {
|
|
|
249
281
|
return await next
|
|
250
282
|
}
|
|
251
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
|
+
|
|
252
355
|
/**
|
|
253
356
|
* Ask the shell's renderer for THIS conversation's browser panel, and report its guest.
|
|
254
357
|
*
|
|
@@ -266,21 +369,28 @@ async function sendCdp(id, method, params) {
|
|
|
266
369
|
* @param url - address to load when a panel has to be opened; `null` to only READ.
|
|
267
370
|
* @returns the renderer's verdict, normalized so a malformed answer is a named failure.
|
|
268
371
|
*/
|
|
269
|
-
async function evaluatePanelService(shellId, sessionId, url, tabId) {
|
|
372
|
+
async function evaluatePanelService(shellId, sessionId, url, tabId, viewId, guestId) {
|
|
270
373
|
// `null` means read-only. This distinction is not cosmetic: `openPanel` CREATES a tab when the
|
|
271
374
|
// conversation has none, so polling with it turned a 20-second wait into one empty tab every
|
|
272
375
|
// 250ms — the "it opens a pile of blank pages at once" report. A wait must never be a write.
|
|
273
376
|
const reading = url === null
|
|
377
|
+
const target = JSON.stringify({
|
|
378
|
+
...typeof viewId === 'string' && viewId !== '' ? { viewId } : {},
|
|
379
|
+
...Number.isSafeInteger(guestId) && guestId > 0 ? { guestId } : {},
|
|
380
|
+
})
|
|
274
381
|
const call = reading
|
|
275
382
|
// `panelGuest` reports state, not success, so the read form supplies the verdict itself: a
|
|
276
383
|
// conversation with no panel yet is a legitimate answer to "what do you have", not a failure.
|
|
277
|
-
? `JSON.stringify({ ok: true, ...api.panelGuest(${JSON.stringify(String(sessionId))}, ${JSON.stringify(tabId ?? null)}) })`
|
|
278
|
-
: `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}))`
|
|
279
386
|
const expression = `(() => {
|
|
280
387
|
const api = globalThis.__dshBuiltinBrowser;
|
|
281
388
|
if (api === undefined || api === null || typeof api.openPanel !== 'function') {
|
|
282
389
|
return JSON.stringify({ ok: false, reason: 'the plugin client half is not loaded in this window' });
|
|
283
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
|
+
}
|
|
284
394
|
try {
|
|
285
395
|
return ${call};
|
|
286
396
|
} catch (error) {
|
|
@@ -321,6 +431,7 @@ async function evaluatePanelService(shellId, sessionId, url, tabId) {
|
|
|
321
431
|
reason: parsed?.reason === undefined ? undefined : String(parsed.reason),
|
|
322
432
|
panel: parsed?.panel === true,
|
|
323
433
|
created: parsed?.created === true,
|
|
434
|
+
...typeof parsed?.displayed === 'boolean' ? { displayed: parsed.displayed } : {},
|
|
324
435
|
guestId: typeof parsed?.guestId === 'number' && Number.isFinite(parsed.guestId) ? parsed.guestId : null,
|
|
325
436
|
...typeof parsed?.tabId === 'string' ? { tabId: parsed.tabId } : {},
|
|
326
437
|
url: typeof parsed?.url === 'string' ? parsed.url : '',
|
|
@@ -339,7 +450,8 @@ function guestShows(id, url) {
|
|
|
339
450
|
if (guest === undefined) return false
|
|
340
451
|
try {
|
|
341
452
|
const current = guest.getURL()
|
|
342
|
-
|
|
453
|
+
// A raw prefix match mistakes https://example.com.evil/ for https://example.com.
|
|
454
|
+
return current === url || current.startsWith(`${url}?`) || current.startsWith(`${url}#`)
|
|
343
455
|
} catch (error) {
|
|
344
456
|
return false
|
|
345
457
|
}
|
|
@@ -430,6 +542,7 @@ async function handle(request) { const op = String(request?.op ?? '')
|
|
|
430
542
|
|| (claims.get(g.id) === owner && (!/^session-/.test(owner) || panelIds.includes(g.id))))
|
|
431
543
|
return {
|
|
432
544
|
ok: true,
|
|
545
|
+
protocol: PROTOCOL,
|
|
433
546
|
guests: mineOrFree,
|
|
434
547
|
sidebar: mineOrFree.filter(g => g.type === 'webview'),
|
|
435
548
|
frame: await sidebarFrameKind(shell?.id),
|
|
@@ -466,10 +579,20 @@ async function handle(request) { const op = String(request?.op ?? '')
|
|
|
466
579
|
}
|
|
467
580
|
if (op === 'cdp') {
|
|
468
581
|
const id = Number(request.id)
|
|
469
|
-
if (!Number.
|
|
582
|
+
if (!Number.isSafeInteger(id) || id <= 0) throw new Error('cdp requires a positive numeric guest id')
|
|
583
|
+
await assertGuestOwner(id, owner)
|
|
470
584
|
const result = await sendCdp(id, String(request.method ?? ''), request.params)
|
|
471
585
|
return { ok: true, result, bridgeRequestId: request.bridgeRequestId }
|
|
472
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
|
+
}
|
|
473
596
|
if (op === 'ensureSidebar') {
|
|
474
597
|
// This conversation's OWN panel, opened through the shell's own navigation — never by
|
|
475
598
|
// simulating input.
|
|
@@ -498,7 +621,8 @@ async function handle(request) { const op = String(request?.op ?? '')
|
|
|
498
621
|
const ask = async (withUrl) => {
|
|
499
622
|
// `null` reads, a string places or navigates. Every round of the wait below uses the READ
|
|
500
623
|
// form, because a wait must never create anything.
|
|
501
|
-
const answer = await evaluatePanelService(shell.id, owner, withUrl ? url : null, tabId
|
|
624
|
+
const answer = await evaluatePanelService(shell.id, owner, withUrl ? url : null, tabId,
|
|
625
|
+
typeof request.viewId === 'string' ? request.viewId : undefined, request.guestId)
|
|
502
626
|
if (answer.ok !== true) {
|
|
503
627
|
// Carry the renderer's own findings into the failure: it is the side that can see why the
|
|
504
628
|
// lookup missed, and a bare "not mounted" leaves the next reader guessing between a real
|
|
@@ -515,8 +639,11 @@ async function handle(request) { const op = String(request?.op ?? '')
|
|
|
515
639
|
// `list` op instead, because this one can drive the shell — that is the difference between "show
|
|
516
640
|
// me the page" and "let me look at it", and keeping the preview off this path is what stops a
|
|
517
641
|
// read-only action from moving the reader's layout.
|
|
518
|
-
const first = await ask(
|
|
642
|
+
const first = await ask(true)
|
|
519
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
|
+
}
|
|
520
647
|
if (first.guestId !== null) {
|
|
521
648
|
claims.set(first.guestId, owner)
|
|
522
649
|
if (!guestShows(first.guestId, url)) {
|
|
@@ -582,13 +709,17 @@ async function handle(request) { const op = String(request?.op ?? '')
|
|
|
582
709
|
if (guest === undefined) throw new Error(`showTab: no guest with id ${viewId}`)
|
|
583
710
|
// Only a guest this caller holds may be brought forward. Without the check, one session could
|
|
584
711
|
// switch the sidebar to another session's page — moving the human's view out from under it.
|
|
585
|
-
|
|
586
|
-
if (claims.has(viewId) && claims.get(viewId) !== owner) {
|
|
587
|
-
throw new Error(`showTab: guest ${viewId} belongs to another session`)
|
|
588
|
-
}
|
|
589
|
-
claims.set(viewId, owner)
|
|
712
|
+
await assertGuestOwner(Number(viewId), owner)
|
|
590
713
|
const shell = webContents.getAllWebContents().find(contents => contents.getType() === 'window')
|
|
591
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
|
+
}
|
|
592
723
|
const wantTitle = String(guest.getTitle() ?? '').trim()
|
|
593
724
|
const clicked = await evaluateInPanel(shell.id, owner, 'Runtime.evaluate', {
|
|
594
725
|
expression: `(() => {
|
|
@@ -689,6 +820,8 @@ async function handle(request) { const op = String(request?.op ?? '')
|
|
|
689
820
|
return { ok: true, closed: Number(clicked?.result?.value ?? 0) }
|
|
690
821
|
}
|
|
691
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')
|
|
692
825
|
// Fold the sidebar away so the agent works without occupying the screen. The
|
|
693
826
|
// guest keeps running — collapsing is presentation, exactly as §3 asks.
|
|
694
827
|
const shell = webContents.getAllWebContents().find(contents => contents.getType() === 'window')
|
|
@@ -802,7 +935,7 @@ export function start() {
|
|
|
802
935
|
authenticationDeadline.unref?.()
|
|
803
936
|
socket.on('close', () => clearTimeout(authenticationDeadline))
|
|
804
937
|
socket.on('data', chunk => {
|
|
805
|
-
if (Buffer.byteLength(buffer, 'utf8') + Buffer.byteLength(chunk, 'utf8') >
|
|
938
|
+
if (Buffer.byteLength(buffer, 'utf8') + Buffer.byteLength(chunk, 'utf8') > 32 * 1024 * 1024) {
|
|
806
939
|
socket.destroy()
|
|
807
940
|
return
|
|
808
941
|
}
|
|
@@ -810,7 +943,7 @@ export function start() {
|
|
|
810
943
|
let newline = buffer.indexOf('\n')
|
|
811
944
|
while (newline !== -1) {
|
|
812
945
|
const line = buffer.slice(0, newline).trim()
|
|
813
|
-
if (Buffer.byteLength(line, 'utf8') > (authed ?
|
|
946
|
+
if (Buffer.byteLength(line, 'utf8') > (authed ? 32 * 1024 * 1024 : 64 * 1024)) {
|
|
814
947
|
socket.destroy()
|
|
815
948
|
return
|
|
816
949
|
}
|
|
@@ -859,7 +992,7 @@ export function start() {
|
|
|
859
992
|
}
|
|
860
993
|
// Authentication may share a TCP chunk with the first real (larger) command. Apply the
|
|
861
994
|
// unauthenticated cap to that frame, not to bytes belonging to an authenticated successor.
|
|
862
|
-
if (Buffer.byteLength(buffer, 'utf8') > (authed ?
|
|
995
|
+
if (Buffer.byteLength(buffer, 'utf8') > (authed ? 32 * 1024 * 1024 : 64 * 1024)) socket.destroy()
|
|
863
996
|
})
|
|
864
997
|
socket.on('error', () => { /* client went away */ })
|
|
865
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
|
+
}
|