dsh-builtin-browser 0.5.6 → 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 (63) hide show
  1. package/CHANGELOG.md +82 -0
  2. package/README.en.md +67 -99
  3. package/README.md +67 -100
  4. package/client.js +381 -322
  5. package/desktop-bridge/install.mjs +122 -33
  6. package/desktop-bridge/plugin-browser-bridge.js +9 -4
  7. package/docs/tool-reference.md +20 -1
  8. package/lib/browser/runtime.d.ts +3 -1
  9. package/lib/browser/runtime.js +9 -0
  10. package/lib/browser/types.d.ts +42 -0
  11. package/lib/browser-electron/authenticated-route.d.ts +27 -0
  12. package/lib/browser-electron/authenticated-route.js +39 -0
  13. package/lib/browser-electron/bridge-endpoint.js +7 -0
  14. package/lib/browser-electron/bridge-install.d.ts +48 -0
  15. package/lib/browser-electron/bridge-install.js +98 -0
  16. package/lib/browser-electron/bridge-status.js +21 -2
  17. package/lib/browser-electron/desktop-bridge-host.d.ts +7 -4
  18. package/lib/browser-electron/desktop-bridge-host.js +36 -15
  19. package/lib/browser-electron/electron-provision.d.ts +1 -1
  20. package/lib/browser-electron/electron-provision.js +31 -11
  21. package/lib/browser-electron/entry.js +84 -8
  22. package/lib/browser-electron/host-main.js +48 -27
  23. package/lib/browser-electron/provider.d.ts +9 -2
  24. package/lib/browser-electron/provider.js +76 -6
  25. package/lib/browser-electron/remote-host.js +4 -4
  26. package/lib/browser-electron/runtime-route.d.ts +3 -5
  27. package/lib/browser-electron/runtime-status.js +4 -2
  28. package/lib/browser-electron/settings-route.d.ts +5 -18
  29. package/lib/browser-electron/settings-route.js +4 -14
  30. package/lib/browser-electron/settings-store.d.ts +17 -0
  31. package/lib/browser-electron/settings-store.js +24 -0
  32. package/lib/browser-electron/system-browser.d.ts +5 -2
  33. package/lib/browser-electron/system-browser.js +12 -4
  34. package/lib/tool-browser/index.js +1041 -4
  35. package/lib/tool-browser/page-probe.d.ts +86 -0
  36. package/lib/tool-browser/page-probe.js +460 -0
  37. package/package.json +4 -2
  38. package/scripts/verify-runtime-status.mjs +14 -0
  39. package/skills/dsh-builtin-browser/SKILL.md +64 -0
  40. package/skills/dsh-builtin-browser/references/batch.md +23 -0
  41. package/skills/dsh-builtin-browser/references/deliver.md +31 -0
  42. package/skills/dsh-builtin-browser/references/locate.md +11 -0
  43. package/skills/dsh-builtin-browser/references/recover.md +11 -0
  44. package/skills/dsh-builtin-browser/references/verify.md +13 -0
  45. package/src/browser/runtime.ts +11 -0
  46. package/src/browser/types.ts +19 -0
  47. package/src/browser-electron/authenticated-route.ts +56 -0
  48. package/src/browser-electron/bridge-endpoint.ts +7 -0
  49. package/src/browser-electron/bridge-install.ts +122 -0
  50. package/src/browser-electron/bridge-status.ts +22 -2
  51. package/src/browser-electron/desktop-bridge-host.ts +33 -15
  52. package/src/browser-electron/electron-provision.ts +30 -12
  53. package/src/browser-electron/entry.ts +76 -8
  54. package/src/browser-electron/host-main.ts +41 -22
  55. package/src/browser-electron/provider.ts +90 -6
  56. package/src/browser-electron/remote-host.ts +4 -4
  57. package/src/browser-electron/runtime-route.ts +3 -5
  58. package/src/browser-electron/runtime-status.ts +4 -2
  59. package/src/browser-electron/settings-route.ts +9 -32
  60. package/src/browser-electron/settings-store.ts +39 -0
  61. package/src/browser-electron/system-browser.ts +9 -3
  62. package/src/tool-browser/index.ts +991 -7
  63. package/src/tool-browser/page-probe.ts +474 -0
