dsh-builtin-browser 0.5.2 → 0.5.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/CHANGELOG.md +145 -0
  2. package/README.en.md +77 -68
  3. package/README.md +69 -89
  4. package/client.js +147 -15
  5. package/desktop-bridge/desktop-identity.json +9 -0
  6. package/desktop-bridge/install.mjs +220 -1
  7. package/desktop-bridge/plugin-browser-bridge.js +5 -0
  8. package/docs/README.md +1 -1
  9. package/docs/architecture.md +1 -1
  10. package/docs/limitations.md +19 -1
  11. package/docs/tool-reference.md +2 -1
  12. package/lib/browser-electron/bridge-status.d.ts +5 -3
  13. package/lib/browser-electron/bridge-status.js +53 -9
  14. package/lib/browser-electron/desktop-bridge-host.d.ts +25 -25
  15. package/lib/browser-electron/desktop-bridge-host.js +67 -40
  16. package/lib/browser-electron/desktop-identity.d.ts +58 -0
  17. package/lib/browser-electron/desktop-identity.js +236 -0
  18. package/lib/browser-electron/electron-provision.d.ts +59 -0
  19. package/lib/browser-electron/electron-provision.js +176 -0
  20. package/lib/browser-electron/entry.js +12 -0
  21. package/lib/browser-electron/host-main.js +68 -14
  22. package/lib/browser-electron/provider.d.ts +53 -3
  23. package/lib/browser-electron/provider.js +26 -5
  24. package/lib/browser-electron/remote-host.d.ts +3 -3
  25. package/lib/browser-electron/remote-host.js +25 -11
  26. package/lib/browser-electron/settings-store.d.ts +19 -0
  27. package/lib/browser-electron/settings-store.js +5 -1
  28. package/package.json +2 -3
  29. package/src/browser-electron/bridge-status.ts +56 -10
  30. package/src/browser-electron/desktop-bridge-host.ts +70 -41
  31. package/src/browser-electron/desktop-identity.ts +260 -0
  32. package/src/browser-electron/electron-provision.ts +208 -0
  33. package/src/browser-electron/entry.ts +12 -0
  34. package/src/browser-electron/host-main.ts +62 -12
  35. package/src/browser-electron/provider.ts +73 -8
  36. package/src/browser-electron/remote-host.ts +26 -12
  37. package/src/browser-electron/settings-store.ts +24 -1
  38. package/src/types/electron-shim.d.ts +8 -0
