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
package/docs/user-guide.md
CHANGED
|
@@ -9,6 +9,10 @@
|
|
|
9
9
|
|
|
10
10
|
## 安装
|
|
11
11
|
|
|
12
|
+
选择 **DSH 侧栏** 后,打开网址会显示目标会话、展开侧栏,并使用该会话的浏览器页面。已有页面继续使用,新增标签各自对应独立的原生标签。连接中断后继续重连所选侧栏。
|
|
13
|
+
|
|
14
|
+
**安静模式** 保留系统前台窗口和鼠标位置,同时支持上述打开网址与显式切换标签操作。文字和按键发送到指定页面,侧栏下载使用页面所属浏览器会话中的登录状态。
|
|
15
|
+
|
|
12
16
|
```sh
|
|
13
17
|
# 从 npm 安装(已发布);`--profile` 换成你实际使用的 profile(DSH Desktop 为 `desktop`)
|
|
14
18
|
dsh plugin --profile web add dsh-builtin-browser
|
|
@@ -40,10 +44,28 @@ dsh plugin --profile web add <本仓库路径>
|
|
|
40
44
|
| --- | --- | --- |
|
|
41
45
|
| 已安装(桌面端正在运行) | 补丁在,进程也在应答 | 无 |
|
|
42
46
|
| 已安装,但桌面端没在运行 | 补丁在,进程不在 —— **最常见** | 打开桌面端 |
|
|
43
|
-
| 未安装 / 已失效 |
|
|
47
|
+
| 未安装 / 已失效 | 桥接组件缺失,或被桌面端升级覆盖 | 点击安装桥接或修复桥接 |
|
|
44
48
|
|
|
45
49
|
差别是实打实的:安装状态写在磁盘上,重启也不会变;能应答的是**此刻在跑的那个进程**,它发布的端点(端口 + pid + 每 15 秒一次的刷新)才是活的证据。只按磁盘判,面板会在桌面端早已关掉时说"可用"。
|
|
46
50
|
|
|
51
|
+
**桥接管理位于 Windows 桌面端设置 → 浏览器**:未安装时提供安装并重启,失效时提供修复并重启,已安装时提供重新安装并重启。诊断中提供卸载并重启和外部终端命令。点击后独立维护进程调用 DSH 原生菜单的退出动作,等待目标进程全部退出,再进行文件维护和重新启动。
|
|
52
|
+
|
|
53
|
+
安装、修复和重装均通过新进程发布的桥接端点和鉴权连接验证后确认成功。维护阶段和结果保存到 DSH 数据目录,桌面端重启后可以继续查看。DSH 对进行中的任务保留自身的退出确认;取消退出或等待超时会取消维护,保留当前安装。安装失败后维护进程尝试重新打开桌面端,并保留原始失败结果。
|
|
54
|
+
|
|
55
|
+
点击维护按钮后会立即显示准备状态。桌面端退出期间,独立进度窗继续显示当前阶段和总用时,完成后自动收起。进度窗跟随界面语言并保持后台显示;关闭进度窗时维护继续运行。维护失败或取消时,窗口保留简短结果,详细原因可在浏览器设置的诊断中查看。
|
|
56
|
+
|
|
57
|
+
插件启动时的桥接自动安装已关闭,`bridge.autoInstall` 默认值为 `false`;旧配置中的 `true` 也按显式维护流程处理。手动卸载先保存自动安装关闭的偏好,再执行卸载。
|
|
58
|
+
|
|
59
|
+
外部终端中运行 `node desktop-bridge/install.mjs "<安装目录>"` 完成维护后,手动启动 DSH Desktop。若使用 Windows 的 `install-and-start.cmd`,也应先正常退出桌面端;该入口仅在目标已关闭时安装并启动。旧版由宿主内的安装调用关闭、强制终止或转交后台重启的流程已由上述退出后维护流程替代。
|
|
60
|
+
|
|
61
|
+
想先确认"能不能装"而不关应用,跑一次只读预检:
|
|
62
|
+
|
|
63
|
+
```sh
|
|
64
|
+
node node_modules/dsh-builtin-browser/desktop-bridge/install.mjs "<DSH Desktop 安装目录>" --preflight
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
它只验身份、不写任何东西,输出 `{"ok":true,"layout":"packed","packageName":"@deepseek-ai/dsh-desktop","version":"…"}`。桌面端升级会把 `resources/app` 重新打包成 `app.asar`,这时预检仍然通过(归档内的 `package.json`、`app.asar.unpacked/package.json`、或产品自身的 exe 都算证据);预检被拒时,面板和命令行给出的是同一条原因。
|
|
68
|
+
|
|
47
69
|
**DSH rc.5 使用 pnpm 11.7 的 `strict-dep-builds`。** 本插件不再声明 `postinstall`,所以正常安装不会出现构建脚本审批提示;若仍有别的包需要审批,请在宿主原生插件管理器中审阅。插件不会自行改写 `allowBuilds`。
|
|
48
70
|
|
|
49
71
|
需要在安装阶段就把运行时准备好(离线部署、CI 镜像),或要手工重试下载时,进入**安装本插件的 profile 目录**(通常为 `$DSH_HOME/profiles/web` 或 `$DSH_HOME/profiles/desktop`),运行本插件已经安装的本地命令:
|
|
@@ -81,10 +103,12 @@ npx --no dsh-browser-install-electron
|
|
|
81
103
|
|
|
82
104
|
## 操作纪律
|
|
83
105
|
|
|
84
|
-
|
|
106
|
+
**坐标点击与拖拽**位于高级设置,对应 `vision.strategy`,控制 Agent 能否直接传入页面坐标执行点击、连续点击和拖拽:
|
|
107
|
+
|
|
108
|
+
- **允许**(默认,`auto`):按元素和按页面坐标操作均可使用。
|
|
109
|
+
- **禁止**(`nonVisual`):点击使用按钮文字、CSS 或其他元素目标,如 `target { by: "text", value: "Sign in" }`。直接传入坐标点击、连续点击和拖拽会返回 `BROWSER_NON_VISUAL_COORDINATES`。
|
|
85
110
|
|
|
86
|
-
|
|
87
|
-
- **`nonVisual`**:**坐标点击被明确拒绝**,报 `BROWSER_NON_VISUAL_COORDINATES`,错误信息直接给出改法 —— 传语义 target,如 `target { by: "text", value: "Sign in" }`。**这是配置,不是故障,不要重试同一次坐标点击。**
|
|
111
|
+
该设置控制坐标输入许可。模型读取图像的能力由 DSH 所用模型决定,浏览器内的输入通过 CDP 发送。
|
|
88
112
|
|
|
89
113
|
**两种策略下 DOM 查询、无障碍树、文本提取与结构化抓取完全一致** —— 所以下面这些纪律对**所有模型**都成立,不是因为谁看不了图。
|
|
90
114
|
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { type MaintenanceBrokerOptions, type MaintenanceBrokerResult } from './maintenance-broker.js';
|
|
2
|
+
import { type MaintenanceState } from './maintenance-lifecycle.js';
|
|
3
|
+
import { type BridgeAction } from './bridge-install.js';
|
|
4
|
+
export interface AutomaticMaintenanceJob extends MaintenanceState {
|
|
5
|
+
readonly id: string;
|
|
6
|
+
readonly workerPid?: number;
|
|
7
|
+
readonly startedAt?: string;
|
|
8
|
+
}
|
|
9
|
+
export interface AutomaticMaintenanceOptions {
|
|
10
|
+
readonly locale?: 'zh' | 'en';
|
|
11
|
+
}
|
|
12
|
+
export interface MaintenanceProgressOptions {
|
|
13
|
+
readonly jobId: string;
|
|
14
|
+
readonly directory: string;
|
|
15
|
+
readonly locale?: 'zh' | 'en';
|
|
16
|
+
}
|
|
17
|
+
export interface MaintenanceProgressNotification {
|
|
18
|
+
readonly started: boolean;
|
|
19
|
+
readonly at: string;
|
|
20
|
+
readonly pid?: number;
|
|
21
|
+
readonly error?: string;
|
|
22
|
+
readonly skipped?: boolean;
|
|
23
|
+
}
|
|
24
|
+
export interface MaintenanceProgressDeps {
|
|
25
|
+
readonly launch?: (options: MaintenanceBrokerOptions) => Promise<MaintenanceBrokerResult>;
|
|
26
|
+
readonly helperExists?: (path: string) => boolean;
|
|
27
|
+
readonly powershellPath?: () => string;
|
|
28
|
+
}
|
|
29
|
+
/** Data-only argv for the independent, read-only progress window. This function starts nothing. */
|
|
30
|
+
export declare function maintenanceProgressLaunchOptions(jobId: string, directory: string, locale?: 'zh' | 'en', powershellPath?: string): MaintenanceBrokerOptions;
|
|
31
|
+
/**
|
|
32
|
+
* Attempt the optional window once per job, after commit and before requesting normal Desktop quit.
|
|
33
|
+
* A missing helper, denied broker or diagnostic write cannot change the maintenance outcome.
|
|
34
|
+
*/
|
|
35
|
+
export declare function startMaintenanceProgressNotification(options: MaintenanceProgressOptions, deps?: MaintenanceProgressDeps): Promise<MaintenanceProgressNotification>;
|
|
36
|
+
/** Last durable outcome survives both the settings page and the HTTP host restarting. */
|
|
37
|
+
export declare function readAutomaticMaintenance(home?: string): AutomaticMaintenanceJob | undefined;
|
|
38
|
+
/** Commit only the armed job after its accepted HTTP response has finished writing. */
|
|
39
|
+
export declare function commitAutomaticMaintenance(jobId: string, home?: string): Promise<void>;
|
|
40
|
+
/** Only the new, authenticated explicit-click endpoint calls this function. */
|
|
41
|
+
export declare function startAutomaticMaintenance(action: BridgeAction, root: string, options?: AutomaticMaintenanceOptions): Promise<AutomaticMaintenanceJob>;
|
|
@@ -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;
|