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
@@ -0,0 +1,14 @@
1
+ /**
2
+ * One shared definition of process liveness.
3
+ *
4
+ * Signal 0 performs the permission and existence checks and delivers nothing, so it is safe to
5
+ * call on a pid we only read from a file. `EPERM` means the process exists and belongs to
6
+ * someone else, which is still "alive" for the endpoint reader and the profile sweeper alike.
7
+ * @module dsh-browser/browser-electron/process
8
+ */
9
+ /**
10
+ * Whether a process with this pid exists, without signalling it.
11
+ * @param pid - the process id to test; a non-integer or non-positive value is never alive.
12
+ * @returns whether that process exists.
13
+ */
14
+ export declare function pidAlive(pid: number): boolean;
@@ -0,0 +1,24 @@
1
+ /**
2
+ * One shared definition of process liveness.
3
+ *
4
+ * Signal 0 performs the permission and existence checks and delivers nothing, so it is safe to
5
+ * call on a pid we only read from a file. `EPERM` means the process exists and belongs to
6
+ * someone else, which is still "alive" for the endpoint reader and the profile sweeper alike.
7
+ * @module dsh-browser/browser-electron/process
8
+ */
9
+ /**
10
+ * Whether a process with this pid exists, without signalling it.
11
+ * @param pid - the process id to test; a non-integer or non-positive value is never alive.
12
+ * @returns whether that process exists.
13
+ */
14
+ export function pidAlive(pid) {
15
+ if (!Number.isSafeInteger(pid) || pid <= 0)
16
+ return false;
17
+ try {
18
+ process.kill(pid, 0);
19
+ return true;
20
+ }
21
+ catch (error) {
22
+ return error?.code === 'EPERM';
23
+ }
24
+ }
@@ -8,7 +8,7 @@
8
8
  */
9
9
  import { type VisitedPage } from './history-store.js';
10
10
  import type { BrowserSettings } from './settings-store.js';
11
- import type { BrowserA11yRequest, BrowserA11yResult, BrowserChallenge, BrowserCheckRequest, BrowserClearRequest, BrowserClickRequest, BrowserClickSequenceRequest, BrowserClickSequenceResult, BrowserContentRequest, BrowserContentResult, BrowserElementTarget, BrowserExecuteRequest, BrowserExecuteResult, BrowserFillRequest, BrowserFillResult, BrowserGetValueRequest, BrowserGetValueResult, BrowserHistoryEntry, BrowserOpenRequest, BrowserProvider, BrowserScrapeRequest, BrowserScrapeResult, BrowserScreenshotRequest, BrowserSelectRequest, BrowserSelectResult, BrowserSessionId, BrowserSetValueRequest, BrowserSetValueResult, BrowserSnapshotResult, BrowserTab, BrowserTypeRequest, BrowserWaitRequest, BrowserWaitResult, BrowserScrollRequest, BrowserKeyRequest, ExportedCookie } from '../browser/types.js';
11
+ import type { BrowserA11yRequest, BrowserA11yResult, BrowserChallenge, BrowserCheckRequest, BrowserClearRequest, BrowserClickRequest, BrowserClickSequenceRequest, BrowserClickSequenceResult, BrowserContentRequest, BrowserContentResult, BrowserElementTarget, BrowserExecuteRequest, BrowserPageOperationRequest, BrowserExecuteResult, BrowserFillRequest, BrowserFillResult, BrowserGetValueRequest, BrowserGetValueResult, BrowserHistoryEntry, BrowserOpenRequest, BrowserProvider, BrowserScrapeRequest, BrowserScrapeResult, BrowserScreenshotRequest, BrowserSelectRequest, BrowserSelectResult, BrowserSessionId, BrowserSetValueRequest, BrowserSetValueResult, BrowserSnapshotResult, BrowserTab, BrowserTypeRequest, BrowserWaitRequest, BrowserWaitResult, BrowserScrollRequest, BrowserKeyRequest, ExportedCookie } from '../browser/types.js';
12
12
  import type { CarrierPage, CarrierLossReason } from '../browser/types.js';
13
13
  /** Stable provider id registered with `ctx.browser`. */
14
14
  export declare const ELECTRON_BROWSER_PROVIDER_ID = "electron";