@@ -0,0 +1,260 @@
1
+ /**
2
+ * What proves a directory is a DSH Desktop install.
3
+ *
4
+ * Reported as issue #40. Every reader of an install directory used to accept a *generic* Electron
5
+ * layout (`resources/app/lib/main.js` or `resources/app.asar`) as proof, and that is not proof of
6
+ * anything: any Electron app has it. The consequence was measured — a throwaway app in a temp
7
+ * directory, whose own package.json said `unrelated-meeting-app`, was accepted by discovery, got a
8
+ * "bridge not installed" verdict with a ready-to-run installer command aimed at it, and (with that
9
+ * command) had its entry file rewritten and the bridge copied in.
10
+ *
11
+ * So identity is one rule, in one file (`desktop-bridge/desktop-identity.json`), read by both the
12
+ * installer and this module. Nothing else may decide what a DSH Desktop install is.
13
+ *
14
+ * Two properties are load-bearing and are why this is not a one-line `name ===` check:
15
+ *
16
+ * - **The archive wins.** Electron loads `resources/app.asar` in preference to `resources/app`, and
17
+ * a desktop update leaves the old extraction lying around. Reading identity from the extraction
18
+ * while the archive holds a different build would verify the wrong bytes, so when the archive is
19
+ * present that is what is read — and the sibling directory is not consulted at all.
20
+ * - **Unreadable means not DSH.** Every failure path (missing file, truncated pickle, unsupported
21
+ * archive version, malformed JSON, unreadable name) refuses. There is no "assume yes" branch: the
22
+ * caller is about to write into, or delete from, this directory.
23
+ * @module dsh-browser/browser-electron/desktop-identity
24
+ */
25
+ import { closeSync, existsSync, openSync, readFileSync, readSync } from 'node:fs'
26
+ import { join } from 'node:path'
27
+
28
+ /** The identity rule, as data. */
29
+ interface IdentityRule {
30
+ readonly packageNames: readonly string[]
31
+ readonly mainEntry: string
32
+ }
33
+
34
+ /**
35
+ * The rule shipped in `desktop-bridge/desktop-identity.json`, used when the file cannot be read.
36
+ *
37
+ * A copy exists here only as a fallback for a broken package layout; the test suite asserts that it
38
+ * equals the JSON, so the two can never drift apart silently.
39
+ */
40
+ export const FALLBACK_RULE: IdentityRule = {
41
+ packageNames: ['@deepseek-ai/dsh-desktop', 'dsh-desktop'],
42
+ mainEntry: 'lib/main.js',
43
+ }
44
+
45
+ /** A verified install. */
46
+ export interface DesktopIdentity {
47
+ readonly ok: true
48
+ /** The install root that was verified. */
49
+ readonly root: string
50
+ /** Which shape was verified — the archive when it exists, the extraction only without one. */
51
+ readonly layout: 'packed' | 'unpacked'
52
+ /** `name` from the package the caller will actually run. */
53
+ readonly packageName: string
54
+ /** `version`, when the package declares one. */
55
+ readonly version?: string
56
+ }
57
+
58
+ /** A refusal, with a reason a human can act on. */
59
+ export interface IdentityRefusal {
60
+ readonly ok: false
61
+ readonly reason: string
62
+ }
63
+
64
+ /**
65
+ * Read the identity rule.
66
+ *
67
+ * Resolved relative to this module, which in both the repository and the published tarball puts
68
+ * `desktop-bridge/` beside `lib/`. A missing file is not fatal — the fallback is the same rule —
69
+ * but a *malformed* one is an error the caller should not ignore, so it is reported through the
70
+ * refusal path rather than silently swapped for the fallback.
71
+ * @returns the rule, or an error string.
72
+ */
73
+ export function readIdentityRule(): IdentityRule | { readonly error: string } {
74
+ try {
75
+ const path = new URL('../../desktop-bridge/desktop-identity.json', import.meta.url)
76
+ const raw = JSON.parse(readFileSync(path, 'utf8')) as Partial<IdentityRule>
77
+ const names = raw.packageNames
78
+ const main = raw.mainEntry
79
+ if (!Array.isArray(names) || names.length === 0 || names.some(n => typeof n !== 'string')) {
80
+ return { error: 'desktop-identity.json: packageNames must be a non-empty array of strings' }
81
+ }
82
+ if (typeof main !== 'string' || main === '') {
83
+ return { error: 'desktop-identity.json: mainEntry must be a non-empty string' }
84
+ }
85
+ return { packageNames: names, mainEntry: main }
86
+ } catch (error) {
87
+ if (error instanceof Error && 'code' in error && (error as NodeJS.ErrnoException).code === 'ENOENT') {
88
+ return FALLBACK_RULE
89
+ }
90
+ return { error: `desktop-identity.json could not be read: ${String(error)}` }
91
+ }
92
+ }
93
+
94
+ /**
95
+ * One entry of a Chromium pickle header.
96
+ *
97
+ * `offset` is relative to the content area that follows the header; `unpacked` entries carry no
98
+ * bytes in the archive and live beside it instead.
99
+ */
100
+ interface AsarEntry {
101
+ readonly size: number
102
+ readonly offset?: string
103
+ readonly unpacked?: boolean
104
+ readonly files?: Record<string, AsarEntry>
105
+ }
106
+
107
+ /**
108
+ * Parse an asar header, the same way the installer does.
109
+ *
110
+ * Layout, for the next reader: an 8-byte outer pickle (`[size][jsonLength]`), then the header
111
+ * pickle whose first 4 bytes are the JSON length, then the JSON tree. File content starts right
112
+ * after the header pickle.
113
+ * @param archive - the archive path.
114
+ * @returns the header tree and the offset where content starts, or an error string.
115
+ */
116
+ function readAsarHeader(archive: string): { header: { files?: Record<string, AsarEntry> }; contentBase: number } | { error: string } {
117
+ let fd: number | undefined
118
+ try {
119
+ fd = openSync(archive, 'r')
120
+ const outer = Buffer.alloc(8)
121
+ if (readSync(fd, outer, 0, 8, 0) !== 8) return { error: 'the archive header is truncated' }
122
+ const headerSize = outer.readUInt32LE(4)
123
+ if (headerSize < 8 || headerSize > 64 * 1024 * 1024) return { error: `implausible archive header size (${headerSize})` }
124
+ const header = Buffer.alloc(headerSize)
125
+ if (readSync(fd, header, 0, headerSize, 8) !== headerSize) return { error: 'the archive header is truncated' }
126
+ const jsonLength = header.readUInt32LE(4)
127
+ if (jsonLength <= 0 || jsonLength > headerSize - 8) return { error: 'the archive header has an implausible JSON length' }
128
+ return { header: JSON.parse(header.toString('utf8', 8, 8 + jsonLength)), contentBase: 8 + headerSize }
129
+ } catch (error) {
130
+ return { error: `the archive header could not be read: ${String(error)}` }
131
+ } finally {
132
+ if (fd !== undefined) {
133
+ try { closeSync(fd) } catch { /* already closed */ }
134
+ }
135
+ }
136
+ }
137
+
138
+ /**
139
+ * Walk a slash-separated path inside an asar header tree.
140
+ * @param tree - the header's `files` node.
141
+ * @param path - e.g. `lib/main.js`.
142
+ * @returns the entry, or undefined when the path does not exist.
143
+ */
144
+ function entryAt(tree: Record<string, AsarEntry> | undefined, path: string): AsarEntry | undefined {
145
+ let node: AsarEntry | undefined
146
+ let files: Record<string, AsarEntry> | undefined = tree
147
+ for (const part of path.split('/')) {
148
+ if (files === undefined) return undefined
149
+ node = files[part]
150
+ if (node === undefined) return undefined
151
+ files = node.files
152
+ }
153
+ return node
154
+ }
155
+
156
+ /**
157
+ * Read one file out of an asar archive without extracting the tree.
158
+ * @param archive - the archive path.
159
+ * @param path - a slash-separated path inside the archive.
160
+ * @returns the bytes, or undefined when the entry is absent or unreadable.
161
+ */
162
+ export function readAsarFile(archive: string, path: string): Buffer | undefined {
163
+ const parsed = readAsarHeader(archive)
164
+ if ('error' in parsed) return undefined
165
+ const entry = entryAt(parsed.header.files, path)
166
+ if (entry === undefined || entry.files !== undefined || entry.unpacked === true) return undefined
167
+ if (typeof entry.offset !== 'string' || typeof entry.size !== 'number' || entry.size < 0) return undefined
168
+ let fd: number | undefined
169
+ try {
170
+ fd = openSync(archive, 'r')
171
+ const buffer = Buffer.alloc(entry.size)
172
+ const read = readSync(fd, buffer, 0, entry.size, parsed.contentBase + Number(entry.offset))
173
+ return read === entry.size ? buffer : undefined
174
+ } catch {
175
+ return undefined
176
+ } finally {
177
+ if (fd !== undefined) {
178
+ try { closeSync(fd) } catch { /* already closed */ }
179
+ }
180
+ }
181
+ }
182
+
183
+ /**
184
+ * Whether an install directory is DSH Desktop.
185
+ *
186
+ * Everything the caller does next (stop the app, delete a tree, extract, rename, write) depends on
187
+ * this being right, so every uncertainty resolves to a refusal that names what was found.
188
+ * @param installRoot - the directory a user or the discovery probe named.
189
+ * @returns the verified identity, or a refusal with a reason.
190
+ */
191
+ export function readDesktopIdentity(installRoot: string): DesktopIdentity | IdentityRefusal {
192
+ const rule = readIdentityRule()
193
+ if ('error' in rule) return { ok: false, reason: rule.error }
194
+ const resources = join(installRoot, 'resources')
195
+ const appDir = join(resources, 'app')
196
+ const archive = join(resources, 'app.asar')
197
+
198
+ let archivePresent: boolean
199
+ try {
200
+ archivePresent = existsSync(archive)
201
+ } catch {
202
+ return { ok: false, reason: `cannot inspect ${archive}` }
203
+ }
204
+
205
+ const layout: 'packed' | 'unpacked' = archivePresent ? 'packed' : 'unpacked'
206
+ let manifestText: string | undefined
207
+ let mainPresent: boolean
208
+ if (archivePresent) {
209
+ const parsed = readAsarHeader(archive)
210
+ if ('error' in parsed) {
211
+ return { ok: false, reason: `${archive} could not be read: ${parsed.error}` }
212
+ }
213
+ const manifest = entryAt(parsed.header.files, 'package.json')
214
+ if (manifest === undefined || manifest.files !== undefined || manifest.unpacked === true) {
215
+ return { ok: false, reason: `${archive} has no plain package.json; an archive without one is not proof of identity` }
216
+ }
217
+ manifestText = readAsarFile(archive, 'package.json')?.toString('utf8')
218
+ if (manifestText === undefined) {
219
+ return { ok: false, reason: `${archive}: package.json is listed but its bytes cannot be read` }
220
+ }
221
+ mainPresent = entryAt(parsed.header.files, rule.mainEntry) !== undefined
222
+ } else {
223
+ const manifestPath = join(appDir, 'package.json')
224
+ try {
225
+ manifestText = readFileSync(manifestPath, 'utf8')
226
+ } catch {
227
+ return { ok: false, reason: `${manifestPath} is missing; a directory without a package manifest is not a DSH Desktop install` }
228
+ }
229
+ mainPresent = existsSync(join(appDir, ...rule.mainEntry.split('/')))
230
+ }
231
+
232
+ let manifest: { name?: unknown; version?: unknown }
233
+ try {
234
+ manifest = JSON.parse(manifestText) as { name?: unknown; version?: unknown }
235
+ } catch {
236
+ return { ok: false, reason: 'the package manifest is not valid JSON' }
237
+ }
238
+ const name = typeof manifest.name === 'string' ? manifest.name : ''
239
+ if (!rule.packageNames.includes(name)) {
240
+ return {
241
+ ok: false,
242
+ reason: `the app calls itself ${name === '' ? '(no name)' : JSON.stringify(name)}, which is not one of `
243
+ + `${rule.packageNames.join(' / ')} — refusing to touch a different application`,
244
+ }
245
+ }
246
+
247
+ // The main entry is the file the installer patches and the shell runs; if it is not there, this
248
+ // is not an install this plugin can reason about even though the manifest looks right.
249
+ if (!mainPresent) {
250
+ return { ok: false, reason: `${rule.mainEntry} is not present under ${archivePresent ? archive : appDir}` }
251
+ }
252
+
253
+ return {
254
+ ok: true,
255
+ root: installRoot,
256
+ layout,
257
+ packageName: name,
258
+ ...typeof manifest.version === 'string' ? { version: manifest.version } : {},
259
+ }
260
+ }
@@ -0,0 +1,208 @@
1
+ /**
2
+ * Prepare the Electron runtime *when it is needed*, instead of making installation depend on it.
3
+ *
4
+ * Reported as issue #41, from a real plugin-market install of 0.5.2:
5
+ *
6
+ * [ERR_PNPM_IGNORED_BUILDS] Ignored build scripts: dsh-builtin-browser@0.5.2
7
+ *
8
+ * and, once the build script was allowed:
9
+ *
10
+ * postinstall: Preparing Electron 44.10.1 … TypeError: fetch failed
11
+ * postinstall: Electron installation failed (exit 1). … [ELIFECYCLE] Command failed with exit code 1
12
+ *
13
+ * Two defects in one design, and both are about WHERE the download lives:
14
+ *
15
+ * 1. A `postinstall` puts a ~100 MB network download inside package installation. pnpm blocks
16
+ * install scripts by default (`strict-dep-builds`), so the plugin could not be installed at all
17
+ * on a default pnpm 11 profile; and if the download fails for any reason the *whole install*
18
+ * fails, which is a network condition reported as "the plugin is broken".
19
+ * 2. Nothing forced the download to happen at install time. The carrier that needs Electron is one
20
+ * of four, and on the desktop the sidebar needs none.
21
+ *
22
+ * So installation is offline by construction now, and this module does the work later: on plugin
23
+ * start when the operator explicitly asked for the bundled carrier, and never fatally — a failure
24
+ * here is a log line plus the existing, actionable resolution error that names the command to run.
25
+ *
26
+ * Being non-fatal is the point, not a detail: this runs inside a request-serving process, and a
27
+ * download that hangs must not be able to hold a browser tool call open.
28
+ * @module dsh-browser/browser-electron/electron-provision
29
+ */
30
+ import { spawn } from 'node:child_process'
31
+ import { existsSync, readFileSync } from 'node:fs'
32
+ import { createRequire } from 'node:module'
33
+ import { dirname, join } from 'node:path'
34
+
35
+ import { internals } from './remote-host.js'
36
+
37
+ /** How long a background provision may run before it is abandoned. */
38
+ export const PROVISION_TIMEOUT_MS = 180_000
39
+
40
+ /** What happened, in terms a log line can carry. */
41
+ export interface ProvisionResult {
42
+ /** `present` — nothing to do; `ready` — provisioned now; `skipped` — opted out; `failed`. */
43
+ readonly status: 'present' | 'ready' | 'skipped' | 'failed'
44
+ /** One line for the log; never contains a stack trace a user has to decode. */
45
+ readonly detail: string
46
+ }
47
+
48
+ /** Everything this module touches from the outside, so a test can drive it without Electron. */
49
+ export interface ProvisionDeps {
50
+ /** Whether a spawnable binary already exists. */
51
+ readonly hasBinary: () => boolean
52
+ /** The installed electron package's own installer script, or undefined when it is not there. */
53
+ readonly installerScript: () => string | undefined
54
+ /** Runs the installer; resolves to an exit code, or rejects/returns null on failure. */
55
+ readonly run: (script: string) => Promise<{ code: number | null; detail?: string }>
56
+ /** Where the outcome goes. */
57
+ readonly log: (message: string) => void
58
+ /** Opt-out honoured exactly like the install script honours it. */
59
+ readonly skip: () => boolean
60
+ /** Budget for one provision. */
61
+ readonly timeoutMs: number
62
+ }
63
+
64
+ /**
65
+ * Whether a spawnable Electron binary is already available.
66
+ *
67
+ * Resolved through the same probe the host uses, so this can never disagree with what a launch
68
+ * would find: a second, cheaper-looking check would be the classic way to report "ready" and then
69
+ * fail at spawn time.
70
+ * @returns true when a launch would find a binary.
71
+ */
72
+ export function hasElectronRuntime(): boolean {
73
+ try {
74
+ internals.resolveElectronPath()
75
+ return true
76
+ } catch {
77
+ return false
78
+ }
79
+ }
80
+
81
+ /**
82
+ * The installed electron package's installer script.
83
+ *
84
+ * `require.resolve('electron/package.json')` is used rather than `require('electron')`: inside an
85
+ * Electron main process that module name is the built-in API, and requiring the package would
86
+ * download the binary as a side effect of asking about it.
87
+ * @returns the path to the dependency's own install script, or undefined.
88
+ */
89
+ function electronInstallerScript(): string | undefined {
90
+ try {
91
+ const require = createRequire(import.meta.url)
92
+ const manifestPath = require.resolve('electron/package.json')
93
+ const script = join(dirname(manifestPath), 'install.js')
94
+ return existsSync(script) ? script : undefined
95
+ } catch {
96
+ return undefined
97
+ }
98
+ }
99
+
100
+ /** The Electron version the installed package asks for, for a log line that names the download. */
101
+ function electronVersion(): string {
102
+ try {
103
+ const require = createRequire(import.meta.url)
104
+ const manifest = JSON.parse(readFileSync(require.resolve('electron/package.json'), 'utf8')) as { version?: unknown }
105
+ return typeof manifest.version === 'string' ? manifest.version : 'unknown'
106
+ } catch {
107
+ return 'unknown'
108
+ }
109
+ }
110
+
111
+ /** The real dependencies: this process's spawn, fs and logger. */
112
+ export function defaultDeps(log: (message: string) => void = () => {}): ProvisionDeps {
113
+ return {
114
+ hasBinary: hasElectronRuntime,
115
+ installerScript: electronInstallerScript,
116
+ run: async script => {
117
+ const child = spawn(process.execPath, [script], {
118
+ env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' },
119
+ stdio: ['ignore', 'ignore', 'ignore'],
120
+ windowsHide: true,
121
+ })
122
+ return await new Promise(resolve => {
123
+ child.once('error', error => resolve({ code: null, detail: String(error) }))
124
+ child.once('close', code => resolve({ code, detail: undefined }))
125
+ })
126
+ },
127
+ log,
128
+ skip: () => typeof process.env.ELECTRON_SKIP_BINARY_DOWNLOAD === 'string'
129
+ && process.env.ELECTRON_SKIP_BINARY_DOWNLOAD !== '',
130
+ timeoutMs: PROVISION_TIMEOUT_MS,
131
+ }
132
+ }
133
+
134
+ /**
135
+ * Provision the runtime once per process, when it is missing.
136
+ *
137
+ * Concurrent callers share the first attempt: two tool calls arriving together must not start two
138
+ * downloads into the same directory.
139
+ * @param deps - the effects, defaulted to this process's.
140
+ * @returns what happened. Never throws.
141
+ */
142
+ export async function ensureElectronRuntime(deps: ProvisionDeps = defaultDeps()): Promise<ProvisionResult> {
143
+ if (deps.hasBinary()) return { status: 'present', detail: 'an Electron runtime is already available' }
144
+ if (deps.skip()) return { status: 'skipped', detail: 'ELECTRON_SKIP_BINARY_DOWNLOAD is set' }
145
+ const script = deps.installerScript()
146
+ if (script === undefined) {
147
+ return { status: 'failed', detail: 'the installed electron package has no install.js; reinstall the plugin in this profile' }
148
+ }
149
+ deps.log(`preparing Electron ${electronVersion()} in the background (a missing runtime needs a download)`)
150
+ // The bound has to be a REFERENCED timer, and it has to be cleared when the race finishes.
151
+ //
152
+ // A first version unref'd it — "do not keep the process alive for a download" — which is exactly
153
+ // backwards: with nothing else on the loop the timer never fires, the promise never settles, and a
154
+ // caller waiting on it hangs with no error at all. CI caught it before a user could: the test for
155
+ // this path failed with "Promise resolution is still pending but the event loop has already
156
+ // resolved". Keep it referenced, and clear it so a success does not leave a 180 s handle behind.
157
+ let timer: ReturnType<typeof setTimeout> | undefined
158
+ const timeout = new Promise<{ code: number | null; detail: string }>(resolve => {
159
+ timer = setTimeout(
160
+ () => resolve({ code: null, detail: `gave up after ${Math.round(deps.timeoutMs / 1000)}s` }),
161
+ deps.timeoutMs,
162
+ )
163
+ })
164
+ let outcome: { code: number | null; detail?: string }
165
+ try {
166
+ outcome = await Promise.race([deps.run(script), timeout])
167
+ } catch (error) {
168
+ return { status: 'failed', detail: `the download failed: ${String(error)}` }
169
+ } finally {
170
+ if (timer !== undefined) clearTimeout(timer)
171
+ }
172
+ if (outcome.code !== 0) {
173
+ return {
174
+ status: 'failed',
175
+ detail: `Electron provisioning did not finish (${outcome.detail ?? `exit ${String(outcome.code)}`}); `
176
+ + 'the browser still works through a sidebar, Chrome or Edge, and `npx --no dsh-browser-install-electron` retries it',
177
+ }
178
+ }
179
+ return { status: 'ready', detail: 'the Electron runtime is ready' }
180
+ }
181
+
182
+ /** One attempt per process, shared by every caller. */
183
+ let attempt: Promise<ProvisionResult> | undefined
184
+
185
+ /**
186
+ * Start (or join) the single background attempt.
187
+ *
188
+ * Returns immediately with the shared promise, so a caller that does not care can ignore it and one
189
+ * that does can await it — the returned promise never rejects.
190
+ * @param log - where the outcome goes.
191
+ * @param deps - the effects; defaulted to this process's, overridable so a test can drive it.
192
+ * @returns the shared attempt.
193
+ */
194
+ export function provisionElectronInBackground(
195
+ log: (message: string) => void,
196
+ deps: ProvisionDeps = defaultDeps(log),
197
+ ): Promise<ProvisionResult> {
198
+ attempt ??= ensureElectronRuntime(deps).then(result => {
199
+ log(`electron runtime: ${result.status} — ${result.detail}`)
200
+ return result
201
+ })
202
+ return attempt
203
+ }
204
+
205
+ /** Forget the attempt. Tests only: a real process provisions at most once. */
206
+ export function resetProvisionStateForTest(): void {
207
+ attempt = undefined
208
+ }
@@ -15,6 +15,7 @@ import type { IncomingMessage, ServerResponse } from 'node:http'
15
15
  import z from '@deepseek-ai/schemastery'
