dsh-builtin-browser 0.5.5 → 0.5.7

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 (77) hide show
  1. package/CHANGELOG.md +143 -1
  2. package/README.en.md +67 -97
  3. package/README.md +67 -98
  4. package/client.js +618 -263
  5. package/desktop-bridge/install.mjs +122 -33
  6. package/desktop-bridge/plugin-browser-bridge.js +9 -4
  7. package/docs/development.md +10 -0
  8. package/docs/tool-reference.md +20 -1
  9. package/docs/user-guide.md +16 -4
  10. package/lib/browser/runtime.d.ts +3 -1
  11. package/lib/browser/runtime.js +9 -0
  12. package/lib/browser/types.d.ts +42 -0
  13. package/lib/browser-electron/authenticated-route.d.ts +27 -0
  14. package/lib/browser-electron/authenticated-route.js +39 -0
  15. package/lib/browser-electron/bridge-connection.d.ts +8 -0
  16. package/lib/browser-electron/bridge-connection.js +8 -0
  17. package/lib/browser-electron/bridge-endpoint.d.ts +30 -0
  18. package/lib/browser-electron/bridge-endpoint.js +130 -0
  19. package/lib/browser-electron/bridge-install.d.ts +48 -0
  20. package/lib/browser-electron/bridge-install.js +98 -0
  21. package/lib/browser-electron/bridge-status.js +21 -2
  22. package/lib/browser-electron/desktop-bridge-host.d.ts +30 -27
  23. package/lib/browser-electron/desktop-bridge-host.js +71 -50
  24. package/lib/browser-electron/electron-provision.d.ts +35 -2
  25. package/lib/browser-electron/electron-provision.js +83 -20
  26. package/lib/browser-electron/entry.js +144 -7
  27. package/lib/browser-electron/host-main.js +48 -27
  28. package/lib/browser-electron/json-reply.d.ts +21 -0
  29. package/lib/browser-electron/json-reply.js +17 -0
  30. package/lib/browser-electron/preview-route.js +1 -12
  31. package/lib/browser-electron/provider.d.ts +9 -2
  32. package/lib/browser-electron/provider.js +76 -6
  33. package/lib/browser-electron/remote-host.js +10 -9
  34. package/lib/browser-electron/runtime-route.d.ts +55 -0
  35. package/lib/browser-electron/runtime-route.js +66 -0
  36. package/lib/browser-electron/runtime-status.d.ts +102 -0
  37. package/lib/browser-electron/runtime-status.js +88 -0
  38. package/lib/browser-electron/settings-route.d.ts +5 -18
  39. package/lib/browser-electron/settings-route.js +4 -14
  40. package/lib/browser-electron/settings-store.d.ts +17 -0
  41. package/lib/browser-electron/settings-store.js +24 -0
  42. package/lib/browser-electron/system-browser.d.ts +5 -2
  43. package/lib/browser-electron/system-browser.js +12 -4
  44. package/lib/tool-browser/index.js +1041 -4
  45. package/lib/tool-browser/page-probe.d.ts +86 -0
  46. package/lib/tool-browser/page-probe.js +460 -0
  47. package/package.json +5 -3
  48. package/scripts/consumer-install-check.mjs +72 -0
  49. package/scripts/verify-runtime-status.mjs +179 -0
  50. package/skills/dsh-builtin-browser/SKILL.md +64 -0
  51. package/skills/dsh-builtin-browser/references/batch.md +23 -0
  52. package/skills/dsh-builtin-browser/references/deliver.md +31 -0
  53. package/skills/dsh-builtin-browser/references/locate.md +11 -0
  54. package/skills/dsh-builtin-browser/references/recover.md +11 -0
  55. package/skills/dsh-builtin-browser/references/verify.md +13 -0
  56. package/src/browser/runtime.ts +11 -0
  57. package/src/browser/types.ts +19 -0
  58. package/src/browser-electron/authenticated-route.ts +56 -0
  59. package/src/browser-electron/bridge-connection.ts +9 -0
  60. package/src/browser-electron/bridge-endpoint.ts +146 -0
  61. package/src/browser-electron/bridge-install.ts +122 -0
  62. package/src/browser-electron/bridge-status.ts +22 -2
  63. package/src/browser-electron/desktop-bridge-host.ts +68 -50
  64. package/src/browser-electron/electron-provision.ts +103 -20
  65. package/src/browser-electron/entry.ts +141 -7
  66. package/src/browser-electron/host-main.ts +41 -22
  67. package/src/browser-electron/json-reply.ts +32 -0
  68. package/src/browser-electron/preview-route.ts +1 -12
  69. package/src/browser-electron/provider.ts +90 -6
  70. package/src/browser-electron/remote-host.ts +10 -9
  71. package/src/browser-electron/runtime-route.ts +104 -0
  72. package/src/browser-electron/runtime-status.ts +188 -0
  73. package/src/browser-electron/settings-route.ts +9 -32
  74. package/src/browser-electron/settings-store.ts +39 -0
  75. package/src/browser-electron/system-browser.ts +9 -3
  76. package/src/tool-browser/index.ts +991 -7
  77. package/src/tool-browser/page-probe.ts +474 -0