@@ -261,7 +261,7 @@ export interface ElectronViewHandle {
261
261
  * Optional: an adapter that cannot focus a view omits it, and the provider
262
262
  * then behaves exactly as before.
263
263
  */
264
- focus?(): Promise<void>;
264
+ focus?(options?: PresentOptions): Promise<void>;
265
265
  /**
266
266
  * Save a URL straight to disk, when the backing view can do that itself.
267
267
  *
@@ -428,13 +428,14 @@ export declare function toCdpCookie(cookie: ExportedCookie): Record<string, unkn
428
428
  * `quiet` is the resolved `ui.quiet` switch. It does not mean "invisible": Chromium drops
429
429
  * synthesized `Input.*` for a view without a display surface, so input still needs one. It means
430
430
  * the carrier must get that surface without taking the screen over — no application activation
431
- * and no keyboard focus. Navigation and tab switching only reveal the view inside its window; the
432
- * pre-input barrier may restore a minimized window (it needs the surface), but even then it shows
433
- * it inactive instead of focusing or raising it. A host that cannot honour this (a headless probe,
434
- * the desktop sidebar) simply ignores it.
431
+ * and no operating-system keyboard focus. New windows open inactive; a minimized window and the
432
+ * foreground window's selected page remain under the operator's control. DOM focus and CDP input
433
+ * still target the task's page. Explicit sidebar navigation can select the task's pane.
435
434
  */
436
435
  export interface PresentOptions {
437
436
  readonly quiet?: boolean;
437
+ /** Explicit navigation or tab selection may change the task's sidebar tab without OS activation. */
438
+ readonly select?: boolean;
438
439
  }
439
440
  /**
440
441
  * How a command should reach its page.
@@ -452,6 +453,8 @@ export interface PresentOptions {
452
453
  export interface CommandOptions {
453
454
  /** Present the view first (default), or only use a page that is already there. */
454
455
  readonly present?: boolean;
456
+ /** Only use a guest already attached to this handle, without sidebar initialization. */
457
+ readonly initialize?: boolean;
455
458
  }
456
459
  /** Native capture options the self-hosted view handle understands. */