@@ -30,9 +30,12 @@ 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'
34
35
  import { findDesktopInstall, readBridgeStatus } from './bridge-status.js'
35
36
  import { readBridgeEndpoint } from './bridge-endpoint.js'
37
+ import { runBridgeAction } from './bridge-install.js'
38
+ import { replyJson } from './json-reply.js'
36
39
  import { readRuntimeStatus } from './runtime-status.js'
37
40
  import { handleRuntimeProvision, handleRuntimeStatus, RUNTIME_PROVISION_ROUTE, RUNTIME_STATUS_ROUTE } from './runtime-route.js'
38
41
 
@@ -373,7 +376,7 @@ export function apply(ctx: Context & { browser: BrowserRuntime }, config: Config
373
376
  // The headless mode rides along so a display-less host (systemd, container, SSH-only server)
374
377
  // still gets a working browser instead of "exited immediately after launch" — issue #32.
375
378
  adopt(new SystemBrowserViewHost(detected, profileDir, [], persist ? undefined : profileDir,
376
- undefined, settings.get().browser.headless),
379
+ undefined, settings.get().browser.headless, () => settings.get().ui.quiet),
377
380
  `will drive the installed ${detected.kind} (${detected.path}${persist ? '' : ', ephemeral profile'})`)
378
381
  }