@@ -45,6 +45,48 @@ export interface ProvisionResult {
45
45
  readonly detail: string
46
46
  }
47
47
 
48
+ /**
49
+ * The state a settings panel shows, which is one state wider than {@link ProvisionResult}.
50
+ *
51
+ * `idle` and `preparing` are the two a log line never needs and a user always does: "nothing has
52
+ * been asked for yet" and "a ~100 MB download is running right now" are the states in which a first
53
+ * browser call is slow, and until this existed neither was visible anywhere in the product — the
54
+ * only trace was a log line the panel cannot read.
55
+ */
56
+ export interface ProvisionSnapshot {
57
+ /** `idle` and `preparing` are provisional; the rest are terminal for this attempt. */
58
+ readonly state: 'idle' | 'preparing' | 'present' | 'ready' | 'skipped' | 'failed'
59
+ /** One line, already user-facing: never a stack trace. */
60
+ readonly detail: string
61
+ /** When the state last changed, ISO. */
62
+ readonly at: string
63
+ }
64
+
65
+ const IDLE: ProvisionSnapshot = {
66
+ state: 'idle',
67
+ detail: 'the runtime has not been asked for yet',
68
+ at: new Date(0).toISOString(),
69
+ }
70
+
71
+ let latest: ProvisionSnapshot = IDLE
72
+
73
+ /**
74
+ * The current provisioning state, for a readiness report.
75
+ *
76
+ * Deliberately a snapshot rather than a promise: a panel polling this must be able to answer in one
77
+ * synchronous read, without awaiting (and thereby echoing) the download it is reporting on.
78
+ * @returns the last state written, or the idle state before anything ran.
79
+ */
80
+ export function provisionSnapshot(): ProvisionSnapshot {
81
+ return latest
82
+ }
83
+
84
+ /** Replace the reported state. Internal: every terminal result is recorded here. */
85
+ function record(result: ProvisionResult): ProvisionResult {
86
+ latest = { state: result.status, detail: result.detail, at: new Date().toISOString() }
87
+ return result
88
+ }
89
+
48
90
  /** Everything this module touches from the outside, so a test can drive it without Electron. */
49
91
  export interface ProvisionDeps {
50
92
  /** Whether a spawnable binary already exists. */
@@ -52,7 +94,7 @@ export interface ProvisionDeps {
52
94
  /** The installed electron package's own installer script, or undefined when it is not there. */
53
95
  readonly installerScript: () => string | undefined
54
96
  /** 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 }>
97
+ readonly run: (script: string, signal?: AbortSignal) => Promise<{ code: number | null; detail?: string }>
56
98
  /** Where the outcome goes. */
57
99
  readonly log: (message: string) => void
58
100
  /** Opt-out honoured exactly like the install script honours it. */
@@ -108,21 +150,35 @@ function electronVersion(): string {
108
150
  }
109
151
  }
110
152
 
153
+ let runningInstaller: Promise<{ code: number | null; detail?: string }> | undefined
154
+
111
155
  /** The real dependencies: this process's spawn, fs and logger. */
112
156
  export function defaultDeps(log: (message: string) => void = () => {}): ProvisionDeps {
113
157
  return {
114
158
  hasBinary: hasElectronRuntime,
115
159
  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 }))
