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
@@ -4,7 +4,7 @@
4
4
  *
5
5
  * WHY
6
6
  * The plugin runs inside the desktop's Node-mode host, where there is no Electron
7
- * API 鈥?which is why it self-hosts a whole browser today. The shell, however, can
7
+ * API — which is why it self-hosts a whole browser today. The shell, however, can
8
8
  * own views, and its sidebar already displays real web pages. This host borrows
9
9
  * that page over the shell's bridge (see apps/desktop/bridge/plugin-browser-bridge.js),
10
10
  * so the agent and the human end up on ONE page instead of two.
@@ -13,7 +13,7 @@
13
13
  * It implements the same `ElectronBrowserViewHost` seam the self-hosted host does,
14
14
  * so the provider, the tools, browsing history, the synthetic cursor and the
15
15
  * teardown rules are all unchanged: only the carrier differs. Everything is
16
- * lazily materialized 鈥?a fresh shell has no sidebar guest until something asks
16
+ * lazily materialized — a fresh shell has no sidebar guest until something asks
17
17
  * for a page, and the bridge creates one on demand.
18
18
  *
19
19
  * FALLBACK
@@ -39,9 +39,10 @@ export function bridgeEndpointPath() {
39
39
  * A display state, not a dead carrier. It must never reach `reportLost`, and it must never be
40
40
  * retried as though a guest had vanished: retrying cannot attach a webview the shell has not
41
41
  * rendered, and treating it as loss swapped the surface to a fresh self-hosted window whose page was
42
- * blank 鈥?losing the page the user had open.
42
+ * blank — losing the page the user had open.
43
43
  */
44
44
  const PANEL_NOT_DISPLAYED = 'panel-not-displayed';
45
+ const PANEL_INITIALIZING = 'panel-initializing';
45
46
  /**
46
47
  * How many times a display-state refusal is retried, and how long each retry waits.
47
48
  *
@@ -58,20 +59,21 @@ const PANEL_DISPLAY_RETRY_MS = 400;
58
59
  *
59
60
  * Thrown instead of a plain Error so callers can distinguish "the panel did not render" from "the
60
61
  * browser broke", which is exactly the distinction issue #37 says was missing. The plugin no longer
61
- * waits for a human to show the conversation 鈥?the client half asks the shell to (`openSession`) and
62
- * this host retries while it renders 鈥?so reaching here means the shell did not render it at all.
62
+ * waits for a human to show the conversation — the client half asks the shell to (`openSession`) and
63
+ * this host retries while it renders — so reaching here means the shell did not render it at all.
63
64
  */
64
65
  export class BrowserPanelNotDisplayedError extends Error {
65
- code = PANEL_NOT_DISPLAYED;
66
+ code;
66
67
  /**
67
68
  * @param detail - the bridge's own explanation, appended so the message says why.
68
69
  */
69
- constructor(detail) {
70
- super('dsh-builtin-browser: this conversation\'s sidebar page did not attach 鈥?the shell was asked to '
70
+ constructor(detail, code = PANEL_NOT_DISPLAYED) {
71
+ super('dsh-builtin-browser: this conversation\'s sidebar page did not attach — the shell was asked to '
71
72
  + 'show this conversation and its panel still did not render. Nothing was lost, and the page '
72
73
  + 'appears as soon as the panel mounts. '
73
74
  + `(${detail})`);
74
75
  this.name = 'BrowserPanelNotDisplayedError';
76
+ this.code = code;
75
77
  }
76
78
  }
77
79
  /**
@@ -87,7 +89,7 @@ function isGuestGone(error) {
87
89
  return false;
88
90
  const message = error instanceof Error ? error.message : String(error);
89
91
  // The panel path reports its own failure when the renderer never produced a page, and that is the
90
- // same class as a vanished guest 鈥?worth one retry on a fresh panel 鈥?so it is listed here too.
92
+ // same class as a vanished guest — worth one retry on a fresh panel — so it is listed here too.
91
93
  return /guest \d+ is not available|sidebar unavailable|produced no page/i.test(message);
92
94
  }
93
95
  /**
@@ -95,16 +97,17 @@ function isGuestGone(error) {
95
97
  *
96
98
  * One sidebar exists per shell window, so every view this host hands out refers
97
99
  * to the same guest: the provider keeps its tab bookkeeping, and the tabs simply
98
- * share the visible page. That is the intended behaviour for this carrier 鈥?the
100
+ * share the visible page. That is the intended behaviour for this carrier — the
99
101
  * point is a single page both parties can see.
100
102
  */
101
103
  export class DesktopBridgeViewHost {
104
+ isQuiet;
102
105
  connection;
103
106
  /**
104
107
  * One entry per view this host handed out: the conversation it serves, and the guest backing it.
105
108
  *
106
109
  * The conversation belongs to the ENTRY, not to this host. A single plugin process serves every
107
- * conversation 鈥?DSH runs them all through one host instance 鈥?so an owner held on the host
110
+ * conversation — DSH runs them all through one host instance — so an owner held on the host
108
111
  * would be one conversation's id applied to all of them, and a page could still land in
109
112
  * another's sidebar however carefully the bridge checked it.
110
113
  */
@@ -114,7 +117,7 @@ export class DesktopBridgeViewHost {
114
117
  *
115
118
  * Every DSH session is its own plugin process, and the sidebar is one surface they all share.
116
119
  * A session can only see its own `views` map, so before the bridge kept a ledger it adopted
117
- * whichever tab it found 鈥?including one another session had opened, which is how a URL from
120
+ * whichever tab it found — including one another session had opened, which is how a URL from
118
121
  * one session appeared in another's sidebar. The id is per process, so two sessions never
119
122
  * collide and one session's tabs are never handed to another; it is deliberately not the DSH
120
123
  * session id, which this layer has no access to and does not need.
@@ -122,17 +125,17 @@ export class DesktopBridgeViewHost {
122
125
  * The whole ledger rests on that premise, so it was measured rather than assumed: with two
123
126
  * sessions running, the desktop had TWO host processes (plus one main, two renderers and a
124
127
  * gpu/utility pair). If sessions ever shared a process, every owner check in the bridge would
125
- * compare equal and the bleed would return in a new shape 鈥?so a change to how DSH spawns
128
+ * compare equal and the bleed would return in a new shape — so a change to how DSH spawns
126
129
  * sessions invalidates this file, not just this comment.
127
130
  *
128
131
  * It is now the CONVERSATION id rather than an invented uuid, read from the plugin's ctx by the
129
132
  * same path DSH's own desktop host uses. That matters because the shell keeps one sidebar per
130
133
  * conversation and writes its session id onto each sidebar container (on the React fiber,
131
- * measured on the running app) 鈥?so the bridge can only answer "is this sidebar mine" if it has
134
+ * measured on the running app) — so the bridge can only answer "is this sidebar mine" if it has
132
135
  * a comparable id. With an invented uuid it never could, which is how a command came to be typed
133
136
  * into another conversation's address bar.
134
137
  *
135
- * Falls back to a random uuid when the host cannot supply one 鈥?an older DSH, or a non-desktop
138
+ * Falls back to a random uuid when the host cannot supply one — an older DSH, or a non-desktop
136
139
  * composition. That is no worse than before: the bridge then knows only "this process", and it
137
140
  * refuses to operate on a sidebar it cannot prove is its own.
138
141
  */
@@ -142,7 +145,7 @@ export class DesktopBridgeViewHost {
142
145
  * conversation each belongs to.
143
146
  *
144
147
  * The provider destroys its view handles before it asks for a release, so the mapping is dropped
145
- * by then 鈥?keeping the guest ids here is what lets us close only our own tabs when several
148
+ * by then — keeping the guest ids here is what lets us close only our own tabs when several
146
149
  * conversations are running (requirements 搂4: each session gets its own page). The owner rides
147
150
  * along for the same reason it does in {@link views}: a release names one conversation.
148
151
  */
@@ -155,7 +158,7 @@ export class DesktopBridgeViewHost {
155
158
  * handler is stored anyway so the interface contract holds (a caller may register
156
159
  * one and must not be surprised) and so a future bridge operation can deliver it
157
160
  * without changing the provider. Consequently no user-action event is emitted while
158
- * the desktop sidebar is the carrier 鈥?by design, not by omission.
161
+ * the desktop sidebar is the carrier — by design, not by omission.
159
162
  */
160
163
  userActionHandler;
161
164
  /** Told when the shell behind this bridge exits; see `onLost`. */
@@ -163,7 +166,8 @@ export class DesktopBridgeViewHost {
163
166
  /**
164
167
  * @param endpoint - the shell's published bridge endpoint.
165
168
  */
166
- constructor(endpoint, sessionId) {
169
+ constructor(endpoint, sessionId, isQuiet = () => false) {
170
+ this.isQuiet = isQuiet;
167
171
  this.owner = sessionId !== undefined && sessionId !== String.fromCharCode(39, 39) ? sessionId : randomUUID();
168
172
  // The transport reaches this only by concluding the shell stopped refreshing its endpoint, which
169
173
  // is `shell-exited`.
@@ -196,7 +200,7 @@ export class DesktopBridgeViewHost {
196
200
  * caller falls back to self-hosting, which always works.
197
201
  * @returns the host, or undefined when no bridge is available.
198
202
  */
199
- static async discover(sessionId) {
203
+ static async discover(sessionId, isQuiet) {
200
204
  let endpoint;
201
205
  try {
202
206
  const raw = JSON.parse(readFileSync(bridgeEndpointPath(), 'utf8'));
@@ -219,7 +223,7 @@ export class DesktopBridgeViewHost {
219
223
  //
220
224
  // The sidebar browser renders as a <webview> only where the shell exposes
221
225
  // `dshDesktop.browser` and enables `webviewTag`. Where it renders as an <iframe> there is
222
- // no webContents, no `getWebContentsId()` and no CDP endpoint 鈥?and every tool here is
226
+ // no webContents, no `getWebContentsId()` and no CDP endpoint — and every tool here is
223
227
  // built on CDP, so adopting it means failing every call, with no path back to a carrier
224
228
  // that works. Reported on DSH Desktop 2.0.17 with both conditions measured.
225
229
  //
@@ -233,7 +237,7 @@ export class DesktopBridgeViewHost {
233
237
  DesktopBridgeViewHost.refuseIframe = true;
234
238
  return undefined;
235
239
  }
236
- return new DesktopBridgeViewHost(endpoint, sessionId);
240
+ return new DesktopBridgeViewHost(endpoint, sessionId, isQuiet);
237
241
  }
238
242
  finally {
239
243
  probe.close();
@@ -264,8 +268,8 @@ export class DesktopBridgeViewHost {
264
268
  * Every page this conversation's sidebar panel currently holds.
265
269
  *
266
270
  * The shell owns page creation inside the panel: a link the user or the agent clicks may open a
267
- * new page, and nothing tells the provider. Those pages are real 鈥?they are what the human sees
268
- * 鈥?but without this the tab model reports only the ones the provider created, so the rest are
271
+ * new page, and nothing tells the provider. Those pages are real — they are what the human sees
272
+ * — but without this the tab model reports only the ones the provider created, so the rest are
269
273
  * invisible to `dsh_browser_list_tabs` and unclosable through `dsh_browser_close_tab`.
270
274
  *
271
275
  * The bridge's `list` already answers with the sidebar guests, which is the same information, so
@@ -276,14 +280,14 @@ export class DesktopBridgeViewHost {
276
280
  * Every sidebar page this conversation holds that THIS HOST did not open.
277
281
  *
278
282
  * The shell owns page creation inside the panel: a link the user or the agent clicks may open a
279
- * new page, and nothing tells the provider. Those pages are real 鈥?they are what the human sees
280
- * 鈥?but without this the tab model reports only the ones the provider created, so the rest are
283
+ * new page, and nothing tells the provider. Those pages are real — they are what the human sees
284
+ * — but without this the tab model reports only the ones the provider created, so the rest are
281
285
  * invisible to `dsh_browser_list_tabs` and unclosable through `dsh_browser_close_tab`.
282
286
  *
283
287
  * Pages this host opened are EXCLUDED here rather than deduplicated by the caller, because the
284
288
  * caller cannot do it: the provider knows a tab by its own id and the carrier knows a page by the
285
289
  * guest id, and the two never match. The first version returned everything and relied on the
286
- * caller to filter, which reported the same page twice 鈥?the mapping that makes the match
290
+ * caller to filter, which reported the same page twice — the mapping that makes the match
287
291
  * possible exists only here.
288
292
  * @returns the panel's pages that are not ours, or an empty list when the bridge cannot answer.
289
293
  */
@@ -308,7 +312,7 @@ export class DesktopBridgeViewHost {
308
312
  /**
309
313
  * Close one sidebar page by the id {@link listPages} reported.
310
314
  *
311
- * The bridge closes sidebar pages by TITLE, and only the ones the caller owns 鈥?that is what
315
+ * The bridge closes sidebar pages by TITLE, and only the ones the caller owns — that is what
312
316
  * stopped one conversation's teardown from destroying another's page. So the title is looked up
313
317
  * through the same listing, and a page that no longer appears is treated as already gone rather
314
318
  * than as an error: the caller asked for it to be closed, and it is.
@@ -326,8 +330,8 @@ export class DesktopBridgeViewHost {
326
330
  /**
327
331
  * The guest backing a view, materialized on first use.
328
332
  *
329
- * The conversation that called owns exactly one sidebar page on this carrier 鈥?a human and the
330
- * agent look at the same page 鈥?so every view resolves to that conversation's own guest, and the
333
+ * The conversation that called owns exactly one sidebar page on this carrier — a human and the
334
+ * agent look at the same page — so every view resolves to that conversation's own guest, and the
331
335
  * page does not multiply behind the provider's own tab bookkeeping.
332
336
  *
333
337
  * A cached guest is used as-is: probing it first cost a round-trip on every command, so liveness
@@ -342,7 +346,10 @@ export class DesktopBridgeViewHost {
342
346
  // and `createView`'s sendCommand then discards the cache and calls back in here.
343
347
  if (entry?.guest !== undefined)
344
348
  return entry.guest;
345
- // The conversation THIS VIEW serves 鈥?read from the view, never from the process.
349
+ if (options?.initialize === false) {
350
+ throw new BrowserPanelNotDisplayedError('this view has no attached guest yet', PANEL_INITIALIZING);
351
+ }
352
+ // The conversation THIS VIEW serves — read from the view, never from the process.
346
353
  //
347
354
  // The difference is the whole bug. This host is one instance shared by every conversation, so
348
355
  // `this.owner` alone can only be "whichever conversation this process happens to name", and
@@ -355,10 +362,11 @@ export class DesktopBridgeViewHost {
355
362
  // shortcut or clicking its card, both of which the shell delivers to whatever it displays.
356
363
  const owner = entry?.owner ?? this.owner;
357
364
  // A command that must not present anything (issue #46: the live preview) takes a read-only path.
358
- // It asks the bridge what this conversation ALREADY has and never enters the retry loop below 鈥? // that loop is what asks the shell to display the conversation, which is right for a tool call
365
+ // It asks the bridge what this conversation ALREADY has and never enters the retry loop below — // that loop is what asks the shell to display the conversation, which is right for a tool call
359
366
  // and wrong for "let me look at it". A page that is not on screen therefore reports as a display
360
367
  // state, and the preview route turns that into the panel's paused state.
361
- if (options?.present === false) {
368
+ const quiet = this.isQuiet();
369
+ if (options?.present === false || quiet) {
362
370
  // `list` and NOT `ensureSidebar`. This is deliberate and it is the whole fix: every version of
363
371
  // `ensureSidebar` can drive the shell — the current one asks the renderer to display the
364
372
  // conversation, and the pre-#37 one literally pressed the sidebar shortcut and typed into the
@@ -370,13 +378,16 @@ export class DesktopBridgeViewHost {
370
378
  ? listed.sidebar.filter(page => page !== null && typeof page === 'object' && page.type === 'webview')
371
379
  : [];
372
380
  const wanted = url !== undefined && url !== '' ? url : undefined;
373
- const match = wanted === undefined
374
- ? pages[0]
375
- : pages.find(page => typeof page.url === 'string' && (page.url === wanted || page.url.startsWith(wanted))) ?? pages[0];
381
+ const matchedUrl = pages.find(page => wanted !== undefined && page.url === wanted);
382
+ const match = quiet && wanted !== undefined
383
+ ? matchedUrl
384
+ : pages.find(page => wanted !== undefined && typeof page.url === 'string' && page.url.startsWith(wanted)) ?? pages[0];
376
385
  const id = match !== undefined ? Number(match.id) : Number.NaN;
377
386
  if (!Number.isFinite(id) || id <= 0) {
378
- throw new BrowserPanelNotDisplayedError('the preview asked for this conversation\'s page without presenting it, and no page is attached '
379
- + `(the shell holds ${pages.length})`);
387
+ throw new BrowserPanelNotDisplayedError(quiet
388
+ ? 'quiet mode will not open a sidebar or switch conversations; open this URL in the sidebar yourself or select the bundled browser for background work'
389
+ : 'the preview asked for this conversation\'s page without presenting it, and no page is attached '
390
+ + `(the shell holds ${pages.length})`);
380
391
  }
381
392
  this.views.set(viewId, { guest: id, owner });
382
393
  return id;
@@ -393,13 +404,13 @@ export class DesktopBridgeViewHost {
393
404
  // panel-not-displayed - the conversation exists but is not the one on screen;
394
405
  // "is not mounted" - its surface store was not minted when the tab was placed.
395
406
  // Both are gone one render later. Measured, this is the whole difference between "the sidebar
396
- // works once I click over to that conversation" and "it works" 鈥?the page is real either way,
407
+ // works once I click over to that conversation" and "it works" — the page is real either way,
397
408
  // and failing the call while the shell is already switching away from it just reported a
398
409
  // problem the plugin had already fixed.
399
410
  const displayRefusal = (value) => value.ok !== true
400
411
  && (String(value.code ?? '') === PANEL_NOT_DISPLAYED
401
412
  || String(value.error ?? '').includes('not mounted')
402
- // Bridges installed before issue #37 send the same refusal with NO code 鈥?the installed copy
413
+ // Bridges installed before issue #37 send the same refusal with NO code — the installed copy
403
414
  // on this machine is one of them (`panel-not-displayed` appears nowhere in it). Reading only
404
415
  // the code therefore turned a retryable display state into a hard failure for exactly the
405
416
  // users who had the old bridge, which is the majority until it is reinstalled. The wording
@@ -410,17 +421,20 @@ export class DesktopBridgeViewHost {
410
421
  answer = await ask();
411
422
  }
412
423
  if (answer.ok !== true) {
413
- // Reachable only after the retries above have run out, and the code still decides 鈥?not the
424
+ // Reachable only after the retries above have run out, and the code still decides — not the
414
425
  // wording:
415
426
  // panel-not-displayed -> the shell was asked to show the conversation (client half's
416
427
  // `openSession`) and did not render it in ~1.6 s: no loss, no swap.
417
- // produced no page -> this shell cannot drive a panel at all (an iframe shell, issue #30);
418
- // fall back, because otherwise every call fails forever.
428
+ // A missing guest within a time budget is still initialization, including on old bridges
429
+ // that only returned text. It is not evidence that this shell uses an undrivable iframe.
419
430
  const code = String(answer.code ?? '');
420
431
  const detail = String(answer.error);
421
432
  if (code === PANEL_NOT_DISPLAYED)
422
433
  throw new BrowserPanelNotDisplayedError(detail);
423
- if (detail.includes('produced no page'))
434
+ if (code === PANEL_INITIALIZING || (code === '' && detail.includes('produced no page'))) {
435
+ throw new BrowserPanelNotDisplayedError(detail, PANEL_INITIALIZING);
436
+ }
437
+ if (code === 'panel-unusable')
424
438
  this.reportLost('panel-unusable');
425
439
  throw new Error(`dsh-builtin-browser: sidebar unavailable (${detail})`);
426
440
  }
@@ -492,16 +506,23 @@ export class DesktopBridgeViewHost {
492
506
  * This used to be empty, on the reasoning that the sidebar is already on screen so there is
493
507
  * nothing to show. That confused "the sidebar is visible" with "this page is the one being
494
508
  * looked at": opening a page left it behind whatever the human had in front, which is issue
495
- * #23. The other two carriers both do this 鈥?the self-hosted window re-adds the view and the
496
- * system browser calls `Page.bringToFront` 鈥?so this carrier was the odd one out.
509
+ * #23. The other two carriers both do this — the self-hosted window re-adds the view and the
510
+ * system browser calls `Page.bringToFront` — so this carrier was the odd one out.
497
511
  *
498
512
  * Best-effort by design: the tab strip belongs to the shell's renderer, and failing to raise
499
513
  * it must not fail the navigation that has already happened.
500
514
  * @param handle - the view to bring forward.
501
515
  */
502
- showView(handle) {
516
+ showView(handle, _label, options) {
517
+ // Quiet mode (`ui.quiet`) means "do not take my screen". On this carrier showing a page means
518
+ // asking the shell to switch the displayed conversation — precisely the takeover the switch
519
+ // forbids. So honour it by asking for nothing: a page that is already displayed keeps working,
520
+ // and one that is not fails with the documented display-state error instead of moving the
521
+ // user's view. Measured before this: the setting was on and every call still switched.
522
+ if (options?.quiet === true)
523
+ return;
503
524
  // `owner` is required: the bridge refuses to bring forward a guest held by another session.
504
- // It comes from the view, not the process 鈥?with several conversations live, a process-wide
525
+ // It comes from the view, not the process — with several conversations live, a process-wide
505
526
  // owner would raise the wrong conversation's tab.
506
527
  const owner = this.views.get(handle.id)?.owner ?? this.owner;
507
528
  const guest = this.views.get(handle.id)?.guest;
@@ -519,7 +540,7 @@ export class DesktopBridgeViewHost {
519
540
  *
520
541
  * Destroying our own view handles is not enough on this carrier: the sidebar
521
542
  * belongs to the shell and would happily keep the page (and its renderer) alive.
522
- * Closing the tabs is what actually ends the page 鈥?and only the page: cookies
543
+ * Closing the tabs is what actually ends the page — and only the page: cookies
523
544
  * live in the partition, history on disk, so both survive.
524
545
  * @param owner - the conversation whose pages to close. Omit to close every conversation's,
525
546
  * which is only correct from a teardown that is itself global.
@@ -527,7 +548,7 @@ export class DesktopBridgeViewHost {
527
548
  */
528
549
  async releasePage(owner) {
529
550
  // Only this conversation's tabs. The host is ONE instance shared by every conversation, so a
530
- // release that named none would close pages other conversations are still driving 鈥?"every
551
+ // release that named none would close pages other conversations are still driving — "every
531
552
  // webview currently visible" is precisely what must never be used here.
532
553
  const mine = [];
533
554
  for (const [viewId, entry] of [...this.views]) {
@@ -553,7 +574,7 @@ export class DesktopBridgeViewHost {
553
574
  // `owner` is REQUIRED here now that the bridge filters `list` by it. Without it the bridge
554
575
  // falls back to a different owner, so the guests this session holds are filtered out of the
555
576
  // answer, `mine.includes(...)` matches nothing, the title list comes back empty and this
556
- // returns without closing anything 鈥?the page stayed open and the human had to close it by
577
+ // returns without closing anything — the page stayed open and the human had to close it by
557
578
  // hand. Adding the ledger to the bridge without updating this call site is exactly the kind
558
579
  // of half-change that made the ownership work take four rounds.
559
580
  const answer = await this.connection.call({ op: 'list', owner: owner ?? this.owner }, 5_000);
@@ -7,6 +7,30 @@ export interface ProvisionResult {
7
7
  /** One line for the log; never contains a stack trace a user has to decode. */
8
8
  readonly detail: string;
9
9
  }
10
+ /**
11
+ * The state a settings panel shows, which is one state wider than {@link ProvisionResult}.
12
+ *
13
+ * `idle` and `preparing` are the two a log line never needs and a user always does: "nothing has
14
+ * been asked for yet" and "a ~100 MB download is running right now" are the states in which a first
15
+ * browser call is slow, and until this existed neither was visible anywhere in the product — the
16
+ * only trace was a log line the panel cannot read.
17
+ */
18
+ export interface ProvisionSnapshot {
19
+ /** `idle` and `preparing` are provisional; the rest are terminal for this attempt. */
20
+ readonly state: 'idle' | 'preparing' | 'present' | 'ready' | 'skipped' | 'failed';
21
+ /** One line, already user-facing: never a stack trace. */
22
+ readonly detail: string;
23
+ /** When the state last changed, ISO. */
24
+ readonly at: string;
25
+ }
26
+ /**
27
+ * The current provisioning state, for a readiness report.
28
+ *
29
+ * Deliberately a snapshot rather than a promise: a panel polling this must be able to answer in one
30
+ * synchronous read, without awaiting (and thereby echoing) the download it is reporting on.
31
+ * @returns the last state written, or the idle state before anything ran.
32
+ */
33
+ export declare function provisionSnapshot(): ProvisionSnapshot;
10
34
  /** Everything this module touches from the outside, so a test can drive it without Electron. */
11
35
  export interface ProvisionDeps {
12
36
  /** Whether a spawnable binary already exists. */
@@ -14,7 +38,7 @@ export interface ProvisionDeps {
14
38
  /** The installed electron package's own installer script, or undefined when it is not there. */
15
39
  readonly installerScript: () => string | undefined;
16
40
  /** Runs the installer; resolves to an exit code, or rejects/returns null on failure. */
17
- readonly run: (script: string) => Promise<{
41
+ readonly run: (script: string, signal?: AbortSignal) => Promise<{
18
42
  code: number | null;
19
43
  detail?: string;
20
44
  }>;
@@ -50,10 +74,19 @@ export declare function ensureElectronRuntime(deps?: ProvisionDeps): Promise<Pro
50
74
  *
51
75
  * Returns immediately with the shared promise, so a caller that does not care can ignore it and one
52
76
  * that does can await it — the returned promise never rejects.
77
+ *
78
+ * `force` is the second half of the settings panel's retry button. Without it the memoised attempt
79
+ * made a failed download permanent for the life of the process: the panel could offer a button, the
80
+ * button could call this, and the answer would be the failure it was trying to replace. An attempt
81
+ * still IN FLIGHT is always joined, never restarted — two downloads into one directory is the one
82
+ * outcome worth refusing.
53
83
  * @param log - where the outcome goes.
54
84
  * @param deps - the effects; defaulted to this process's, overridable so a test can drive it.
85
+ * @param options - `force` discards a settled attempt so a new one may start.
55
86
  * @returns the shared attempt.
56
87
  */
57
- export declare function provisionElectronInBackground(log: (message: string) => void, deps?: ProvisionDeps): Promise<ProvisionResult>;
88
+ export declare function provisionElectronInBackground(log: (message: string) => void, deps?: ProvisionDeps, options?: {
89
+ readonly force?: boolean;
90
+ }): Promise<ProvisionResult>;
58
91
  /** Forget the attempt. Tests only: a real process provisions at most once. */
59
92
  export declare function resetProvisionStateForTest(): void;
@@ -34,6 +34,27 @@ import { dirname, join } from 'node:path';
34
34
  import { internals } from './remote-host.js';
35
35
  /** How long a background provision may run before it is abandoned. */
36
36
  export const PROVISION_TIMEOUT_MS = 180_000;
37
+ const IDLE = {
38
+ state: 'idle',
39
+ detail: 'the runtime has not been asked for yet',
40
+ at: new Date(0).toISOString(),
41
+ };
42
+ let latest = IDLE;
43
+ /**
44
+ * The current provisioning state, for a readiness report.
45
+ *
46
+ * Deliberately a snapshot rather than a promise: a panel polling this must be able to answer in one
47
+ * synchronous read, without awaiting (and thereby echoing) the download it is reporting on.
48
+ * @returns the last state written, or the idle state before anything ran.
49
+ */
50
+ export function provisionSnapshot() {
51
+ return latest;
52
+ }
53
+ /** Replace the reported state. Internal: every terminal result is recorded here. */
54
+ function record(result) {
55
+ latest = { state: result.status, detail: result.detail, at: new Date().toISOString() };
56
+ return result;
57
+ }
37
58
  /**
38
59
  * Whether a spawnable Electron binary is already available.
39
60
  *
@@ -81,21 +102,37 @@ function electronVersion() {
81
102
  return 'unknown';
82
103
  }
83
104
  }
105
+ let runningInstaller;
84
106
  /** The real dependencies: this process's spawn, fs and logger. */
85
107
  export function defaultDeps(log = () => { }) {
86
108
  return {
87
109
  hasBinary: hasElectronRuntime,
88
110
  installerScript: electronInstallerScript,
89
- run: async (script) => {
90
- const child = spawn(process.execPath, [script], {
91
- env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' },
92
- stdio: ['ignore', 'ignore', 'ignore'],
93
- windowsHide: true,
94
- });
95
- return await new Promise(resolve => {
96
- child.once('error', error => resolve({ code: null, detail: String(error) }));
97
- child.once('close', code => resolve({ code, detail: undefined }));
111
+ run: (script, signal) => {
112
+ if (runningInstaller !== undefined)
113
+ return runningInstaller;
114
+ const run = new Promise(resolve => {
115
+ const child = spawn(process.execPath, [script], {
116
+ env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' },
117
+ stdio: ['ignore', 'ignore', 'ignore'],
118
+ windowsHide: true,
119
+ });
120
+ let failure;
121
+ const abort = () => { child.kill('SIGKILL'); };
122
+ signal?.addEventListener('abort', abort, { once: true });
123
+ if (signal?.aborted)
124
+ abort();
125
+ child.once('error', error => { failure = String(error); });
126
+ child.once('close', code => {
127
+ signal?.removeEventListener('abort', abort);
128
+ resolve({ code, detail: failure });
129
+ });
98
130
  });
131
+ runningInstaller = run;
132
+ const clear = () => { if (runningInstaller === run)
133
+ runningInstaller = undefined; };
134
+ void run.then(clear, clear);
135
+ return run;
99
136
  },
100
137
  log,
101
138
  skip: () => typeof process.env.ELECTRON_SKIP_BINARY_DOWNLOAD === 'string'
@@ -113,13 +150,18 @@ export function defaultDeps(log = () => { }) {
113
150
  */
114
151
  export async function ensureElectronRuntime(deps = defaultDeps()) {
115
152
  if (deps.hasBinary())
116
- return { status: 'present', detail: 'an Electron runtime is already available' };
153
+ return record({ status: 'present', detail: 'an Electron runtime is already available' });
117
154
  if (deps.skip())
118
- return { status: 'skipped', detail: 'ELECTRON_SKIP_BINARY_DOWNLOAD is set' };
155
+ return record({ status: 'skipped', detail: 'ELECTRON_SKIP_BINARY_DOWNLOAD is set' });
119
156
  const script = deps.installerScript();
120
157
  if (script === undefined) {
121
- return { status: 'failed', detail: 'the installed electron package has no install.js; reinstall the plugin in this profile' };
158
+ return record({ status: 'failed', detail: 'the installed electron package has no install.js; reinstall the plugin in this profile' });
122
159
  }
160
+ latest = {
161
+ state: 'preparing',
162
+ detail: `downloading Electron ${electronVersion()} (one time, about a minute)`,
163
+ at: new Date().toISOString(),
164
+ };
123
165
  deps.log(`preparing Electron ${electronVersion()} in the background (a missing runtime needs a download)`);
124
166
  // The bound has to be a REFERENCED timer, and it has to be cleared when the race finishes.
125
167
  //
@@ -129,42 +171,61 @@ export async function ensureElectronRuntime(deps = defaultDeps()) {
129
171
  // this path failed with "Promise resolution is still pending but the event loop has already
130
172
  // resolved". Keep it referenced, and clear it so a success does not leave a 180 s handle behind.
131
173
  let timer;
174
+ const controller = new AbortController();
132
175
  const timeout = new Promise(resolve => {
133
- timer = setTimeout(() => resolve({ code: null, detail: `gave up after ${Math.round(deps.timeoutMs / 1000)}s` }), deps.timeoutMs);
176
+ timer = setTimeout(() => {
177
+ controller.abort();
178
+ resolve({ code: null, detail: `gave up after ${Math.round(deps.timeoutMs / 1000)}s` });
179
+ }, deps.timeoutMs);
134
180
  });
135
181
  let outcome;
136
182
  try {
137
- outcome = await Promise.race([deps.run(script), timeout]);
183
+ outcome = await Promise.race([deps.run(script, controller.signal), timeout]);
138
184
  }
139
185
  catch (error) {
140
- return { status: 'failed', detail: `the download failed: ${String(error)}` };
186
+ return record({ status: 'failed', detail: `the download failed: ${String(error)}` });
141
187
  }
142
188
  finally {
143
189
  if (timer !== undefined)
144
190
  clearTimeout(timer);
145
191
  }
146
192
  if (outcome.code !== 0) {
147
- return {
193
+ return record({
148
194
  status: 'failed',
149
195
  detail: `Electron provisioning did not finish (${outcome.detail ?? `exit ${String(outcome.code)}`}); `
150
- + 'the browser still works through a sidebar, Chrome or Edge, and `npx --no dsh-browser-install-electron` retries it',
151
- };
196
+ + 'the browser still works through a sidebar, Chrome or Edge; retry from Settings → Browser → '
197
+ + 'Readiness ("Prepare the bundled browser"), or run `npx --no dsh-browser-install-electron`',
198
+ });
152
199
  }
153
- return { status: 'ready', detail: 'the Electron runtime is ready' };
200
+ return record({ status: 'ready', detail: 'the Electron runtime is ready' });
154
201
  }
155
202
  /** One attempt per process, shared by every caller. */
156
203
  let attempt;
204
+ /** Whether {@link attempt} has settled, which is what makes a retry possible. */
205
+ let settled = false;
157
206
  /**
158
207
  * Start (or join) the single background attempt.
159
208
  *
160
209
  * Returns immediately with the shared promise, so a caller that does not care can ignore it and one
161
210
  * that does can await it — the returned promise never rejects.
211
+ *
212
+ * `force` is the second half of the settings panel's retry button. Without it the memoised attempt
213
+ * made a failed download permanent for the life of the process: the panel could offer a button, the
214
+ * button could call this, and the answer would be the failure it was trying to replace. An attempt
215
+ * still IN FLIGHT is always joined, never restarted — two downloads into one directory is the one
216
+ * outcome worth refusing.
162
217
  * @param log - where the outcome goes.
163
218
  * @param deps - the effects; defaulted to this process's, overridable so a test can drive it.
219
+ * @param options - `force` discards a settled attempt so a new one may start.
164
220
  * @returns the shared attempt.
165
221
  */
166
- export function provisionElectronInBackground(log, deps = defaultDeps(log)) {
222
+ export function provisionElectronInBackground(log, deps = defaultDeps(log), options = {}) {
223
+ if (options.force === true && settled) {
224
+ attempt = undefined;
225
+ settled = false;
226
+ }
167
227
  attempt ??= ensureElectronRuntime(deps).then(result => {
228
+ settled = true;
168
229
  log(`electron runtime: ${result.status} — ${result.detail}`);
169
230
  return result;
170
231
  });
@@ -173,4 +234,6 @@ export function provisionElectronInBackground(log, deps = defaultDeps(log)) {
173
234
  /** Forget the attempt. Tests only: a real process provisions at most once. */
174
235
  export function resetProvisionStateForTest() {
175
236
  attempt = undefined;
237
+ settled = false;
238
+ latest = IDLE;
176
239
  }