379
382
  } else if (adoptedCarrier !== undefined) {
@@ -404,7 +407,7 @@ export function apply(ctx: Context & { browser: BrowserRuntime }, config: Config
404
407
  if (signal.aborted || disposed) return
405
408
  let sidebar: Awaited<ReturnType<typeof DesktopBridgeViewHost.discover>>
406
409
  try {
407
- sidebar = await DesktopBridgeViewHost.discover(sessionId)
410
+ sidebar = await DesktopBridgeViewHost.discover(sessionId, () => settings.get().ui.quiet)
408
411
  } catch {
409
412
  sidebar = undefined // discovery is documented not to throw; never let it stop the retries
410
413
  }
@@ -472,13 +475,13 @@ export function apply(ctx: Context & { browser: BrowserRuntime }, config: Config
472
475
  host.effect(() => host.webServer.register({
473
476
  kind: 'exact',
474
477
  path: PREVIEW_ROUTE,
475
- handler: (request, response) => handlePreviewFrame(request, response, settings, browser),
478
+ handler: authenticated(ctx, (request, response) => handlePreviewFrame(request, response, settings, browser)),
476
479
  }, 'dsh-builtin-browser: live view frame'))
477
480
  // The list the panel needs before it can build a frame URL at all: session ids only.
478
481
  host.effect(() => host.webServer.register({
479
482
  kind: 'exact',
480
483
  path: PREVIEW_SESSIONS_ROUTE,
481
- handler: (request, response) => handlePreviewSessions(request, response, settings, browser),
484
+ handler: authenticated(ctx, (request, response) => handlePreviewSessions(request, response, settings, browser)),
482
485
  }, 'dsh-builtin-browser: live view sessions')) })
483
486
  } catch {
484
487
  // No web server on this surface: watching is simply unavailable, and nothing else changes.
@@ -493,6 +496,56 @@ export function apply(ctx: Context & { browser: BrowserRuntime }, config: Config
493
496
  * exactly like the other two.
494
497
  * @param ctx - the plugin context.
495
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
+
496
549
  function installBridgeStatusRoute(ctx: Context): void {
497
550
  const injectStatus = (ctx as unknown as {
498
551
  inject?: (deps: readonly string[], callback: (host: WebServerHost) => void) => void
@@ -503,8 +556,15 @@ export function apply(ctx: Context & { browser: BrowserRuntime }, config: Config
503
556
  host.effect(() => host.webServer.register({
504
557
  kind: 'exact',
505
558
  path: BRIDGE_STATUS_ROUTE,
506
- handler: (request, response) => handleBridgeStatus(request, response),
559
+ handler: authenticated(ctx, (request, response) => handleBridgeStatus(request, response)),
507
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'))
508
568
  })
509
569
  } catch {
510
570
  // No web server: the panel is unreachable, and the installer stays the interface.
@@ -561,12 +621,12 @@ export function apply(ctx: Context & { browser: BrowserRuntime }, config: Config
561
621
  host.effect(() => host.webServer.register({
562
622
  kind: 'exact',
563
623
  path: RUNTIME_STATUS_ROUTE,
564
- handler: (request, response) => handleRuntimeStatus(request, response, deps),
624
+ handler: authenticated(ctx, (request, response) => handleRuntimeStatus(request, response, deps)),
565
625
  }, 'dsh-builtin-browser: runtime status'))
566
626
  host.effect(() => host.webServer.register({
567
627
  kind: 'exact',
568
628
  path: RUNTIME_PROVISION_ROUTE,
569
- handler: (request, response) => handleRuntimeProvision(request, response, deps),
629
+ handler: authenticated(ctx, (request, response) => handleRuntimeProvision(request, response, deps)),
570
630
  }, 'dsh-builtin-browser: runtime provision'))
571
631
  })
572
632
  } catch {
@@ -667,6 +727,14 @@ interface PreviewBrowser {
667
727
  watchableSessions?(): readonly string[]
668
728
  }
669
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
+
670
738
  /** The host web-server surface this plugin uses, described structurally. */
671
739
  interface WebServerHost {
672
740
  readonly webServer: {
@@ -704,7 +772,7 @@ function installSettingsRoute(
704
772
  host.effect(() => host.webServer.register({
705
773
  kind: 'exact',
706
774
  path: SETTINGS_ROUTE,
707
- handler: (request, response) => handleSettingsRequest(request, response, settings, onChannelChange),
775
+ handler: authenticated(ctx, (request, response) => handleSettingsRequest(request, response, settings, onChannelChange)),
708
776
  }, 'dsh-builtin-browser: settings'))
709
777
  })
710
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()
@@ -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
  *
@@ -644,6 +646,8 @@ export interface PresentOptions {
644
646
  export interface CommandOptions {
645
647
  /** Present the view first (default), or only use a page that is already there. */
646
648
  readonly present?: boolean
649
+ /** Only use a guest already attached to this handle, without sidebar initialization. */
650
+ readonly initialize?: boolean
647
651
  }
648
652
 
649
653
  /** Native capture options the self-hosted view handle understands. */
@@ -1165,7 +1169,7 @@ export class ElectronBrowserProvider implements BrowserProvider {
1165
1169
  private async documentProbe(handle: ElectronViewHandle): Promise<{ stamp: string; readyState: string } | null> {
1166
1170
  try {
1167
1171
  const result = await withTimeout(
1168
- handleSendEvaluate(handle, 'String(performance.timeOrigin) + "|" + document.readyState'),
1172
+ handleSendEvaluate(handle, 'String(performance.timeOrigin) + "|" + document.readyState', undefined, { present: false, initialize: false }),
1169
1173
  3_000,
1170
1174
  undefined,
1171
1175
  'browser: document probe timed out',
@@ -1311,13 +1315,15 @@ export class ElectronBrowserProvider implements BrowserProvider {
1311
1315
  */
1312
1316
  private async focusView(handle: ElectronViewHandle): Promise<void> {
1313
1317
  if (handle.focus === undefined) return
1318
+ const quiet = this.isQuiet()
1314
1319
  try {
1315
1320
  // Bounded, unlike the rest of this call: the child RPC has no timeout of its own,
1316
1321
  // and this runs before typing, so an unresponsive child would hang dsh_browser_key for
1317
1322
  // good. A timeout is caught below exactly like any other focus failure, so the
1318
1323
  // best-effort contract is unchanged.
1319
- await withTimeout(handle.focus(), 5_000, undefined, 'browser: focusing the view timed out')
1320
- } catch {
1324
+ await withTimeout(handle.focus(quiet ? { quiet } : undefined), 5_000, undefined, 'browser: focusing the view timed out')
1325
+ } catch (error) {
1326
+ if (quiet) throw error
1321
1327
  // Best-effort: a view that refuses focus must not fail the caller's key
1322
1328
  // press; the dispatch below reports a real channel failure itself.
1323
1329
  }
@@ -1326,6 +1332,81 @@ export class ElectronBrowserProvider implements BrowserProvider {
1326
1332
  /** Execute JS in the active tab's page context. */
1327
1333
  async execute(session: BrowserSessionId, request: BrowserExecuteRequest, signal?: AbortSignal): Promise<BrowserExecuteResult> {
1328
1334
  this.assertActionAllowed('execute')
1335
+ return this.evaluatePage(session, request, signal)
1336
+ }
1337
+
1338
+ /** Run a fixed browser operation; the request cannot contain a script. */
1339
+ async pageOperation(session: BrowserSessionId, request: BrowserPageOperationRequest, signal?: AbortSignal): Promise<BrowserExecuteResult> {
1340
+ const script = pageOperationScript(request)
1341
+ if (request.operation === 'drag') {
1342
+ return this.dispatchPointer(session, request.from, request.to, request.steps, signal)
1343
+ }
1344
+ if (request.operation === 'probe' && request.method === 'hoverAt') {
1345
+ const point = { x: Number(request.args?.[0]), y: Number(request.args?.[1]) }
1346
+ return this.dispatchPointer(session, point, undefined, 1, signal)
1347
+ }
1348
+ return this.evaluatePage(session, { script }, signal)
1349
+ }
1350
+
1351
+ /** Send page pointer input through CDP while preserving presentation and cancellation policy. */
1352
+ private async dispatchPointer(
1353
+ session: BrowserSessionId,
1354
+ from: { readonly x: number; readonly y: number },
1355
+ to: { readonly x: number; readonly y: number } | undefined,
1356
+ steps: number,
1357
+ signal?: AbortSignal,
1358
+ ): Promise<BrowserExecuteResult> {
1359
+ const coordinates = [from.x, from.y, ...to === undefined ? [] : [to.x, to.y]]
1360
+ if (coordinates.some(value => !Number.isFinite(value) || value < 0)) {
1361
+ throw new BrowserError('browser: pointer coordinates must be finite nonnegative viewport pixels', 'BROWSER_POINTER_INVALID')
1362
+ }
1363
+ if (to !== undefined && this.settingsSource?.().vision.strategy === 'nonVisual') {
1364
+ throw new BrowserError('browser: coordinate dragging requires the visual strategy', 'BROWSER_NON_VISUAL_COORDINATES')
1365
+ }
1366
+ const s = this.session(session)
1367
+ const handle = await this.present(s, signal)
1368
+ const viewport = await withTimeout(
1369
+ handleSendEvaluate(handle, '({width:innerWidth,height:innerHeight})'),
1370
+ 5_000, signal, 'browser: pointer viewport check timed out',
1371
+ )
1372
+ if (!viewport.ok) throw new BrowserError('browser: could not read the pointer viewport', 'BROWSER_POINTER_INVALID')
1373
+ const size = viewport.value as { width: number; height: number }
1374
+ if (from.x >= size.width || from.y >= size.height || (to !== undefined && (to.x >= size.width || to.y >= size.height))) {
1375
+ return { ok: true, value: JSON.stringify(to === undefined ? false : { ok: false, reason: 'drag points must be inside the current viewport' }) }
1376
+ }
1377
+ const send = async (params: CdpMouseParams): Promise<void> => {
1378
+ signal?.throwIfAborted()
1379
+ this.assertSameView(session, handle, this.activeTab(s).handle)
1380
+ await withTimeout(handle.sendCommand('Input.dispatchMouseEvent', { ...params }), 5_000, signal, 'browser: pointer input timed out')
1381
+ }
1382
+ await send({ type: 'mouseMoved', x: from.x, y: from.y, buttons: 0 })
1383
+ if (to === undefined) return { ok: true, value: 'true' }
1384
+ let at = from
1385
+ let held = true
1386
+ try {
1387
+ await send({ type: 'mousePressed', x: from.x, y: from.y, button: 'left', buttons: 1, clickCount: 1 })
1388
+ const count = Math.max(1, Math.min(Math.trunc(steps) || 12, 60))
1389
+ for (let step = 1; step <= count; step += 1) {
1390
+ const next = { x: from.x + (to.x - from.x) * step / count, y: from.y + (to.y - from.y) * step / count }
1391
+ await send({ type: 'mouseMoved', ...next, button: 'left', buttons: 1 })
1392
+ at = next
1393
+ }
1394
+ // Native HTML drag targets need a final drag-over before releasing at the destination.
1395
+ await send({ type: 'mouseMoved', ...to, button: 'left', buttons: 1 })
1396
+ await send({ type: 'mouseReleased', ...to, button: 'left', buttons: 0, clickCount: 1 })
1397
+ held = false
1398
+ return { ok: true, value: JSON.stringify({ ok: true, moved: count, at: to }) }
1399
+ } finally {
1400
+ if (held) {
1401
+ await withTimeout(
1402
+ handle.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', ...at, button: 'left', buttons: 0, clickCount: 1 }),
1403
+ 1_000, undefined, 'browser: pointer release timed out',
1404
+ ).catch(() => {})
1405
+ }
1406
+ }
1407
+ }
1408
+
1409
+ private async evaluatePage(session: BrowserSessionId, request: BrowserExecuteRequest, signal?: AbortSignal): Promise<BrowserExecuteResult> {
1329
1410
  const s = this.session(session)
1330
1411
  const { handle } = this.activeTab(s)
1331
1412
  signal?.throwIfAborted()
@@ -3821,7 +3902,9 @@ export class ElectronBrowserProvider implements BrowserProvider {
3821
3902
  * silently desynchronising the two and failing every screenshot.
3822
3903
  */
3823
3904
  private showActive(s: Session): void {
3824
- this.host.showView?.(this.activeTab(s).handle, s.label, { quiet: this.isQuiet() })
3905
+ const quiet = this.isQuiet()
3906
+ this.host.showView?.(this.activeTab(s).handle, s.label, { quiet })
3907
+ if (quiet) 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' }
@@ -775,8 +775,8 @@ class RemoteView implements ElectronViewHandle {
775
775
  }
776
776
 
777
777
  /** 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 })
778
+ focus(options?: PresentOptions): Promise<void> {
779
+ return this.client.call<void>('focus', { viewId: this.id, ...options?.quiet ? { quiet: true } : {} })
780
780
  }
781
781
 
782
782
  /** Ask the child to download a URL to a local file (keeps cookies/login). */
@@ -1376,8 +1376,8 @@ class DeferredRemoteView implements ElectronViewHandle {
1376
1376
  return this.withRecovery(view => view.capture(opts))
1377
1377
  }
1378
1378
 
1379
- async focus(): Promise<void> {
1380
- return this.withRecovery(view => view.focus())
1379
+ async focus(options?: PresentOptions): Promise<void> {
1380
+ return this.withRecovery(view => view.focus(options))
1381
1381
  }
1382
1382
 
1383
1383
  async flushAuth(): Promise<ExportedCookie[]> {
@@ -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.
@@ -130,10 +130,12 @@ export function readRuntimeStatus(deps: RuntimeStatusDeps): RuntimeStatusReport
130
130
  // on a live install, and the kind of contradiction a reader cannot resolve.
131
131
  const snapshot = deps.provision()
132
132
  const runnable = deps.hasBinary()
133
- const state: ElectronReadiness['state'] = runnable ? 'present' : snapshot.state
133
+ const missingAfterReady = !runnable && (snapshot.state === 'present' || snapshot.state === 'ready')
134
+ const state: ElectronReadiness['state'] = runnable ? 'present' : missingAfterReady ? 'failed' : snapshot.state
134
135
  const electron: ElectronReadiness = {
135
136
  state,
136
- detail: runnable ? 'an Electron runtime is already available' : snapshot.detail,
137
+ detail: runnable ? 'an Electron runtime is already available'
138
+ : missingAfterReady ? 'the previously prepared Electron runtime is missing; prepare it again' : snapshot.detail,
137
139
  at: runnable ? new Date().toISOString() : snapshot.at,
138
140
  }
139
141
 
@@ -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
 
@@ -124,6 +124,23 @@ export interface BrowserSettings {
124
124
  /** Write cookies — importing login state (`dsh_browser_auth` restore). */
125
125
  readonly allowCredentialWrite: boolean
126
126
  }
127
+ /**
128
+ * Where a downloaded file goes after it lands on disk.
129
+ *
130
+ * An ATTRIBUTE of a download, not a new concept: an empty `tool` means the behaviour is exactly
131
+ * what it was before this existed. The user owns the field, can point it at any MCP tool that
132
+ * takes a path (Feishu drive, Baidu Netdisk), and can empty it again at any time.
133
+ */
134
+ readonly delivery: {
135
+ /** MCP tool that receives the saved file. Empty = save locally and stop there. */
136
+ readonly tool: string
137
+ /** Flat argument template; {path}, {name} and {size} are substituted into string values. */
138
+ readonly args: Readonly<Record<string, string>>
139
+ /** `keep-local` reports both outcomes; `stop` reports the handoff failure as the result. */
140
+ readonly onFail: 'keep-local' | 'stop'
141
+ /** Per-site override: page host → tool name. */
142
+ readonly sites: Readonly<Record<string, string>>
143
+ }
127
144
  }
128
145
 
129
146
  /** Defaults for every switch: the documented out-of-the-box behaviour. */
@@ -141,6 +158,9 @@ export const DEFAULT_SETTINGS: BrowserSettings = {
141
158
  // content, so watching is an explicit decision rather than something a remote client can arrange.
142
159
  remoteView: { enabled: false },
143
160
  actions: { allowExecute: true, allowDownload: true, allowCredentialWrite: true },
161
+ // Local by default: the file lands in downloadDir and nothing leaves the machine until the user
162
+ // names a tool here. {file_path} is the argument name both Feishu's and Netdisk's upload tools use.
163
+ delivery: { tool: '', args: { file_path: '{path}' }, onFail: 'keep-local', sites: {} },
144
164
  }
145
165
 
146
166
  /**
@@ -299,6 +319,17 @@ export function resolveSettings(raw: unknown, warn?: (message: string) => void):
299
319
  const browser = section(source, 'browser')
300
320
  const actions = section(source, 'actions')
301
321
  const remoteView = section(source, 'remoteView')
322
+ // Read defensively: this section is hand-editable, and a bad value must fall back to "local only"
323
+ // rather than fail the whole document.
324
+ const deliverySection = (section(source, 'delivery') ?? {}) as { tool?: unknown; args?: unknown; onFail?: unknown; sites?: unknown }
325
+ const strings = (value: unknown, fallback: Record<string, string>): Record<string, string> => {
326
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return { ...fallback }
327
+ const out: Record<string, string> = {}
328
+ for (const [key, entry] of Object.entries(value as Record<string, unknown>)) {
329
+ if (typeof entry === 'string') out[key] = entry
330
+ }
331
+ return Object.keys(out).length === 0 ? { ...fallback } : out
332
+ }
302
333
  // A section that is present but unreadable refuses its gates rather than defaulting them
303
334
  // open. The rest of a broken section keeps its defaults: refusing history or presentation
304
335
  // would punish the user for a bad file without protecting anything.
@@ -351,6 +382,14 @@ export function resolveSettings(raw: unknown, warn?: (message: string) => void):
351
382
  ? false
352
383
  : gate((remoteView as { enabled?: unknown }).enabled, false),
353
384
  },
385
+ delivery: {
386
+ tool: typeof deliverySection.tool === 'string' && /^[A-Za-z0-9_.-]+$/.test(deliverySection.tool)
387
+ ? deliverySection.tool
388
+ : '',
389
+ args: strings(deliverySection.args, DEFAULT_SETTINGS.delivery.args),
390
+ onFail: deliverySection.onFail === 'stop' ? 'stop' : 'keep-local',
391
+ sites: strings(deliverySection.sites, {}),
392
+ },
354
393
  }
355
394
  }
356
395
 
@@ -592,6 +592,7 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
592
592
  * and why a display-less host needs headless at all (issue #32).
593
593
  */
594
594
  private readonly headlessMode: HeadlessMode = 'auto',
595
+ private readonly isQuiet: () => boolean = () => false,
595
596
  ) {}
596
597
 
597
598
  /** Which product this host would drive (for diagnostics). */
@@ -765,7 +766,7 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
765
766
  // after launch (exit code 0)" that required killing seven processes by hand.
766
767
  const adopted = await this.adoptRunningBrowser('before launch')
767
768
  if (adopted !== undefined) return adopted
768
- const launch = resolveLaunchMode(this.headlessMode)
769
+ const launch = resolveLaunchMode(this.isQuiet() ? 'headless' : this.headlessMode)
769
770
  const args = [
770
771
  '--remote-debugging-port=0',
771
772
  `--user-data-dir=${this.profileDir}`,
@@ -1093,6 +1094,7 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
1093
1094
  const ours = new Set(this.sessions.values())
1094
1095
  return (listed?.targetInfos ?? [])
1095
1096
  .filter(entry => entry.type === 'page' && typeof entry.targetId === 'string')
1097
+ .filter(entry => !/^edge:\/\/sync-confirmation-dialog(?:\/|$)/.test(entry.url ?? ''))
1096
1098
  .filter(entry => !ours.has(entry.targetId as string))
1097
1099
  .map(entry => ({
1098
1100
  id: entry.targetId as string,
@@ -1248,7 +1250,8 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
1248
1250
  * two, and the order is honoured either way.
1249
1251
  * @param handle - the view to present.
1250
1252
  */
1251
- async presentView(handle: ElectronViewHandle): Promise<void> {
1253
+ async presentView(handle: ElectronViewHandle, _label?: string, options?: { readonly quiet?: boolean }): Promise<void> {
1254
+ if (options?.quiet === true || this.isQuiet()) return
1252
1255
  try {
1253
1256
  await handle.sendCommand('Page.bringToFront')
1254
1257
  } catch {
@@ -1456,7 +1459,10 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
1456
1459
 
1457
1460
  /** Create one page, refusing to go on without an id. */
1458
1461
  private async createTarget(client: CdpClient): Promise<string> {
1459
- const created = await client.send('Target.createTarget', { url: 'about:blank' }) as { targetId?: string }
1462
+ const created = await client.send('Target.createTarget', {
1463
+ url: 'about:blank',
1464
+ ...this.isQuiet() ? { background: true } : {},
1465
+ }) as { targetId?: string }
1460
1466
  const targetId = created?.targetId
1461
1467
  if (typeof targetId !== 'string') throw new Error('dsh-builtin-browser: the browser did not create a page')
1462
1468
  return targetId