16
16
  import type { BrowserRuntime } from '../browser/runtime.js'
17
17
  import { ElectronBrowserProvider } from './provider.js'
18
+ import { provisionElectronInBackground } from './electron-provision.js'
18
19
  import type { ElectronBrowserViewHost } from './provider.js'
19
20
  import type { CarrierLossReason } from '../browser/types.js'
20
21
  import { randomUUID } from 'node:crypto'
@@ -153,6 +154,17 @@ export function apply(ctx: Context & { browser: BrowserRuntime }, config: Config
153
154
  // different lifetimes (a spawned child vs. the shell's view), and pretending
154
155
  // otherwise would leave a stray window behind.
155
156
  const selfHosted = new RemoteElectronViewHost(defaultHostMainPath())
157
+ // The self-hosted carrier is the only one that needs Electron, and it is prepared HERE, lazily,
158
+ // rather than during package installation (issue #41: a `postinstall` download made a default
159
+ // pnpm 11 profile refuse the install outright, and a failed fetch failed the install too).
160
+ //
161
+ // Non-fatal by construction: this never rejects, never blocks a tool call, and its failure leaves
162
+ // the sidebar / Chrome / Edge carriers untouched. Only the two channels that can use the bundled
163
+ // runtime are worth the download; an explicit chrome/edge choice is not.
164
+ const wantedChannel = settings.get().browser.channel
165
+ if (wantedChannel === 'bundled' || wantedChannel === 'auto') {
166
+ void provisionElectronInBackground(message => ctx.logger?.info?.(`dsh-builtin-browser: ${message}`))
167
+ }
156
168
  let unregister = ctx.browser.registerBrowserProvider(new ElectronBrowserProvider(selfHosted, providerConfig))
157
169
  let disposed = false
158
170
  let carrierChoice = 0
@@ -565,8 +565,17 @@ function updateWindowTitle(win: HostWindow, viewId: string | undefined, label: s
565
565
  } catch { /* destroyed */ }
566
566
  }
