dsh-builtin-browser 0.5.7 → 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 (94) hide show
  1. package/CHANGELOG.md +66 -0
  2. package/README.en.md +48 -22
  3. package/README.md +48 -22
  4. package/client.js +469 -81
  5. package/desktop-bridge/install-and-start.cmd +4 -5
  6. package/desktop-bridge/install.mjs +251 -159
  7. package/desktop-bridge/maintenance-progress.ps1 +166 -0
  8. package/desktop-bridge/plugin-browser-bridge.js +151 -18
  9. package/desktop-bridge/request-desktop-quit.ps1 +170 -0
  10. package/docs/user-guide.md +28 -4
  11. package/lib/browser-electron/automatic-maintenance.d.ts +41 -0
  12. package/lib/browser-electron/automatic-maintenance.js +426 -0
  13. package/lib/browser-electron/bridge-auto.d.ts +93 -0
  14. package/lib/browser-electron/bridge-auto.js +113 -0
  15. package/lib/browser-electron/bridge-connection.d.ts +0 -2
  16. package/lib/browser-electron/bridge-connection.js +2 -4
  17. package/lib/browser-electron/bridge-endpoint.js +1 -19
  18. package/lib/browser-electron/bridge-install.d.ts +41 -4
  19. package/lib/browser-electron/bridge-install.js +131 -18
  20. package/lib/browser-electron/bridge-maintenance.d.ts +24 -0
  21. package/lib/browser-electron/bridge-maintenance.js +125 -0
  22. package/lib/browser-electron/bridge-status.d.ts +10 -3
  23. package/lib/browser-electron/bridge-status.js +76 -45
  24. package/lib/browser-electron/desktop-bridge-host.d.ts +5 -2
  25. package/lib/browser-electron/desktop-bridge-host.js +54 -33
  26. package/lib/browser-electron/desktop-identity.js +21 -9
  27. package/lib/browser-electron/electron-provision.js +5 -2
  28. package/lib/browser-electron/entry.js +104 -74
  29. package/lib/browser-electron/ephemeral-profile.js +67 -26
  30. package/lib/browser-electron/history-store.js +2 -2
  31. package/lib/browser-electron/host-main.js +26 -37
  32. package/lib/browser-electron/http-body.d.ts +24 -0
  33. package/lib/browser-electron/http-body.js +33 -0
  34. package/lib/browser-electron/json-reply.d.ts +13 -1
  35. package/lib/browser-electron/json-reply.js +16 -2
  36. package/lib/browser-electron/maintenance-broker.d.ts +35 -0
  37. package/lib/browser-electron/maintenance-broker.js +114 -0
  38. package/lib/browser-electron/maintenance-lifecycle.d.ts +32 -0
  39. package/lib/browser-electron/maintenance-lifecycle.js +67 -0
  40. package/lib/browser-electron/maintenance-route.d.ts +18 -0
  41. package/lib/browser-electron/maintenance-route.js +75 -0
  42. package/lib/browser-electron/paths.d.ts +4 -0
  43. package/lib/browser-electron/paths.js +19 -0
  44. package/lib/browser-electron/process.d.ts +14 -0
  45. package/lib/browser-electron/process.js +24 -0
  46. package/lib/browser-electron/provider.d.ts +7 -7
  47. package/lib/browser-electron/provider.js +13 -14
  48. package/lib/browser-electron/remote-host.js +18 -16
  49. package/lib/browser-electron/runtime-status.d.ts +27 -13
  50. package/lib/browser-electron/runtime-status.js +24 -4
  51. package/lib/browser-electron/settings-store.d.ts +11 -0
  52. package/lib/browser-electron/settings-store.js +8 -2
  53. package/lib/browser-electron/sidebar-only-host.d.ts +36 -0
  54. package/lib/browser-electron/sidebar-only-host.js +192 -0
  55. package/lib/browser-electron/system-browser.d.ts +1 -9
  56. package/lib/browser-electron/system-browser.js +19 -22
  57. package/lib/browser-electron/timing.d.ts +8 -0
  58. package/lib/browser-electron/timing.js +13 -0
  59. package/lib/browser-electron/windows-system.d.ts +3 -0
  60. package/lib/browser-electron/windows-system.js +19 -0
  61. package/lib/tool-browser/index.js +5 -4
  62. package/package.json +2 -2
  63. package/scripts/run-tests.mjs +32 -0
  64. package/scripts/verify-preview-route.mjs +19 -1
  65. package/src/browser-electron/automatic-maintenance.ts +414 -0
  66. package/src/browser-electron/bridge-auto.ts +158 -0
  67. package/src/browser-electron/bridge-connection.ts +2 -4
  68. package/src/browser-electron/bridge-endpoint.ts +1 -18
  69. package/src/browser-electron/bridge-install.ts +151 -20
  70. package/src/browser-electron/bridge-maintenance.ts +161 -0
  71. package/src/browser-electron/bridge-status.ts +78 -48
  72. package/src/browser-electron/desktop-bridge-host.ts +48 -32
  73. package/src/browser-electron/desktop-identity.ts +18 -9
  74. package/src/browser-electron/electron-provision.ts +5 -2
  75. package/src/browser-electron/entry.ts +91 -69
  76. package/src/browser-electron/ephemeral-profile.ts +65 -28
  77. package/src/browser-electron/history-store.ts +2 -2
  78. package/src/browser-electron/host-main.ts +23 -36
  79. package/src/browser-electron/http-body.ts +42 -0
  80. package/src/browser-electron/json-reply.ts +18 -3
  81. package/src/browser-electron/maintenance-broker.ts +142 -0
  82. package/src/browser-electron/maintenance-lifecycle.ts +86 -0
  83. package/src/browser-electron/maintenance-route.ts +64 -0
  84. package/src/browser-electron/paths.ts +21 -0
  85. package/src/browser-electron/process.ts +23 -0
  86. package/src/browser-electron/provider.ts +18 -18
  87. package/src/browser-electron/remote-host.ts +19 -19
  88. package/src/browser-electron/runtime-status.ts +52 -17
  89. package/src/browser-electron/settings-store.ts +20 -3
  90. package/src/browser-electron/sidebar-only-host.ts +199 -0
  91. package/src/browser-electron/system-browser.ts +19 -22
  92. package/src/browser-electron/timing.ts +16 -0
  93. package/src/browser-electron/windows-system.ts +23 -0
  94. package/src/tool-browser/index.ts +5 -4
