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
@@ -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' }
@@ -141,11 +141,12 @@ function resolveElectronPathImpl(inputs: ElectronPathInputs): string {
141
141
  'dsh-builtin-browser: cannot locate a spawnable Electron binary. ' +
142
142
  'The electron package ships with the plugin and its binary is downloaded on first use, not at install time ' +
143
143
  '(issue #41: an install-time download made default profiles refuse the plugin). The plugin prepares it ' +
144
- 'automatically when the bundled carrier is selected; to do it by hand, run ' +
145
- '`npx --no dsh-browser-install-electron` in the profile that installed the plugin, then retry. ' +
146
- 'Alternatively set ELECTRON_PATH to an electron executable. Note: the host\'s own executable cannot be ' +
147
- 'reused when it is a packaged Electron app (e.g. DSH Desktop.exe) — only a real electron binary can be ' +
148
- 'spawned.',
144
+ 'automatically when the bundled carrier is selected, so right after an install this can mean the ' +
145
+ 'download is still running: Settings → Browser → Readiness shows that state and can retry it. To do it ' +
146
+ 'by hand instead, run `npx --no dsh-browser-install-electron` in the profile that installed the ' +
147
+ 'plugin, then retry. Alternatively set ELECTRON_PATH to an electron executable. Note: the host\'s own ' +
148
+ 'executable cannot be reused when it is a packaged Electron app (e.g. DSH Desktop.exe) — only a real ' +
149
+ 'electron binary can be spawned.',
149
150
  )
150
151
  }
151
152
 
@@ -774,8 +775,8 @@ class RemoteView implements ElectronViewHandle {
774
775
  }
775
776
 
776
777
  /** Give this view web focus in the child, so keyboard input reaches the page. */
777
- focus(): Promise<void> {
778
- 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 } : {} })
779
780
  }
780
781
 
781
782
  /** Ask the child to download a URL to a local file (keeps cookies/login). */
@@ -1375,8 +1376,8 @@ class DeferredRemoteView implements ElectronViewHandle {
1375
1376
  return this.withRecovery(view => view.capture(opts))
1376
1377
  }
1377
1378
 