567
567
 
568
- /** Make one view the visible (topmost) one within its window. */
569
- function showViewInWindow(win: HostWindow, viewId: string, label?: string): void {
568
+ /**
569
+ * Make one view the visible (topmost) one WITHIN its window, leaving the window itself alone.
570
+ *
571
+ * Split out of {@link showViewInWindow} for quiet-mode capture: a screenshot still has to look
572
+ * at the active tab rather than another tab of the same window, but it must not show, restore,
573
+ * raise or focus the window to do it. Everything here is contentView-local.
574
+ * @param win - the window holding the view.
575
+ * @param viewId - the view to reveal.
576
+ * @param label - session/task label, when known, for the window title.
577
+ */
578
+ function revealViewInWindow(win: HostWindow, viewId: string, label?: string): void {
570
579
  const entry = win.views.get(viewId)
571
580
  if (entry === undefined) return
572
581
  // A navigation replaced this view's renderer, and the new one has no
@@ -598,11 +607,39 @@ function showViewInWindow(win: HostWindow, viewId: string, label?: string): void
598
607
  // Always refresh the title: it reflects the CURRENT page of the visible
599
608
  // view, which changes as the agent navigates.
600
609
  updateWindowTitle(win, viewId, label)
610
+ }
611
+
612
+ /**
613
+ * Make one view the visible one within its window, and — outside quiet mode — raise the window.
614
+ * @param win - the window holding the view.
615
+ * @param viewId - the view to present.
616
+ * @param label - session/task label, when known, for the window title.
617
+ * @param quiet - `ui.quiet`: present without taking the screen over.
618
+ * @param needSurface - quiet mode only: this presentation is the barrier before synthesized
619
+ * input, so the window has to be visible even if the user minimized it. A navigation or a tab
620
+ * switch does not need that and leaves a minimized window alone.
621
+ */
622
+ function showViewInWindow(win: HostWindow, viewId: string, label?: string, quiet = false, needSurface = false): void {
623
+ revealViewInWindow(win, viewId, label)
601
624
  // Raise this session's window so the human sees the page being worked on
602
625
  // (moveTop raises without stealing keyboard focus).
626
+ //
627
+ // Quiet mode (`ui.quiet`): the user asked not to be interrupted, so this must not
628
+ // activate the application, steal keyboard focus, or pull the window in front of the one
629
+ // they are using. Chromium drops `Input.*` for a view with no display surface, so the one
630
+ // case that still needs a visible window — the barrier before synthesized input — restores
631
+ // it with `showInactive()`, which shows it without becoming the key window, and never calls
632
+ // `moveTop()`. Everything else (navigation, tab switching, screenshots) leaves a minimized
633
+ // window minimized.
603
634
  try {
604
- if (!win.window.isVisible()) win.window.show()
605
- win.window.moveTop()
635
+ if (quiet) {
636
+ if (!needSurface) return
637
+ if (win.window.isMinimized()) win.window.restore()
638
+ if (!win.window.isVisible()) win.window.showInactive()
639
+ } else {
640
+ if (!win.window.isVisible()) win.window.show()
641
+ win.window.moveTop()
642
+ }
606
643
  } catch { /* closing */ }
607
644
  }
608
645
 
@@ -619,7 +656,7 @@ function scheduleWindowClose(win: HostWindow): void {
619
656
  }
620
657
 
621
658
  /** Handle one command. */
622
- async function handle(op: string, msg: { id: number; viewId?: string; windowId?: string; method?: string; params?: Record<string, unknown>; url?: string; savePath?: string; cookies?: unknown[]; label?: string; format?: string; quality?: number; maxWidth?: number; maxHeight?: number; message?: string }): Promise<void> {
659
+ async function handle(op: string, msg: { id: number; viewId?: string; windowId?: string; method?: string; params?: Record<string, unknown>; url?: string; savePath?: string; cookies?: unknown[]; label?: string; format?: string; quality?: number; maxWidth?: number; maxHeight?: number; message?: string; quiet?: boolean; needSurface?: boolean }): Promise<void> {
623
660
  try {
624
661
  switch (op) {
625
662
  case 'ping':
@@ -741,7 +778,7 @@ async function handle(op: string, msg: { id: number; viewId?: string; windowId?:
741
778
  const viewId = msg.viewId
742
779
  if (viewId === undefined) throw new Error('showView missing viewId')
743
780
  const win = windowOfView(viewId)
744
- if (win !== undefined) showViewInWindow(win, viewId, typeof msg.label === 'string' ? msg.label : undefined)
781
+ if (win !== undefined) showViewInWindow(win, viewId, typeof msg.label === 'string' ? msg.label : undefined, msg.quiet === true, msg.needSurface === true)
745
782
  reply(msg.id, { ok: true })
746
783
  return
747
784
  }
@@ -811,12 +848,25 @@ async function handle(op: string, msg: { id: number; viewId?: string; windowId?:
811
848
  const wantQuality = typeof msg.quality === 'number' ? msg.quality : 80
812
849
  const maxW = typeof msg.maxWidth === 'number' ? msg.maxWidth : 0
813
850
  const maxH = typeof msg.maxHeight === 'number' ? msg.maxHeight : 0
851
+ // Quiet mode: a screenshot is not a reason to take the screen over. Skipping the
852
+ // raise below is what makes a minimized window survive a screenshot: capturePage on
853
+ // a hidden view returns an empty image, and the CDP fallback captures without needing
854
+ // a display surface. The default path keeps the raise, because there a screenshot is
855
+ // how the human follows what the agent is doing.
856
+ const quiet = msg.quiet === true
814
857
  let mime = 'image/png'
815
- try {
816
- if (!win.window.isVisible()) win.window.show()
817
- } catch { /* closing */ }
818
- try { win.window.restore() } catch { /* not minimized */ }
819
- win.window.focus()
858
+ if (quiet) {
859
+ // The active tab has to be the visible one INSIDE the window, or the capture may read
860
+ // another tab. Keep that switch contentView-local: show/restore/focus are precisely
861
+ // what quiet mode forbids.
862
+ revealViewInWindow(win, viewId)
863
+ } else {
864
+ try {
865
+ if (!win.window.isVisible()) win.window.show()
866
+ } catch { /* closing */ }
867
+ try { win.window.restore() } catch { /* not minimized */ }
868
+ win.window.focus()
869
+ }
820
870
  let base64 = ''
821
871
  let renderedSize: { width: number; height: number } | undefined
822
872
  try {
@@ -1143,7 +1193,7 @@ void app.whenReady().then(() => {
1143
1193
  rl.on('line', line => {
1144
1194
  const text = line.trim()
1145
1195
  if (text === '') return
1146
- let msg: { id: number; op?: string; viewId?: string; windowId?: string; method?: string; params?: Record<string, unknown>; url?: string; savePath?: string; cookies?: unknown[]; label?: string; format?: string; quality?: number; maxWidth?: number; maxHeight?: number; message?: string }
1196
+ let msg: { id: number; op?: string; viewId?: string; windowId?: string; method?: string; params?: Record<string, unknown>; url?: string; savePath?: string; cookies?: unknown[]; label?: string; format?: string; quality?: number; maxWidth?: number; maxHeight?: number; message?: string; quiet?: boolean; needSurface?: boolean }
1147
1197
  try {
1148
1198
  msg = JSON.parse(text) as typeof msg
1149
1199
  } catch {