dsh-builtin-browser 0.5.6 → 0.5.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/CHANGELOG.md +148 -0
  2. package/README.en.md +75 -81
  3. package/README.md +75 -82
  4. package/client.js +831 -384
  5. package/desktop-bridge/install-and-start.cmd +4 -5
  6. package/desktop-bridge/install.mjs +322 -141
  7. package/desktop-bridge/maintenance-progress.ps1 +166 -0
  8. package/desktop-bridge/plugin-browser-bridge.js +157 -19
  9. package/desktop-bridge/request-desktop-quit.ps1 +170 -0
  10. package/docs/tool-reference.md +20 -1
  11. package/docs/user-guide.md +28 -4
  12. package/lib/browser/runtime.d.ts +3 -1
  13. package/lib/browser/runtime.js +9 -0
  14. package/lib/browser/types.d.ts +42 -0
  15. package/lib/browser-electron/authenticated-route.d.ts +27 -0
  16. package/lib/browser-electron/authenticated-route.js +39 -0
  17. package/lib/browser-electron/automatic-maintenance.d.ts +41 -0
  18. package/lib/browser-electron/automatic-maintenance.js +426 -0
  19. package/lib/browser-electron/bridge-auto.d.ts +93 -0
  20. package/lib/browser-electron/bridge-auto.js +113 -0
  21. package/lib/browser-electron/bridge-connection.d.ts +0 -2
  22. package/lib/browser-electron/bridge-connection.js +2 -4
  23. package/lib/browser-electron/bridge-endpoint.js +8 -19
  24. package/lib/browser-electron/bridge-install.d.ts +85 -0
  25. package/lib/browser-electron/bridge-install.js +211 -0
  26. package/lib/browser-electron/bridge-maintenance.d.ts +24 -0
  27. package/lib/browser-electron/bridge-maintenance.js +125 -0
  28. package/lib/browser-electron/bridge-status.d.ts +10 -3
  29. package/lib/browser-electron/bridge-status.js +74 -24
  30. package/lib/browser-electron/desktop-bridge-host.d.ts +11 -5
  31. package/lib/browser-electron/desktop-bridge-host.js +67 -25
  32. package/lib/browser-electron/desktop-identity.js +21 -9
  33. package/lib/browser-electron/electron-provision.d.ts +1 -1
  34. package/lib/browser-electron/electron-provision.js +36 -13
  35. package/lib/browser-electron/entry.js +173 -67
  36. package/lib/browser-electron/ephemeral-profile.js +67 -26
  37. package/lib/browser-electron/history-store.js +2 -2
  38. package/lib/browser-electron/host-main.js +48 -38
  39. package/lib/browser-electron/http-body.d.ts +24 -0
  40. package/lib/browser-electron/http-body.js +33 -0
  41. package/lib/browser-electron/json-reply.d.ts +13 -1
  42. package/lib/browser-electron/json-reply.js +16 -2
  43. package/lib/browser-electron/maintenance-broker.d.ts +35 -0
  44. package/lib/browser-electron/maintenance-broker.js +114 -0
  45. package/lib/browser-electron/maintenance-lifecycle.d.ts +32 -0
  46. package/lib/browser-electron/maintenance-lifecycle.js +67 -0
  47. package/lib/browser-electron/maintenance-route.d.ts +18 -0
  48. package/lib/browser-electron/maintenance-route.js +75 -0
  49. package/lib/browser-electron/paths.d.ts +4 -0
  50. package/lib/browser-electron/paths.js +19 -0
  51. package/lib/browser-electron/process.d.ts +14 -0
  52. package/lib/browser-electron/process.js +24 -0
  53. package/lib/browser-electron/provider.d.ts +16 -9
  54. package/lib/browser-electron/provider.js +87 -18
  55. package/lib/browser-electron/remote-host.js +22 -20
  56. package/lib/browser-electron/runtime-route.d.ts +3 -5
  57. package/lib/browser-electron/runtime-status.d.ts +27 -13
  58. package/lib/browser-electron/runtime-status.js +28 -6
  59. package/lib/browser-electron/settings-route.d.ts +5 -18
  60. package/lib/browser-electron/settings-route.js +4 -14
  61. package/lib/browser-electron/settings-store.d.ts +28 -0
  62. package/lib/browser-electron/settings-store.js +32 -2
  63. package/lib/browser-electron/sidebar-only-host.d.ts +36 -0
  64. package/lib/browser-electron/sidebar-only-host.js +192 -0
  65. package/lib/browser-electron/system-browser.d.ts +6 -11
  66. package/lib/browser-electron/system-browser.js +29 -24
  67. package/lib/browser-electron/timing.d.ts +8 -0
  68. package/lib/browser-electron/timing.js +13 -0
  69. package/lib/browser-electron/windows-system.d.ts +3 -0
  70. package/lib/browser-electron/windows-system.js +19 -0
  71. package/lib/tool-browser/index.js +1045 -7
  72. package/lib/tool-browser/page-probe.d.ts +86 -0
  73. package/lib/tool-browser/page-probe.js +460 -0
  74. package/package.json +5 -3
  75. package/scripts/run-tests.mjs +32 -0
  76. package/scripts/verify-preview-route.mjs +19 -1
  77. package/scripts/verify-runtime-status.mjs +14 -0
  78. package/skills/dsh-builtin-browser/SKILL.md +64 -0
  79. package/skills/dsh-builtin-browser/references/batch.md +23 -0
  80. package/skills/dsh-builtin-browser/references/deliver.md +31 -0
  81. package/skills/dsh-builtin-browser/references/locate.md +11 -0
  82. package/skills/dsh-builtin-browser/references/recover.md +11 -0
  83. package/skills/dsh-builtin-browser/references/verify.md +13 -0
  84. package/src/browser/runtime.ts +11 -0
  85. package/src/browser/types.ts +19 -0
  86. package/src/browser-electron/authenticated-route.ts +56 -0
  87. package/src/browser-electron/automatic-maintenance.ts +414 -0
  88. package/src/browser-electron/bridge-auto.ts +158 -0
  89. package/src/browser-electron/bridge-connection.ts +2 -4
  90. package/src/browser-electron/bridge-endpoint.ts +8 -18
  91. package/src/browser-electron/bridge-install.ts +253 -0
  92. package/src/browser-electron/bridge-maintenance.ts +161 -0
  93. package/src/browser-electron/bridge-status.ts +76 -26
  94. package/src/browser-electron/desktop-bridge-host.ts +60 -26
  95. package/src/browser-electron/desktop-identity.ts +18 -9
  96. package/src/browser-electron/electron-provision.ts +35 -14
  97. package/src/browser-electron/entry.ts +152 -62
  98. package/src/browser-electron/ephemeral-profile.ts +65 -28
  99. package/src/browser-electron/history-store.ts +2 -2
  100. package/src/browser-electron/host-main.ts +40 -34
  101. package/src/browser-electron/http-body.ts +42 -0
  102. package/src/browser-electron/json-reply.ts +18 -3
  103. package/src/browser-electron/maintenance-broker.ts +142 -0
  104. package/src/browser-electron/maintenance-lifecycle.ts +86 -0
  105. package/src/browser-electron/maintenance-route.ts +64 -0
  106. package/src/browser-electron/paths.ts +21 -0
  107. package/src/browser-electron/process.ts +23 -0
  108. package/src/browser-electron/provider.ts +106 -22
  109. package/src/browser-electron/remote-host.ts +23 -23
  110. package/src/browser-electron/runtime-route.ts +3 -5
  111. package/src/browser-electron/runtime-status.ts +56 -19
  112. package/src/browser-electron/settings-route.ts +9 -32
  113. package/src/browser-electron/settings-store.ts +59 -3
  114. package/src/browser-electron/sidebar-only-host.ts +199 -0
  115. package/src/browser-electron/system-browser.ts +26 -23
  116. package/src/browser-electron/timing.ts +16 -0
  117. package/src/browser-electron/windows-system.ts +23 -0
  118. package/src/tool-browser/index.ts +995 -10
  119. package/src/tool-browser/page-probe.ts +474 -0