160
+ run: (script, signal) => {
161
+ if (runningInstaller !== undefined) return runningInstaller
162
+ const run = new Promise<{ code: number | null; detail?: string }>(resolve => {
163
+ const child = spawn(process.execPath, [script], {
164
+ env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' },
165
+ stdio: ['ignore', 'ignore', 'ignore'],
166
+ windowsHide: true,
167
+ })
168
+ let failure: string | undefined
169
+ const abort = (): void => { child.kill('SIGKILL') }
170
+ signal?.addEventListener('abort', abort, { once: true })
171
+ if (signal?.aborted) abort()
172
+ child.once('error', error => { failure = String(error) })
173
+ child.once('close', code => {
174
+ signal?.removeEventListener('abort', abort)
175
+ resolve({ code, detail: failure })
176
+ })
125
177
  })
178
+ runningInstaller = run
179
+ const clear = (): void => { if (runningInstaller === run) runningInstaller = undefined }
180
+ void run.then(clear, clear)
181
+ return run
126
182
  },
127
183
  log,
128
184
  skip: () => typeof process.env.ELECTRON_SKIP_BINARY_DOWNLOAD === 'string'
@@ -140,11 +196,16 @@ export function defaultDeps(log: (message: string) => void = () => {}): Provisio
140
196
  * @returns what happened. Never throws.
141
197
  */
142
198
  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' }
199
+ if (deps.hasBinary()) return record({ status: 'present', detail: 'an Electron runtime is already available' })
200
+ if (deps.skip()) return record({ status: 'skipped', detail: 'ELECTRON_SKIP_BINARY_DOWNLOAD is set' })
145
201
  const script = deps.installerScript()
146
202
  if (script === undefined) {
147
- return { status: 'failed', detail: 'the installed electron package has no install.js; reinstall the plugin in this profile' }
203
+ return record({ status: 'failed', detail: 'the installed electron package has no install.js; reinstall the plugin in this profile' })
204
+ }
205
+ latest = {
206
+ state: 'preparing',
207
+ detail: `downloading Electron ${electronVersion()} (one time, about a minute)`,
208
+ at: new Date().toISOString(),
148
209
  }
149
210
  deps.log(`preparing Electron ${electronVersion()} in the background (a missing runtime needs a download)`)
150
211
  // The bound has to be a REFERENCED timer, and it has to be cleared when the race finishes.
@@ -155,47 +216,67 @@ export async function ensureElectronRuntime(deps: ProvisionDeps = defaultDeps())
155
216
  // this path failed with "Promise resolution is still pending but the event loop has already
156
217
  // resolved". Keep it referenced, and clear it so a success does not leave a 180 s handle behind.
157
218
  let timer: ReturnType<typeof setTimeout> | undefined
219
+ const controller = new AbortController()
158
220
  const timeout = new Promise<{ code: number | null; detail: string }>(resolve => {
159
221
  timer = setTimeout(
160
- () => resolve({ code: null, detail: `gave up after ${Math.round(deps.timeoutMs / 1000)}s` }),
222
+ () => {
223
+ controller.abort()
224
+ resolve({ code: null, detail: `gave up after ${Math.round(deps.timeoutMs / 1000)}s` })
225
+ },
161
226
  deps.timeoutMs,
162
227
  )
163
228
  })
164
229
  let outcome: { code: number | null; detail?: string }
165
230
  try {
166
- outcome = await Promise.race([deps.run(script), timeout])
231
+ outcome = await Promise.race([deps.run(script, controller.signal), timeout])
167
232
  } catch (error) {
168
- return { status: 'failed', detail: `the download failed: ${String(error)}` }
233
+ return record({ status: 'failed', detail: `the download failed: ${String(error)}` })
169
234
  } finally {
170
235
  if (timer !== undefined) clearTimeout(timer)
171
236
  }
172
237
  if (outcome.code !== 0) {
173
- return {
238
+ return record({
174
239
  status: 'failed',
175
240
  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
- }
241
+ + 'the browser still works through a sidebar, Chrome or Edge; retry from Settings → Browser → '
242
+ + 'Readiness ("Prepare the bundled browser"), or run `npx --no dsh-browser-install-electron`',
243
+ })
178
244
  }
179
- return { status: 'ready', detail: 'the Electron runtime is ready' }
245
+ return record({ status: 'ready', detail: 'the Electron runtime is ready' })
180
246
  }
181
247
 
182
248
  /** One attempt per process, shared by every caller. */
183
249
  let attempt: Promise<ProvisionResult> | undefined
250
+ /** Whether {@link attempt} has settled, which is what makes a retry possible. */
251
+ let settled = false
184
252
 