@@ -8,18 +8,27 @@
8
8
  *
9
9
  * The states are the three that actually occur:
10
10
  *
11
- * - `installed` — the shell's main.js carries our marker and the archive is still moved aside.
11
+ * - `installed` — the loaded main.js carries our marker and its bridge matches this plugin.
12
12
  * - `missing` — no marker. Either never installed, or the shell was upgraded (which restores
13
13
  * `app.asar` and replaces `lib/main.js`) and the bridge went with it.
14
- * - `stale` — the marker is present but `app.asar` is back. That is the signature of a desktop
15
- * update that restored the archive without removing our patch: the shell loads the archive, so the
16
- * patch inside the unpacked tree has no effect. This is the case that looks installed and is not.
14
+ * - `stale` — the archive is back, or the deployed bridge module is missing or outdated.
17
15
  * @module dsh-browser/browser-electron/bridge-status
18
16
  */
19
17
  import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
20
18
  import { join } from 'node:path';
21
19
  import { fileURLToPath } from 'node:url';
20
+ import { createRequire } from 'node:module';
22
21
  import { readDesktopIdentity } from './desktop-identity.js';
22
+ // A normal Electron existsSync(app.asar) caches the archive and keeps it locked on Windows.
23
+ // Status inspection must leave maintenance free to rename it after Desktop exits.
24
+ const rawExistsSync = (() => {
25
+ try {
26
+ return createRequire(import.meta.url)('original-fs').existsSync;
27
+ }
28
+ catch {
29
+ return existsSync;
30
+ }
31
+ })();
23
32
  /**
24
33
  * Find the desktop install to report on.
25
34
  *
@@ -31,31 +40,51 @@ import { readDesktopIdentity } from './desktop-identity.js';
31
40
  * @param localAppData - the base directory; defaults to the environment's.
32
41
  * @returns the install directory, or undefined when nothing matches.
33
42
  */