1378
- async focus(): Promise<void> {
1379
- return this.withRecovery(view => view.focus())
1379
+ async focus(options?: PresentOptions): Promise<void> {
1380
+ return this.withRecovery(view => view.focus(options))
1380
1381
  }
1381
1382
 
1382
1383
  async flushAuth(): Promise<ExportedCookie[]> {
@@ -0,0 +1,104 @@
1
+ /**
2
+ * The readiness endpoints the settings panel reads.
3
+ *
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.
7
+ *
8
+ * Both answer with the whole report rather than a delta: the panel replaces what it shows with what
9
+ * it is told, so a stale poll can never leave a wrong state on screen.
10
+ * @module dsh-browser/browser-electron/runtime-route
11
+ */
12
+ import type { IncomingMessage, ServerResponse } from 'node:http'
13
+ import type { ProvisionSnapshot } from './electron-provision.js'
14
+ import { replyJson } from './json-reply.js'
15
+ import { sameOrigin } from './settings-route.js'
16
+ import type { RuntimeStatusReport } from './runtime-status.js'
17
+
18
+ /** Where the panel reads readiness. */
19
+ export const RUNTIME_STATUS_ROUTE = '/dsh-builtin-browser/runtime-status'
20
+
21
+ /**
22
+ * Where the panel asks for the bundled runtime.
23
+ *
24
+ * Non-blocking by design: it starts (or joins) the one background attempt and answers immediately
25
+ * with the state that attempt is in, which is `preparing`. A request that waited for the download
26
+ * would time out in the browser long before a slow network finished, and would hold a connection
27
+ * open for something the panel can poll instead.
28
+ */
29
+ export const RUNTIME_PROVISION_ROUTE = '/dsh-builtin-browser/runtime-provision'
30
+
31
+ /** What both handlers need. */
32
+ export interface RuntimeRouteDeps {
33
+ /** The current report; a cheap read, never a spawn. */
34
+ readonly report: () => RuntimeStatusReport
35
+ /**
36
+ * Start (or join) a provision and return the state it is in now.
37
+ *
38
+ * Must not throw: a failure belongs in the report as a 200 with a `failed` state, because a user
39
+ * looking at a panel needs to read the reason, not an HTTP status.
40
+ */
41
+ readonly provision: () => ProvisionSnapshot
42
+ }
43
+
44
+ /**
45
+ * Read readiness: `{ ok, runtime }`.
46
+ * @param request - the incoming request.
47
+ * @param response - the response to write.
48
+ * @param deps - the readers.
49
+ */
50
+ export async function handleRuntimeStatus(
51
+ request: IncomingMessage,
52
+ response: ServerResponse,
53
+ deps: RuntimeRouteDeps,
54
+ ): Promise<void> {
55
+ if (request.method !== 'GET') {
56
+ replyJson(response, 405, { error: 'method-not-allowed' })
57
+ return
58
+ }
59
+ if (!sameOrigin(request)) {
60
+ replyJson(response, 403, { error: 'not-same-origin' })
61
+ return
62
+ }
63
+ replyJson(response, 200, { ok: true, runtime: deps.report() })
64
+ }
65
+
66
+ /**
67
+ * Start (or join) a provision, then answer with the state it is in.
68
+ *
69
+ * Always 200 once admitted, whatever happened: the state carries `failed` with its reason, and a
70
+ * panel that had to distinguish 4xx from 5xx to say "the download failed" would show a network
71
+ * error where the user needs the sentence explaining it.
72
+ * @param request - the incoming request.
73
+ * @param response - the response to write.
74
+ * @param deps - the readers.
75
+ */
76
+ export async function handleRuntimeProvision(
77
+ request: IncomingMessage,
78
+ response: ServerResponse,
79
+ deps: RuntimeRouteDeps,
80
+ ): Promise<void> {
81
+ if (request.method !== 'POST') {
82
+ replyJson(response, 405, { error: 'method-not-allowed' })
83
+ return
84
+ }
85
+ // `true`: starting a download is a write, and is admitted the way a settings write is.
86
+ if (!sameOrigin(request, true)) {
87
+ replyJson(response, 403, { error: 'not-same-origin' })
88
+ return
89
+ }
90
+ let snapshot: ProvisionSnapshot
91
+ try {
92
+ snapshot = deps.provision()
93
+ } catch (error) {
94
+ // `provision` is documented not to throw; if a caller breaks that contract the panel still gets
95
+ // an answer it can render, rather than a dropped connection it cannot tell from a hang.
96
+ replyJson(response, 200, {
97
+ ok: true,
98
+ runtime: deps.report(),
99
+ provisionError: String(error),
100
+ })
101
+ return
102
+ }
103
+ replyJson(response, 200, { ok: true, runtime: deps.report(), provision: snapshot })
104
+ }
@@ -0,0 +1,188 @@
1
+ /**
2
+ * One answer to "can I use the browser right now", assembled from the three things that decide it.
3
+ *
4
+ * WHY THIS EXISTS
5
+ * Installing this plugin made the browser work with no setup, and that property got silently
6
+ * weaker as the carriers were added: the bundled carrier downloads a ~100 MB Electron runtime on
7
+ * first need (issue #41 — the download had to leave `postinstall`), so on a fresh install the first
8
+ * browser call can arrive while that download is still running, and the only trace anywhere in the
9
+ * product was a log line the settings panel cannot read. A user who saw "cannot locate a spawnable
10
+ * Electron binary" had no way to learn that the plugin was already fetching one, and no button to
11
+ * retry it once it failed.
12
+ *
13
+ * So the readiness of each part is computed ONCE here, in a pure function over injectable readers:
14
+ * the settings panel renders it, and a test drives it without touching Electron, a desktop install
15
+ * or the file system.
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.
20
+ * @module dsh-browser/browser-electron/runtime-status
21
+ */
22
+ import type { BridgeStatus } from './bridge-status.js'
23
+ import type { BridgeEndpointState } from './bridge-endpoint.js'
24
+ import type { ProvisionSnapshot } from './electron-provision.js'
25
+ import type { BrowserChannel } from './system-browser.js'
26
+
27
+ /** The part of the carrier the channel names, in the terms the panel has to explain. */
28
+ export type CarrierKind = 'sidebar' | 'bundled' | 'system' | 'auto'
29
+
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'
38
+
39
+ /** The Electron runtime's state, as the panel needs it. */
40
+ export interface ElectronReadiness {
41
+ /** `present` — a launch would find a binary; `preparing` — a download is running now; and so on. */
42
+ readonly state: ProvisionSnapshot['state']
43
+ /** One line, already user-facing: the provisioning module's own words. */
44
+ readonly detail: string
45
+ /** When that state was reached, ISO. */
46
+ readonly at: string
47
+ }
48
+
49
+ /** The desktop sidebar bridge, or the honest "there is no desktop here" shape. */
50
+ export interface BridgeReadiness {
51
+ /** Whether a DSH Desktop install was found at all. */
52
+ readonly present: boolean
53
+ /** `absent` is reported separately from `missing`: nothing to repair versus something to repair. */
54
+ readonly state: BridgeStatus['state'] | 'absent'
55
+ /** The plugin's own words about the install tree. */
56
+ readonly detail: string
57
+ /**
58
+ * Whether a shell is RUNNING and answering, as opposed to merely installed.
59
+ *
60
+ * Install-tree state survives a reboot and says nothing about a process; the published endpoint is
61
+ * the only thing that does. Reporting "installed" as "ready" is how a panel goes green while every
62
+ * call dials a port nobody owns — the desktop app being closed is the most common broken state
63
+ * there is.
64
+ */
65
+ readonly running: boolean
66
+ /** The plugin's own words about the running shell (or about why there is none). */
67
+ readonly runningDetail: string
68
+ /** The command that installs or repairs it, for a human to run. Never run by the plugin. */
69
+ readonly command?: string
70
+ }
71
+
72
+ /** The whole report. */
73
+ export interface RuntimeStatusReport {
74
+ /** What the settings document says, verbatim: the panel shows the switch it is honouring. */
75
+ readonly channel: BrowserChannel
76
+ /** What that channel resolves to, in panel terms. */
77
+ readonly carrier: CarrierKind
78
+ /** Whether the browser this channel names can serve a call right now. */
79
+ readonly readiness: Readiness
80
+ readonly electron: ElectronReadiness
81
+ readonly bridge: BridgeReadiness
82
+ /** Whether "Prepare the bundled browser" is worth offering (it is not while one is running). */
83
+ readonly canProvision: boolean
84
+ }
85
+
86
+ /** Everything the report reads, so a test can answer without any of the real machinery. */
87
+ export interface RuntimeStatusDeps {
88
+ /** The stored `browser.channel`. */
89
+ readonly channel: () => BrowserChannel
90
+ /** Whether a launch would find an Electron binary — the launch path's own probe. */
91
+ readonly hasBinary: () => boolean
92
+ /** The provisioning state machine's current state. */
93
+ readonly provision: () => ProvisionSnapshot
94
+ /** The desktop install's bridge state, or undefined when there is no desktop install. */
95
+ readonly bridge: () => BridgeStatus | undefined
96
+ /** The endpoint the shell publishes while it runs; undefined when nothing published one. */
97
+ readonly endpoint: () => BridgeEndpointState | undefined
98
+ }
99
+
100
+ /** Which carrier a channel names. */
101
+ function carrierOf(channel: BrowserChannel): CarrierKind {
102
+ if (channel === 'sidebar') return 'sidebar'
103
+ if (channel === 'bundled') return 'bundled'
104
+ if (channel === 'auto') return 'auto'
105
+ return 'system'
106
+ }
107
+
108
+ /** Whether a binary being present settles the Electron question. */
109
+ function electronReady(state: ElectronReadiness['state']): boolean {
110
+ return state === 'present' || state === 'ready'
111
+ }
112
+
113
+ /**
114
+ * Assemble the report.
115
+ *
116
+ * The `readiness` field is per carrier on purpose: "the browser is ready" is not a property of this
117
+ * plugin, it is a property of the carrier the user chose. A bundled carrier with a finished download
118
+ * is ready; the sidebar carrier with no bridge is not, however healthy the bundled runtime is.
119
+ * @param deps - the readers; every one of them is a cheap, side-effect-free read.
120
+ * @returns the report the panel renders.
121
+ */
122
+ export function readRuntimeStatus(deps: RuntimeStatusDeps): RuntimeStatusReport {
123
+ const channel = deps.channel()
124
+ const carrier = carrierOf(channel)
125
+
126
+ // The binary check comes first and wins: a runtime that is on disk is ready whatever the
127
+ // provisioning state machine last said, which is also how a runtime installed by hand (or by an
128
+ // earlier process) is reported correctly without a restart. The DETAIL has to follow the same
129
+ // rule, or the panel shows "present" next to "the runtime has not been asked for yet" — measured
130
+ // on a live install, and the kind of contradiction a reader cannot resolve.
131
+ const snapshot = deps.provision()
132
+ const runnable = deps.hasBinary()
133
+ const missingAfterReady = !runnable && (snapshot.state === 'present' || snapshot.state === 'ready')
134
+ const state: ElectronReadiness['state'] = runnable ? 'present' : missingAfterReady ? 'failed' : snapshot.state
135
+ const electron: ElectronReadiness = {
136
+ state,
137
+ detail: runnable ? 'an Electron runtime is already available'
138
+ : missingAfterReady ? 'the previously prepared Electron runtime is missing; prepare it again' : snapshot.detail,
139
+ at: runnable ? new Date().toISOString() : snapshot.at,
140
+ }
141
+
142
+ const bridgeStatus = deps.bridge()
143
+ const endpoint = deps.endpoint()
144
+ const bridge: BridgeReadiness = bridgeStatus === undefined
145
+ ? {
146
+ present: false,
147
+ state: 'absent',
148
+ detail: 'no DSH Desktop install was found on this machine',
149
+ running: endpoint?.alive === true,
150
+ runningDetail: endpoint?.detail ?? 'no desktop shell has published a bridge endpoint',
151
+ }
152
+ : {
153
+ present: bridgeStatus.present,
154
+ state: bridgeStatus.state,
155
+ detail: bridgeStatus.detail,
156
+ running: endpoint?.alive === true,
157
+ runningDetail: endpoint?.detail ?? 'no desktop shell has published a bridge endpoint',
158
+ ...bridgeStatus.command === undefined ? {} : { command: bridgeStatus.command },
159
+ }
160
+
161
+ // The sidebar needs BOTH halves: our patch inside the shell it will be driven through, and that
162
+ // shell actually running. Either one alone is the false green this report exists to prevent.
163
+ const sidebarReady = bridge.state === 'installed' && bridge.running
164
+
165
+ let readiness: Readiness
166
+ if (carrier === 'sidebar') {
167
+ readiness = sidebarReady ? 'ready' : 'blocked'
168
+ } else if (carrier === 'bundled') {
169
+ readiness = electronReady(state) ? 'ready' : 'blocked'
170
+ } else if (carrier === 'auto') {
171
+ // `auto` is satisfied by either carrier, so a working sidebar covers a missing runtime. An
172
+ // explicit Chrome / Edge install would satisfy it too, but proving that means launching one.
173
+ readiness = electronReady(state) || sidebarReady ? 'ready' : 'unknown'
174
+ } else {
175
+ readiness = 'unknown'
176
+ }
177
+
178
+ return {
179
+ channel,
180
+ carrier,
181
+ readiness,
182
+ electron,
183
+ bridge,
184
+ // Offering the button while a download runs would be a second download, which is the one thing
185
+ // the shared attempt exists to prevent.
186
+ canProvision: !electronReady(state) && state !== 'preparing',
187
+ }
188
+ }
@@ -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