185
253
  /**
186
254
  * Start (or join) the single background attempt.
187
255
  *
188
256
  * Returns immediately with the shared promise, so a caller that does not care can ignore it and one
189
257
  * that does can await it — the returned promise never rejects.
258
+ *
259
+ * `force` is the second half of the settings panel's retry button. Without it the memoised attempt
260
+ * made a failed download permanent for the life of the process: the panel could offer a button, the
261
+ * button could call this, and the answer would be the failure it was trying to replace. An attempt
262
+ * still IN FLIGHT is always joined, never restarted — two downloads into one directory is the one
263
+ * outcome worth refusing.
190
264
  * @param log - where the outcome goes.
191
265
  * @param deps - the effects; defaulted to this process's, overridable so a test can drive it.
266
+ * @param options - `force` discards a settled attempt so a new one may start.
192
267
  * @returns the shared attempt.
193
268
  */
194
269
  export function provisionElectronInBackground(
195
270
  log: (message: string) => void,
196
271
  deps: ProvisionDeps = defaultDeps(log),
272
+ options: { readonly force?: boolean } = {},
197
273
  ): Promise<ProvisionResult> {
274
+ if (options.force === true && settled) {
275
+ attempt = undefined
276
+ settled = false
277
+ }
198
278
  attempt ??= ensureElectronRuntime(deps).then(result => {
279
+ settled = true
199
280
  log(`electron runtime: ${result.status} — ${result.detail}`)
200
281
  return result
201
282
  })
@@ -205,4 +286,6 @@ export function provisionElectronInBackground(
205
286
  /** Forget the attempt. Tests only: a real process provisions at most once. */
206
287
  export function resetProvisionStateForTest(): void {
207
288
  attempt = undefined
289
+ settled = false
290
+ latest = IDLE
208
291
  }
@@ -15,7 +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
+ import { provisionElectronInBackground, provisionSnapshot, hasElectronRuntime } from './electron-provision.js'
19
19
  import type { ElectronBrowserViewHost } from './provider.js'
20
20
  import type { CarrierLossReason } from '../browser/types.js'
21
21
  import { randomUUID } from 'node:crypto'
@@ -30,7 +30,14 @@ import { claimEphemeralProfile, ephemeralProfileName, sweepAbandonedEphemeralPro
30
30
  import { MissingSystemBrowserHost } from './missing-system-browser.js'
31
31
  import { SettingsStore, settingsPath } from './settings-store.js'
32
32
  import { sameOrigin } from './settings-route.js'
33
+ import { authenticatedRoute, isDirectLoopback, type BrowserConnection, type BrowserHttpHandler } from './authenticated-route.js'
33
34
  import { handleBridgeStatus, handlePreviewFrame, handlePreviewSessions, BRIDGE_STATUS_ROUTE, PREVIEW_ROUTE, PREVIEW_SESSIONS_ROUTE } from './preview-route.js'
35
+ import { findDesktopInstall, readBridgeStatus } from './bridge-status.js'
36
+ import { readBridgeEndpoint } from './bridge-endpoint.js'
37
+ import { runBridgeAction } from './bridge-install.js'
38
+ import { replyJson } from './json-reply.js'
39
+ import { readRuntimeStatus } from './runtime-status.js'
40
+ import { handleRuntimeProvision, handleRuntimeStatus, RUNTIME_PROVISION_ROUTE, RUNTIME_STATUS_ROUTE } from './runtime-route.js'
34
41
 
35
42
  export {
36
43
  ELECTRON_BROWSER_PROVIDER_ID,
@@ -369,7 +376,7 @@ export function apply(ctx: Context & { browser: BrowserRuntime }, config: Config
369
376
  // The headless mode rides along so a display-less host (systemd, container, SSH-only server)
370
377
  // still gets a working browser instead of "exited immediately after launch" — issue #32.
371
378
  adopt(new SystemBrowserViewHost(detected, profileDir, [], persist ? undefined : profileDir,
372
- undefined, settings.get().browser.headless),
379
+ undefined, settings.get().browser.headless, () => settings.get().ui.quiet),
373
380
  `will drive the installed ${detected.kind} (${detected.path}${persist ? '' : ', ephemeral profile'})`)
374
381
  }
375
382
  } else if (adoptedCarrier !== undefined) {
@@ -400,7 +407,7 @@ export function apply(ctx: Context & { browser: BrowserRuntime }, config: Config
400
407
  if (signal.aborted || disposed) return
401
408
  let sidebar: Awaited<ReturnType<typeof DesktopBridgeViewHost.discover>>
402
409
  try {
403
- sidebar = await DesktopBridgeViewHost.discover(sessionId)
410
+ sidebar = await DesktopBridgeViewHost.discover(sessionId, () => settings.get().ui.quiet)
404
411
  } catch {
405
412
  sidebar = undefined // discovery is documented not to throw; never let it stop the retries
406
413
  }
@@ -468,13 +475,13 @@ export function apply(ctx: Context & { browser: BrowserRuntime }, config: Config
468
475
  host.effect(() => host.webServer.register({
469
476
  kind: 'exact',
470
477
  path: PREVIEW_ROUTE,
471
- handler: (request, response) => handlePreviewFrame(request, response, settings, browser),
478
+ handler: authenticated(ctx, (request, response) => handlePreviewFrame(request, response, settings, browser)),
472
479
  }, 'dsh-builtin-browser: live view frame'))
473
480
  // The list the panel needs before it can build a frame URL at all: session ids only.
474
481
  host.effect(() => host.webServer.register({
475
482
  kind: 'exact',
476
483
  path: PREVIEW_SESSIONS_ROUTE,
477
- handler: (request, response) => handlePreviewSessions(request, response, settings, browser),
484
+ handler: authenticated(ctx, (request, response) => handlePreviewSessions(request, response, settings, browser)),
478
485
  }, 'dsh-builtin-browser: live view sessions')) })
479
486
  } catch {
480
487
  // No web server on this surface: watching is simply unavailable, and nothing else changes.
@@ -489,6 +496,56 @@ export function apply(ctx: Context & { browser: BrowserRuntime }, config: Config
489
496
  * exactly like the other two.
490
497
  * @param ctx - the plugin context.
491
498
  */
499
+ /** Where the panel asks to install or remove the bridge. */
500
+ const BRIDGE_ACTION_ROUTE = '/dsh-builtin-browser/bridge-action'
501
+ let bridgeActionRunning = false
502
+
503
+ /**
504
+ * Install, repair or remove the bridge, from a button.
505
+ *
506
+ * The panel used to print a command. This step closes and reopens the desktop app, so a
507
+ * half-finished manual run leaves the shell in a state the user then has to diagnose — the
508
+ * packaged installer already handles the whole sequence unattended, and this hands it the one
509
+ * decision that is not its own: which action the user pressed.
510
+ * @param request - the incoming request (POST, JSON body `{action}`).
511
+ * @param response - the response to write.
512
+ */
513
+ async function handleBridgeAction(request: IncomingMessage, response: ServerResponse): Promise<void> {
514
+ if (request.method !== 'POST') { replyJson(response, 405, { error: 'method-not-allowed' }); return }
515
+ // A write: it stops the shell. Same admission as a settings write, not the read rule.
516
+ if (!sameOrigin(request, true)) { replyJson(response, 403, { error: 'not-same-origin' }); return }
517
+ if (!isDirectLoopback(request)) { replyJson(response, 403, { error: 'local-request-required' }); return }
518
+ let action: unknown
519
+ try {
520
+ const body = await readBody(request)
521
+ action = (JSON.parse(body === '' ? '{}' : body) as { action?: unknown }).action
522
+ } catch (error) {
523
+ replyJson(response, 400, { ok: false, error: `unreadable body: ${String(error)}` })
524
+ return
525
+ }
526
+ if (action !== 'install' && action !== 'uninstall') {
527
+ replyJson(response, 400, { ok: false, error: 'action must be "install" or "uninstall"' })
528
+ return
529
+ }
530
+ const root = findDesktopInstall()
531
+ if (root === undefined) {
532
+ // Nothing to patch: say so instead of running an installer against a guess.
533
+ replyJson(response, 409, { ok: false, error: 'no DSH Desktop install was found on this machine' })
534
+ return
535
+ }
536
+ if (bridgeActionRunning) {
537
+ replyJson(response, 409, { ok: false, error: 'bridge-action-in-progress' })
538
+ return
539
+ }
540
+ bridgeActionRunning = true
541
+ try {
542
+ const result = await runBridgeAction(action, root)
543
+ replyJson(response, 200, { ok: result.ok, action, code: result.code, output: result.output, command: result.command })
544
+ } finally {
545
+ bridgeActionRunning = false
546
+ }
547
+ }
548
+
492
549
  function installBridgeStatusRoute(ctx: Context): void {
493
550
  const injectStatus = (ctx as unknown as {
494
551
  inject?: (deps: readonly string[], callback: (host: WebServerHost) => void) => void
@@ -499,8 +556,15 @@ export function apply(ctx: Context & { browser: BrowserRuntime }, config: Config
499
556
  host.effect(() => host.webServer.register({
500
557
  kind: 'exact',
501
558
  path: BRIDGE_STATUS_ROUTE,
502
- handler: (request, response) => handleBridgeStatus(request, response),
559
+ handler: authenticated(ctx, (request, response) => handleBridgeStatus(request, response)),
503
560
  }, 'dsh-builtin-browser: bridge status'))
561
+ // The same information, one action later: install/repair or remove the bridge without the
562
+ // user opening a terminal. Admitted as a write, because it closes and restarts the shell.
563
+ host.effect(() => host.webServer.register({
564
+ kind: 'exact',
565
+ path: BRIDGE_ACTION_ROUTE,
566
+ handler: authenticated(ctx, (request, response) => handleBridgeAction(request, response)),
567
+ }, 'dsh-builtin-browser: bridge action'))
504
568
  })
505
569
  } catch {
506
570
  // No web server: the panel is unreachable, and the installer stays the interface.
@@ -509,6 +573,67 @@ export function apply(ctx: Context & { browser: BrowserRuntime }, config: Config
509
573
 
510
574
  installSettingsRoute(ctx, settings, () => { chooseCarrier() })
511
575
 
576
+ /**
577
+ * Expose readiness — "can the browser serve a call right now" — for the settings panel.
578
+ *
579
+ * The panel had switches for every behaviour and no answer to the one question a new install
580
+ * raises: the bundled runtime is downloaded on first need (issue #41 moved it out of `postinstall`
581
+ * for good reasons), so for the first minute of a fresh install the honest state is "preparing",
582
+ * and until this route existed that state was a log line no panel could read. Both readings are
583
+ * cheap and side-effect free: a path probe for the runtime, an install-tree inspection for the
584
+ * bridge — the same two the launch path and the bridge-status route already use.
585
+ *
586
+ * Skipped, like its siblings, on a surface with no web server: a CLI has no panel to show it to.
587
+ * @param ctx - the plugin context.
588
+ * @param settings - the settings document, for the channel being honoured.
589
+ */
590
+ function installRuntimeStatusRoute(ctx: Context, settings: SettingsStore): void {
591
+ const injectRuntime = (ctx as unknown as {
592
+ inject?: (deps: readonly string[], callback: (host: WebServerHost) => void) => void
593
+ }).inject
594
+ if (typeof injectRuntime !== 'function') return
595
+ const deps = {
596
+ report: () => readRuntimeStatus({
597
+ channel: () => settings.get().browser.channel,
598
+ hasBinary: hasElectronRuntime,
599
+ provision: provisionSnapshot,
600
+ bridge: () => {
601
+ const root = findDesktopInstall()
602
+ return root === undefined ? undefined : readBridgeStatus(root)
603
+ },
604
+ // Installed is not running: the install tree survives a reboot, the endpoint does not. Both
605
+ // readings are cheap and side-effect free — a file read and a signal-0 pid check.
606
+ endpoint: () => readBridgeEndpoint(),
607
+ }),
608
+ // `force` is what makes the panel's retry button mean anything: without it the answer would be
609
+ // the settled failure the user is trying to replace. An attempt still running is joined.
610
+ provision: () => {
611
+ void provisionElectronInBackground(
612
+ message => ctx.logger?.info?.(`dsh-builtin-browser: ${message}`),
613
+ undefined,
614
+ { force: true },
615
+ )
616
+ return provisionSnapshot()
617
+ },
618
+ }
619
+ try {
620
+ injectRuntime(['webServer'], (host) => {
621
+ host.effect(() => host.webServer.register({
622
+ kind: 'exact',
623
+ path: RUNTIME_STATUS_ROUTE,
624
+ handler: authenticated(ctx, (request, response) => handleRuntimeStatus(request, response, deps)),
625
+ }, 'dsh-builtin-browser: runtime status'))
626
+ host.effect(() => host.webServer.register({
627
+ kind: 'exact',
628
+ path: RUNTIME_PROVISION_ROUTE,
629
+ handler: authenticated(ctx, (request, response) => handleRuntimeProvision(request, response, deps)),
630
+ }, 'dsh-builtin-browser: runtime provision'))
631
+ })
632
+ } catch {
633
+ // No web server: the panel is unreachable, and the readiness report has no reader.
634
+ }
635
+ }
636
+
512
637
  /**
513
638
  * Re-run the carrier choice when the settings FILE changes on disk.
514
639
  *
@@ -545,6 +670,7 @@ export function apply(ctx: Context & { browser: BrowserRuntime }, config: Config
545
670
  watchSettingsFile()
546
671
  installPreviewRoute(ctx, settings)
547
672
  installBridgeStatusRoute(ctx)
673
+ installRuntimeStatusRoute(ctx, settings)
548
674
  }
549
675
 
550
676
  /** Route the settings panel reads and writes. */
@@ -601,6 +727,14 @@ interface PreviewBrowser {
601
727
  watchableSessions?(): readonly string[]
602
728
  }
603
729
 
730
+ /** Bind the host's signed browser-session authentication to a plugin route. */
731
+ function authenticated(ctx: Context, handler: BrowserHttpHandler): BrowserHttpHandler {
732
+ return authenticatedRoute(() => {
733
+ const surface = ctx as unknown as { get(name: string): BrowserConnection | undefined }
734
+ return surface.get('connection')
735
+ }, handler)
736
+ }
737
+
604
738
  /** The host web-server surface this plugin uses, described structurally. */
605
739
  interface WebServerHost {
606
740
  readonly webServer: {
@@ -638,7 +772,7 @@ function installSettingsRoute(
638
772
  host.effect(() => host.webServer.register({
639
773
  kind: 'exact',
640
774
  path: SETTINGS_ROUTE,
641
- handler: (request, response) => handleSettingsRequest(request, response, settings, onChannelChange),
775
+ handler: authenticated(ctx, (request, response) => handleSettingsRequest(request, response, settings, onChannelChange)),
642
776
  }, 'dsh-builtin-browser: settings'))
643
777
  })
644
778
  } catch {
@@ -412,7 +412,12 @@ function windowFor(windowId: string | undefined): HostWindow {
412
412
  const key = windowId === undefined || windowId === '' ? SHARED_WINDOW_ID : windowId
413
413
  const existing = windows.get(key)
414
414
  if (existing !== undefined) return existing
415
- const w = new BrowserWindow({ width: 1400, height: 900, show: true, title: 'dsh-browser' })
415
+ // `show: false` on purpose: creating a window must not be a presentation decision. With `show: true`
416
+ // the window appeared and took the screen the moment the first tool call created it — before any
417
+ // `showView` message could carry `ui.quiet`, so quiet mode had no effect at all on this carrier
418
+ // (measured: the setting was on and the window still popped up). The first presentation decides:
419
+ // quiet shows it inactive, a normal call shows it normally.
420
+ const w = new BrowserWindow({ width: 1400, height: 900, show: false, title: 'dsh-browser' })
416
421
  w.on('closed', () => {
417
422
  const closing = windows.get(key)
418
423
  windows.delete(key)
@@ -616,30 +621,41 @@ function revealViewInWindow(win: HostWindow, viewId: string, label?: string): vo
616
621
  * @param label - session/task label, when known, for the window title.
617
622
  * @param quiet - `ui.quiet`: present without taking the screen over.
618
623
  * @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.
624
+ * input, so a newly created window needs an invisible display surface. A minimized window
625
+ * stays minimized because restoring it can activate it.
621
626
  */
622
627
  function showViewInWindow(win: HostWindow, viewId: string, label?: string, quiet = false, needSurface = false): void {
628
+ if (quiet) {
629
+ if (win.window.isMinimized()) {
630
+ if (needSurface) throw new Error('quiet mode will not restore a minimized browser window; restore it manually to send input')
631
+ return
632
+ }
633
+ if (win.window.isVisible() && win.window.getOpacity() > 0) {
634
+ if (win.visibleViewId !== viewId) {
635
+ if (needSurface) throw new Error('quiet mode will not replace a visible browser tab; select the target tab manually to send input')
636
+ return
637
+ }
638
+ revealViewInWindow(win, viewId, label)
639
+ return
640
+ }
641
+ revealViewInWindow(win, viewId, label)
642
+ if (!needSurface || win.window.isVisible()) return
643
+ win.window.setOpacity(0)
644
+ if (win.window.getOpacity() > 0) throw new Error('quiet mode could not create an invisible browser surface')
645
+ win.window.setSkipTaskbar(true)
646
+ win.window.setFocusable(false)
647
+ win.window.showInactive()
648
+ return
649
+ }
623
650
  revealViewInWindow(win, viewId, label)
624
- // Raise this session's window so the human sees the page being worked on
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.
634
651
  try {
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()
652
+ if (win.window.getOpacity() === 0) {
653
+ win.window.setFocusable(true)
654
+ win.window.setOpacity(1)
655
+ win.window.setSkipTaskbar(false)
642
656
  }
657
+ if (!win.window.isVisible()) win.window.show()
658
+ win.window.moveTop()
643
659
  } catch { /* closing */ }
644
660
  }
645
661
 
@@ -821,7 +837,10 @@ async function handle(op: string, msg: { id: number; viewId?: string; windowId?:
821
837
  // and `document.hasFocus()` inside the page even read true.
822
838
  const contents = entry.webContentsView.webContents
823
839
  const hadWebFocus = contents.isFocused()
824
- contents.focus()
840
+ if (msg.quiet === true && win.window.getOpacity() > 0 && !hadWebFocus) {
841
+ throw new Error('quiet mode will not take keyboard focus from the visible browser; focus the target page manually')
842
+ }
843
+ if (msg.quiet !== true || !hadWebFocus) contents.focus()
825
844
  // Focus lands asynchronously, and a key dispatched in the same turn as
826
845
  // the request is still dropped, so hold the reply until the renderer can
827
846
  // take input. Only on the call where focus actually had to move.
@@ -859,7 +878,7 @@ async function handle(op: string, msg: { id: number; viewId?: string; windowId?:
859
878
  // The active tab has to be the visible one INSIDE the window, or the capture may read
860
879
  // another tab. Keep that switch contentView-local: show/restore/focus are precisely
861
880
  // what quiet mode forbids.
862
- revealViewInWindow(win, viewId)
881
+ if (!win.window.isVisible() || win.window.getOpacity() === 0) revealViewInWindow(win, viewId)
863
882
  } else {
864
883
  try {
865
884
  if (!win.window.isVisible()) win.window.show()
@@ -0,0 +1,32 @@
1
+ /**
2
+ * One JSON reply, written the same way by every route this plugin serves.
3
+ *
4
+ * Its own module rather than a helper inside one route file: there are four endpoints now, and the
5
+ * second one that needed this had to import it from the live-view route — which reads as though the
6
+ * readiness endpoints belong to the preview. They do not; only the header rules are shared.
7
+ *
8
+ * The header set is the substance, not boilerplate:
9
+ * - `content-length` computed from the bytes actually written, so a proxy cannot truncate;
10
+ * - `no-store` because every answer here is a reading of the current moment;
11
+ * - `nosniff` + a same-origin resource policy, because these bodies name paths and pids.
12
+ * @module dsh-browser/browser-electron/json-reply
13
+ */
14
+ import type { ServerResponse } from 'node:http'
15
+
16
+ /**
17
+ * Write one JSON body with no caching and no sniffing.
18
+ * @param response - the response to write.
19
+ * @param status - the HTTP status.
20
+ * @param body - anything JSON-serialisable.
21
+ */
22
+ export function replyJson(response: ServerResponse, status: number, body: unknown): void {
23
+ const text = JSON.stringify(body)
24
+ response.writeHead(status, {
25
+ 'content-type': 'application/json; charset=utf-8',
26
+ 'content-length': Buffer.byteLength(text),
27
+ 'cache-control': 'no-store, private',
28
+ 'x-content-type-options': 'nosniff',
29
+ 'cross-origin-resource-policy': 'same-origin',
30
+ })
31
+ response.end(text)
32
+ }
@@ -14,6 +14,7 @@
14
14
  */
15
15
  import type { IncomingMessage, ServerResponse } from 'node:http'
16
16
  import type { BrowserError } from '../browser/types.js'
17
+ import { replyJson } from './json-reply.js'
17
18
  import { sameOrigin } from './settings-route.js'
18
19
  import { findDesktopInstall, readBridgeStatus } from './bridge-status.js'
19
20
 
@@ -89,18 +90,6 @@ export async function handlePreviewSessions(
89
90
  replyJson(response, 200, { enabled: true, sessions: [...sessions] })
90
91
  }
91
92
 
92
- /** Write one JSON body with no caching and no sniffing. */
93
- function replyJson(response: ServerResponse, status: number, body: unknown): void {
94
- const text = JSON.stringify(body)
95
- response.writeHead(status, {
96
- 'content-type': 'application/json; charset=utf-8',
97
- 'content-length': Buffer.byteLength(text),
98
- 'cache-control': 'no-store, private',
99
- 'x-content-type-options': 'nosniff',
100
- 'cross-origin-resource-policy': 'same-origin',
101
- })
102
- response.end(text)
103
- }
104
93
 
105
94
  /**
106
95
  * Serve one frame, or say precisely why not.