34
- export function findDesktopInstall(localAppData = process.env.LOCALAPPDATA ?? '') {
35
- if (localAppData === '')
36
- return undefined;
37
- const programs = join(localAppData, 'Programs');
38
- // An archive-only layout is still a DSH Desktop install: a desktop update repacks `resources/app`
39
- // into `resources/app.asar`, and the identity rule (which reads the unpacked main entry) then has
40
- // nothing to read. Treating that as "no desktop here" hid the repair command exactly when it was
41
- // needed most — measured on this machine after an update.
42
- const isDesktop = (candidate) => readDesktopIdentity(candidate).ok || safeExists(join(candidate, 'resources', 'app.asar'));
43
- for (const named of ['DSH Desktop', 'DeepSeek Harness']) {
44
- const candidate = join(programs, named);
45
- if (isDesktop(candidate))
46
- return candidate;
43
+ export function findDesktopInstall(localAppData) {
44
+ // Not every install lives in %LOCALAPPDATA%\\Programs: people put the app on another drive, under
45
+ // Program Files, or in their own folder. DSH_DESKTOP_PATH names one explicitly, and the usual roots
46
+ // are all probed. A test or a caller that passes a base directory gets exactly that base, so the
47
+ // behaviour stays pinnable.
48
+ const isDesktop = (candidate) => readDesktopIdentity(candidate).ok;
49
+ const explicit = process.env.DSH_DESKTOP_PATH;
50
+ if (explicit !== undefined && explicit !== '') {
51
+ const named = explicit;
52
+ if (isDesktop(named))
53
+ return named;
54
+ // A parent directory is a reasonable thing to point at too: look one level down.
55
+ try {
56
+ for (const entry of readdirSync(named, { withFileTypes: true })) {
57
+ if (entry.isDirectory() && isDesktop(join(named, entry.name)))
58
+ return join(named, entry.name);
59
+ }
60
+ }
61
+ catch {
62
+ // Not a directory: fall through to the usual roots.
63
+ }
47
64
  }
48
- try {
49
- for (const entry of readdirSync(programs, { withFileTypes: true })) {
50
- if (!entry.isDirectory())
51
- continue;
52
- const candidate = join(programs, entry.name);
65
+ const roots = localAppData === undefined
66
+ ? [process.env.LOCALAPPDATA ?? '', process.env['ProgramFiles'] ?? '', process.env['ProgramFiles(x86)'] ?? '', process.env.APPDATA ?? '', process.env.ProgramData ?? '']
67
+ .filter(base => base !== '')
68
+ .map(base => (base === process.env.LOCALAPPDATA ? join(base, 'Programs') : base))
69
+ : [join(localAppData, 'Programs')];
70
+ for (const base of roots) {
71
+ for (const named of ['DSH Desktop', 'DeepSeek Harness']) {
72
+ const candidate = join(base, named);
53
73
  if (isDesktop(candidate))
54
74
  return candidate;
55
75
  }
56
- }
57
- catch {
58
- // No Programs directory: nothing to report on, which is a state rather than an error.
76
+ try {
77
+ for (const entry of readdirSync(base, { withFileTypes: true })) {
78
+ if (!entry.isDirectory())
79
+ continue;
80
+ const candidate = join(base, entry.name);
81
+ if (isDesktop(candidate))
82
+ return candidate;
83
+ }
84
+ }
85
+ catch {
86
+ // A root that does not exist is a state, not an error.
87
+ }
59
88
  }
60
89
  return undefined;
61
90
  }
@@ -95,7 +124,7 @@ function repairCommand(installRoot) {
95
124
  // No absolute path means the package is laid out in a way this module cannot navigate; the bare
96
125
  // relative form is still better than nothing, but it is the fallback, not the default.
97
126
  const runner = script === undefined ? 'desktop-bridge/install.mjs' : `"${script}"`;
98
- return `node ${runner} "${installRoot}" --restart`;
127
+ return `node ${runner} "${installRoot}"`;
99
128
  }
100
129
  /**
101
130
  * Read the bridge's state from an install directory.
@@ -117,30 +146,16 @@ export function readBridgeStatus(installRoot) {
117
146
  // aimed at an application that merely looked like Electron.
118
147
  const identity = readDesktopIdentity(installRoot);
119
148
  if (!identity.ok) {
120
- // The identity rule reads the unpacked main entry. When the archive is what exists, the tree it
121
- // wants is gone — the signature of a desktop update that restored app.asar and took the bridge
122
- // with it. Reporting `absent` there was wrong twice over: the desktop is installed, and the
123
- // user needs the repair command.
124
- if (safeExists(archivePath)) {
125
- return {
126
- state: 'stale',
127
- present: true,
128
- installRoot,
129
- archivePresent: true,
130
- command: repairCommand(installRoot),
131
- detail: 'the desktop is packed (resources/app.asar) and the unpacked tree the bridge lives in '
132
- + 'is gone — most likely a desktop update restored the archive: re-run the installer to repair',
133
- };
134
- }
135
149
  return {
136
150
  state: 'missing',
137
151
  present: false,
138
152
  installRoot,
139
- archivePresent: false,
153
+ archivePresent: safeExists(archivePath),
140
154
  detail: `not a DSH Desktop install: ${identity.reason}`,
141
155
  };
142
156
  }
143
157
  const archivePresent = safeExists(archivePath);
158
+ const version = identity.version ?? 'unknown';
144
159
  const mainPresent = safeExists(mainPath);
145
160
  if (!mainPresent && !archivePresent) {
146
161
  // Unreachable once identity has passed (identity requires the loaded main entry), kept as the
@@ -150,6 +165,7 @@ export function readBridgeStatus(installRoot) {
150
165
  present: false,
151
166
  installRoot,
152
167
  archivePresent,
168
+ version,
153
169
  detail: 'not a DSH Desktop install: no resources/app/lib/main.js and no resources/app.asar',
154
170
  };
155
171
  }
@@ -169,6 +185,7 @@ export function readBridgeStatus(installRoot) {
169
185
  present: true,
170
186
  installRoot,
171
187
  archivePresent,
188
+ version,
172
189
  ...backupAt === undefined ? {} : { backupAt },
173
190
  command: repairCommand(installRoot),
174
191
  detail: 'packed layout with no bridge in the loaded tree: the bridge is not installed',
@@ -180,6 +197,7 @@ export function readBridgeStatus(installRoot) {
180
197
  present: true,
181
198
  installRoot,
182
199
  archivePresent,
200
+ version,
183
201
  ...backupAt === undefined ? {} : { backupAt },
184
202
  command: repairCommand(installRoot),
185
203
  detail: 'the archive is back alongside the patched tree, so the shell loads the archive: '
@@ -192,25 +210,38 @@ export function readBridgeStatus(installRoot) {
192
210
  present: true,
193
211
  installRoot,
194
212
  archivePresent,
213
+ version,
195
214
  ...backupAt === undefined ? {} : { backupAt },
196
215
  command: repairCommand(installRoot),
197
216
  detail: 'unpacked layout without the bridge patch: the bridge is not installed',
198
217
  };
199
218
  }
219
+ const bridgePath = join(appDir, 'lib', 'plugin-browser-bridge.js');
220
+ let bridgeDetail;
221
+ try {
222
+ const deployed = readFileSync(bridgePath);
223
+ const shipped = readFileSync(new URL('../../desktop-bridge/plugin-browser-bridge.js', import.meta.url));
224
+ if (!deployed.equals(shipped))
225
+ bridgeDetail = 'the deployed bridge module differs from this plugin version; reinstall the bridge to refresh it';
226
+ }
227
+ catch {
228
+ bridgeDetail = 'the bridge module is missing or cannot be verified; reinstall the bridge to restore it';
229
+ }
200
230
  return {
201
- state: 'installed',
231
+ state: bridgeDetail === undefined ? 'installed' : 'stale',
202
232
  present: true,
203
233
  installRoot,
204
234
  archivePresent,
235
+ version,
205
236
  ...backupAt === undefined ? {} : { backupAt },
206
237
  command: repairCommand(installRoot),
207
- detail: 'the shell loads the patched tree and the bridge is in it',
238
+ detail: bridgeDetail ?? 'the shell loads the patched tree and its bridge module matches this plugin version',
208
239
  };
209
240
  }
210
241
  /** Whether a path exists, treating any error as absence. */
211
242
  function safeExists(path) {
212
243
  try {
213
- return existsSync(path);
244
+ return rawExistsSync(path);
214
245
  }
215
246
  catch {
216
247
  return false;
@@ -22,11 +22,12 @@
22
22
  * then keeps the self-hosted Electron it has always used.
23
23
  * @module dsh-browser/browser-electron/desktop-bridge-host
24
24
  */
25
+ import { bridgeEndpointPath } from './paths.js';
25
26
  import type { ElectronBrowserViewHost, ElectronViewHandle } from './provider.js';
26
27
  import type { BrowserUserAction } from './provider.js';
27
28
  import type { CarrierPage, CarrierLossReason } from '../browser/types.js';
28
29
  /** Absolute path of the endpoint file the shell writes. */
29
- export declare function bridgeEndpointPath(): string;
30
+ export { bridgeEndpointPath };
30
31
  /**
31
32
  * A failure worth showing as-is: the carrier is alive and this is a condition the shell can change.
32
33
  *
@@ -51,7 +52,8 @@ export declare class BrowserPanelNotDisplayedError extends Error {
51
52
  * point is a single page both parties can see.
52
53
  */
53
54
  export declare class DesktopBridgeViewHost implements ElectronBrowserViewHost {
54
- private readonly isQuiet;
55
+ private readonly _isQuiet;
56
+ private readonly protocol;
55
57
  private readonly connection;
56
58
  /**
57
59
  * One entry per view this host handed out: the conversation it serves, and the guest backing it.
@@ -220,6 +222,7 @@ export declare class DesktopBridgeViewHost implements ElectronBrowserViewHost {
220
222
  */
221
223
  showView(handle: ElectronViewHandle, _label?: string, options?: {
222
224
  readonly quiet?: boolean;
225
+ readonly select?: boolean;
223
226
  }): void;
224
227
  onUserAction(handler: (action: BrowserUserAction) => void): void;
225
228
  /**
@@ -24,14 +24,10 @@
24
24
  */
25
25
  import { BridgeConnection } from './bridge-connection.js';
26
26
  import { readFileSync } from 'node:fs';
27
- import { homedir } from 'node:os';
28
- import { join } from 'node:path';
27
+ import { bridgeEndpointPath } from './paths.js';
29
28
  import { randomUUID } from 'node:crypto';
30
29
  /** Absolute path of the endpoint file the shell writes. */
31
- export function bridgeEndpointPath() {
32
- const home = process.env.DSH_HOME ?? join(homedir(), '.dsh');
33
- return join(home, 'dsh-builtin-browser-bridge.json');
34
- }
30
+ export { bridgeEndpointPath };
35
31
  /**
36
32
  * The error code the bridge uses when the conversation's panel exists but the shell is not showing
37
33
  * that conversation, so no webview has attached yet (issue #37).
@@ -101,7 +97,8 @@ function isGuestGone(error) {
101
97
  * point is a single page both parties can see.
102
98
  */
103
99
  export class DesktopBridgeViewHost {
104
- isQuiet;
100
+ _isQuiet;
101
+ protocol;
105
102
  connection;
106
103
  /**
107
104
  * One entry per view this host handed out: the conversation it serves, and the guest backing it.
@@ -166,8 +163,9 @@ export class DesktopBridgeViewHost {
166
163
  /**
167
164
  * @param endpoint - the shell's published bridge endpoint.
168
165
  */
169
- constructor(endpoint, sessionId, isQuiet = () => false) {
170
- this.isQuiet = isQuiet;
166
+ constructor(endpoint, sessionId, _isQuiet = () => false, protocol = 2) {
167
+ this._isQuiet = _isQuiet;
168
+ this.protocol = protocol;
171
169
  this.owner = sessionId !== undefined && sessionId !== String.fromCharCode(39, 39) ? sessionId : randomUUID();
172
170
  // The transport reaches this only by concluding the shell stopped refreshing its endpoint, which
173
171
  // is `shell-exited`.
@@ -237,7 +235,7 @@ export class DesktopBridgeViewHost {
237
235
  DesktopBridgeViewHost.refuseIframe = true;
238
236
  return undefined;
239
237
  }
240
- return new DesktopBridgeViewHost(endpoint, sessionId, isQuiet);
238
+ return new DesktopBridgeViewHost(endpoint, sessionId, isQuiet, Number(answer.protocol ?? 2));
241
239
  }
242
240
  finally {
243
241
  probe.close();
@@ -341,10 +339,18 @@ export class DesktopBridgeViewHost {
341
339
  */
342
340
  async guestFor(viewId, url, options) {
343
341
  const entry = this.views.get(viewId);
342
+ if (entry === undefined)
343
+ throw new Error('dsh-builtin-browser: sidebar view was released');
344
+ const stillOwned = () => {
345
+ if (this.views.get(viewId) !== entry)
346
+ throw new Error('dsh-builtin-browser: sidebar view was released');
347
+ };
344
348
  // No liveness check here: verifying the cached guest cost a round-trip on every
345
349
  // command. A guest that has gone away is detected by the command itself failing,
346
350
  // and `createView`'s sendCommand then discards the cache and calls back in here.
347
- if (entry?.guest !== undefined)
351
+ // Explicit navigation also reopens a folded panel. Cached guests are sufficient for reads
352
+ // and input, but not for the user's request to open an address in this conversation's sidebar.
353
+ if (entry?.guest !== undefined && url === undefined)
348
354
  return entry.guest;
349
355
  if (options?.initialize === false) {
350
356
  throw new BrowserPanelNotDisplayedError('this view has no attached guest yet', PANEL_INITIALIZING);
@@ -361,12 +367,19 @@ export class DesktopBridgeViewHost {
361
367
  // conversation's own panel by id through the renderer, rather than by pressing the shell's
362
368
  // shortcut or clicking its card, both of which the shell delivers to whatever it displays.
363
369
  const owner = entry?.owner ?? this.owner;
370
+ if (url !== undefined && this.protocol < 3
371
+ && [...this.views.entries()].some(([id, view]) => id !== viewId && view.owner === owner && view.guest !== undefined)) {
372
+ throw new Error('dsh-builtin-browser: this desktop bridge needs an update for separate sidebar tabs; use Repair and restart in Browser settings');
373
+ }
364
374
  // A command that must not present anything (issue #46: the live preview) takes a read-only path.
365
375
  // 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
366
376
  // and wrong for "let me look at it". A page that is not on screen therefore reports as a display
367
377
  // state, and the preview route turns that into the panel's paused state.
368
- const quiet = this.isQuiet();
369
- if (options?.present === false || quiet) {
378
+ if (options?.present === false) {
379
+ // A logical view without a binding cannot borrow a neighbouring tab for a preview.
380
+ if (this.protocol >= 3) {
381
+ throw new BrowserPanelNotDisplayedError('this view has no attached guest yet', PANEL_INITIALIZING);
382
+ }
370
383
  // `list` and NOT `ensureSidebar`. This is deliberate and it is the whole fix: every version of
371
384
  // `ensureSidebar` can drive the shell — the current one asks the renderer to display the
372
385
  // conversation, and the pre-#37 one literally pressed the sidebar shortcut and typed into the
@@ -378,23 +391,22 @@ export class DesktopBridgeViewHost {
378
391
  ? listed.sidebar.filter(page => page !== null && typeof page === 'object' && page.type === 'webview')
379
392
  : [];
380
393
  const wanted = url !== undefined && url !== '' ? url : undefined;
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];
394
+ const samePage = (url, wanted) => url === wanted || url.startsWith(`${wanted}?`) || url.startsWith(`${wanted}#`);
395
+ const match = pages.find(page => wanted !== undefined && typeof page.url === 'string' && samePage(page.url, wanted)) ?? pages[0];
385
396
  const id = match !== undefined ? Number(match.id) : Number.NaN;
386
397
  if (!Number.isFinite(id) || id <= 0) {
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})`);
398
+ throw new BrowserPanelNotDisplayedError('the preview asked for this conversation\'s page without presenting it, and no page is attached '
399
+ + `(the shell holds ${pages.length})`);
391
400
  }
392
- this.views.set(viewId, { guest: id, owner });
401
+ stillOwned();
402
+ entry.guest = id;
393
403
  return id;
394
404
  }
395
405
  const ask = () => this.connection.call({
396
406
  op: 'ensureSidebar',
397
407
  owner,
408
+ viewId,
409
+ ...entry?.guest === undefined ? {} : { guestId: entry.guest },
398
410
  ...url !== undefined && url !== '' ? { url } : {},
399
411
  }, 30_000);
400
412
  let answer = await ask();
@@ -418,8 +430,10 @@ export class DesktopBridgeViewHost {
418
430
  || String(value.error ?? '').includes('can only attach'));
419
431
  for (let attempt = 0; attempt < PANEL_DISPLAY_RETRIES && displayRefusal(answer); attempt += 1) {
420
432
  await new Promise(resolve => setTimeout(resolve, PANEL_DISPLAY_RETRY_MS));
433
+ stillOwned();
421
434
  answer = await ask();
422
435
  }
436
+ stillOwned();
423
437
  if (answer.ok !== true) {
424
438
  // Reachable only after the retries above have run out, and the code still decides — not the
425
439
  // wording:
@@ -428,7 +442,7 @@ export class DesktopBridgeViewHost {
428
442
  // A missing guest within a time budget is still initialization, including on old bridges
429
443
  // that only returned text. It is not evidence that this shell uses an undrivable iframe.
430
444
  const code = String(answer.code ?? '');
431
- const detail = String(answer.error);
445
+ const detail = String(answer.error ?? answer.code ?? 'unknown sidebar failure');
432
446
  if (code === PANEL_NOT_DISPLAYED)
433
447
  throw new BrowserPanelNotDisplayedError(detail);
434
448
  if (code === PANEL_INITIALIZING || (code === '' && detail.includes('produced no page'))) {
@@ -442,7 +456,7 @@ export class DesktopBridgeViewHost {
442
456
  if (!Number.isFinite(id) || id <= 0) {
443
457
  throw new Error('dsh-builtin-browser: the sidebar reported no browser page for this conversation');
444
458
  }
445
- this.views.set(viewId, { guest: id, owner });
459
+ entry.guest = id;
446
460
  return id;
447
461
  }
448
462
  /**
@@ -454,7 +468,8 @@ export class DesktopBridgeViewHost {
454
468
  this.views.set(viewId, { owner: owner !== undefined && owner !== '' ? owner : this.owner });
455
469
  const navigateUrl = (method, params) => method === 'Page.navigate' ? String(params?.url ?? '') : undefined;
456
470
  const run = async (guest, method, params) => {
457
- const answer = await this.connection.call({ op: 'cdp', id: guest, method, params });
471
+ const owner = this.views.get(viewId)?.owner ?? this.owner;
472
+ const answer = await this.connection.call({ op: 'cdp', id: guest, method, params, owner });
458
473
  if (answer.ok !== true)
459
474
  throw new Error(`dsh-builtin-browser: sidebar command failed: ${String(answer.error)}`);
460
475
  // The bridge forwards whatever CDP answered; the seam expects an object.
@@ -462,6 +477,15 @@ export class DesktopBridgeViewHost {
462
477
  };
463
478
  return {
464
479
  id: viewId,
480
+ download: async (url, savePath) => {
481
+ if (this.protocol < 3)
482
+ throw new Error('dsh-builtin-browser: repair and restart the desktop bridge for sidebar downloads');
483
+ const guest = await this.guestFor(viewId);
484
+ const owner = this.views.get(viewId)?.owner ?? this.owner;
485
+ const answer = await this.connection.call({ op: 'download', id: guest, owner, url, savePath }, 60_000);
486
+ if (answer.ok !== true)
487
+ throw new Error(`dsh-builtin-browser: sidebar download failed: ${String(answer.error)}`);
488
+ },
465
489
  sendCommand: async (method, params, options) => {
466
490
  // No liveness probe up front. Checking first cost a whole round-trip on
467
491
  // every command; instead the command runs and its failure is what triggers
@@ -514,12 +538,9 @@ export class DesktopBridgeViewHost {
514
538
  * @param handle - the view to bring forward.
515
539
  */
516
540
  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)
541
+ // Selecting a sidebar tab only changes the task's pane. The bridge never activates the
542
+ // desktop window, so explicit tab selection works in quiet mode as well.
543
+ if (options?.quiet === true && options.select !== true)
523
544
  return;
524
545
  // `owner` is required: the bridge refuses to bring forward a guest held by another session.
525
546
  // It comes from the view, not the process — with several conversations live, a process-wide
@@ -530,7 +551,7 @@ export class DesktopBridgeViewHost {
530
551
  // present it. Once materialized, only the shell's numeric guest id can name its tab.
531
552
  if (guest === undefined)
532
553
  return;
533
- void this.connection.call({ op: 'showTab', viewId: guest, owner }, 5_000).catch(() => undefined);
554
+ void this.connection.call({ op: 'showTab', viewId: guest, logicalViewId: handle.id, owner }, 5_000).catch(() => undefined);
534
555
  }
535
556
  onUserAction(handler) {
536
557
  this.userActionHandler = handler;
@@ -608,7 +629,7 @@ export class DesktopBridgeViewHost {
608
629
  */
609
630
  async collapse() {
610
631
  try {
611
- await this.connection.call({ op: 'collapseSidebar' }, 10_000);
632
+ await this.connection.call({ op: 'collapseSidebar', owner: this.owner }, 10_000);
612
633
  }
613
634
  catch {
614
635
  // Presentation only; failing to fold is never worth an error.
@@ -23,7 +23,18 @@
23
23
  * @module dsh-browser/browser-electron/desktop-identity
24
24
  */
25
25
  import { closeSync, existsSync, openSync, readFileSync, readSync } from 'node:fs';
26
+ import { createRequire } from 'node:module';
26
27
  import { join } from 'node:path';
28
+ // Electron's patched fs opens an ASAR as a virtual directory. Identity needs the raw archive
29
+ // header and file offsets, including when this reader runs in the Desktop's Node-mode worker.
30
+ const archiveFs = (() => {
31
+ try {
32
+ return createRequire(import.meta.url)('original-fs');
33
+ }
34
+ catch {
35
+ return { openSync, readSync, closeSync, existsSync };
36
+ }
37
+ })();
27
38
  /**
28
39
  * The rule shipped in `desktop-bridge/desktop-identity.json`, used when the file cannot be read.
29
40
  *
@@ -76,15 +87,15 @@ export function readIdentityRule() {
76
87
  function readAsarHeader(archive) {
77
88
  let fd;
78
89
  try {
79
- fd = openSync(archive, 'r');
90
+ fd = archiveFs.openSync(archive, 'r');
80
91
  const outer = Buffer.alloc(8);
81
- if (readSync(fd, outer, 0, 8, 0) !== 8)
92
+ if (archiveFs.readSync(fd, outer, 0, 8, 0) !== 8)
82
93
  return { error: 'the archive header is truncated' };
83
94
  const headerSize = outer.readUInt32LE(4);
84
95
  if (headerSize < 8 || headerSize > 64 * 1024 * 1024)
85
96
  return { error: `implausible archive header size (${headerSize})` };
86
97
  const header = Buffer.alloc(headerSize);
87
- if (readSync(fd, header, 0, headerSize, 8) !== headerSize)
98
+ if (archiveFs.readSync(fd, header, 0, headerSize, 8) !== headerSize)
88
99
  return { error: 'the archive header is truncated' };
89
100
  const jsonLength = header.readUInt32LE(4);
90
101
  if (jsonLength <= 0 || jsonLength > headerSize - 8)
@@ -97,7 +108,7 @@ function readAsarHeader(archive) {
97
108
  finally {
98
109
  if (fd !== undefined) {
99
110
  try {
100
- closeSync(fd);
111
+ archiveFs.closeSync(fd);
101
112
  }
102
113
  catch { /* already closed */ }
103
114
  }
@@ -139,9 +150,9 @@ export function readAsarFile(archive, path) {
139
150
  return undefined;
140
151
  let fd;
141
152
  try {
142
- fd = openSync(archive, 'r');
153
+ fd = archiveFs.openSync(archive, 'r');
143
154
  const buffer = Buffer.alloc(entry.size);
144
- const read = readSync(fd, buffer, 0, entry.size, parsed.contentBase + Number(entry.offset));
155
+ const read = archiveFs.readSync(fd, buffer, 0, entry.size, parsed.contentBase + Number(entry.offset));
145
156
  return read === entry.size ? buffer : undefined;
146
157
  }
147
158
  catch {
@@ -150,7 +161,7 @@ export function readAsarFile(archive, path) {
150
161
  finally {
151
162
  if (fd !== undefined) {
152
163
  try {
153
- closeSync(fd);
164
+ archiveFs.closeSync(fd);
154
165
  }
155
166
  catch { /* already closed */ }
156
167
  }
@@ -173,7 +184,7 @@ export function readDesktopIdentity(installRoot) {
173
184
  const archive = join(resources, 'app.asar');
174
185
  let archivePresent;
175
186
  try {
176
- archivePresent = existsSync(archive);
187
+ archivePresent = archiveFs.existsSync(archive);
177
188
  }
178
189
  catch {
179
190
  return { ok: false, reason: `cannot inspect ${archive}` };
@@ -201,7 +212,8 @@ export function readDesktopIdentity(installRoot) {
201
212
  try {
202
213
  manifestText = readFileSync(manifestPath, 'utf8');
203
214
  }
204
- catch {
215
+ catch (error) {
216
+ console.error(`[dsh-browser] cannot read the package manifest at ${manifestPath}: ${String(error)}`);
205
217
  return { ok: false, reason: `${manifestPath} is missing; a directory without a package manifest is not a DSH Desktop install` };
206
218
  }
207
219
  mainPresent = existsSync(join(appDir, ...rule.mainEntry.split('/')));
@@ -157,12 +157,15 @@ export async function ensureElectronRuntime(deps = defaultDeps()) {
157
157
  if (script === undefined) {
158
158
  return record({ status: 'failed', detail: 'the installed electron package has no install.js; reinstall the plugin in this profile' });
159
159
  }
160
+ // Resolve the installed Electron version once: each call re-runs createRequire,
161
+ // require.resolve and a synchronous package.json read + parse.
162
+ const version = electronVersion();
160
163
  latest = {
161
164
  state: 'preparing',
162
- detail: `downloading Electron ${electronVersion()} (one time, about a minute)`,
165
+ detail: `downloading Electron ${version} (one time, about a minute)`,
163
166
  at: new Date().toISOString(),
164
167
  };
165
- deps.log(`preparing Electron ${electronVersion()} in the background (a missing runtime needs a download)`);
168
+ deps.log(`preparing Electron ${version} in the background (a missing runtime needs a download)`);
166
169
  // The bound has to be a REFERENCED timer, and it has to be cleared when the race finishes.
167
170
  //
168
171
  // A first version unref'd it — "do not keep the process alive for a download" — which is exactly