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,158 @@
|
|
|
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
|
+
|
|
11
|
+
import type { BridgeStatus } from './bridge-status.js'
|
|
12
|
+
import type { BrowserChannel } from './system-browser.js'
|
|
13
|
+
import { writeFileAtomic } from './settings-store.js'
|
|
14
|
+
|
|
15
|
+
/** What the last automatic attempt was, and for which desktop build. */
|
|
16
|
+
export interface AutoInstallMarker {
|
|
17
|
+
/** Desktop build the attempt belonged to (`version` from the identity check when known). */
|
|
18
|
+
readonly build: string
|
|
19
|
+
/** ISO timestamp of the attempt, recorded BEFORE running, so a crash still counts. */
|
|
20
|
+
readonly attemptedAt: string
|
|
21
|
+
/** Outcome recorded afterwards, for the panel and for support: `started` / `installed` / a reason. */
|
|
22
|
+
readonly outcome: string
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Everything the decision needs, so it can be tested without a filesystem or a shell. */
|
|
26
|
+
export interface AutoInstallInput {
|
|
27
|
+
/** The launcher's current profile name, rather than an installed Desktop found on disk. */
|
|
28
|
+
readonly profile: string | undefined
|
|
29
|
+
/** Only sidebar and automatic selection need the desktop bridge. */
|
|
30
|
+
readonly channel: BrowserChannel
|
|
31
|
+
/** Quiet mode preserves the current desktop session instead of restarting it implicitly. */
|
|
32
|
+
readonly quiet: boolean
|
|
33
|
+
/** The desktop install directory, or undefined when this is the web end. */
|
|
34
|
+
readonly installRoot: string | undefined
|
|
35
|
+
/** Whether the operator left automatic installation on. */
|
|
36
|
+
readonly enabled: boolean
|
|
37
|
+
/** The reading the panel would show. */
|
|
38
|
+
readonly status: BridgeStatus
|
|
39
|
+
/** The last attempt, when one is recorded. */
|
|
40
|
+
readonly marker: AutoInstallMarker | undefined
|
|
41
|
+
/** How long an attempt for the same build suppresses the next one. */
|
|
42
|
+
readonly cooldownMs: number
|
|
43
|
+
/** Current time, injected. */
|
|
44
|
+
readonly now: number
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Why the automatic install did or did not run, in words a log line can carry. */
|
|
48
|
+
export interface AutoInstallDecision {
|
|
49
|
+
/** Whether to start the installer now. */
|
|
50
|
+
readonly run: boolean
|
|
51
|
+
/** The reason, either way. */
|
|
52
|
+
readonly why: string
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Historical attempt-record interval, retained for compatibility with existing diagnostics. */
|
|
56
|
+
export const AUTO_INSTALL_COOLDOWN_MS = 24 * 60 * 60 * 1_000
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Report that runtime bridge installation is deferred to explicit maintenance.
|
|
60
|
+
*
|
|
61
|
+
* @param input - the readings described by {@link AutoInstallInput}.
|
|
62
|
+
* @returns whether to run, and why.
|
|
63
|
+
*/
|
|
64
|
+
export function autoInstallDecision(_input: AutoInstallInput): AutoInstallDecision {
|
|
65
|
+
return { run: false, why: 'runtime automatic bridge installation is disabled; close DSH Desktop and run bridge maintenance explicitly' }
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Read the profile identity supplied by DSH's launcher before plugins mount.
|
|
70
|
+
* A Desktop installation or Electron executable can also belong to a Web/CLI invocation,
|
|
71
|
+
* so neither is used to infer the current surface.
|
|
72
|
+
* @param ctx - plugin context; older or custom compositions may omit the profile service.
|
|
73
|
+
* @returns the current profile name, or undefined when the launcher did not provide it.
|
|
74
|
+
*/
|
|
75
|
+
export function readAutoInstallProfile(ctx: unknown): string | undefined {
|
|
76
|
+
try {
|
|
77
|
+
const context = ctx as { get?: (name: string) => unknown }
|
|
78
|
+
if (typeof context?.get !== 'function') return undefined
|
|
79
|
+
const profile = context.get('profileContext') as { name?: unknown } | undefined
|
|
80
|
+
return typeof profile?.name === 'string' ? profile.name : undefined
|
|
81
|
+
} catch {
|
|
82
|
+
return undefined
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** A manual uninstall could not record the operator's automatic-install opt-out. */
|
|
87
|
+
export class BridgeAutoInstallPreferenceError extends Error {
|
|
88
|
+
constructor(cause: unknown) {
|
|
89
|
+
super(`could not save automatic bridge installation preference: ${String(cause)}`, { cause })
|
|
90
|
+
this.name = 'BridgeAutoInstallPreferenceError'
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Preserve an explicit uninstall as an automatic-install opt-out in historical settings.
|
|
96
|
+
* The preference is written before the installer starts, so a failed write cannot launch maintenance.
|
|
97
|
+
* A failed uninstall retains the opt-out; an explicit install leaves an existing opt-out unchanged.
|
|
98
|
+
* @param action - the authenticated user's selected action.
|
|
99
|
+
* @param update - persist the operator's bridge preference.
|
|
100
|
+
* @param run - perform the installer action after its preference is durable.
|
|
101
|
+
* @returns the installer's result.
|
|
102
|
+
*/
|
|
103
|
+
export async function runWithManualBridgePreference<T>(
|
|
104
|
+
action: 'install' | 'uninstall',
|
|
105
|
+
update: (patch: { readonly bridge: { readonly autoInstall: false } }) => unknown,
|
|
106
|
+
run: () => Promise<T>,
|
|
107
|
+
): Promise<T> {
|
|
108
|
+
if (action === 'uninstall') {
|
|
109
|
+
try { update({ bridge: { autoInstall: false } }) }
|
|
110
|
+
catch (error) { throw new BridgeAutoInstallPreferenceError(error) }
|
|
111
|
+
}
|
|
112
|
+
return await run()
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** Where the attempt record lives, beside the settings the plugin already owns. */
|
|
116
|
+
export function autoInstallMarkerPath(dshHome: string): string {
|
|
117
|
+
return join(dshHome, 'dsh-builtin-browser-host', 'bridge-auto-install.json')
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Read the last attempt.
|
|
122
|
+
*
|
|
123
|
+
* A record that cannot be parsed is treated as absent: the guard exists to prevent loops, and a single
|
|
124
|
+
* extra attempt after a corrupt file is cheaper than refusing to ever install again.
|
|
125
|
+
* @param path - marker file path.
|
|
126
|
+
* @returns the marker, or undefined.
|
|
127
|
+
*/
|
|
128
|
+
export function readAutoInstallMarker(path: string): AutoInstallMarker | undefined {
|
|
129
|
+
if (!existsSync(path)) return undefined
|
|
130
|
+
try {
|
|
131
|
+
const parsed = JSON.parse(readFileSync(path, 'utf8')) as Partial<AutoInstallMarker>
|
|
132
|
+
if (typeof parsed.build !== 'string' || typeof parsed.attemptedAt !== 'string') return undefined
|
|
133
|
+
return {
|
|
134
|
+
build: parsed.build,
|
|
135
|
+
attemptedAt: parsed.attemptedAt,
|
|
136
|
+
outcome: typeof parsed.outcome === 'string' ? parsed.outcome : 'unknown',
|
|
137
|
+
}
|
|
138
|
+
} catch {
|
|
139
|
+
return undefined
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Record an attempt. Written before the installer runs: if the shell is killed mid-install, the next
|
|
145
|
+
* launch must still see that an attempt happened rather than starting another restart.
|
|
146
|
+
* @param path - marker file path.
|
|
147
|
+
* @param marker - what to record.
|
|
148
|
+
* @returns whether the record was saved; callers skip automatic restarts without a durable guard.
|
|
149
|
+
*/
|
|
150
|
+
export function writeAutoInstallMarker(path: string, marker: AutoInstallMarker): boolean {
|
|
151
|
+
try {
|
|
152
|
+
mkdirSync(dirname(path), { recursive: true })
|
|
153
|
+
writeFileAtomic(path, `${JSON.stringify(marker, null, 2)}\n`)
|
|
154
|
+
return true
|
|
155
|
+
} catch {
|
|
156
|
+
return false
|
|
157
|
+
}
|
|
158
|
+
}
|
|
@@ -93,8 +93,6 @@ export class BridgeConnection {
|
|
|
93
93
|
/** Ids of the requests sent on the current socket, oldest first. */
|
|
94
94
|
private readonly queue: number[] = []
|
|
95
95
|
private nextId = 1
|
|
96
|
-
/** True once any reply arrived without an id: this bridge does not echo request ids. */
|
|
97
|
-
private idLessBridge = false
|
|
98
96
|
/** True once this connection may only have one request in flight at a time. */
|
|
99
97
|
private serialisable = false
|
|
100
98
|
/** True once the shell behind this connection has been reported gone. */
|
|
@@ -299,7 +297,6 @@ export class BridgeConnection {
|
|
|
299
297
|
// from the right one. Remember that this bridge does not echo ids, and serialise every
|
|
300
298
|
// later call so the ambiguity cannot arise again.
|
|
301
299
|
if (echoed === undefined) {
|
|
302
|
-
this.idLessBridge = true
|
|
303
300
|
this.serialisable = true
|
|
304
301
|
}
|
|
305
302
|
try {
|
|
@@ -356,7 +353,8 @@ function endpointExpired(updatedAt: unknown): boolean {
|
|
|
356
353
|
return Date.now() - at > ENDPOINT_TTL_MS
|
|
357
354
|
}
|
|
358
355
|
|
|
359
|
-
/** The request id a raw answer line echoes back, when it carries one. */
|
|
356
|
+
/** The request id a raw answer line echoes back, when it carries one. */
|
|
357
|
+
function echoOf(line: string): number | undefined {
|
|
360
358
|
try {
|
|
361
359
|
const answer = JSON.parse(line) as Record<string, unknown>
|
|
362
360
|
const value = answer[REQUEST_ID_FIELD]
|
|
@@ -24,6 +24,7 @@ import { existsSync, readFileSync, statSync } from 'node:fs'
|
|
|
24
24
|
|
|
25
25
|
import { ENDPOINT_STALE_AFTER_MS } from './bridge-connection.js'
|
|
26
26
|
import { bridgeEndpointPath } from './desktop-bridge-host.js'
|
|
27
|
+
import { pidAlive } from './process.js'
|
|
27
28
|
|
|
28
29
|
/** What the panel needs to know about the running shell. */
|
|
29
30
|
export interface BridgeEndpointState {
|
|
@@ -37,24 +38,6 @@ export interface BridgeEndpointState {
|
|
|
37
38
|
readonly updatedAt?: string
|
|
38
39
|
}
|
|
39
40
|
|
|
40
|
-
/**
|
|
41
|
-
* Whether a pid is alive, without signalling it.
|
|
42
|
-
*
|
|
43
|
-
* Signal 0 performs the permission and existence checks and delivers nothing. `EPERM` means the
|
|
44
|
-
* process exists and belongs to someone else, which is still "alive" for this purpose.
|
|
45
|
-
* @param pid - the process id from the endpoint file.
|
|
46
|
-
* @returns whether that process exists.
|
|
47
|
-
*/
|
|
48
|
-
function pidAlive(pid: number): boolean {
|
|
49
|
-
if (!Number.isSafeInteger(pid) || pid <= 0) return false
|
|
50
|
-
try {
|
|
51
|
-
process.kill(pid, 0)
|
|
52
|
-
return true
|
|
53
|
-
} catch (error) {
|
|
54
|
-
return (error as NodeJS.ErrnoException)?.code === 'EPERM'
|
|
55
|
-
}
|
|
56
|
-
}
|
|
57
|
-
|
|
58
41
|
/**
|
|
59
42
|
* Read the endpoint the shell publishes.
|
|
60
43
|
*
|
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Install, repair or remove the desktop bridge from the settings panel.
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
* user has to diagnose. The installer already knows how to do the whole dance unattended
|
|
8
|
-
* (`--restart --yes`), so the panel calls it and reports what happened.
|
|
9
|
-
*
|
|
10
|
-
* What this deliberately does NOT do: invent its own patching. Every path, backup and identity check
|
|
11
|
-
* stays inside `desktop-bridge/install.mjs`, which is the same file a human would run.
|
|
4
|
+
* Maintenance changes files after the target Desktop has exited. The installer checks this before
|
|
5
|
+
* writing; the panel never asks it to close or restart its own host. The same packaged installer
|
|
6
|
+
* owns identity checks, backups and patching for both the panel and an external terminal.
|
|
12
7
|
* @module dsh-browser/browser-electron/bridge-install
|
|
13
8
|
*/
|
|
14
9
|
import { spawn } from 'node:child_process'
|
|
10
|
+
import { mkdtemp, readFile } from 'node:fs/promises'
|
|
11
|
+
import { tmpdir } from 'node:os'
|
|
12
|
+
import { join } from 'node:path'
|
|
15
13
|
import { fileURLToPath } from 'node:url'
|
|
14
|
+
import { BridgeConnection } from './bridge-connection.js'
|
|
15
|
+
import { bridgeEndpointPath } from './paths.js'
|
|
16
16
|
|
|
17
17
|
/** What the panel may ask for. */
|
|
18
18
|
export type BridgeAction = 'install' | 'uninstall'
|
|
@@ -20,16 +20,22 @@ export type BridgeAction = 'install' | 'uninstall'
|
|
|
20
20
|
/** Everything this module touches from outside, so a test can drive it without spawning. */
|
|
21
21
|
export interface BridgeActionDeps {
|
|
22
22
|
/** Runs the installer; resolves with an exit code and the tail of its output. */
|
|
23
|
-
readonly run: (command: string, argv: readonly string[]) => Promise<{ readonly code: number | null; readonly output: string }>
|
|
23
|
+
readonly run: (command: string, argv: readonly string[], environment?: Readonly<Record<string, string>>) => Promise<{ readonly code: number | null; readonly output: string }>
|
|
24
24
|
/** Absolute path of the packaged installer. */
|
|
25
25
|
readonly installer: () => string
|
|
26
26
|
/** Node executable used to run it (the host's own, so no PATH surprises). */
|
|
27
27
|
readonly node: () => string
|
|
28
|
+
/** Follow the installer's atomic completion file. */
|
|
29
|
+
readonly trackResult?: boolean
|
|
30
|
+
/** Completion budget, injectable for a fast failure test. */
|
|
31
|
+
readonly resultTimeoutMs?: number
|
|
32
|
+
/** Poll interval for the installer's atomic completion file. */
|
|
33
|
+
readonly resultPollMs?: number
|
|
28
34
|
}
|
|
29
35
|
|
|
30
36
|
/** What the panel is told. */
|
|
31
37
|
export interface BridgeActionResult {
|
|
32
|
-
/** Whether the
|
|
38
|
+
/** Whether the requested file maintenance completed successfully. */
|
|
33
39
|
readonly ok: boolean
|
|
34
40
|
/** Its exit code, or null when it was killed. */
|
|
35
41
|
readonly code: number | null
|
|
@@ -37,13 +43,105 @@ export interface BridgeActionResult {
|
|
|
37
43
|
readonly output: string
|
|
38
44
|
/** The exact command line, so a failure can be reproduced by hand. */
|
|
39
45
|
readonly command: string
|
|
46
|
+
/** Persisted completion and installer output, retained for diagnosis. */
|
|
47
|
+
readonly resultFile?: string
|
|
48
|
+
readonly logFile?: string
|
|
49
|
+
readonly restarted?: boolean
|
|
50
|
+
readonly pid?: number
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Final record written by the installer that actually performed the operation. */
|
|
54
|
+
export interface BridgeActionCompletion {
|
|
55
|
+
readonly action: BridgeAction
|
|
56
|
+
readonly ok: boolean
|
|
57
|
+
readonly code: number
|
|
58
|
+
readonly restarted: boolean
|
|
59
|
+
readonly pid?: number
|
|
60
|
+
readonly error?: string
|
|
61
|
+
readonly completedAt: string
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Read-only startup verification, with a private endpoint path available to isolated tests. */
|
|
65
|
+
export interface BridgeReadyOptions {
|
|
66
|
+
readonly endpointPath?: string
|
|
67
|
+
readonly timeoutMs?: number
|
|
68
|
+
readonly pollMs?: number
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Verify that the restarted process published a working authenticated bridge.
|
|
73
|
+
* A previous shell's endpoint, a listening socket, or an authentication refusal is insufficient.
|
|
74
|
+
*/
|
|
75
|
+
export async function waitForRestartedBridge(pid: number, options: BridgeReadyOptions = {}): Promise<void> {
|
|
76
|
+
const path = options.endpointPath ?? bridgeEndpointPath()
|
|
77
|
+
const timeoutMs = options.timeoutMs ?? 30_000
|
|
78
|
+
const deadline = Date.now() + timeoutMs
|
|
79
|
+
while (Date.now() < deadline) {
|
|
80
|
+
try {
|
|
81
|
+
const endpoint = JSON.parse(await readFile(path, 'utf8')) as { port?: unknown; token?: unknown; pid?: unknown }
|
|
82
|
+
if (endpoint !== null && typeof endpoint === 'object' && endpoint.pid === pid
|
|
83
|
+
&& Number.isInteger(endpoint.port) && Number(endpoint.port) > 0 && Number(endpoint.port) <= 65535
|
|
84
|
+
&& typeof endpoint.token === 'string' && endpoint.token.trim() !== '') {
|
|
85
|
+
const remaining = deadline - Date.now()
|
|
86
|
+
if (remaining <= 0) break
|
|
87
|
+
const connection = new BridgeConnection({ port: Number(endpoint.port), token: endpoint.token, pid })
|
|
88
|
+
try {
|
|
89
|
+
const answer = await connection.call({ op: 'list' }, Math.min(1_000, remaining))
|
|
90
|
+
if (answer.ok === true && Array.isArray(answer.guests) && Array.isArray(answer.sidebar)) return
|
|
91
|
+
} finally { connection.close() }
|
|
92
|
+
}
|
|
93
|
+
} catch {
|
|
94
|
+
// Endpoint publication and the socket can race startup. Diagnostics deliberately exclude
|
|
95
|
+
// the endpoint body and authentication token; the caller retains the installer's own log.
|
|
96
|
+
}
|
|
97
|
+
const remaining = deadline - Date.now()
|
|
98
|
+
if (remaining > 0) await new Promise(resolve => setTimeout(resolve, Math.min(options.pollMs ?? 100, remaining)))
|
|
99
|
+
}
|
|
100
|
+
throw new Error(`the restarted DSH Desktop bridge did not become ready within ${String(timeoutMs)}ms`)
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Wait for completed file maintenance. The installer publishes this file by rename so a reader
|
|
105
|
+
* cannot accept a partial result. A panel operation must report no Desktop restart.
|
|
106
|
+
*/
|
|
107
|
+
export async function waitForBridgeActionCompletion(
|
|
108
|
+
path: string,
|
|
109
|
+
action: BridgeAction,
|
|
110
|
+
timeoutMs = 180_000,
|
|
111
|
+
pollMs = 100,
|
|
112
|
+
): Promise<BridgeActionCompletion> {
|
|
113
|
+
const deadline = Date.now() + timeoutMs
|
|
114
|
+
for (;;) {
|
|
115
|
+
let text: string | undefined
|
|
116
|
+
try { text = await readFile(path, 'utf8') } catch (error) {
|
|
117
|
+
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
|
|
118
|
+
}
|
|
119
|
+
if (text !== undefined) {
|
|
120
|
+
let record: Partial<BridgeActionCompletion>
|
|
121
|
+
try { record = JSON.parse(text) as Partial<BridgeActionCompletion> } catch {
|
|
122
|
+
throw new Error('the bridge installer wrote an unreadable completion record')
|
|
123
|
+
}
|
|
124
|
+
if (record === null || typeof record !== 'object'
|
|
125
|
+
|| record.action !== action || typeof record.ok !== 'boolean'
|
|
126
|
+
|| !Number.isSafeInteger(record.code) || record.restarted !== false
|
|
127
|
+
|| typeof record.completedAt !== 'string' || !Number.isFinite(Date.parse(record.completedAt))
|
|
128
|
+
|| record.pid !== undefined
|
|
129
|
+
|| (record.error !== undefined && typeof record.error !== 'string')
|
|
130
|
+
|| (record.ok !== (record.code === 0))) {
|
|
131
|
+
throw new Error('the bridge installer wrote an invalid completion record')
|
|
132
|
+
}
|
|
133
|
+
return record as BridgeActionCompletion
|
|
134
|
+
}
|
|
135
|
+
if (Date.now() >= deadline) throw new Error(`the bridge installer did not report completion within ${String(timeoutMs)}ms`)
|
|
136
|
+
await new Promise(resolve => setTimeout(resolve, Math.min(pollMs, Math.max(1, deadline - Date.now()))))
|
|
137
|
+
}
|
|
40
138
|
}
|
|
41
139
|
|
|
42
140
|
/**
|
|
43
141
|
* The argv the installer expects, in one place so the panel and a human run the same thing.
|
|
44
142
|
*
|
|
45
|
-
*
|
|
46
|
-
*
|
|
143
|
+
* The target Desktop must already be closed. In particular, the panel cannot grant its child
|
|
144
|
+
* permission to terminate the process that owns the current tool call or settings request.
|
|
47
145
|
* @param action - install/repair, or restore the pre-bridge state.
|
|
48
146
|
* @param installRoot - the desktop install directory that was discovered.
|
|
49
147
|
* @returns argv for the installer.
|
|
@@ -51,7 +149,6 @@ export interface BridgeActionResult {
|
|
|
51
149
|
export function bridgeActionArgv(action: BridgeAction, installRoot: string): string[] {
|
|
52
150
|
const argv = [installRoot]
|
|
53
151
|
if (action === 'uninstall') argv.push('--revert')
|
|
54
|
-
argv.push('--restart', '--yes')
|
|
55
152
|
return argv
|
|
56
153
|
}
|
|
57
154
|
|
|
@@ -67,16 +164,19 @@ function tail(text: string, limit = 600): string {
|
|
|
67
164
|
}
|
|
68
165
|
|
|
69
166
|
/** Default runner: the host's own node, a bounded wait, and no shell (so a path with spaces is data). */
|
|
70
|
-
function defaultRun(command: string, argv: readonly string[]): Promise<{ code: number | null; output: string }> {
|
|
167
|
+
function defaultRun(command: string, argv: readonly string[], environment?: Readonly<Record<string, string>>): Promise<{ code: number | null; output: string }> {
|
|
71
168
|
return new Promise(resolve => {
|
|
72
|
-
const child = spawn(command, [...argv], {
|
|
169
|
+
const child = spawn(command, [...argv], {
|
|
170
|
+
stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true,
|
|
171
|
+
env: environment === undefined ? process.env : { ...process.env, ...environment },
|
|
172
|
+
})
|
|
73
173
|
let output = ''
|
|
74
174
|
const collect = (chunk: unknown): void => { output += String(chunk); if (output.length > 20_000) output = output.slice(-20_000) }
|
|
75
175
|
child.stdout?.on('data', collect)
|
|
76
176
|
child.stderr?.on('data', collect)
|
|
77
177
|
const timer = setTimeout(() => { try { child.kill() } catch { /* already gone */ } }, 180_000)
|
|
78
178
|
child.on('error', error => { clearTimeout(timer); resolve({ code: null, output: `${output}\nfailed to start: ${String(error)}` }) })
|
|
79
|
-
child.on('
|
|
179
|
+
child.on('close', code => { clearTimeout(timer); resolve({ code, output }) })
|
|
80
180
|
})
|
|
81
181
|
}
|
|
82
182
|
|
|
@@ -93,11 +193,24 @@ function defaultRun(command: string, argv: readonly string[]): Promise<{ code: n
|
|
|
93
193
|
export async function runBridgeAction(
|
|
94
194
|
action: BridgeAction,
|
|
95
195
|
installRoot: string,
|
|
96
|
-
deps: BridgeActionDeps = {
|
|
196
|
+
deps: BridgeActionDeps = {
|
|
197
|
+
run: defaultRun, installer: defaultInstallerPath, node: () => process.execPath, trackResult: true,
|
|
198
|
+
},
|
|
97
199
|
): Promise<BridgeActionResult> {
|
|
98
200
|
const command = deps.node()
|
|
99
201
|
const argv = [deps.installer(), ...bridgeActionArgv(action, installRoot)]
|
|
100
202
|
const printable = [command, ...argv].map(part => (/\s/.test(part) ? `"${part}"` : part)).join(' ')
|
|
203
|
+
let resultFile: string | undefined
|
|
204
|
+
let logFile: string | undefined
|
|
205
|
+
let installerOutput = ''
|
|
206
|
+
const recordedOutput = async (): Promise<string> => {
|
|
207
|
+
if (logFile === undefined) return ''
|
|
208
|
+
try { return (await readFile(logFile, 'utf8')).slice(-20_000) }
|
|
209
|
+
catch (error) {
|
|
210
|
+
console.error(`[dsh-browser] cannot read the installer log: ${String(error)}`)
|
|
211
|
+
return ''
|
|
212
|
+
}
|
|
213
|
+
}
|
|
101
214
|
try {
|
|
102
215
|
// Ask the installer to check identity FIRST, without touching anything. It is the same preflight
|
|
103
216
|
// a human can run, and it turns "the button did nothing" into a named reason.
|
|
@@ -114,9 +227,27 @@ export async function runBridgeAction(
|
|
|
114
227
|
command: printable,
|
|
115
228
|
}
|
|
116
229
|
}
|
|
117
|
-
|
|
118
|
-
|
|
230
|
+
let environment: Record<string, string> | undefined
|
|
231
|
+
const deadline = Date.now() + (deps.resultTimeoutMs ?? 180_000)
|
|
232
|
+
if (deps.trackResult === true) {
|
|
233
|
+
const directory = await mkdtemp(join(tmpdir(), 'dsh-bridge-action-'))
|
|
234
|
+
resultFile = join(directory, 'result.json')
|
|
235
|
+
logFile = join(directory, 'installer.log')
|
|
236
|
+
environment = { DSH_BRIDGE_ACTION_RESULT_FILE: resultFile, DSH_BRIDGE_ACTION_LOG_FILE: logFile }
|
|
237
|
+
}
|
|
238
|
+
const result = await deps.run(command, argv, environment)
|
|
239
|
+
installerOutput = result.output
|
|
240
|
+
if (result.code !== 0 || resultFile === undefined) {
|
|
241
|
+
return { ok: result.code === 0, code: result.code, output: tail(result.output), command: printable, restarted: false,
|
|
242
|
+
...resultFile === undefined ? {} : { resultFile, logFile } }
|
|
243
|
+
}
|
|
244
|
+
const final = await waitForBridgeActionCompletion(resultFile, action, Math.max(0, deadline - Date.now()), deps.resultPollMs)
|
|
245
|
+
const output = [installerOutput, await recordedOutput(), final.error].filter(Boolean).join('\n')
|
|
246
|
+
return { ok: final.ok, code: final.code, output: tail(output), command: printable, resultFile, logFile,
|
|
247
|
+
restarted: final.restarted, ...final.pid === undefined ? {} : { pid: final.pid } }
|
|
119
248
|
} catch (error) {
|
|
120
|
-
return { ok: false, code: null,
|
|
249
|
+
return { ok: false, code: null,
|
|
250
|
+
output: tail([installerOutput, await recordedOutput(), String(error)].filter(Boolean).join('\n')),
|
|
251
|
+
command: printable, ...resultFile === undefined ? {} : { resultFile, logFile } }
|
|
121
252
|
}
|
|
122
253
|
}
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Prepare Windows bridge maintenance for the user to run after exiting DSH Desktop.
|
|
3
|
+
* Preparation writes a private launcher and plan; it never starts a process or changes Desktop.
|
|
4
|
+
* The current packaged installer performs identity and running-process checks at execution time.
|
|
5
|
+
* @module dsh-browser/browser-electron/bridge-maintenance
|
|
6
|
+
*/
|
|
7
|
+
import { existsSync, realpathSync, statSync } from 'node:fs'
|
|
8
|
+
import { mkdir, mkdtemp, writeFile } from 'node:fs/promises'
|
|
9
|
+
import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path'
|
|
10
|
+
import { fileURLToPath } from 'node:url'
|
|
11
|
+
import { readDesktopIdentity } from './desktop-identity.js'
|
|
12
|
+
import { dshHome as dshHomePath } from './paths.js'
|
|
13
|
+
import type { BridgeAction } from './bridge-install.js'
|
|
14
|
+
|
|
15
|
+
export interface BridgeMaintenanceOptions {
|
|
16
|
+
/** Parent of a new, unique maintenance directory; defaults to the user's DSH home. */
|
|
17
|
+
readonly directory?: string
|
|
18
|
+
/** Explicit Node executable; a verified Desktop executable may be used in Electron Node mode. */
|
|
19
|
+
readonly nodePath?: string
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface PreparedBridgeMaintenance {
|
|
23
|
+
readonly ok: true
|
|
24
|
+
readonly prepared: true
|
|
25
|
+
readonly action: BridgeAction
|
|
26
|
+
readonly path: string
|
|
27
|
+
/** Literal-path invocation for the user's PowerShell terminal. */
|
|
28
|
+
readonly command: string
|
|
29
|
+
readonly commandShell: 'powershell'
|
|
30
|
+
readonly directory: string
|
|
31
|
+
readonly runnerPath: string
|
|
32
|
+
readonly planPath: string
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
interface MaintenancePlan {
|
|
36
|
+
readonly version: 1
|
|
37
|
+
readonly action: BridgeAction
|
|
38
|
+
readonly installRoot: string
|
|
39
|
+
readonly installerPath: string
|
|
40
|
+
readonly nodePath: string
|
|
41
|
+
readonly electronNode: boolean
|
|
42
|
+
readonly dshHome: string
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Batch literals cannot contain these characters; other path content stays in JSON arguments. */
|
|
46
|
+
function checkedPath(value: string, label: string): string {
|
|
47
|
+
if (!isAbsolute(value) || /[\0\r\n"]/.test(value)) throw new Error(`${label} must be an absolute path without quotes or control characters`)
|
|
48
|
+
return resolve(value)
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Escape only a batch literal. Delayed expansion is disabled before a literal is read. */
|
|
52
|
+
function batchLiteral(value: string): string {
|
|
53
|
+
return value.replace(/%/g, '%%')
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function withinOrEqual(root: string, path: string): boolean {
|
|
57
|
+
const part = relative(root, path)
|
|
58
|
+
return part === '' || (!isAbsolute(part) && part !== '..' && !part.startsWith('..\\') && !part.startsWith('../'))
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Resolve existing ancestors before mkdir so a redirected output cannot create files in Desktop. */
|
|
62
|
+
function prospectiveRealPath(path: string): string {
|
|
63
|
+
let ancestor = path
|
|
64
|
+
const missing: string[] = []
|
|
65
|
+
while (!existsSync(ancestor)) {
|
|
66
|
+
const parent = dirname(ancestor)
|
|
67
|
+
if (parent === ancestor) throw new Error('maintenance directory has no existing ancestor')
|
|
68
|
+
missing.unshift(basename(ancestor))
|
|
69
|
+
ancestor = parent
|
|
70
|
+
}
|
|
71
|
+
return resolve(realpathSync(ancestor), ...missing)
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** This runner is deliberately data-driven: paths and actions are never evaluated as shell text. */
|
|
75
|
+
const RUNNER = `import { readFileSync, existsSync } from 'node:fs';
|
|
76
|
+
import { isAbsolute } from 'node:path';
|
|
77
|
+
import { spawnSync } from 'node:child_process';
|
|
78
|
+
const plan = JSON.parse(readFileSync(new URL('./maintenance.json', import.meta.url), 'utf8'));
|
|
79
|
+
if (plan.version !== 1 || !['install', 'uninstall'].includes(plan.action)
|
|
80
|
+
|| ![plan.installRoot, plan.installerPath, plan.nodePath, plan.dshHome].every(value => typeof value === 'string' && isAbsolute(value))
|
|
81
|
+
|| typeof plan.electronNode !== 'boolean') throw new Error('Invalid bridge maintenance plan');
|
|
82
|
+
if (!existsSync(plan.installerPath)) throw new Error('The browser plugin installer is missing. Install or update the plugin and prepare maintenance again.');
|
|
83
|
+
const environment = { ...process.env };
|
|
84
|
+
for (const key of Object.keys(environment)) {
|
|
85
|
+
if (['DSH_BRIDGE_DETACHED', 'DSH_BRIDGE_HANDOFF_PARENT', 'DSH_BRIDGE_ACTION_RESULT_FILE', 'DSH_BRIDGE_ACTION_LOG_FILE', 'ELECTRON_RUN_AS_NODE'].includes(key.toUpperCase())) delete environment[key];
|
|
86
|
+
}
|
|
87
|
+
if (plan.electronNode) environment.ELECTRON_RUN_AS_NODE = '1';
|
|
88
|
+
// Test boundaries and their private home must survive this launcher unchanged.
|
|
89
|
+
if (environment.DSH_BROWSER_TEST !== '1' && environment.NODE_TEST_CONTEXT === undefined) environment.DSH_HOME = plan.dshHome;
|
|
90
|
+
const args = [...(plan.electronNode ? ['--expose-internals'] : []), plan.installerPath, plan.installRoot, ...(plan.action === 'uninstall' ? ['--revert'] : [])];
|
|
91
|
+
const result = spawnSync(plan.nodePath, args, { shell: false, windowsHide: true, stdio: 'inherit', env: environment });
|
|
92
|
+
if (result.error) { console.error('Bridge maintenance could not start: ' + result.error.message); process.exitCode = 1; }
|
|
93
|
+
else process.exitCode = result.status ?? 1;
|
|
94
|
+
`
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Prepare an offline Windows launcher. The target may still be running during preparation.
|
|
98
|
+
* User execution remains subject to the installer's closed-Desktop and ancestry guards.
|
|
99
|
+
*/
|
|
100
|
+
export async function prepareBridgeMaintenance(
|
|
101
|
+
action: BridgeAction,
|
|
102
|
+
installRoot: string,
|
|
103
|
+
options: BridgeMaintenanceOptions = {},
|
|
104
|
+
): Promise<PreparedBridgeMaintenance> {
|
|
105
|
+
if (action !== 'install' && action !== 'uninstall') throw new Error('bridge maintenance action must be install or uninstall')
|
|
106
|
+
const requestedRoot = checkedPath(installRoot, 'Desktop installation')
|
|
107
|
+
const identity = readDesktopIdentity(requestedRoot)
|
|
108
|
+
if (!identity.ok) throw new Error(`cannot prepare bridge maintenance: ${identity.reason}`)
|
|
109
|
+
const target = realpathSync(requestedRoot)
|
|
110
|
+
const installerPath = fileURLToPath(new URL('../../desktop-bridge/install.mjs', import.meta.url))
|
|
111
|
+
if (!existsSync(installerPath)) throw new Error('the packaged bridge installer is missing')
|
|
112
|
+
|
|
113
|
+
const currentIsNode = /^(?:node|node\.exe)$/i.test(basename(process.execPath))
|
|
114
|
+
const selected = options.nodePath ?? (currentIsNode ? process.execPath : join(target, 'DeepSeek Harness.exe'))
|
|
115
|
+
const nodePath = checkedPath(selected, 'Maintenance runtime')
|
|
116
|
+
if (!existsSync(nodePath) || !statSync(nodePath).isFile()) throw new Error('the maintenance runtime does not exist')
|
|
117
|
+
const electronNode = !/^(?:node|node\.exe)$/i.test(basename(nodePath))
|
|
118
|
+
const desktopRuntime = join(target, 'DeepSeek Harness.exe')
|
|
119
|
+
if (electronNode && (!existsSync(desktopRuntime) || realpathSync(nodePath).toLowerCase() !== realpathSync(desktopRuntime).toLowerCase())) {
|
|
120
|
+
throw new Error('the Electron maintenance runtime must belong to the verified Desktop installation')
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const dshHome = checkedPath(dshHomePath(), 'DSH home')
|
|
124
|
+
const testContext = process.env.DSH_BROWSER_TEST === '1' || process.env.NODE_TEST_CONTEXT !== undefined
|
|
125
|
+
if (testContext && options.directory === undefined && process.env.DSH_BRIDGE_TEST_ROOT === undefined) {
|
|
126
|
+
throw new Error('test preparation requires an explicit private maintenance directory')
|
|
127
|
+
}
|
|
128
|
+
const directory = checkedPath(options.directory ?? join(dshHome, 'dsh-builtin-browser-host', 'maintenance'), 'Maintenance directory')
|
|
129
|
+
if (withinOrEqual(target, directory) || withinOrEqual(target, prospectiveRealPath(directory))) {
|
|
130
|
+
throw new Error('maintenance launchers must be stored outside the Desktop installation')
|
|
131
|
+
}
|
|
132
|
+
await mkdir(directory, { recursive: true, mode: 0o700 })
|
|
133
|
+
if (withinOrEqual(target, realpathSync(directory))) throw new Error('maintenance directory resolves inside the Desktop installation')
|
|
134
|
+
const output = await mkdtemp(join(directory, `${action}-`))
|
|
135
|
+
const runnerPath = join(output, 'run-maintenance.mjs')
|
|
136
|
+
const planPath = join(output, 'maintenance.json')
|
|
137
|
+
const path = join(output, action === 'uninstall' ? 'uninstall-bridge.cmd' : 'install-bridge.cmd')
|
|
138
|
+
const plan: MaintenancePlan = { version: 1, action, installRoot: target, installerPath, nodePath, electronNode, dshHome }
|
|
139
|
+
const command = [
|
|
140
|
+
'@echo off',
|
|
141
|
+
'setlocal DisableDelayedExpansion',
|
|
142
|
+
'chcp 65001 >nul',
|
|
143
|
+
'echo Exit DSH Desktop normally before running bridge maintenance.',
|
|
144
|
+
`set "ELECTRON_RUN_AS_NODE=${electronNode ? '1' : ''}"`,
|
|
145
|
+
`"${batchLiteral(nodePath)}"${electronNode ? ' --expose-internals' : ''} "%~dp0run-maintenance.mjs"`,
|
|
146
|
+
'set "DSH_BRIDGE_MAINTENANCE_EXIT=%ERRORLEVEL%"',
|
|
147
|
+
'if not "%DSH_BRIDGE_MAINTENANCE_EXIT%"=="0" goto failed',
|
|
148
|
+
'echo Bridge maintenance completed. You can now open DSH Desktop.',
|
|
149
|
+
'goto finished',
|
|
150
|
+
':failed',
|
|
151
|
+
'echo Bridge maintenance failed. Read the reason above, then prepare maintenance again if needed.',
|
|
152
|
+
':finished',
|
|
153
|
+
'if not "%DSH_BRIDGE_MAINTENANCE_NO_PAUSE%"=="1" pause',
|
|
154
|
+
'exit /b %DSH_BRIDGE_MAINTENANCE_EXIT%',
|
|
155
|
+
'',
|
|
156
|
+
].join('\r\n')
|
|
157
|
+
await writeFile(planPath, JSON.stringify(plan, null, 2) + '\n', { flag: 'wx', mode: 0o600 })
|
|
158
|
+
await writeFile(runnerPath, RUNNER, { flag: 'wx', mode: 0o600 })
|
|
159
|
+
await writeFile(path, command, { flag: 'wx', mode: 0o600 })
|
|
160
|
+
return { ok: true, prepared: true, action, path, command: `& '${path.replace(/'/g, "''")}'`, commandShell: 'powershell', directory: output, runnerPath, planPath }
|
|
161
|
+
}
|