457
460
  export interface ScreenshotOptions {
@@ -617,6 +620,11 @@ export declare class ElectronBrowserProvider implements BrowserProvider {
617
620
  private focusView;
618
621
  /** Execute JS in the active tab's page context. */
619
622
  execute(session: BrowserSessionId, request: BrowserExecuteRequest, signal?: AbortSignal): Promise<BrowserExecuteResult>;
623
+ /** Run a fixed browser operation; the request cannot contain a script. */
624
+ pageOperation(session: BrowserSessionId, request: BrowserPageOperationRequest, signal?: AbortSignal): Promise<BrowserExecuteResult>;
625
+ /** Send page pointer input through CDP while preserving presentation and cancellation policy. */
626
+ private dispatchPointer;
627
+ private evaluatePage;
620
628
  /**
621
629
  * Poll until the active tab's page is ready (and optional URL/selector
622
630
  * match), or the budget runs out. Returns a verdict instead of throwing on
@@ -756,9 +764,8 @@ export declare class ElectronBrowserProvider implements BrowserProvider {
756
764
  private admitSavePath;
757
765
  /**
758
766
  * Download an HTTP(S) URL with the session's cookies to a local file.
759
- * Admission is the shared {@link admitSavePath} gate; only the self-hosted
760
- * host implements it (the desktop shell's embedded views delegate downloads
761
- * to the real browser UI). Both admitted paths and screenshots are confined
767
+ * Admission is the shared {@link admitSavePath} gate. The carrier downloads
768
+ * with its own authenticated browser session. Both admitted paths and screenshots are confined
762
769
  * to `downloadDir`, so a prompt-injected agent cannot write arbitrary
763
770
  * machine paths.
764
771
  * @param session - the session whose cookies are used.
@@ -6,6 +6,7 @@
6
6
  * shell that owns the `BrowserWindow`.
7
7
  * @module dsh-browser/browser-electron
8
8
  */
9
+ import { pageOperationScript } from '../tool-browser/page-probe.js';
9
10
  import { randomUUID } from 'node:crypto';
10
11
  import { existsSync, lstatSync, mkdirSync, realpathSync } from 'node:fs';
11
12
  import { writeFileNoReplace } from './file-write.js';
@@ -414,7 +415,7 @@ export class ElectronBrowserProvider {
414
415
  const tab = { id: `page:${match.id}`, handle, url: match.url };
415
416
  s.tabs.push(tab);
416
417
  s.activeIndex = s.tabs.length - 1;
417
- this.showActive(s);
418
+ this.showActive(s, true);
418
419
  return true;
419
420
  }
420
421
  catch {
@@ -500,7 +501,7 @@ export class ElectronBrowserProvider {
500
501
  }
501
502
  const found = this.locateTab(session, tabId);
502
503
  found.s.activeIndex = found.index;
503
- this.showActive(found.s);
504
+ this.showActive(found.s, true);
504
505
  }
505
506
  /** Close one tab; closing the active tab activates the next. */
506
507
  closeTab(session, tabId) {
@@ -631,7 +632,7 @@ export class ElectronBrowserProvider {
631
632
  tab.url = url;
632
633
  await this.settleDocument(handle, before, signal);
633
634
  this.recordVisit(s, handle);
634
- this.showActive(s);
635
+ this.showActive(s, true);
635
636
  }
636
637
  catch (error) {
637
638
  if (!(error instanceof BrowserError && error.code === 'BROWSER_NAVIGATION_BLOCKED')) {
@@ -661,7 +662,7 @@ export class ElectronBrowserProvider {
661
662
  */
662
663
  async documentProbe(handle) {
663
664
  try {
664
- const result = await withTimeout(handleSendEvaluate(handle, 'String(performance.timeOrigin) + "|" + document.readyState'), 3_000, undefined, 'browser: document probe timed out');
665
+ const result = await withTimeout(handleSendEvaluate(handle, 'String(performance.timeOrigin) + "|" + document.readyState', undefined, { present: false, initialize: false }), 3_000, undefined, 'browser: document probe timed out');
665
666
  if (!result.ok)
666
667
  return null;
667
668
  if (typeof result.value !== 'string')
@@ -794,14 +795,17 @@ export class ElectronBrowserProvider {
794
795
  async focusView(handle) {
795
796
  if (handle.focus === undefined)
796
797
  return;
798
+ const quiet = this.isQuiet();
797
799
  try {
798
800
  // Bounded, unlike the rest of this call: the child RPC has no timeout of its own,
799
801
  // and this runs before typing, so an unresponsive child would hang dsh_browser_key for
800
802
  // good. A timeout is caught below exactly like any other focus failure, so the
801
803
  // best-effort contract is unchanged.
802
- await withTimeout(handle.focus(), 5_000, undefined, 'browser: focusing the view timed out');
804
+ await withTimeout(handle.focus(quiet ? { quiet } : undefined), 5_000, undefined, 'browser: focusing the view timed out');
803
805
  }
804
- catch {
806
+ catch (error) {
807
+ if (quiet)
808
+ throw error;
805
809
  // Best-effort: a view that refuses focus must not fail the caller's key
806
810
  // press; the dispatch below reports a real channel failure itself.
807
811
  }
@@ -809,6 +813,69 @@ export class ElectronBrowserProvider {
809
813
  /** Execute JS in the active tab's page context. */
810
814
  async execute(session, request, signal) {
811
815
  this.assertActionAllowed('execute');
816
+ return this.evaluatePage(session, request, signal);
817
+ }
818
+ /** Run a fixed browser operation; the request cannot contain a script. */
819
+ async pageOperation(session, request, signal) {
820
+ const script = pageOperationScript(request);
821
+ if (request.operation === 'drag') {
822
+ return this.dispatchPointer(session, request.from, request.to, request.steps, signal);
823
+ }
824
+ if (request.operation === 'probe' && request.method === 'hoverAt') {
825
+ const point = { x: Number(request.args?.[0]), y: Number(request.args?.[1]) };
826
+ return this.dispatchPointer(session, point, undefined, 1, signal);
827
+ }
828
+ return this.evaluatePage(session, { script }, signal);
829
+ }
830
+ /** Send page pointer input through CDP while preserving presentation and cancellation policy. */
831
+ async dispatchPointer(session, from, to, steps, signal) {
832
+ const coordinates = [from.x, from.y, ...to === undefined ? [] : [to.x, to.y]];
833
+ if (coordinates.some(value => !Number.isFinite(value) || value < 0)) {
834
+ throw new BrowserError('browser: pointer coordinates must be finite nonnegative viewport pixels', 'BROWSER_POINTER_INVALID');
835
+ }
836
+ if (to !== undefined && this.settingsSource?.().vision.strategy === 'nonVisual') {
837
+ throw new BrowserError('browser: coordinate dragging requires the visual strategy', 'BROWSER_NON_VISUAL_COORDINATES');
838
+ }
839
+ const s = this.session(session);
840
+ const handle = await this.present(s, signal);
841
+ const viewport = await withTimeout(handleSendEvaluate(handle, '({width:innerWidth,height:innerHeight})'), 5_000, signal, 'browser: pointer viewport check timed out');
842
+ if (!viewport.ok)
843
+ throw new BrowserError('browser: could not read the pointer viewport', 'BROWSER_POINTER_INVALID');
844
+ const size = viewport.value;
845
+ if (from.x >= size.width || from.y >= size.height || (to !== undefined && (to.x >= size.width || to.y >= size.height))) {
846
+ return { ok: true, value: JSON.stringify(to === undefined ? false : { ok: false, reason: 'drag points must be inside the current viewport' }) };
847
+ }
848
+ const send = async (params) => {
849
+ signal?.throwIfAborted();
850
+ this.assertSameView(session, handle, this.activeTab(s).handle);
851
+ await withTimeout(handle.sendCommand('Input.dispatchMouseEvent', { ...params }), 5_000, signal, 'browser: pointer input timed out');
852
+ };
853
+ await send({ type: 'mouseMoved', x: from.x, y: from.y, buttons: 0 });
854
+ if (to === undefined)
855
+ return { ok: true, value: 'true' };
856
+ let at = from;
857
+ let held = true;
858
+ try {
859
+ await send({ type: 'mousePressed', x: from.x, y: from.y, button: 'left', buttons: 1, clickCount: 1 });
860
+ const count = Math.max(1, Math.min(Math.trunc(steps) || 12, 60));
861
+ for (let step = 1; step <= count; step += 1) {
862
+ const next = { x: from.x + (to.x - from.x) * step / count, y: from.y + (to.y - from.y) * step / count };
863
+ await send({ type: 'mouseMoved', ...next, button: 'left', buttons: 1 });
864
+ at = next;
865
+ }
866
+ // Native HTML drag targets need a final drag-over before releasing at the destination.
867
+ await send({ type: 'mouseMoved', ...to, button: 'left', buttons: 1 });
868
+ await send({ type: 'mouseReleased', ...to, button: 'left', buttons: 0, clickCount: 1 });
869
+ held = false;
870
+ return { ok: true, value: JSON.stringify({ ok: true, moved: count, at: to }) };
871
+ }
872
+ finally {
873
+ if (held) {
874
+ await withTimeout(handle.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', ...at, button: 'left', buttons: 0, clickCount: 1 }), 1_000, undefined, 'browser: pointer release timed out').catch(() => { });
875
+ }
876
+ }
877
+ }
878
+ async evaluatePage(session, request, signal) {
812
879
  const s = this.session(session);
813
880
  const { handle } = this.activeTab(s);
814
881
  signal?.throwIfAborted();
@@ -2427,9 +2494,8 @@ export class ElectronBrowserProvider {
2427
2494
  }
2428
2495
  /**
2429
2496
  * Download an HTTP(S) URL with the session's cookies to a local file.
2430
- * Admission is the shared {@link admitSavePath} gate; only the self-hosted
2431
- * host implements it (the desktop shell's embedded views delegate downloads
2432
- * to the real browser UI). Both admitted paths and screenshots are confined
2497
+ * Admission is the shared {@link admitSavePath} gate. The carrier downloads
2498
+ * with its own authenticated browser session. Both admitted paths and screenshots are confined
2433
2499
  * to `downloadDir`, so a prompt-injected agent cannot write arbitrary
2434
2500
  * machine paths.
2435
2501
  * @param session - the session whose cookies are used.
@@ -2462,7 +2528,7 @@ export class ElectronBrowserProvider {
2462
2528
  const savePath = this.admitSavePath(request.savePath, 'download');
2463
2529
  const downloadable = handle;
2464
2530
  if (typeof downloadable.download !== 'function') {
2465
- throw new BrowserError('browser: download is only available on the self-hosted browser', 'BROWSER_DOWNLOAD_UNSUPPORTED');
2531
+ throw new BrowserError('browser: the selected carrier does not provide file downloads', 'BROWSER_DOWNLOAD_UNSUPPORTED');
2466
2532
  }
2467
2533
  // The child fetches and writes the file; a slow/hung network can block
2468
2534
  // it well past the tool budget, so bound it. NOTE: unlike CDP calls,
@@ -2554,10 +2620,10 @@ export class ElectronBrowserProvider {
2554
2620
  if (dropped > 0) {
2555
2621
  process.stderr.write(`[dsh-browser] restoreAuth: dropped ${dropped} of ${mapped.length} cookie(s) with no usable domain; the rest were still restored\n`);
2556
2622
  }
2557
- const result = await withTimeout(handle.sendCommand('Storage.setCookies', { cookies: convertible }), timeoutMs, undefined, `browser: auth restore timed out after ${timeoutMs}ms`);
2558
- // Storage.setCookies returns nothing, so the count comes from what was actually
2559
- // sent. Reading result.cookies here was always undefined, which rendered as
2560
- // "Restored 0 cookies." while the write had succeeded.
2623
+ await withTimeout(handle.sendCommand('Storage.setCookies', { cookies: convertible }), timeoutMs, undefined, `browser: auth restore timed out after ${timeoutMs}ms`);
2624
+ // Storage.setCookies returns nothing, so the count comes from what was actually sent.
2625
+ // An earlier version read result.cookies here; it was always undefined and rendered as
2626
+ // "Restored 0 cookies." even though the write had succeeded.
2561
2627
  const restored = convertible.length;
2562
2628
  this.record(s, 'restoreAuth', { count: cookies.length, dropped }, true, { result: `${restored} cookies (CDP)${dropped > 0 ? `; ${dropped} dropped` : ''}` });
2563
2629
  return restored;
@@ -3121,8 +3187,11 @@ export class ElectronBrowserProvider {
3121
3187
  * method did nothing at all on carriers without `collapse` (the self-hosted one),
3122
3188
  * silently desynchronising the two and failing every screenshot.
3123
3189
  */
3124
- showActive(s) {
3125
- this.host.showView?.(this.activeTab(s).handle, s.label, { quiet: this.isQuiet() });
3190
+ showActive(s, select = false) {
3191
+ const quiet = this.isQuiet();
3192
+ this.host.showView?.(this.activeTab(s).handle, s.label, { quiet, ...select ? { select: true } : {} });
3193
+ if (quiet || select)
3194
+ return;
3126
3195
  const autoExpand = this.settingsSource === undefined || this.settingsSource().ui.autoExpandOnce;
3127
3196
  if (autoExpand)
3128
3197
  return;
@@ -3269,13 +3338,13 @@ function scriptPoint(out) {
3269
3338
  const y = Number(point?.y);
3270
3339
  return Number.isFinite(x) && Number.isFinite(y) ? { x, y } : undefined;
3271
3340
  }
3272
- async function handleSendEvaluate(handle, expression, signal) {
3341
+ async function handleSendEvaluate(handle, expression, signal, options) {
3273
3342
  signal?.throwIfAborted();
3274
3343
  const result = await handle.sendCommand(CDP_RUNTIME_EVALUATE, {
3275
3344
  expression,
3276
3345
  returnByValue: true,
3277
3346
  awaitPromise: true,
3278
- });
3347
+ }, options);
3279
3348
  if (result.exceptionDetails !== undefined) {
3280
3349
  const detail = result.exceptionDetails;
3281
3350
  return { ok: false, exception: detail.exception?.description ?? detail.text ?? 'unknown exception' };
@@ -33,6 +33,7 @@ import { createRequire } from 'node:module';
33
33
  import { existsSync, readFileSync, readdirSync, readlinkSync } from 'node:fs';
34
34
  import { basename, dirname, isAbsolute, join } from 'node:path';
35
35
  import { createServer } from 'node:net';
36
+ import { withTimeoutShared } from './timing.js';
36
37
  import { fileURLToPath } from 'node:url';
37
38
  /** How long to wait for the child to signal readiness before failing. */
38
39
  const READY_TIMEOUT_MS = 20_000;
@@ -223,15 +224,19 @@ function hostElectronViaProcessTree() {
223
224
  }
224
225
  return undefined;
225
226
  }
227
+ /** One scalar property of a Windows process, read through CIM. */
228
+ function cimQuery(pid, property) {
229
+ const out = execFileSync('powershell.exe', [
230
+ '-NoProfile', '-NonInteractive', '-Command',
231
+ `(Get-CimInstance Win32_Process -Filter "ProcessId=${pid}").${property}`,
232
+ ], { encoding: 'utf8', windowsHide: true, timeout: 3000 });
233
+ return out.trim().split(/\r?\n/)[0] ?? '';
234
+ }
226
235
  /** The executable path of a running process, or undefined when unknown. */
227
236
  function processExecutable(pid) {
228
237
  try {
229
238
  if (process.platform === 'win32') {
230
- const out = execFileSync('powershell.exe', [
231
- '-NoProfile', '-NonInteractive', '-Command',
232
- `(Get-CimInstance Win32_Process -Filter "ProcessId=${pid}").ExecutablePath`,
233
- ], { encoding: 'utf8', windowsHide: true, timeout: 3000 });
234
- const line = out.trim().split(/\r?\n/)[0] ?? '';
239
+ const line = cimQuery(pid, 'ExecutablePath');
235
240
  return line.length > 0 ? line : undefined;
236
241
  }
237
242
  const exe = readlinkSync(`/proc/${pid}/exe`);
@@ -245,11 +250,7 @@ function processExecutable(pid) {
245
250
  function processParent(pid) {
246
251
  try {
247
252
  if (process.platform === 'win32') {
248
- const out = execFileSync('powershell.exe', [
249
- '-NoProfile', '-NonInteractive', '-Command',
250
- `(Get-CimInstance Win32_Process -Filter "ProcessId=${pid}").ParentProcessId`,
251
- ], { encoding: 'utf8', windowsHide: true, timeout: 3000 });
252
- const n = Number(out.trim().split(/\r?\n/)[0]);
253
+ const n = Number(cimQuery(pid, 'ParentProcessId'));
253
254
  return Number.isInteger(n) && n > 1 ? n : undefined;
254
255
  }
255
256
  const stat = readFileSync(`/proc/${pid}/stat`, 'utf8');
@@ -745,8 +746,8 @@ class RemoteView {
745
746
  });
746
747
  }
747
748
  /** Give this view web focus in the child, so keyboard input reaches the page. */
748
- focus() {
749
- return this.client.call('focus', { viewId: this.id });
749
+ focus(options) {
750
+ return this.client.call('focus', { viewId: this.id, ...options?.quiet ? { quiet: true } : {} });
750
751
  }
751
752
  /** Ask the child to download a URL to a local file (keeps cookies/login). */
752
753
  async download(url, savePath) {
@@ -1322,8 +1323,8 @@ class DeferredRemoteView {
1322
1323
  async capture(opts) {
1323
1324
  return this.withRecovery(view => view.capture(opts));
1324
1325
  }
1325
- async focus() {
1326
- return this.withRecovery(view => view.focus());
1326
+ async focus(options) {
1327
+ return this.withRecovery(view => view.focus(options));
1327
1328
  }
1328
1329
  async flushAuth() {
1329
1330
  return this.withRecovery(view => view.flushAuth());
@@ -1367,18 +1368,19 @@ function appendHostLog(text) {
1367
1368
  writeFileSync(file, `${hostStamp()} log rotated: previous content exceeded ${String(HOST_LOG_MAX_BYTES)} bytes and was discarded\n`);
1368
1369
  }
1369
1370
  }
1370
- catch { /* first write, or unreadable: just append */ }
1371
- mkdirSync(dir, { recursive: true });
1371
+ catch {
1372
+ // No readable file yet: the log directory may not exist. When statSync
1373
+ // succeeded the file exists, so its directory does too and creating it
1374
+ // again was a redundant syscall on every child stdout/stderr line.
1375
+ mkdirSync(dir, { recursive: true });
1376
+ }
1372
1377
  appendFileSync(file, text);
1373
1378
  }
1374
1379
  catch { /* diagnostics are best-effort only */ }
1375
1380
  }
1376
1381
  /** Reject a promise if it does not settle within the budget. */
1377
1382
  function withTimeout(promise, ms, message) {
1378
- return new Promise((resolve, reject) => {
1379
- const timer = setTimeout(() => reject(new Error(`${message} (${ms}ms)`)), ms);
1380
- promise.then(value => { clearTimeout(timer); resolve(value); }, error => { clearTimeout(timer); reject(error); });
1381
- });
1383
+ return withTimeoutShared(promise, ms, () => new Error(`${message} (${ms}ms)`));
1382
1384
  }
1383
1385
  /** Default host-main path relative to this module's build output. */
1384
1386
  export function defaultHostMainPath() {
@@ -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,25 +14,30 @@
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 { type BrowserChannel, type DetectedBrowser } from './system-browser.js';
26
27
  /** The part of the carrier the channel names, in the terms the panel has to explain. */
27
28
  export type CarrierKind = 'sidebar' | 'bundled' | 'system' | 'auto';
28
- /**
29
- * Whether the readiness question has an answer at all.
30
- *
31
- * `unknown` is not a defect: an explicit Chrome / Edge choice is only falsifiable by launching one,
32
- * and launching a browser to answer a status question is exactly what this report must not do. The
33
- * panel says so in words instead of guessing a colour.
34
- */
35
- export type Readiness = 'ready' | 'blocked' | 'unknown';
29
+ /** Whether the chosen carrier's required files or running bridge are available. */
30
+ export type Readiness = 'ready' | 'blocked';
31
+ /** The system-browser discovery result, obtained without launching an executable. */
32
+ export interface SystemBrowserReadiness {
33
+ /** False for channels that use the sidebar or bundled runtime directly. */
34
+ readonly checked: boolean;
35
+ readonly present: boolean;
36
+ readonly kind?: DetectedBrowser['kind'];
37
+ readonly path?: string;
38
+ /** What was found or which configured product is missing. */
39
+ readonly detail: string;
40
+ }
36
41
  /** The Electron runtime's state, as the panel needs it. */
37
42
  export interface ElectronReadiness {
38
43
  /** `present` — a launch would find a binary; `preparing` — a download is running now; and so on. */
@@ -70,8 +75,13 @@ export interface RuntimeStatusReport {
70
75
  readonly channel: BrowserChannel;
71
76
  /** What that channel resolves to, in panel terms. */
72
77
  readonly carrier: CarrierKind;
73
- /** Whether the browser this channel names can serve a call right now. */
78
+ /** The concrete carrier selected by the same discovery priority as the browser provider. */
79
+ readonly resolvedCarrier: Exclude<CarrierKind, 'auto'>;
80
+ /** Whether the carrier's environment requirements are available. */
74
81
  readonly readiness: Readiness;
82
+ readonly systemBrowser: SystemBrowserReadiness;
83
+ /** The system executable selected for the resolved carrier, when applicable. */
84
+ readonly executable?: string;
75
85
  readonly electron: ElectronReadiness;
76
86
  readonly bridge: BridgeReadiness;
77
87
  /** Whether "Prepare the bundled browser" is worth offering (it is not while one is running). */
@@ -89,6 +99,10 @@ export interface RuntimeStatusDeps {
89
99
  readonly bridge: () => BridgeStatus | undefined;
90
100
  /** The endpoint the shell publishes while it runs; undefined when nothing published one. */
91
101
  readonly endpoint: () => BridgeEndpointState | undefined;
102
+ /** The launch path's filesystem-only browser discovery; defaults to the production reader. */
103
+ readonly detectBrowser?: (channel: BrowserChannel) => DetectedBrowser | undefined;
104
+ /** The provider's current carrier, including a fallback selected after sidebar loss. */
105
+ readonly selectedCarrier?: () => Exclude<CarrierKind, 'auto'> | undefined;
92
106
  }
93
107
  /**
94
108
  * Assemble the report.
@@ -1,3 +1,4 @@
1
+ import { detectBrowser } from './system-browser.js';
1
2
  /** Which carrier a channel names. */
2
3
  function carrierOf(channel) {
3
4
  if (channel === 'sidebar')
@@ -31,10 +32,12 @@ export function readRuntimeStatus(deps) {
31
32
  // on a live install, and the kind of contradiction a reader cannot resolve.
32
33
  const snapshot = deps.provision();
33
34
  const runnable = deps.hasBinary();
34
- const state = runnable ? 'present' : snapshot.state;
35
+ const missingAfterReady = !runnable && (snapshot.state === 'present' || snapshot.state === 'ready');
36
+ const state = runnable ? 'present' : missingAfterReady ? 'failed' : snapshot.state;
35
37
  const electron = {
36
38
  state,
37
- detail: runnable ? 'an Electron runtime is already available' : snapshot.detail,
39
+ detail: runnable ? 'an Electron runtime is already available'
40
+ : missingAfterReady ? 'the previously prepared Electron runtime is missing; prepare it again' : snapshot.detail,
38
41
  at: runnable ? new Date().toISOString() : snapshot.at,
39
42
  };
40
43
  const bridgeStatus = deps.bridge();
@@ -58,25 +61,44 @@ export function readRuntimeStatus(deps) {
58
61
  // The sidebar needs BOTH halves: our patch inside the shell it will be driven through, and that
59
62
  // shell actually running. Either one alone is the false green this report exists to prevent.
60
63
  const sidebarReady = bridge.state === 'installed' && bridge.running;
64
+ const checkSystemBrowser = carrier === 'system' || carrier === 'auto';
65
+ const detected = checkSystemBrowser ? (deps.detectBrowser ?? detectBrowser)(channel) : undefined;
66
+ const systemBrowser = {
67
+ checked: checkSystemBrowser,
68
+ present: detected !== undefined,
69
+ ...detected === undefined ? {} : { kind: detected.kind, path: detected.path },
70
+ detail: detected !== undefined ? `${detected.kind} is available at ${detected.path}`
71
+ : !checkSystemBrowser ? `the ${carrier} channel uses its own carrier`
72
+ : channel === 'auto' ? 'no Chrome, Edge or Brave installation was found'
73
+ : `the selected ${channel} installation was not found`,
74
+ };
61
75
  let readiness;
76
+ let resolvedCarrier;
62
77
  if (carrier === 'sidebar') {
78
+ resolvedCarrier = 'sidebar';
63
79
  readiness = sidebarReady ? 'ready' : 'blocked';
64
80
  }
65
81
  else if (carrier === 'bundled') {
82
+ resolvedCarrier = 'bundled';
66
83
  readiness = electronReady(state) ? 'ready' : 'blocked';
67
84
  }
68
85
  else if (carrier === 'auto') {
69
- // `auto` is satisfied by either carrier, so a working sidebar covers a missing runtime. An
70
- // explicit Chrome / Edge install would satisfy it too, but proving that means launching one.
71
- readiness = electronReady(state) || sidebarReady ? 'ready' : 'unknown';
86
+ // Discovery may adopt a live desktop bridge after initially choosing a system browser. Match
87
+ // that priority here, then use the bundled runtime when no system browser was found.
88
+ resolvedCarrier = deps.selectedCarrier?.() ?? (sidebarReady ? 'sidebar' : detected !== undefined ? 'system' : 'bundled');
89
+ readiness = (resolvedCarrier === 'sidebar' ? sidebarReady : resolvedCarrier === 'system' ? detected !== undefined : electronReady(state)) ? 'ready' : 'blocked';
72
90
  }
73
91
  else {
74
- readiness = 'unknown';
92
+ resolvedCarrier = 'system';
93
+ readiness = detected !== undefined ? 'ready' : 'blocked';
75
94
  }
76
95
  return {
77
96
  channel,
78
97
  carrier,
98
+ resolvedCarrier,
79
99
  readiness,
100
+ systemBrowser,
101
+ ...resolvedCarrier === 'system' && detected !== undefined ? { executable: detected.path } : {},
80
102
  electron,
81
103
  bridge,
82
104
  // 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
  /**
@@ -29,25 +29,15 @@ export function sameOrigin(request, writing = false) {
29
29
  return true;
30
30
  if (APP_SCHEMES.includes(schemeOf(String(request.headers.referer ?? '')) ?? ''))
31
31
  return true;
32
- // MEASURED on the running desktop, and what three earlier attempts each guessed wrong: a
33
- // request from the shell's own settings panel carries NO origin, NO sec-fetch-site and NO
34
- // referer. It is not "dsh-app://app" and it is not "null" — the headers are simply absent,
35
- // because Chromium attaches no cross-origin metadata to a request leaving a custom scheme.
36
- //
37
- // So the rule for that shape cannot be "a request without an Origin is a script", which is
38
- // what refused every desktop save, and it cannot lean on `Sec-Fetch-Site` either. It has to
39
- // test what a hand-rolled client does not send:
40
- // - a renderer sends a full Mozilla-compatible `user-agent` AND an `accept-language`;
41
- // - curl sends neither unless told to, and a local process that forges both can also read
42
- // the settings document directly — it sits readable on disk, as the panel's own text
43
- // says. This was never the boundary it looked like.
32
+ // Desktop custom-scheme requests can omit browser origin metadata. The route's host-cookie
33
+ // gate has already authenticated them; the renderer headers retain compatibility with older
34
+ // shells that omit Origin while forwarding settings writes.
44
35
  if (origin === '') {
45
36
  const agent = String(request.headers['user-agent'] ?? '');
46
37
  const language = String(request.headers['accept-language'] ?? '');
47
38
  if (/^Mozilla\/5\.0/.test(agent) && language !== '')
48
39
  return true;
49
- // Reads stay open: they return the document the panel is already showing, and refusing them
50
- // would only break hand-inspection of a file that sits readable on disk anyway.
40
+ // A missing Origin is valid for reads after the host-cookie gate has admitted the caller.
51
41
  return !writing;
52
42
  }
53
43
  // `cross-site` is another origin entirely; `same-site` is another origin of the same site