@@ -7,6 +7,7 @@
7
7
  * @module dsh-browser/browser-electron
8
8
  */
9
9
 
10
+ import { pageOperationScript } from '../tool-browser/page-probe.js'
10
11
  import { randomUUID } from 'node:crypto'
11
12
  import { existsSync, lstatSync, mkdirSync, realpathSync } from 'node:fs'
12
13
  import { writeFileNoReplace } from './file-write.js'
@@ -28,6 +29,7 @@ import type {
28
29
  BrowserContentResult,
29
30
  BrowserElementTarget,
30
31
  BrowserExecuteRequest,
32
+ BrowserPageOperationRequest,
31
33
  BrowserExecuteResult,
32
34
  BrowserFillRequest,
33
35
  BrowserFillResult,
@@ -346,7 +348,7 @@ export interface ElectronViewHandle {
346
348
  * Optional: an adapter that cannot focus a view omits it, and the provider
347
349
  * then behaves exactly as before.
348
350
  */
349
- focus?(): Promise<void>
351
+ focus?(options?: PresentOptions): Promise<void>
350
352
  /**
351
353
  * Save a URL straight to disk, when the backing view can do that itself.
352
354
  *
@@ -619,13 +621,14 @@ export function toCdpCookie(cookie: ExportedCookie): Record<string, unknown> | u
619
621
  * `quiet` is the resolved `ui.quiet` switch. It does not mean "invisible": Chromium drops
620
622
  * synthesized `Input.*` for a view without a display surface, so input still needs one. It means
621
623
  * the carrier must get that surface without taking the screen over — no application activation
622
- * and no keyboard focus. Navigation and tab switching only reveal the view inside its window; the
623
- * pre-input barrier may restore a minimized window (it needs the surface), but even then it shows
624
- * it inactive instead of focusing or raising it. A host that cannot honour this (a headless probe,
625
- * the desktop sidebar) simply ignores it.
624
+ * and no operating-system keyboard focus. New windows open inactive; a minimized window and the
625
+ * foreground window's selected page remain under the operator's control. DOM focus and CDP input
626
+ * still target the task's page. Explicit sidebar navigation can select the task's pane.
626
627
  */
627
628
  export interface PresentOptions {
628
629
  readonly quiet?: boolean
630
+ /** Explicit navigation or tab selection may change the task's sidebar tab without OS activation. */
631
+ readonly select?: boolean
629
632
  }
630
633
 
631
634
  /**
@@ -644,6 +647,8 @@ export interface PresentOptions {
644
647
  export interface CommandOptions {
645
648
  /** Present the view first (default), or only use a page that is already there. */
646
649
  readonly present?: boolean
650
+ /** Only use a guest already attached to this handle, without sidebar initialization. */
651
+ readonly initialize?: boolean
647
652
  }
648
653
 
649
654
  /** Native capture options the self-hosted view handle understands. */
@@ -906,7 +911,7 @@ export class ElectronBrowserProvider implements BrowserProvider {
906
911
  const tab: Tab = { id: `page:${match.id}`, handle, url: match.url }
907
912
  s.tabs.push(tab)
908
913
  s.activeIndex = s.tabs.length - 1
909
- this.showActive(s)
914
+ this.showActive(s, true)
910
915
  return true
911
916
  } catch {
912
917
  // The page went away between listing and adopting: fall through to an ordinary navigation.
@@ -992,7 +997,7 @@ export class ElectronBrowserProvider implements BrowserProvider {
992
997
  }
993
998
  const found = this.locateTab(session, tabId)
994
999
  found.s.activeIndex = found.index
995
- this.showActive(found.s)
1000
+ this.showActive(found.s, true)
996
1001
  }
997
1002
 
998
1003
  /** Close one tab; closing the active tab activates the next. */
@@ -1133,7 +1138,7 @@ export class ElectronBrowserProvider implements BrowserProvider {
1133
1138
  tab.url = url
1134
1139
  await this.settleDocument(handle, before, signal)
1135
1140
  this.recordVisit(s, handle)
1136
- this.showActive(s)
1141
+ this.showActive(s, true)
1137
1142
  } catch (error) {
1138
1143
  if (!(error instanceof BrowserError && (error as { code?: string }).code === 'BROWSER_NAVIGATION_BLOCKED')) {
1139
1144
  this.record(s, 'navigate', { url }, false, { error: String(error) })
@@ -1165,7 +1170,7 @@ export class ElectronBrowserProvider implements BrowserProvider {
1165
1170
  private async documentProbe(handle: ElectronViewHandle): Promise<{ stamp: string; readyState: string } | null> {
1166
1171
  try {
1167
1172
  const result = await withTimeout(
1168
- handleSendEvaluate(handle, 'String(performance.timeOrigin) + "|" + document.readyState'),
1173
+ handleSendEvaluate(handle, 'String(performance.timeOrigin) + "|" + document.readyState', undefined, { present: false, initialize: false }),
1169
1174
  3_000,
1170
1175
  undefined,
1171
1176
  'browser: document probe timed out',
@@ -1311,13 +1316,15 @@ export class ElectronBrowserProvider implements BrowserProvider {
1311
1316
  */
1312
1317
  private async focusView(handle: ElectronViewHandle): Promise<void> {
1313
1318
  if (handle.focus === undefined) return
1319
+ const quiet = this.isQuiet()
1314
1320
  try {
1315
1321
  // Bounded, unlike the rest of this call: the child RPC has no timeout of its own,
1316
1322
  // and this runs before typing, so an unresponsive child would hang dsh_browser_key for
1317
1323
  // good. A timeout is caught below exactly like any other focus failure, so the
1318
1324
  // best-effort contract is unchanged.
1319
- await withTimeout(handle.focus(), 5_000, undefined, 'browser: focusing the view timed out')
1320
- } catch {
1325
+ await withTimeout(handle.focus(quiet ? { quiet } : undefined), 5_000, undefined, 'browser: focusing the view timed out')
1326
+ } catch (error) {
1327
+ if (quiet) throw error
1321
1328
  // Best-effort: a view that refuses focus must not fail the caller's key
1322
1329
  // press; the dispatch below reports a real channel failure itself.
1323
1330
  }
@@ -1326,6 +1333,81 @@ export class ElectronBrowserProvider implements BrowserProvider {
1326
1333
  /** Execute JS in the active tab's page context. */
1327
1334
  async execute(session: BrowserSessionId, request: BrowserExecuteRequest, signal?: AbortSignal): Promise<BrowserExecuteResult> {
1328
1335
  this.assertActionAllowed('execute')
1336
+ return this.evaluatePage(session, request, signal)
1337
+ }
1338
+
1339
+ /** Run a fixed browser operation; the request cannot contain a script. */
1340
+ async pageOperation(session: BrowserSessionId, request: BrowserPageOperationRequest, signal?: AbortSignal): Promise<BrowserExecuteResult> {
1341
+ const script = pageOperationScript(request)
1342
+ if (request.operation === 'drag') {
1343
+ return this.dispatchPointer(session, request.from, request.to, request.steps, signal)
1344
+ }
1345
+ if (request.operation === 'probe' && request.method === 'hoverAt') {
1346
+ const point = { x: Number(request.args?.[0]), y: Number(request.args?.[1]) }
1347
+ return this.dispatchPointer(session, point, undefined, 1, signal)
1348
+ }
1349
+ return this.evaluatePage(session, { script }, signal)
1350
+ }
1351
+
1352
+ /** Send page pointer input through CDP while preserving presentation and cancellation policy. */
1353
+ private async dispatchPointer(
1354
+ session: BrowserSessionId,
1355
+ from: { readonly x: number; readonly y: number },
1356
+ to: { readonly x: number; readonly y: number } | undefined,
1357
+ steps: number,
1358
+ signal?: AbortSignal,
1359
+ ): Promise<BrowserExecuteResult> {
1360
+ const coordinates = [from.x, from.y, ...to === undefined ? [] : [to.x, to.y]]
1361
+ if (coordinates.some(value => !Number.isFinite(value) || value < 0)) {
1362
+ throw new BrowserError('browser: pointer coordinates must be finite nonnegative viewport pixels', 'BROWSER_POINTER_INVALID')
1363
+ }
1364
+ if (to !== undefined && this.settingsSource?.().vision.strategy === 'nonVisual') {
1365
+ throw new BrowserError('browser: coordinate dragging requires the visual strategy', 'BROWSER_NON_VISUAL_COORDINATES')
1366
+ }
1367
+ const s = this.session(session)
1368
+ const handle = await this.present(s, signal)
1369
+ const viewport = await withTimeout(
1370
+ handleSendEvaluate(handle, '({width:innerWidth,height:innerHeight})'),
1371
+ 5_000, signal, 'browser: pointer viewport check timed out',
1372
+ )
1373
+ if (!viewport.ok) throw new BrowserError('browser: could not read the pointer viewport', 'BROWSER_POINTER_INVALID')
1374
+ const size = viewport.value as { width: number; height: number }
1375
+ if (from.x >= size.width || from.y >= size.height || (to !== undefined && (to.x >= size.width || to.y >= size.height))) {
1376
+ return { ok: true, value: JSON.stringify(to === undefined ? false : { ok: false, reason: 'drag points must be inside the current viewport' }) }
1377
+ }
1378
+ const send = async (params: CdpMouseParams): Promise<void> => {
1379
+ signal?.throwIfAborted()
1380
+ this.assertSameView(session, handle, this.activeTab(s).handle)
1381
+ await withTimeout(handle.sendCommand('Input.dispatchMouseEvent', { ...params }), 5_000, signal, 'browser: pointer input timed out')
1382
+ }
1383
+ await send({ type: 'mouseMoved', x: from.x, y: from.y, buttons: 0 })
1384
+ if (to === undefined) return { ok: true, value: 'true' }
1385
+ let at = from
1386
+ let held = true
1387
+ try {
1388
+ await send({ type: 'mousePressed', x: from.x, y: from.y, button: 'left', buttons: 1, clickCount: 1 })
1389
+ const count = Math.max(1, Math.min(Math.trunc(steps) || 12, 60))
1390
+ for (let step = 1; step <= count; step += 1) {
1391
+ const next = { x: from.x + (to.x - from.x) * step / count, y: from.y + (to.y - from.y) * step / count }
1392
+ await send({ type: 'mouseMoved', ...next, button: 'left', buttons: 1 })
1393
+ at = next
1394
+ }
1395
+ // Native HTML drag targets need a final drag-over before releasing at the destination.
1396
+ await send({ type: 'mouseMoved', ...to, button: 'left', buttons: 1 })
1397
+ await send({ type: 'mouseReleased', ...to, button: 'left', buttons: 0, clickCount: 1 })
1398
+ held = false
1399
+ return { ok: true, value: JSON.stringify({ ok: true, moved: count, at: to }) }
1400
+ } finally {
1401
+ if (held) {
1402
+ await withTimeout(
1403
+ handle.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', ...at, button: 'left', buttons: 0, clickCount: 1 }),
1404
+ 1_000, undefined, 'browser: pointer release timed out',
1405
+ ).catch(() => {})
1406
+ }
1407
+ }
1408
+ }
1409
+
1410
+ private async evaluatePage(session: BrowserSessionId, request: BrowserExecuteRequest, signal?: AbortSignal): Promise<BrowserExecuteResult> {
1329
1411
  const s = this.session(session)
1330
1412
  const { handle } = this.activeTab(s)
1331
1413
  signal?.throwIfAborted()
@@ -3058,9 +3140,8 @@ export class ElectronBrowserProvider implements BrowserProvider {
3058
3140
 
3059
3141
  /**
3060
3142
  * Download an HTTP(S) URL with the session's cookies to a local file.
3061
- * Admission is the shared {@link admitSavePath} gate; only the self-hosted
3062
- * host implements it (the desktop shell's embedded views delegate downloads
3063
- * to the real browser UI). Both admitted paths and screenshots are confined
3143
+ * Admission is the shared {@link admitSavePath} gate. The carrier downloads
3144
+ * with its own authenticated browser session. Both admitted paths and screenshots are confined
3064
3145
  * to `downloadDir`, so a prompt-injected agent cannot write arbitrary
3065
3146
  * machine paths.
3066
3147
  * @param session - the session whose cookies are used.
@@ -3092,7 +3173,7 @@ export class ElectronBrowserProvider implements BrowserProvider {
3092
3173
  const savePath = this.admitSavePath(request.savePath, 'download')
3093
3174
  const downloadable = handle
3094
3175
  if (typeof downloadable.download !== 'function') {
3095
- throw new BrowserError('browser: download is only available on the self-hosted browser', 'BROWSER_DOWNLOAD_UNSUPPORTED')
3176
+ throw new BrowserError('browser: the selected carrier does not provide file downloads', 'BROWSER_DOWNLOAD_UNSUPPORTED')
3096
3177
  }
3097
3178
  // The child fetches and writes the file; a slow/hung network can block
3098
3179
  // it well past the tool budget, so bound it. NOTE: unlike CDP calls,
@@ -3199,15 +3280,15 @@ export class ElectronBrowserProvider implements BrowserProvider {
3199
3280
  if (dropped > 0) {
3200
3281
  process.stderr.write(`[dsh-browser] restoreAuth: dropped ${dropped} of ${mapped.length} cookie(s) with no usable domain; the rest were still restored\n`)
3201
3282
  }
3202
- const result = await withTimeout(
3283
+ await withTimeout(
3203
3284
  handle.sendCommand('Storage.setCookies', { cookies: convertible }),
3204
3285
  timeoutMs,
3205
3286
  undefined,
3206
3287
  `browser: auth restore timed out after ${timeoutMs}ms`,
3207
3288
  )
3208
- // Storage.setCookies returns nothing, so the count comes from what was actually
3209
- // sent. Reading result.cookies here was always undefined, which rendered as
3210
- // "Restored 0 cookies." while the write had succeeded.
3289
+ // Storage.setCookies returns nothing, so the count comes from what was actually sent.
3290
+ // An earlier version read result.cookies here; it was always undefined and rendered as
3291
+ // "Restored 0 cookies." even though the write had succeeded.
3211
3292
  const restored = convertible.length
3212
3293
  this.record(s, 'restoreAuth', { count: cookies.length, dropped }, true, { result: `${restored} cookies (CDP)${dropped > 0 ? `; ${dropped} dropped` : ''}` })
3213
3294
  return restored
@@ -3820,8 +3901,10 @@ export class ElectronBrowserProvider implements BrowserProvider {
3820
3901
  * method did nothing at all on carriers without `collapse` (the self-hosted one),
3821
3902
  * silently desynchronising the two and failing every screenshot.
3822
3903
  */
3823
- private showActive(s: Session): void {
3824
- this.host.showView?.(this.activeTab(s).handle, s.label, { quiet: this.isQuiet() })
3904
+ private showActive(s: Session, select = false): void {
3905
+ const quiet = this.isQuiet()
3906
+ this.host.showView?.(this.activeTab(s).handle, s.label, { quiet, ...select ? { select: true } : {} })
3907
+ if (quiet || select) return
3825
3908
  const autoExpand = this.settingsSource === undefined || this.settingsSource().ui.autoExpandOnce
3826
3909
  if (autoExpand) return
3827
3910
  // Best effort: a carrier that owns no presentation (self-hosted) simply has none.
@@ -3989,13 +4072,14 @@ async function handleSendEvaluate(
3989
4072
  handle: ElectronViewHandle,
3990
4073
  expression: string,
3991
4074
  signal?: AbortSignal,
4075
+ options?: CommandOptions,
3992
4076
  ): Promise<BrowserExecuteResult> {
3993
4077
  signal?.throwIfAborted()
3994
4078
  const result = await handle.sendCommand(CDP_RUNTIME_EVALUATE, {
3995
4079
  expression,
3996
4080
  returnByValue: true,
3997
4081
  awaitPromise: true,
3998
- } satisfies CdpEvaluateParams)
4082
+ } satisfies CdpEvaluateParams, options)
3999
4083
  if (result.exceptionDetails !== undefined) {
4000
4084
  const detail = result.exceptionDetails as { text?: string; exception?: { description?: string } }
4001
4085
  return { ok: false, exception: detail.exception?.description ?? detail.text ?? 'unknown exception' }
@@ -34,6 +34,7 @@ import { createRequire } from 'node:module'
34
34
  import { existsSync, readFileSync, readdirSync, readlinkSync } from 'node:fs'
35
35
  import { basename, dirname, isAbsolute, join } from 'node:path'
36
36
  import { createServer, type Server, type Socket } from 'node:net'
37
+ import { withTimeoutShared } from './timing.js'
37
38
  import { fileURLToPath } from 'node:url'
38
39
  import type { BrowserUserAction, ElectronBrowserViewHost, ElectronViewHandle, PresentOptions, ScreenshotOptions } from './provider.js'
39
40
  import type { ExportedCookie } from '../browser/types.js'
@@ -263,15 +264,20 @@ function hostElectronViaProcessTree(): string | undefined {
263
264
  return undefined
264
265
  }
265
266
 
267
+ /** One scalar property of a Windows process, read through CIM. */
268
+ function cimQuery(pid: number, property: 'ExecutablePath' | 'ParentProcessId'): string {
269
+ const out = execFileSync('powershell.exe', [
270
+ '-NoProfile', '-NonInteractive', '-Command',
271
+ `(Get-CimInstance Win32_Process -Filter "ProcessId=${pid}").${property}`,
272
+ ], { encoding: 'utf8', windowsHide: true, timeout: 3000 })
273
+ return out.trim().split(/\r?\n/)[0] ?? ''
274
+ }
275
+
266
276
  /** The executable path of a running process, or undefined when unknown. */
267
277
  function processExecutable(pid: number): string | undefined {
268
278
  try {
269
279
  if (process.platform === 'win32') {
270
- const out = execFileSync('powershell.exe', [
271
- '-NoProfile', '-NonInteractive', '-Command',
272
- `(Get-CimInstance Win32_Process -Filter "ProcessId=${pid}").ExecutablePath`,
273
- ], { encoding: 'utf8', windowsHide: true, timeout: 3000 })
274
- const line = out.trim().split(/\r?\n/)[0] ?? ''
280
+ const line = cimQuery(pid, 'ExecutablePath')
275
281
  return line.length > 0 ? line : undefined
276
282
  }
277
283
  const exe = readlinkSync(`/proc/${pid}/exe`)
@@ -285,11 +291,7 @@ function processExecutable(pid: number): string | undefined {
285
291
  function processParent(pid: number): number | undefined {
286
292
  try {
287
293
  if (process.platform === 'win32') {
288
- const out = execFileSync('powershell.exe', [
289
- '-NoProfile', '-NonInteractive', '-Command',
290
- `(Get-CimInstance Win32_Process -Filter "ProcessId=${pid}").ParentProcessId`,
291
- ], { encoding: 'utf8', windowsHide: true, timeout: 3000 })
292
- const n = Number(out.trim().split(/\r?\n/)[0])
294
+ const n = Number(cimQuery(pid, 'ParentProcessId'))
293
295
  return Number.isInteger(n) && n > 1 ? n : undefined
294
296
  }
295
297
  const stat = readFileSync(`/proc/${pid}/stat`, 'utf8')
@@ -775,8 +777,8 @@ class RemoteView implements ElectronViewHandle {
775
777
  }
776
778
 
777
779
  /** Give this view web focus in the child, so keyboard input reaches the page. */
778
- focus(): Promise<void> {
779
- return this.client.call<void>('focus', { viewId: this.id })
780
+ focus(options?: PresentOptions): Promise<void> {
781
+ return this.client.call<void>('focus', { viewId: this.id, ...options?.quiet ? { quiet: true } : {} })
780
782
  }
781
783
 
782
784
  /** Ask the child to download a URL to a local file (keeps cookies/login). */
@@ -1376,8 +1378,8 @@ class DeferredRemoteView implements ElectronViewHandle {
1376
1378
  return this.withRecovery(view => view.capture(opts))
1377
1379
  }
1378
1380
 
1379
- async focus(): Promise<void> {
1380
- return this.withRecovery(view => view.focus())
1381
+ async focus(options?: PresentOptions): Promise<void> {
1382
+ return this.withRecovery(view => view.focus(options))
1381
1383
  }
1382
1384
 
1383
1385
  async flushAuth(): Promise<ExportedCookie[]> {
@@ -1425,21 +1427,19 @@ function appendHostLog(text: string): void {
1425
1427
  // history of a crash loop gets silently swallowed.
1426
1428
  writeFileSync(file, `${hostStamp()} log rotated: previous content exceeded ${String(HOST_LOG_MAX_BYTES)} bytes and was discarded\n`)
1427
1429
  }
1428
- } catch { /* first write, or unreadable: just append */ }
1429
- mkdirSync(dir, { recursive: true })
1430
+ } catch {
1431
+ // No readable file yet: the log directory may not exist. When statSync
1432
+ // succeeded the file exists, so its directory does too and creating it
1433
+ // again was a redundant syscall on every child stdout/stderr line.
1434
+ mkdirSync(dir, { recursive: true })
1435
+ }
1430
1436
  appendFileSync(file, text)
1431
1437
  } catch { /* diagnostics are best-effort only */ }
1432
1438
  }
1433
1439
 
1434
1440
  /** Reject a promise if it does not settle within the budget. */
1435
1441
  function withTimeout<T>(promise: Promise<T>, ms: number, message: string): Promise<T> {
1436
- return new Promise<T>((resolve, reject) => {
1437
- const timer = setTimeout(() => reject(new Error(`${message} (${ms}ms)`)), ms)
1438
- promise.then(
1439
- value => { clearTimeout(timer); resolve(value) },
1440
- error => { clearTimeout(timer); reject(error) },
1441
- )
1442
- })
1442
+ return withTimeoutShared(promise, ms, () => new Error(`${message} (${ms}ms)`))
1443
1443
  }
1444
1444
 
1445
1445
  /** Default host-main path relative to this module's build output. */
@@ -1,11 +1,9 @@
1
1
  /**
2
2
  * The readiness endpoints the settings panel reads.
3
3
  *
4
- * Two of them, because the two questions have different weights: reading the state is a `GET` any
5
- * same-origin document may make, and starting a download is a `POST` held to the stricter admission
6
- * rule in `settings-route.ts`. No credential system exists here — that module's own comment says
7
- * what the rule buys — but a request that STARTS a 100 MB download is on the wrong side of the same
8
- * line the settings write is on, so it is checked the way a write is.
4
+ * The host authenticates both routes with its signed browser-session cookie. The read returns
5
+ * readiness, while a POST starts runtime preparation and also passes the settings write-origin
6
+ * checks.
9
7
  *
10
8
  * Both answer with the whole report rather than a delta: the panel replaces what it shows with what
11
9
  * it is told, so a stale poll can never leave a wrong state on screen.
@@ -14,27 +14,33 @@
14
14
  * the settings panel renders it, and a test drives it without touching Electron, a desktop install
15
15
  * or the file system.
16
16
  *
17
- * Everything here is a cheap read by construction. `hasBinary` resolves a path (the same probe a
18
- * launch uses, so the answer can never disagree with a launch), and the bridge reading is the same
19
- * install-tree inspection the bridge-status route already serves. Nothing spawns anything.
17
+ * Everything here is a cheap environment check. The launch path's own binary probes resolve the
18
+ * bundled runtime and installed system browsers; bridge readers inspect the installation and its
19
+ * published endpoint. Available files establish availability, while browser calls establish whether
20
+ * a particular page can be driven. Nothing spawns anything.
20
21
  * @module dsh-browser/browser-electron/runtime-status
21
22
  */
22
23
  import type { BridgeStatus } from './bridge-status.js'
23
24
  import type { BridgeEndpointState } from './bridge-endpoint.js'
24
25
  import type { ProvisionSnapshot } from './electron-provision.js'
25
- import type { BrowserChannel } from './system-browser.js'
26
+ import { detectBrowser, type BrowserChannel, type DetectedBrowser } from './system-browser.js'
26
27
 
27
28
  /** The part of the carrier the channel names, in the terms the panel has to explain. */
28
29
  export type CarrierKind = 'sidebar' | 'bundled' | 'system' | 'auto'
29
30
 
30
- /**
31
- * Whether the readiness question has an answer at all.
32
- *
33
- * `unknown` is not a defect: an explicit Chrome / Edge choice is only falsifiable by launching one,
34
- * and launching a browser to answer a status question is exactly what this report must not do. The
35
- * panel says so in words instead of guessing a colour.
36
- */
37
- export type Readiness = 'ready' | 'blocked' | 'unknown'
31
+ /** Whether the chosen carrier's required files or running bridge are available. */
32
+ export type Readiness = 'ready' | 'blocked'
33
+
34
+ /** The system-browser discovery result, obtained without launching an executable. */
35
+ export interface SystemBrowserReadiness {
36
+ /** False for channels that use the sidebar or bundled runtime directly. */
37
+ readonly checked: boolean
38
+ readonly present: boolean
39
+ readonly kind?: DetectedBrowser['kind']
40
+ readonly path?: string
41
+ /** What was found or which configured product is missing. */
42
+ readonly detail: string
43
+ }
38
44
 
39
45
  /** The Electron runtime's state, as the panel needs it. */
40
46
  export interface ElectronReadiness {
@@ -75,8 +81,13 @@ export interface RuntimeStatusReport {
75
81
  readonly channel: BrowserChannel
76
82
  /** What that channel resolves to, in panel terms. */
77
83
  readonly carrier: CarrierKind
78
- /** Whether the browser this channel names can serve a call right now. */
84
+ /** The concrete carrier selected by the same discovery priority as the browser provider. */
85
+ readonly resolvedCarrier: Exclude<CarrierKind, 'auto'>
86
+ /** Whether the carrier's environment requirements are available. */
79
87
  readonly readiness: Readiness
88
+ readonly systemBrowser: SystemBrowserReadiness
89
+ /** The system executable selected for the resolved carrier, when applicable. */
90
+ readonly executable?: string
80
91
  readonly electron: ElectronReadiness
81
92
  readonly bridge: BridgeReadiness
82
93
  /** Whether "Prepare the bundled browser" is worth offering (it is not while one is running). */
@@ -95,6 +106,10 @@ export interface RuntimeStatusDeps {
95
106
  readonly bridge: () => BridgeStatus | undefined
96
107
  /** The endpoint the shell publishes while it runs; undefined when nothing published one. */
97
108
  readonly endpoint: () => BridgeEndpointState | undefined
109
+ /** The launch path's filesystem-only browser discovery; defaults to the production reader. */
110
+ readonly detectBrowser?: (channel: BrowserChannel) => DetectedBrowser | undefined
111
+ /** The provider's current carrier, including a fallback selected after sidebar loss. */
112
+ readonly selectedCarrier?: () => Exclude<CarrierKind, 'auto'> | undefined
98
113
  }
99
114
 
100
115
  /** Which carrier a channel names. */
@@ -130,10 +145,12 @@ export function readRuntimeStatus(deps: RuntimeStatusDeps): RuntimeStatusReport
130
145
  // on a live install, and the kind of contradiction a reader cannot resolve.
131
146
  const snapshot = deps.provision()
132
147
  const runnable = deps.hasBinary()
133
- const state: ElectronReadiness['state'] = runnable ? 'present' : snapshot.state
148
+ const missingAfterReady = !runnable && (snapshot.state === 'present' || snapshot.state === 'ready')
149
+ const state: ElectronReadiness['state'] = runnable ? 'present' : missingAfterReady ? 'failed' : snapshot.state
134
150
  const electron: ElectronReadiness = {
135
151
  state,
136
- detail: runnable ? 'an Electron runtime is already available' : snapshot.detail,
152
+ detail: runnable ? 'an Electron runtime is already available'
153
+ : missingAfterReady ? 'the previously prepared Electron runtime is missing; prepare it again' : snapshot.detail,
137
154
  at: runnable ? new Date().toISOString() : snapshot.at,
138
155
  }
139
156
 
@@ -160,23 +177,43 @@ export function readRuntimeStatus(deps: RuntimeStatusDeps): RuntimeStatusReport
160
177
  // shell actually running. Either one alone is the false green this report exists to prevent.
161
178
  const sidebarReady = bridge.state === 'installed' && bridge.running
162
179
 
180
+ const checkSystemBrowser = carrier === 'system' || carrier === 'auto'
181
+ const detected = checkSystemBrowser ? (deps.detectBrowser ?? detectBrowser)(channel) : undefined
182
+ const systemBrowser: SystemBrowserReadiness = {
183
+ checked: checkSystemBrowser,
184
+ present: detected !== undefined,
185
+ ...detected === undefined ? {} : { kind: detected.kind, path: detected.path },
186
+ detail: detected !== undefined ? `${detected.kind} is available at ${detected.path}`
187
+ : !checkSystemBrowser ? `the ${carrier} channel uses its own carrier`
188
+ : channel === 'auto' ? 'no Chrome, Edge or Brave installation was found'
189
+ : `the selected ${channel} installation was not found`,
190
+ }
191
+
163
192
  let readiness: Readiness
193
+ let resolvedCarrier: RuntimeStatusReport['resolvedCarrier']
164
194
  if (carrier === 'sidebar') {
195
+ resolvedCarrier = 'sidebar'
165
196
  readiness = sidebarReady ? 'ready' : 'blocked'
166
197
  } else if (carrier === 'bundled') {
198
+ resolvedCarrier = 'bundled'
167
199
  readiness = electronReady(state) ? 'ready' : 'blocked'
168
200
  } else if (carrier === 'auto') {
169
- // `auto` is satisfied by either carrier, so a working sidebar covers a missing runtime. An
170
- // explicit Chrome / Edge install would satisfy it too, but proving that means launching one.
171
- readiness = electronReady(state) || sidebarReady ? 'ready' : 'unknown'
201
+ // Discovery may adopt a live desktop bridge after initially choosing a system browser. Match
202
+ // that priority here, then use the bundled runtime when no system browser was found.
203
+ resolvedCarrier = deps.selectedCarrier?.() ?? (sidebarReady ? 'sidebar' : detected !== undefined ? 'system' : 'bundled')
204
+ readiness = (resolvedCarrier === 'sidebar' ? sidebarReady : resolvedCarrier === 'system' ? detected !== undefined : electronReady(state)) ? 'ready' : 'blocked'
172
205
  } else {
173
- readiness = 'unknown'
206
+ resolvedCarrier = 'system'
207
+ readiness = detected !== undefined ? 'ready' : 'blocked'
174
208
  }
175
209
 
176
210
  return {
177
211
  channel,
178
212
  carrier,
213
+ resolvedCarrier,
179
214
  readiness,
215
+ systemBrowser,
216
+ ...resolvedCarrier === 'system' && detected !== undefined ? { executable: detected.path } : {},
180
217
  electron,
181
218
  bridge,
182
219
  // Offering the button while a download runs would be a second download, which is the one thing
@@ -1,22 +1,9 @@
1
1
  /**
2
- * Admission for the settings route: who may read the document, and who may write it.
3
- *
4
- * Its own module for a blunt reason — `entry.ts` imports the host's peer packages (cordis, the
5
- * tools registry) and therefore cannot be loaded by the test suite, while this is precisely the
6
- * logic whose failure is invisible in a browser: too strict and the panel silently stops being
7
- * able to save, too loose and any process on the machine can rewrite the operator's switches.
8
- *
9
- * It is NOT authentication, and cannot be. The plugin has no credential to check: DSH hands
10
- * plugin routes the raw request (`packages/host/webserver/src/index.ts` registers handlers with
11
- * no gate of its own), so the strongest same-origin evidence available is what a browser
12
- * reliably sends.
13
- *
14
- * What that buys and what it does not:
15
- * - a plain HTTP client (curl, a script, another process) cannot WRITE, because it sends no
16
- * `user-agent` and no `accept-language`;
17
- * - a page of THIS origin can, because a browser sending a same-origin write looks exactly
18
- * like the panel. That is inherent to exposing an HTTP endpoint at all, and it is why the
19
- * settings panel's own text must not promise a lock that does not exist.
2
+ * Browser-origin checks used after DSH authenticates each plugin HTTP request.
3
+ * Desktop protocol forwarding supplies the host session cookie while Chromium may omit Origin
4
+ * and Referer for the custom application scheme. These checks preserve that request shape and
5
+ * reject browser requests that explicitly name another web origin.
6
+ * @module dsh-browser/browser-electron/settings-route
20
7
  */
21
8
  import type { IncomingMessage } from 'node:http'
22
9
 
@@ -51,24 +38,14 @@ export function sameOrigin(request: IncomingMessage, writing = false): boolean {
51
38
  if (APP_SCHEMES.includes(schemeOf(origin) ?? '')) return true
52
39
  if (APP_SCHEMES.includes(schemeOf(String(request.headers.referer ?? '')) ?? '')) return true
53
40
 
54
- // MEASURED on the running desktop, and what three earlier attempts each guessed wrong: a
55
- // request from the shell's own settings panel carries NO origin, NO sec-fetch-site and NO
56
- // referer. It is not "dsh-app://app" and it is not "null" — the headers are simply absent,
57
- // because Chromium attaches no cross-origin metadata to a request leaving a custom scheme.
58
- //
59
- // So the rule for that shape cannot be "a request without an Origin is a script", which is
60
- // what refused every desktop save, and it cannot lean on `Sec-Fetch-Site` either. It has to
61
- // test what a hand-rolled client does not send:
62
- // - a renderer sends a full Mozilla-compatible `user-agent` AND an `accept-language`;
63
- // - curl sends neither unless told to, and a local process that forges both can also read
64
- // the settings document directly — it sits readable on disk, as the panel's own text
65
- // says. This was never the boundary it looked like.
41
+ // Desktop custom-scheme requests can omit browser origin metadata. The route's host-cookie
42
+ // gate has already authenticated them; the renderer headers retain compatibility with older
43
+ // shells that omit Origin while forwarding settings writes.
66
44
  if (origin === '') {
67
45
  const agent = String(request.headers['user-agent'] ?? '')
68
46
  const language = String(request.headers['accept-language'] ?? '')
69
47
  if (/^Mozilla\/5\.0/.test(agent) && language !== '') return true
70
- // Reads stay open: they return the document the panel is already showing, and refusing them
71
- // would only break hand-inspection of a file that sits readable on disk anyway.
48
+ // A missing Origin is valid for reads after the host-cookie gate has admitted the caller.
72
49
  return !writing
73
50
  }
74
51