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.
- package/CHANGELOG.md +148 -0
- package/README.en.md +75 -81
- package/README.md +75 -82
- package/client.js +831 -384
- package/desktop-bridge/install-and-start.cmd +4 -5
- package/desktop-bridge/install.mjs +322 -141
- package/desktop-bridge/maintenance-progress.ps1 +166 -0
- package/desktop-bridge/plugin-browser-bridge.js +157 -19
- package/desktop-bridge/request-desktop-quit.ps1 +170 -0
- package/docs/tool-reference.md +20 -1
- package/docs/user-guide.md +28 -4
- package/lib/browser/runtime.d.ts +3 -1
- package/lib/browser/runtime.js +9 -0
- package/lib/browser/types.d.ts +42 -0
- package/lib/browser-electron/authenticated-route.d.ts +27 -0
- package/lib/browser-electron/authenticated-route.js +39 -0
- 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 +8 -19
- package/lib/browser-electron/bridge-install.d.ts +85 -0
- package/lib/browser-electron/bridge-install.js +211 -0
- 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 +74 -24
- package/lib/browser-electron/desktop-bridge-host.d.ts +11 -5
- package/lib/browser-electron/desktop-bridge-host.js +67 -25
- package/lib/browser-electron/desktop-identity.js +21 -9
- package/lib/browser-electron/electron-provision.d.ts +1 -1
- package/lib/browser-electron/electron-provision.js +36 -13
- package/lib/browser-electron/entry.js +173 -67
- 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 +48 -38
- 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 +16 -9
- package/lib/browser-electron/provider.js +87 -18
- package/lib/browser-electron/remote-host.js +22 -20
- package/lib/browser-electron/runtime-route.d.ts +3 -5
- package/lib/browser-electron/runtime-status.d.ts +27 -13
- package/lib/browser-electron/runtime-status.js +28 -6
- package/lib/browser-electron/settings-route.d.ts +5 -18
- package/lib/browser-electron/settings-route.js +4 -14
- package/lib/browser-electron/settings-store.d.ts +28 -0
- package/lib/browser-electron/settings-store.js +32 -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 +6 -11
- package/lib/browser-electron/system-browser.js +29 -24
- 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 +1045 -7
- package/lib/tool-browser/page-probe.d.ts +86 -0
- package/lib/tool-browser/page-probe.js +460 -0
- package/package.json +5 -3
- package/scripts/run-tests.mjs +32 -0
- package/scripts/verify-preview-route.mjs +19 -1
- package/scripts/verify-runtime-status.mjs +14 -0
- package/skills/dsh-builtin-browser/SKILL.md +64 -0
- package/skills/dsh-builtin-browser/references/batch.md +23 -0
- package/skills/dsh-builtin-browser/references/deliver.md +31 -0
- package/skills/dsh-builtin-browser/references/locate.md +11 -0
- package/skills/dsh-builtin-browser/references/recover.md +11 -0
- package/skills/dsh-builtin-browser/references/verify.md +13 -0
- package/src/browser/runtime.ts +11 -0
- package/src/browser/types.ts +19 -0
- package/src/browser-electron/authenticated-route.ts +56 -0
- 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 +8 -18
- package/src/browser-electron/bridge-install.ts +253 -0
- package/src/browser-electron/bridge-maintenance.ts +161 -0
- package/src/browser-electron/bridge-status.ts +76 -26
- package/src/browser-electron/desktop-bridge-host.ts +60 -26
- package/src/browser-electron/desktop-identity.ts +18 -9
- package/src/browser-electron/electron-provision.ts +35 -14
- package/src/browser-electron/entry.ts +152 -62
- 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 +40 -34
- 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 +106 -22
- package/src/browser-electron/remote-host.ts +23 -23
- package/src/browser-electron/runtime-route.ts +3 -5
- package/src/browser-electron/runtime-status.ts +56 -19
- package/src/browser-electron/settings-route.ts +9 -32
- package/src/browser-electron/settings-store.ts +59 -3
- package/src/browser-electron/sidebar-only-host.ts +199 -0
- package/src/browser-electron/system-browser.ts +26 -23
- package/src/browser-electron/timing.ts +16 -0
- package/src/browser-electron/windows-system.ts +23 -0
- package/src/tool-browser/index.ts +995 -10
- package/src/tool-browser/page-probe.ts +474 -0
|
@@ -0,0 +1,426 @@
|
|
|
1
|
+
/** User-requested Windows maintenance, coordinated outside the Desktop process tree. */
|
|
2
|
+
import { execFile, spawn } from 'node:child_process';
|
|
3
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
4
|
+
import { mkdir, open, readFile, rename, stat as statAsync, unlink, writeFile } from 'node:fs/promises';
|
|
5
|
+
import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path';
|
|
6
|
+
import { fileURLToPath } from 'node:url';
|
|
7
|
+
import { prepareBridgeMaintenance } from './bridge-maintenance.js';
|
|
8
|
+
import { launchMaintenanceBroker } from './maintenance-broker.js';
|
|
9
|
+
import { runMaintenanceLifecycle } from './maintenance-lifecycle.js';
|
|
10
|
+
import { defaultInstallerPath, runBridgeAction, waitForRestartedBridge } from './bridge-install.js';
|
|
11
|
+
import { readDesktopIdentity } from './desktop-identity.js';
|
|
12
|
+
import { dshHome } from './paths.js';
|
|
13
|
+
import { encodePowerShellScript, windowsPowerShellPath } from './windows-system.js';
|
|
14
|
+
const terminal = new Set(['completed', 'failed', 'cancelled']);
|
|
15
|
+
const workerPath = fileURLToPath(new URL('./automatic-maintenance.js', import.meta.url));
|
|
16
|
+
const quitPath = fileURLToPath(new URL('../../desktop-bridge/request-desktop-quit.ps1', import.meta.url));
|
|
17
|
+
const progressPath = fileURLToPath(new URL('../../desktop-bridge/maintenance-progress.ps1', import.meta.url));
|
|
18
|
+
const delay = async (ms) => await new Promise(resolve => setTimeout(resolve, ms));
|
|
19
|
+
/** A swallowed maintenance write still deserves one line of diagnostics; it never changes the answer. */
|
|
20
|
+
function reportMaintenanceFailure(label, error) {
|
|
21
|
+
console.error(`[dsh-browser maintenance] ${label}: ${String(error)}`);
|
|
22
|
+
}
|
|
23
|
+
function homePath() { return resolve(dshHome()); }
|
|
24
|
+
function basePath(home = homePath()) { return join(home, 'dsh-builtin-browser-host', 'maintenance'); }
|
|
25
|
+
function inside(base, path) {
|
|
26
|
+
const part = relative(base, path);
|
|
27
|
+
return part !== '' && !isAbsolute(part) && part !== '..' && !part.startsWith('..\\') && !part.startsWith('../');
|
|
28
|
+
}
|
|
29
|
+
function requireLiveWindows() {
|
|
30
|
+
if (process.platform !== 'win32')
|
|
31
|
+
throw new Error('automatic bridge maintenance requires Windows Desktop');
|
|
32
|
+
if (process.env.DSH_BROWSER_TEST === '1' || process.env.NODE_TEST_CONTEXT !== undefined) {
|
|
33
|
+
throw new Error('automatic Desktop maintenance is forbidden in a test process');
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
async function execute(command, args, timeout = 15_000, environment) {
|
|
37
|
+
return await new Promise(resolve => {
|
|
38
|
+
execFile(command, [...args], { windowsHide: true, shell: false, encoding: 'utf8', timeout, maxBuffer: 1_048_576,
|
|
39
|
+
...(environment === undefined ? {} : { env: environment }) }, (error, stdout, stderr) => {
|
|
40
|
+
resolve({ code: error === null ? 0 : typeof error.code === 'number' ? error.code : 1, output: `${stdout}\n${stderr}`.trim(), stdout });
|
|
41
|
+
});
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
async function desktopProcesses(root) {
|
|
45
|
+
const script = "$ProgressPreference='SilentlyContinue'; $ErrorActionPreference='Stop'; [Console]::OutputEncoding=[System.Text.UTF8Encoding]::new($false); $rows = @((Get-CimInstance Win32_Process -Filter \"Name='DeepSeek Harness.exe'\" -ErrorAction Stop) | ForEach-Object { @{pid=[int]$_.ProcessId;path=$_.ExecutablePath;command=$_.CommandLine;started=$_.CreationDate.ToUniversalTime().ToString('o')} }); ConvertTo-Json -InputObject $rows -Compress";
|
|
46
|
+
const r = await execute(windowsPowerShellPath(), ['-NoProfile', '-NonInteractive', '-EncodedCommand', encodePowerShellScript(script)]);
|
|
47
|
+
if (r.code !== 0)
|
|
48
|
+
throw new Error('cannot inspect running DSH Desktop processes');
|
|
49
|
+
let value;
|
|
50
|
+
try {
|
|
51
|
+
value = JSON.parse(r.stdout.replace(/^\uFEFF/, '').trim());
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
throw new Error('Desktop process inspection returned invalid data');
|
|
55
|
+
}
|
|
56
|
+
const rows = Array.isArray(value) ? value : value === null ? [] : [value];
|
|
57
|
+
const expected = resolve(root, 'DeepSeek Harness.exe').toLowerCase();
|
|
58
|
+
return rows.filter((row) => {
|
|
59
|
+
if (row === null || typeof row !== 'object')
|
|
60
|
+
throw new Error('Desktop process inspection was incomplete');
|
|
61
|
+
const p = row;
|
|
62
|
+
if (typeof p.path !== 'string' || p.path === '' || typeof p.command !== 'string' || !Number.isSafeInteger(p.pid) || typeof p.started !== 'string') {
|
|
63
|
+
throw new Error('cannot identify a running DSH Desktop process');
|
|
64
|
+
}
|
|
65
|
+
if (resolve(p.path).toLowerCase() !== expected)
|
|
66
|
+
return false;
|
|
67
|
+
// The Desktop also ships a Node-mode CLI under this exe; it is not a GUI to close.
|
|
68
|
+
return !/(?:^|\s)--expose-internals(?:\s|$)|\.[cm]?js(?:"|\s|$)|(?:^|\s)(?:--eval|--print|--input-type)(?:=|\s|$)|(?:^|\s)-(?:e|p)(?:\s|$)/i.test(p.command);
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
async function atomicJson(path, value, exclusive = false) {
|
|
72
|
+
if (exclusive && existsSync(path)) {
|
|
73
|
+
const error = new Error(`EEXIST: ${path} already exists`);
|
|
74
|
+
error.code = 'EEXIST';
|
|
75
|
+
throw error;
|
|
76
|
+
}
|
|
77
|
+
const temp = `${path}.${String(process.pid)}.tmp`;
|
|
78
|
+
await writeFile(temp, JSON.stringify(value, null, 2) + '\n', { mode: 0o600 });
|
|
79
|
+
await rename(temp, path);
|
|
80
|
+
}
|
|
81
|
+
/** Data-only argv for the independent, read-only progress window. This function starts nothing. */
|
|
82
|
+
export function maintenanceProgressLaunchOptions(jobId, directory, locale = 'zh', powershellPath = windowsPowerShellPath()) {
|
|
83
|
+
if (typeof jobId !== 'string' || !/^(?:install|uninstall)-[A-Za-z0-9]+$/.test(jobId)
|
|
84
|
+
|| typeof directory !== 'string' || !isAbsolute(directory) || basename(directory) !== jobId
|
|
85
|
+
|| !['zh', 'en'].includes(locale))
|
|
86
|
+
throw new Error('invalid maintenance progress request');
|
|
87
|
+
return {
|
|
88
|
+
runtimePath: powershellPath,
|
|
89
|
+
args: ['-NoLogo', '-NoProfile', '-NonInteractive', '-STA', '-ExecutionPolicy', 'Bypass', '-File', progressPath,
|
|
90
|
+
'-StatePath', join(directory, 'state.json'), '-JobId', jobId, '-Locale', locale],
|
|
91
|
+
cwd: directory,
|
|
92
|
+
environment: { ELECTRON_RUN_AS_NODE: undefined },
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Attempt the optional window once per job, after commit and before requesting normal Desktop quit.
|
|
97
|
+
* A missing helper, denied broker or diagnostic write cannot change the maintenance outcome.
|
|
98
|
+
*/
|
|
99
|
+
export async function startMaintenanceProgressNotification(options, deps = {}) {
|
|
100
|
+
let directory;
|
|
101
|
+
let result;
|
|
102
|
+
try {
|
|
103
|
+
const request = maintenanceProgressLaunchOptions(options.jobId, options.directory, options.locale ?? 'zh', (deps.powershellPath ?? windowsPowerShellPath)());
|
|
104
|
+
directory = options.directory;
|
|
105
|
+
try {
|
|
106
|
+
const claim = await open(join(directory, 'progress-notification.claim'), 'wx', 0o600);
|
|
107
|
+
await claim.close();
|
|
108
|
+
}
|
|
109
|
+
catch (error) {
|
|
110
|
+
if (error.code === 'EEXIST')
|
|
111
|
+
return { started: false, skipped: true, at: new Date().toISOString() };
|
|
112
|
+
throw error;
|
|
113
|
+
}
|
|
114
|
+
if (!(deps.helperExists ?? existsSync)(progressPath))
|
|
115
|
+
throw new Error('the packaged maintenance progress window is unavailable');
|
|
116
|
+
const launched = await (deps.launch ?? launchMaintenanceBroker)(request);
|
|
117
|
+
result = { started: true, at: new Date().toISOString(), pid: launched.pid };
|
|
118
|
+
}
|
|
119
|
+
catch (error) {
|
|
120
|
+
result = { started: false, at: new Date().toISOString(), error: String(error) };
|
|
121
|
+
}
|
|
122
|
+
if (directory !== undefined) {
|
|
123
|
+
await atomicJson(join(directory, 'progress-notification.json'), { ...result, jobId: options.jobId })
|
|
124
|
+
.catch(error => reportMaintenanceFailure('cannot write the progress notification', error));
|
|
125
|
+
}
|
|
126
|
+
return result;
|
|
127
|
+
}
|
|
128
|
+
/** Last durable outcome survives both the settings page and the HTTP host restarting. */
|
|
129
|
+
export function readAutomaticMaintenance(home = homePath()) {
|
|
130
|
+
try {
|
|
131
|
+
const base = basePath(home);
|
|
132
|
+
const pointer = JSON.parse(readFileSync(join(base, 'latest.json'), 'utf8'));
|
|
133
|
+
if (typeof pointer.id !== 'string' || typeof pointer.directory !== 'string' || !inside(base, pointer.directory)
|
|
134
|
+
|| basename(pointer.directory) !== pointer.id)
|
|
135
|
+
return undefined;
|
|
136
|
+
const state = JSON.parse(readFileSync(join(pointer.directory, 'state.json'), 'utf8'));
|
|
137
|
+
if (state.id !== pointer.id || !['armed', 'closing', 'installing', 'restarting', 'verifying', ...terminal].includes(state.phase)
|
|
138
|
+
|| !['install', 'uninstall'].includes(state.action) || !Number.isFinite(Date.parse(state.at)))
|
|
139
|
+
return undefined;
|
|
140
|
+
return state;
|
|
141
|
+
}
|
|
142
|
+
catch {
|
|
143
|
+
return undefined;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
/** A lock left behind by a killed worker never releases itself; clear only clearly stale ones. */
|
|
147
|
+
async function clearStaleLock(lockPath, home) {
|
|
148
|
+
try {
|
|
149
|
+
const info = await statAsync(lockPath);
|
|
150
|
+
// Never touch a lock another request may still be preparing (concurrent start window).
|
|
151
|
+
if (Date.now() - info.mtimeMs < 5 * 60_000)
|
|
152
|
+
return false;
|
|
153
|
+
const id = (await readFile(lockPath, 'utf8')).trim();
|
|
154
|
+
if (!/^(?:install|uninstall)-[A-Za-z0-9]+$/.test(id))
|
|
155
|
+
return false;
|
|
156
|
+
const prior = readAutomaticMaintenance(home);
|
|
157
|
+
if (prior === undefined || prior.id !== id)
|
|
158
|
+
return true;
|
|
159
|
+
if (terminal.has(prior.phase))
|
|
160
|
+
return true;
|
|
161
|
+
const pid = Number(prior.workerPid);
|
|
162
|
+
if (Number.isSafeInteger(pid) && pid > 0) {
|
|
163
|
+
try {
|
|
164
|
+
process.kill(pid, 0);
|
|
165
|
+
}
|
|
166
|
+
catch (error) {
|
|
167
|
+
if (error.code === 'ESRCH')
|
|
168
|
+
return true;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
return false;
|
|
172
|
+
}
|
|
173
|
+
catch (error) {
|
|
174
|
+
reportMaintenanceFailure('cannot inspect a stale maintenance lock', error);
|
|
175
|
+
return false;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
async function releaseLock(plan) {
|
|
179
|
+
const lock = join(basePath(plan.home), 'active.lock');
|
|
180
|
+
try {
|
|
181
|
+
if ((await readFile(lock, 'utf8')).trim() === plan.id)
|
|
182
|
+
await unlink(lock);
|
|
183
|
+
}
|
|
184
|
+
catch { /* no other job's lock is touched */ }
|
|
185
|
+
}
|
|
186
|
+
/** Validate the staged plan again in the independent process before it can request a quit. */
|
|
187
|
+
function validatePlan(value, path, now = Date.now()) {
|
|
188
|
+
if (value === null || typeof value !== 'object')
|
|
189
|
+
throw new Error('invalid automatic maintenance plan');
|
|
190
|
+
const plan = value;
|
|
191
|
+
const created = typeof plan.createdAt === 'string' ? Date.parse(plan.createdAt) : NaN;
|
|
192
|
+
if (plan.version !== 1 || !['install', 'uninstall'].includes(plan.action)
|
|
193
|
+
|| typeof plan.id !== 'string' || !/^(?:install|uninstall)-[A-Za-z0-9]+$/.test(plan.id)
|
|
194
|
+
|| ![plan.root, plan.home, plan.nodePath, plan.directory].every(p => typeof p === 'string' && isAbsolute(p))
|
|
195
|
+
|| typeof plan.electronNode !== 'boolean' || !Number.isFinite(created) || created > now || now - created > 30_000
|
|
196
|
+
|| (plan.locale !== undefined && !['zh', 'en'].includes(plan.locale))) {
|
|
197
|
+
throw new Error('invalid or expired automatic maintenance plan');
|
|
198
|
+
}
|
|
199
|
+
const checked = plan;
|
|
200
|
+
if (!inside(basePath(checked.home), checked.directory) || dirname(checked.directory) !== basePath(checked.home)
|
|
201
|
+
|| basename(checked.directory) !== checked.id || checked.id.split('-')[0] !== checked.action
|
|
202
|
+
|| resolve(path) !== join(checked.directory, 'automatic.json') || !readDesktopIdentity(checked.root).ok) {
|
|
203
|
+
throw new Error('invalid automatic maintenance plan paths or target');
|
|
204
|
+
}
|
|
205
|
+
const target = checked.target;
|
|
206
|
+
if (target === null || typeof target !== 'object' || !Number.isSafeInteger(target.pid) || target.pid <= 0
|
|
207
|
+
|| typeof target.path !== 'string' || resolve(target.path).toLowerCase() !== join(checked.root, 'DeepSeek Harness.exe').toLowerCase()
|
|
208
|
+
|| typeof target.command !== 'string' || /(?:^|\s)--type(?:=|\s)/i.test(target.command)
|
|
209
|
+
|| typeof target.started !== 'string' || !Number.isFinite(Date.parse(target.started)) || Date.parse(target.started) > now) {
|
|
210
|
+
throw new Error('invalid automatic maintenance target process');
|
|
211
|
+
}
|
|
212
|
+
return checked;
|
|
213
|
+
}
|
|
214
|
+
/** Commit only the armed job after its accepted HTTP response has finished writing. */
|
|
215
|
+
export async function commitAutomaticMaintenance(jobId, home = homePath()) {
|
|
216
|
+
if (typeof jobId !== 'string' || !/^(?:install|uninstall)-[A-Za-z0-9]+$/.test(jobId))
|
|
217
|
+
throw new Error('invalid bridge maintenance job id');
|
|
218
|
+
const state = readAutomaticMaintenance(home);
|
|
219
|
+
if (state?.id !== jobId || state.phase !== 'armed' || !Number.isSafeInteger(state.workerPid) || Number(state.workerPid) <= 0) {
|
|
220
|
+
throw new Error('the bridge maintenance job is no longer armed');
|
|
221
|
+
}
|
|
222
|
+
const directory = join(basePath(home), jobId);
|
|
223
|
+
const planPath = join(directory, 'automatic.json');
|
|
224
|
+
const plan = validatePlan(JSON.parse(await readFile(planPath, 'utf8')), planPath);
|
|
225
|
+
if (plan.home !== resolve(home) || plan.action !== state.action || existsSync(join(directory, 'cancel.json'))) {
|
|
226
|
+
throw new Error('the bridge maintenance job cannot be committed');
|
|
227
|
+
}
|
|
228
|
+
try {
|
|
229
|
+
await atomicJson(join(directory, 'commit.json'), { id: jobId, workerPid: state.workerPid, at: new Date().toISOString() }, true);
|
|
230
|
+
}
|
|
231
|
+
catch (error) {
|
|
232
|
+
// The worker is polling this file; cancel it at once instead of leaving a successful-looking
|
|
233
|
+
// 202 to turn into a generic "not committed" twenty seconds later. An EEXIST is a duplicate
|
|
234
|
+
// commit of an already-approved job, not a failure: cancelling it would abort good work.
|
|
235
|
+
if (error.code !== 'EEXIST') {
|
|
236
|
+
await atomicJson(join(directory, 'cancel.json'), { at: new Date().toISOString(), reason: String(error) }).catch(() => { });
|
|
237
|
+
}
|
|
238
|
+
throw error;
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
/** Only the new, authenticated explicit-click endpoint calls this function. */
|
|
242
|
+
export async function startAutomaticMaintenance(action, root, options = {}) {
|
|
243
|
+
requireLiveWindows();
|
|
244
|
+
if (!['install', 'uninstall'].includes(action))
|
|
245
|
+
throw new Error('invalid bridge maintenance action');
|
|
246
|
+
if (options.locale !== undefined && !['zh', 'en'].includes(options.locale))
|
|
247
|
+
throw new Error('invalid bridge maintenance locale');
|
|
248
|
+
if (!readDesktopIdentity(root).ok)
|
|
249
|
+
throw new Error('the maintenance target is not a verified DSH Desktop installation');
|
|
250
|
+
if (!existsSync(quitPath))
|
|
251
|
+
throw new Error('the packaged Desktop quit helper is missing');
|
|
252
|
+
const processes = await desktopProcesses(root);
|
|
253
|
+
const mains = processes.filter(p => !/(?:^|\s)--type(?:=|\s)/i.test(p.command));
|
|
254
|
+
if (mains.length !== 1)
|
|
255
|
+
throw new Error('automatic maintenance requires one running DSH Desktop window');
|
|
256
|
+
const home = homePath();
|
|
257
|
+
const base = basePath(home);
|
|
258
|
+
await mkdir(base, { recursive: true, mode: 0o700 });
|
|
259
|
+
const lockPath = join(base, 'active.lock');
|
|
260
|
+
let lock;
|
|
261
|
+
try {
|
|
262
|
+
lock = await open(lockPath, 'wx', 0o600);
|
|
263
|
+
}
|
|
264
|
+
catch {
|
|
265
|
+
if (!(await clearStaleLock(lockPath, home)))
|
|
266
|
+
throw new Error('bridge maintenance is already in progress');
|
|
267
|
+
await unlink(lockPath).catch(error => reportMaintenanceFailure('cannot remove a stale maintenance lock', error));
|
|
268
|
+
lock = await open(lockPath, 'wx', 0o600);
|
|
269
|
+
}
|
|
270
|
+
let plan;
|
|
271
|
+
try {
|
|
272
|
+
const prepared = await prepareBridgeMaintenance(action, root, { directory: base });
|
|
273
|
+
const original = JSON.parse(await readFile(prepared.planPath, 'utf8'));
|
|
274
|
+
const id = basename(prepared.directory);
|
|
275
|
+
await lock.writeFile(id + '\n');
|
|
276
|
+
await lock.close();
|
|
277
|
+
plan = { version: 1, id, action, root: resolve(root), nodePath: original.nodePath, electronNode: original.electronNode,
|
|
278
|
+
home, directory: prepared.directory, target: mains[0], createdAt: new Date().toISOString(),
|
|
279
|
+
...options.locale === undefined ? {} : { locale: options.locale } };
|
|
280
|
+
const path = join(prepared.directory, 'automatic.json');
|
|
281
|
+
await writeFile(path, JSON.stringify(plan, null, 2) + '\n', { flag: 'wx', mode: 0o600 });
|
|
282
|
+
await atomicJson(join(base, 'latest.json'), { id, directory: prepared.directory });
|
|
283
|
+
const launched = await launchMaintenanceBroker({ runtimePath: plan.nodePath,
|
|
284
|
+
args: [...plan.electronNode ? ['--expose-internals'] : [], workerPath, '--automatic-maintenance', path], cwd: prepared.directory,
|
|
285
|
+
environment: { DSH_HOME: home, ELECTRON_RUN_AS_NODE: plan.electronNode ? '1' : undefined } });
|
|
286
|
+
// WMI's return code proves creation only. The worker must actually load and publish its arm.
|
|
287
|
+
const deadline = Date.now() + 12_000;
|
|
288
|
+
while (Date.now() < deadline) {
|
|
289
|
+
const state = readAutomaticMaintenance(home);
|
|
290
|
+
if (state?.id === id && state.workerPid === launched.pid) {
|
|
291
|
+
if (state.phase !== 'armed')
|
|
292
|
+
throw new Error(state.error ?? 'the maintenance worker did not arm');
|
|
293
|
+
return state;
|
|
294
|
+
}
|
|
295
|
+
await delay(100);
|
|
296
|
+
}
|
|
297
|
+
throw new Error('the independent maintenance worker did not become ready');
|
|
298
|
+
}
|
|
299
|
+
catch (error) {
|
|
300
|
+
await lock.close().catch(error => reportMaintenanceFailure('cannot close the maintenance lock', error));
|
|
301
|
+
if (plan !== undefined) {
|
|
302
|
+
await atomicJson(join(plan.directory, 'cancel.json'), { at: new Date().toISOString() })
|
|
303
|
+
.catch(error => reportMaintenanceFailure('cannot stage the maintenance cancellation', error));
|
|
304
|
+
await atomicJson(join(plan.directory, 'state.json'), { id: plan.id, action, phase: 'failed', ok: false, restarted: false,
|
|
305
|
+
at: new Date().toISOString(), startedAt: plan.createdAt, error: String(error) })
|
|
306
|
+
.catch(writeError => reportMaintenanceFailure('cannot record the failed maintenance state', writeError));
|
|
307
|
+
await releaseLock(plan);
|
|
308
|
+
}
|
|
309
|
+
else {
|
|
310
|
+
await unlink(lockPath).catch(error => reportMaintenanceFailure('cannot remove the unused maintenance lock', error));
|
|
311
|
+
}
|
|
312
|
+
throw error;
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
async function runWorker(path) {
|
|
316
|
+
requireLiveWindows();
|
|
317
|
+
const plan = validatePlan(JSON.parse(await readFile(path, 'utf8')), path);
|
|
318
|
+
const checkCancelled = () => {
|
|
319
|
+
if (existsSync(join(plan.directory, 'cancel.json')))
|
|
320
|
+
throw new Error('bridge maintenance was cancelled before Desktop exited');
|
|
321
|
+
};
|
|
322
|
+
process.env.DSH_HOME = plan.home;
|
|
323
|
+
const publish = async (state) => {
|
|
324
|
+
// If the host gave up on this job (readiness timeout), its terminal state wins. Without this
|
|
325
|
+
// a late worker flips "failed" back to "armed" and the settings page oscillates.
|
|
326
|
+
const prior = readAutomaticMaintenance(plan.home);
|
|
327
|
+
if (prior?.id === plan.id && terminal.has(prior.phase))
|
|
328
|
+
return;
|
|
329
|
+
await atomicJson(join(plan.directory, 'state.json'), { ...state, id: plan.id, workerPid: process.pid, startedAt: plan.createdAt });
|
|
330
|
+
};
|
|
331
|
+
try {
|
|
332
|
+
checkCancelled();
|
|
333
|
+
await runMaintenanceLifecycle(plan.action, {
|
|
334
|
+
publish,
|
|
335
|
+
requestQuit: async () => {
|
|
336
|
+
// Arming proves the worker is independent and loaded. It grants no permission to quit
|
|
337
|
+
// until the original request's response has finished and its host commits this exact job.
|
|
338
|
+
const deadline = Date.now() + 20_000;
|
|
339
|
+
let committed = false;
|
|
340
|
+
while (Date.now() < deadline) {
|
|
341
|
+
checkCancelled();
|
|
342
|
+
try {
|
|
343
|
+
const record = JSON.parse(await readFile(join(plan.directory, 'commit.json'), 'utf8'));
|
|
344
|
+
if (record.id !== plan.id || record.workerPid !== process.pid || typeof record.at !== 'string' || !Number.isFinite(Date.parse(record.at))) {
|
|
345
|
+
throw new Error('invalid bridge maintenance commit');
|
|
346
|
+
}
|
|
347
|
+
committed = true;
|
|
348
|
+
break;
|
|
349
|
+
}
|
|
350
|
+
catch (error) {
|
|
351
|
+
// An empty or half-written commit.json is a transient state, not a cancellation.
|
|
352
|
+
if (error.code !== 'ENOENT' && !(error instanceof SyntaxError))
|
|
353
|
+
throw error;
|
|
354
|
+
}
|
|
355
|
+
await delay(100);
|
|
356
|
+
}
|
|
357
|
+
if (!committed)
|
|
358
|
+
throw new Error('the maintenance request was not committed; Desktop remains open');
|
|
359
|
+
checkCancelled();
|
|
360
|
+
await publish({ phase: 'closing', action: plan.action, at: new Date().toISOString() });
|
|
361
|
+
await startMaintenanceProgressNotification({ jobId: plan.id, directory: plan.directory, locale: plan.locale ?? 'zh' });
|
|
362
|
+
const result = await execute(windowsPowerShellPath(), ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', quitPath,
|
|
363
|
+
'-TargetPid', String(plan.target.pid), '-ExpectedExecutable', plan.target.path,
|
|
364
|
+
'-ExpectedStartTimeUtc', plan.target.started, '-TimeoutSeconds', '20'], 25_000);
|
|
365
|
+
checkCancelled();
|
|
366
|
+
if (result.code !== 0)
|
|
367
|
+
throw new Error(result.output || 'the official Desktop Quit menu was not available');
|
|
368
|
+
},
|
|
369
|
+
waitUntilClosed: async () => {
|
|
370
|
+
const deadline = Date.now() + 60_000;
|
|
371
|
+
while (Date.now() < deadline) {
|
|
372
|
+
checkCancelled();
|
|
373
|
+
if ((await desktopProcesses(plan.root)).length === 0)
|
|
374
|
+
return;
|
|
375
|
+
await delay(1_000);
|
|
376
|
+
}
|
|
377
|
+
throw new Error('Desktop did not exit; maintenance was cancelled. Any running-task confirmation remains under your control.');
|
|
378
|
+
},
|
|
379
|
+
maintain: async () => {
|
|
380
|
+
checkCancelled();
|
|
381
|
+
if ((await desktopProcesses(plan.root)).length > 0)
|
|
382
|
+
throw new Error('DSH Desktop was reopened during maintenance; refusing to modify its files');
|
|
383
|
+
return await runBridgeAction(plan.action, plan.root, {
|
|
384
|
+
node: () => plan.nodePath, installer: defaultInstallerPath, trackResult: true,
|
|
385
|
+
run: async (cmd, args, extra) => await execute(cmd, [...plan.electronNode ? ['--expose-internals'] : [], ...args], 180_000, { ...process.env, ...extra, ELECTRON_RUN_AS_NODE: plan.electronNode ? '1' : undefined }),
|
|
386
|
+
});
|
|
387
|
+
},
|
|
388
|
+
restart: async () => {
|
|
389
|
+
if ((await desktopProcesses(plan.root)).length > 0)
|
|
390
|
+
throw new Error('DSH Desktop is already running; not opening a second instance');
|
|
391
|
+
const identity = readDesktopIdentity(plan.root);
|
|
392
|
+
if (!identity.ok)
|
|
393
|
+
throw new Error(`Desktop cannot be safely reopened: ${identity.reason}`);
|
|
394
|
+
const environment = { ...process.env };
|
|
395
|
+
for (const key of Object.keys(environment))
|
|
396
|
+
if (key.toUpperCase() === 'ELECTRON_RUN_AS_NODE' || key.toUpperCase().startsWith('DSH_BRIDGE_'))
|
|
397
|
+
delete environment[key];
|
|
398
|
+
return await new Promise((resolve, reject) => {
|
|
399
|
+
const child = spawn(join(plan.root, 'DeepSeek Harness.exe'), [], { cwd: plan.root, env: environment, stdio: 'ignore', windowsHide: true, detached: true });
|
|
400
|
+
child.once('error', reject);
|
|
401
|
+
child.once('spawn', () => { child.unref(); resolve(child.pid); });
|
|
402
|
+
});
|
|
403
|
+
},
|
|
404
|
+
verify: async (pid, action) => {
|
|
405
|
+
if (action === 'install') {
|
|
406
|
+
await waitForRestartedBridge(pid, { timeoutMs: 45_000 });
|
|
407
|
+
return;
|
|
408
|
+
}
|
|
409
|
+
await delay(1_500);
|
|
410
|
+
if (!(await desktopProcesses(plan.root)).some(p => p.pid === pid))
|
|
411
|
+
throw new Error('the reopened Desktop did not remain running');
|
|
412
|
+
},
|
|
413
|
+
});
|
|
414
|
+
}
|
|
415
|
+
catch (error) {
|
|
416
|
+
await publish({ phase: 'cancelled', action: plan.action, at: new Date().toISOString(), ok: false, restarted: false, error: String(error) })
|
|
417
|
+
.catch(writeError => reportMaintenanceFailure('cannot publish the cancelled maintenance state', writeError));
|
|
418
|
+
}
|
|
419
|
+
finally {
|
|
420
|
+
await releaseLock(plan);
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
// Importing this module only exposes functions. Execution requires the private staged plan.
|
|
424
|
+
if (process.argv[2] === '--automatic-maintenance' && process.argv[1] !== undefined && resolve(process.argv[1]) === workerPath) {
|
|
425
|
+
void runWorker(resolve(process.argv[3] ?? '')).catch(error => { console.error(String(error)); process.exitCode = 1; });
|
|
426
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import type { BridgeStatus } from './bridge-status.js';
|
|
2
|
+
import type { BrowserChannel } from './system-browser.js';
|
|
3
|
+
/** What the last automatic attempt was, and for which desktop build. */
|
|
4
|
+
export interface AutoInstallMarker {
|
|
5
|
+
/** Desktop build the attempt belonged to (`version` from the identity check when known). */
|
|
6
|
+
readonly build: string;
|
|
7
|
+
/** ISO timestamp of the attempt, recorded BEFORE running, so a crash still counts. */
|
|
8
|
+
readonly attemptedAt: string;
|
|
9
|
+
/** Outcome recorded afterwards, for the panel and for support: `started` / `installed` / a reason. */
|
|
10
|
+
readonly outcome: string;
|
|
11
|
+
}
|
|
12
|
+
/** Everything the decision needs, so it can be tested without a filesystem or a shell. */
|
|
13
|
+
export interface AutoInstallInput {
|
|
14
|
+
/** The launcher's current profile name, rather than an installed Desktop found on disk. */
|
|
15
|
+
readonly profile: string | undefined;
|
|
16
|
+
/** Only sidebar and automatic selection need the desktop bridge. */
|
|
17
|
+
readonly channel: BrowserChannel;
|
|
18
|
+
/** Quiet mode preserves the current desktop session instead of restarting it implicitly. */
|
|
19
|
+
readonly quiet: boolean;
|
|
20
|
+
/** The desktop install directory, or undefined when this is the web end. */
|
|
21
|
+
readonly installRoot: string | undefined;
|
|
22
|
+
/** Whether the operator left automatic installation on. */
|
|
23
|
+
readonly enabled: boolean;
|
|
24
|
+
/** The reading the panel would show. */
|
|
25
|
+
readonly status: BridgeStatus;
|
|
26
|
+
/** The last attempt, when one is recorded. */
|
|
27
|
+
readonly marker: AutoInstallMarker | undefined;
|
|
28
|
+
/** How long an attempt for the same build suppresses the next one. */
|
|
29
|
+
readonly cooldownMs: number;
|
|
30
|
+
/** Current time, injected. */
|
|
31
|
+
readonly now: number;
|
|
32
|
+
}
|
|
33
|
+
/** Why the automatic install did or did not run, in words a log line can carry. */
|
|
34
|
+
export interface AutoInstallDecision {
|
|
35
|
+
/** Whether to start the installer now. */
|
|
36
|
+
readonly run: boolean;
|
|
37
|
+
/** The reason, either way. */
|
|
38
|
+
readonly why: string;
|
|
39
|
+
}
|
|
40
|
+
/** Historical attempt-record interval, retained for compatibility with existing diagnostics. */
|
|
41
|
+
export declare const AUTO_INSTALL_COOLDOWN_MS: number;
|
|
42
|
+
/**
|
|
43
|
+
* Report that runtime bridge installation is deferred to explicit maintenance.
|
|
44
|
+
*
|
|
45
|
+
* @param input - the readings described by {@link AutoInstallInput}.
|
|
46
|
+
* @returns whether to run, and why.
|
|
47
|
+
*/
|
|
48
|
+
export declare function autoInstallDecision(_input: AutoInstallInput): AutoInstallDecision;
|
|
49
|
+
/**
|
|
50
|
+
* Read the profile identity supplied by DSH's launcher before plugins mount.
|
|
51
|
+
* A Desktop installation or Electron executable can also belong to a Web/CLI invocation,
|
|
52
|
+
* so neither is used to infer the current surface.
|
|
53
|
+
* @param ctx - plugin context; older or custom compositions may omit the profile service.
|
|
54
|
+
* @returns the current profile name, or undefined when the launcher did not provide it.
|
|
55
|
+
*/
|
|
56
|
+
export declare function readAutoInstallProfile(ctx: unknown): string | undefined;
|
|
57
|
+
/** A manual uninstall could not record the operator's automatic-install opt-out. */
|
|
58
|
+
export declare class BridgeAutoInstallPreferenceError extends Error {
|
|
59
|
+
constructor(cause: unknown);
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Preserve an explicit uninstall as an automatic-install opt-out in historical settings.
|
|
63
|
+
* The preference is written before the installer starts, so a failed write cannot launch maintenance.
|
|
64
|
+
* A failed uninstall retains the opt-out; an explicit install leaves an existing opt-out unchanged.
|
|
65
|
+
* @param action - the authenticated user's selected action.
|
|
66
|
+
* @param update - persist the operator's bridge preference.
|
|
67
|
+
* @param run - perform the installer action after its preference is durable.
|
|
68
|
+
* @returns the installer's result.
|
|
69
|
+
*/
|
|
70
|
+
export declare function runWithManualBridgePreference<T>(action: 'install' | 'uninstall', update: (patch: {
|
|
71
|
+
readonly bridge: {
|
|
72
|
+
readonly autoInstall: false;
|
|
73
|
+
};
|
|
74
|
+
}) => unknown, run: () => Promise<T>): Promise<T>;
|
|
75
|
+
/** Where the attempt record lives, beside the settings the plugin already owns. */
|
|
76
|
+
export declare function autoInstallMarkerPath(dshHome: string): string;
|
|
77
|
+
/**
|
|
78
|
+
* Read the last attempt.
|
|
79
|
+
*
|
|
80
|
+
* A record that cannot be parsed is treated as absent: the guard exists to prevent loops, and a single
|
|
81
|
+
* extra attempt after a corrupt file is cheaper than refusing to ever install again.
|
|
82
|
+
* @param path - marker file path.
|
|
83
|
+
* @returns the marker, or undefined.
|
|
84
|
+
*/
|
|
85
|
+
export declare function readAutoInstallMarker(path: string): AutoInstallMarker | undefined;
|
|
86
|
+
/**
|
|
87
|
+
* Record an attempt. Written before the installer runs: if the shell is killed mid-install, the next
|
|
88
|
+
* launch must still see that an attempt happened rather than starting another restart.
|
|
89
|
+
* @param path - marker file path.
|
|
90
|
+
* @param marker - what to record.
|
|
91
|
+
* @returns whether the record was saved; callers skip automatic restarts without a durable guard.
|
|
92
|
+
*/
|
|
93
|
+
export declare function writeAutoInstallMarker(path: string, marker: AutoInstallMarker): boolean;
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Compatibility for historical automatic-install settings and explicit bridge-maintenance intent.
|
|
3
|
+
* Runtime automatic installation is disabled. Bridge maintenance requires the user to close DSH
|
|
4
|
+
* Desktop before explicitly running the installer; loading a plugin never changes the installation.
|
|
5
|
+
* Historical marker readers remain available for diagnostics.
|
|
6
|
+
* @module dsh-browser/browser-electron/bridge-auto
|
|
7
|
+
*/
|
|
8
|
+
import { existsSync, mkdirSync, readFileSync } from 'node:fs';
|
|
9
|
+
import { dirname, join } from 'node:path';
|
|
10
|
+
import { writeFileAtomic } from './settings-store.js';
|
|
11
|
+
/** Historical attempt-record interval, retained for compatibility with existing diagnostics. */
|
|
12
|
+
export const AUTO_INSTALL_COOLDOWN_MS = 24 * 60 * 60 * 1_000;
|
|
13
|
+
/**
|
|
14
|
+
* Report that runtime bridge installation is deferred to explicit maintenance.
|
|
15
|
+
*
|
|
16
|
+
* @param input - the readings described by {@link AutoInstallInput}.
|
|
17
|
+
* @returns whether to run, and why.
|
|
18
|
+
*/
|
|
19
|
+
export function autoInstallDecision(_input) {
|
|
20
|
+
return { run: false, why: 'runtime automatic bridge installation is disabled; close DSH Desktop and run bridge maintenance explicitly' };
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Read the profile identity supplied by DSH's launcher before plugins mount.
|
|
24
|
+
* A Desktop installation or Electron executable can also belong to a Web/CLI invocation,
|
|
25
|
+
* so neither is used to infer the current surface.
|
|
26
|
+
* @param ctx - plugin context; older or custom compositions may omit the profile service.
|
|
27
|
+
* @returns the current profile name, or undefined when the launcher did not provide it.
|
|
28
|
+
*/
|
|
29
|
+
export function readAutoInstallProfile(ctx) {
|
|
30
|
+
try {
|
|
31
|
+
const context = ctx;
|
|
32
|
+
if (typeof context?.get !== 'function')
|
|
33
|
+
return undefined;
|
|
34
|
+
const profile = context.get('profileContext');
|
|
35
|
+
return typeof profile?.name === 'string' ? profile.name : undefined;
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
return undefined;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
/** A manual uninstall could not record the operator's automatic-install opt-out. */
|
|
42
|
+
export class BridgeAutoInstallPreferenceError extends Error {
|
|
43
|
+
constructor(cause) {
|
|
44
|
+
super(`could not save automatic bridge installation preference: ${String(cause)}`, { cause });
|
|
45
|
+
this.name = 'BridgeAutoInstallPreferenceError';
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Preserve an explicit uninstall as an automatic-install opt-out in historical settings.
|
|
50
|
+
* The preference is written before the installer starts, so a failed write cannot launch maintenance.
|
|
51
|
+
* A failed uninstall retains the opt-out; an explicit install leaves an existing opt-out unchanged.
|
|
52
|
+
* @param action - the authenticated user's selected action.
|
|
53
|
+
* @param update - persist the operator's bridge preference.
|
|
54
|
+
* @param run - perform the installer action after its preference is durable.
|
|
55
|
+
* @returns the installer's result.
|
|
56
|
+
*/
|
|
57
|
+
export async function runWithManualBridgePreference(action, update, run) {
|
|
58
|
+
if (action === 'uninstall') {
|
|
59
|
+
try {
|
|
60
|
+
update({ bridge: { autoInstall: false } });
|
|
61
|
+
}
|
|
62
|
+
catch (error) {
|
|
63
|
+
throw new BridgeAutoInstallPreferenceError(error);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
return await run();
|
|
67
|
+
}
|
|
68
|
+
/** Where the attempt record lives, beside the settings the plugin already owns. */
|
|
69
|
+
export function autoInstallMarkerPath(dshHome) {
|
|
70
|
+
return join(dshHome, 'dsh-builtin-browser-host', 'bridge-auto-install.json');
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Read the last attempt.
|
|
74
|
+
*
|
|
75
|
+
* A record that cannot be parsed is treated as absent: the guard exists to prevent loops, and a single
|
|
76
|
+
* extra attempt after a corrupt file is cheaper than refusing to ever install again.
|
|
77
|
+
* @param path - marker file path.
|
|
78
|
+
* @returns the marker, or undefined.
|
|
79
|
+
*/
|
|
80
|
+
export function readAutoInstallMarker(path) {
|
|
81
|
+
if (!existsSync(path))
|
|
82
|
+
return undefined;
|
|
83
|
+
try {
|
|
84
|
+
const parsed = JSON.parse(readFileSync(path, 'utf8'));
|
|
85
|
+
if (typeof parsed.build !== 'string' || typeof parsed.attemptedAt !== 'string')
|
|
86
|
+
return undefined;
|
|
87
|
+
return {
|
|
88
|
+
build: parsed.build,
|
|
89
|
+
attemptedAt: parsed.attemptedAt,
|
|
90
|
+
outcome: typeof parsed.outcome === 'string' ? parsed.outcome : 'unknown',
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
catch {
|
|
94
|
+
return undefined;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Record an attempt. Written before the installer runs: if the shell is killed mid-install, the next
|
|
99
|
+
* launch must still see that an attempt happened rather than starting another restart.
|
|
100
|
+
* @param path - marker file path.
|
|
101
|
+
* @param marker - what to record.
|
|
102
|
+
* @returns whether the record was saved; callers skip automatic restarts without a durable guard.
|
|
103
|
+
*/
|
|
104
|
+
export function writeAutoInstallMarker(path, marker) {
|
|
105
|
+
try {
|
|
106
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
107
|
+
writeFileAtomic(path, `${JSON.stringify(marker, null, 2)}\n`);
|
|
108
|
+
return true;
|
|
109
|
+
}
|
|
110
|
+
catch {
|
|
111
|
+
return false;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
@@ -39,8 +39,6 @@ export declare class BridgeConnection {
|
|
|
39
39
|
/** Ids of the requests sent on the current socket, oldest first. */
|
|
40
40
|
private readonly queue;
|
|
41
41
|
private nextId;
|
|
42
|
-
/** True once any reply arrived without an id: this bridge does not echo request ids. */
|
|
43
|
-
private idLessBridge;
|
|
44
42
|
/** True once this connection may only have one request in flight at a time. */
|
|
45
43
|
private serialisable;
|
|
46
44
|
/** True once the shell behind this connection has been reported gone. */
|