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,20 +8,26 @@
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
 
23
22
  import { readDesktopIdentity } from './desktop-identity.js'
24
23
 
24
+ // A normal Electron existsSync(app.asar) caches the archive and keeps it locked on Windows.
25
+ // Status inspection must leave maintenance free to rename it after Desktop exits.
26
+ const rawExistsSync: typeof existsSync = (() => {
27
+ try { return (createRequire(import.meta.url)('original-fs') as typeof import('node:fs')).existsSync }
28
+ catch { return existsSync }
29
+ })()
30
+
25
31
  /**
26
32
  * Find the desktop install to report on.
27
33
  *
@@ -33,27 +39,44 @@ import { readDesktopIdentity } from './desktop-identity.js'
33
39
  * @param localAppData - the base directory; defaults to the environment's.
34
40
  * @returns the install directory, or undefined when nothing matches.
35
41
  */
36
- export function findDesktopInstall(localAppData = process.env.LOCALAPPDATA ?? ''): string | undefined {
37
- if (localAppData === '') return undefined
38
- const programs = join(localAppData, 'Programs')
39
- // An archive-only layout is still a DSH Desktop install: a desktop update repacks `resources/app`
40
- // into `resources/app.asar`, and the identity rule (which reads the unpacked main entry) then has
41
- // nothing to read. Treating that as "no desktop here" hid the repair command exactly when it was
42
- // needed most — measured on this machine after an update.
43
- const isDesktop = (candidate: string): boolean =>
44
- readDesktopIdentity(candidate).ok || safeExists(join(candidate, 'resources', 'app.asar'))
45
- for (const named of ['DSH Desktop', 'DeepSeek Harness']) {
46
- const candidate = join(programs, named)
47
- if (isDesktop(candidate)) return candidate
42
+ export function findDesktopInstall(localAppData?: string): string | undefined {
43
+ // Not every install lives in %LOCALAPPDATA%\\Programs: people put the app on another drive, under
44
+ // Program Files, or in their own folder. DSH_DESKTOP_PATH names one explicitly, and the usual roots
45
+ // are all probed. A test or a caller that passes a base directory gets exactly that base, so the
46
+ // behaviour stays pinnable.
47
+ const isDesktop = (candidate: string): boolean => readDesktopIdentity(candidate).ok
48
+ const explicit = process.env.DSH_DESKTOP_PATH
49
+ if (explicit !== undefined && explicit !== '') {
50
+ const named = explicit
51
+ if (isDesktop(named)) return named
52
+ // A parent directory is a reasonable thing to point at too: look one level down.
53
+ try {
54
+ for (const entry of readdirSync(named, { withFileTypes: true })) {
55
+ if (entry.isDirectory() && isDesktop(join(named, entry.name))) return join(named, entry.name)
56
+ }
57
+ } catch {
58
+ // Not a directory: fall through to the usual roots.
59
+ }
48
60
  }
49
- try {
50
- for (const entry of readdirSync(programs, { withFileTypes: true })) {
51
- if (!entry.isDirectory()) continue
52
- const candidate = join(programs, entry.name)
61
+ const roots = localAppData === undefined
62
+ ? [process.env.LOCALAPPDATA ?? '', process.env['ProgramFiles'] ?? '', process.env['ProgramFiles(x86)'] ?? '', process.env.APPDATA ?? '', process.env.ProgramData ?? '']
63
+ .filter(base => base !== '')
64
+ .map(base => (base === process.env.LOCALAPPDATA ? join(base, 'Programs') : base))
65
+ : [join(localAppData, 'Programs')]
66
+ for (const base of roots) {
67
+ for (const named of ['DSH Desktop', 'DeepSeek Harness']) {
68
+ const candidate = join(base, named)
53
69
  if (isDesktop(candidate)) return candidate
54
70
  }
55
- } catch {
56
- // No Programs directory: nothing to report on, which is a state rather than an error.
71
+ try {
72
+ for (const entry of readdirSync(base, { withFileTypes: true })) {
73
+ if (!entry.isDirectory()) continue
74
+ const candidate = join(base, entry.name)
75
+ if (isDesktop(candidate)) return candidate
76
+ }
77
+ } catch {
78
+ // A root that does not exist is a state, not an error.
79
+ }
57
80
  }
58
81
  return undefined
59
82
  }
@@ -65,8 +88,15 @@ const MARKER = '// dsh-builtin-browser: hand the plugin a way to drive the sideb
65
88
  export interface BridgeStatus {
66
89
  /** `installed`, `missing` or `stale`; see the module comment for what each means. */
67
90
  readonly state: 'installed' | 'missing' | 'stale'
68
- /** Whether the install directory looks like a DSH Desktop install at all. */
91
+ /** Whether the loaded application passed DSH Desktop identity verification. */
69
92
  readonly present: boolean
93
+ /**
94
+ * The desktop build this reading belongs to, when the identity check could name one.
95
+ *
96
+ * The automatic install runs once per build: a desktop update is exactly when the bridge has to be
97
+ * installed again, so the guard needs to tell the two apart.
98
+ */
99
+ readonly version?: string
70
100
  /** The directory that was inspected, when one was found. */
71
101
  readonly installRoot?: string
72
102
  /** Whether `resources/app.asar` exists — the archive the shell actually loads. */
@@ -78,8 +108,8 @@ export interface BridgeStatus {
78
108
  /**
79
109
  * The command that installs or repairs the bridge.
80
110
  *
81
- * Shown rather than run. Executing it from a web request would mean a page can decide to close the
82
- * desktop shell, and no amount of same-origin checking makes that a good idea; the user runs it.
111
+ * The panel can show this command for manual use. Its install button calls the same packaged
112
+ * installer through the separately authenticated local bridge-action route.
83
113
  */
84
114
  readonly command?: string
85
115
  }
@@ -117,7 +147,7 @@ function repairCommand(installRoot: string | undefined): string | undefined {
117
147
  // No absolute path means the package is laid out in a way this module cannot navigate; the bare
118
148
  // relative form is still better than nothing, but it is the fallback, not the default.
119
149
  const runner = script === undefined ? 'desktop-bridge/install.mjs' : `"${script}"`
120
- return `node ${runner} "${installRoot}" --restart`
150
+ return `node ${runner} "${installRoot}"`
121
151
  }
122
152
 
123
153
  /**
@@ -141,31 +171,17 @@ export function readBridgeStatus(installRoot: string): BridgeStatus {
141
171
  // aimed at an application that merely looked like Electron.
142
172
  const identity = readDesktopIdentity(installRoot)
143
173
  if (!identity.ok) {
144
- // The identity rule reads the unpacked main entry. When the archive is what exists, the tree it
145
- // wants is gone — the signature of a desktop update that restored app.asar and took the bridge
146
- // with it. Reporting `absent` there was wrong twice over: the desktop is installed, and the
147
- // user needs the repair command.
148
- if (safeExists(archivePath)) {
149
- return {
150
- state: 'stale',
151
- present: true,
152
- installRoot,
153
- archivePresent: true,
154
- command: repairCommand(installRoot),
155
- detail: 'the desktop is packed (resources/app.asar) and the unpacked tree the bridge lives in '
156
- + 'is gone — most likely a desktop update restored the archive: re-run the installer to repair',
157
- }
158
- }
159
174
  return {
160
175
  state: 'missing',
161
176
  present: false,
162
177
  installRoot,
163
- archivePresent: false,
178
+ archivePresent: safeExists(archivePath),
164
179
  detail: `not a DSH Desktop install: ${identity.reason}`,
165
180
  }
166
181
  }
167
182
 
168
183
  const archivePresent = safeExists(archivePath)
184
+ const version = identity.version ?? 'unknown'
169
185
  const mainPresent = safeExists(mainPath)
170
186
  if (!mainPresent && !archivePresent) {
171
187
  // Unreachable once identity has passed (identity requires the loaded main entry), kept as the
@@ -175,6 +191,7 @@ export function readBridgeStatus(installRoot: string): BridgeStatus {
175
191
  present: false,
176
192
  installRoot,
177
193
  archivePresent,
194
+ version,
178
195
  detail: 'not a DSH Desktop install: no resources/app/lib/main.js and no resources/app.asar',
179
196
  }
180
197
  }
@@ -192,9 +209,10 @@ export function readBridgeStatus(installRoot: string): BridgeStatus {
192
209
  present: true,
193
210
  installRoot,
194
211
  archivePresent,
212
+ version,
195
213
  ...backupAt === undefined ? {} : { backupAt },
196
214
  command: repairCommand(installRoot),
197
- detail: 'packed layout with no bridge in the loaded tree: the bridge is not installed',
215
+ detail: 'packed layout with no bridge in the loaded tree: the bridge is not installed',
198
216
  }
199
217
  }
200
218
  if (archivePresent) {
@@ -203,9 +221,10 @@ export function readBridgeStatus(installRoot: string): BridgeStatus {
203
221
  present: true,
204
222
  installRoot,
205
223
  archivePresent,
224
+ version,
206
225
  ...backupAt === undefined ? {} : { backupAt },
207
226
  command: repairCommand(installRoot),
208
- detail: 'the archive is back alongside the patched tree, so the shell loads the archive: '
227
+ detail: 'the archive is back alongside the patched tree, so the shell loads the archive: '
209
228
  + 'a desktop update restored it. Re-run the installer to repair.',
210
229
  }
211
230
  }
@@ -215,25 +234,36 @@ export function readBridgeStatus(installRoot: string): BridgeStatus {
215
234
  present: true,
216
235
  installRoot,
217
236
  archivePresent,
237
+ version,
218
238
  ...backupAt === undefined ? {} : { backupAt },
219
239
  command: repairCommand(installRoot),
220
- detail: 'unpacked layout without the bridge patch: the bridge is not installed',
240
+ detail: 'unpacked layout without the bridge patch: the bridge is not installed',
221
241
  }
222
242
  }
243
+ const bridgePath = join(appDir, 'lib', 'plugin-browser-bridge.js')
244
+ let bridgeDetail: string | undefined
245
+ try {
246
+ const deployed = readFileSync(bridgePath)
247
+ const shipped = readFileSync(new URL('../../desktop-bridge/plugin-browser-bridge.js', import.meta.url))
248
+ if (!deployed.equals(shipped)) bridgeDetail = 'the deployed bridge module differs from this plugin version; reinstall the bridge to refresh it'
249
+ } catch {
250
+ bridgeDetail = 'the bridge module is missing or cannot be verified; reinstall the bridge to restore it'
251
+ }
223
252
  return {
224
- state: 'installed',
253
+ state: bridgeDetail === undefined ? 'installed' : 'stale',
225
254
  present: true,
226
255
  installRoot,
227
256
  archivePresent,
257
+ version,
228
258
  ...backupAt === undefined ? {} : { backupAt },
229
259
  command: repairCommand(installRoot),
230
- detail: 'the shell loads the patched tree and the bridge is in it',
260
+ detail: bridgeDetail ?? 'the shell loads the patched tree and its bridge module matches this plugin version',
231
261
  }
232
262
  }
233
263
 
234
264
  /** Whether a path exists, treating any error as absence. */
235
265
  function safeExists(path: string): boolean {
236
- try { return existsSync(path) } catch { return false }
266
+ try { return rawExistsSync(path) } catch { return false }
237
267
  }
238
268
 
239
269
  /** Whether a file contains a string, treating any error as absence. */
@@ -25,8 +25,7 @@
25
25
 
26
26
  import { BridgeConnection, type BridgeEndpoint } from './bridge-connection.js'
27
27
  import { readFileSync } from 'node:fs'
28
- import { homedir } from 'node:os'
29
- import { join } from 'node:path'
28
+ import { bridgeEndpointPath } from './paths.js'
30
29
  import { randomUUID } from 'node:crypto'
31
30
  import type { CommandOptions, ElectronBrowserViewHost, ElectronViewHandle } from './provider.js'
32
31
  import type { BrowserUserAction } from './provider.js'
@@ -34,10 +33,7 @@ import type { CarrierPage, CarrierLossReason } from '../browser/types.js'
34
33
 
35
34
 
36
35
  /** Absolute path of the endpoint file the shell writes. */
37
- export function bridgeEndpointPath(): string {
38
- const home = process.env.DSH_HOME ?? join(homedir(), '.dsh')
39
- return join(home, 'dsh-builtin-browser-bridge.json')
40
- }
36
+ export { bridgeEndpointPath }
41
37
 
42
38
  /**
43
39
  * The error code the bridge uses when the conversation's panel exists but the shell is not showing
@@ -179,7 +175,8 @@ export class DesktopBridgeViewHost implements ElectronBrowserViewHost {
179
175
  /**
180
176
  * @param endpoint - the shell's published bridge endpoint.
181
177
  */
182
- private constructor(endpoint: BridgeEndpoint, sessionId?: string, private readonly isQuiet: () => boolean = () => false) {
178
+ private constructor(endpoint: BridgeEndpoint, sessionId?: string, private readonly _isQuiet: () => boolean = () => false,
179
+ private readonly protocol = 2) {
183
180
  this.owner = sessionId !== undefined && sessionId !== String.fromCharCode(39,39) ? sessionId : randomUUID()
184
181
  // The transport reaches this only by concluding the shell stopped refreshing its endpoint, which
185
182
  // is `shell-exited`.
@@ -248,7 +245,7 @@ export class DesktopBridgeViewHost implements ElectronBrowserViewHost {
248
245
  DesktopBridgeViewHost.refuseIframe = true
249
246
  return undefined
250
247
  }
251
- return new DesktopBridgeViewHost(endpoint, sessionId, isQuiet)
248
+ return new DesktopBridgeViewHost(endpoint, sessionId, isQuiet, Number(answer.protocol ?? 2))
252
249
  } finally {
253
250
  probe.close()
254
251
  }
@@ -354,10 +351,16 @@ export class DesktopBridgeViewHost implements ElectronBrowserViewHost {
354
351
 
355
352
  private async guestFor(viewId: string, url?: string, options?: CommandOptions): Promise<number> {
356
353
  const entry = this.views.get(viewId)
354
+ if (entry === undefined) throw new Error('dsh-builtin-browser: sidebar view was released')
355
+ const stillOwned = (): void => {
356
+ if (this.views.get(viewId) !== entry) throw new Error('dsh-builtin-browser: sidebar view was released')
357
+ }
357
358
  // No liveness check here: verifying the cached guest cost a round-trip on every
358
359
  // command. A guest that has gone away is detected by the command itself failing,
359
360
  // and `createView`'s sendCommand then discards the cache and calls back in here.
360
- if (entry?.guest !== undefined) return entry.guest
361
+ // Explicit navigation also reopens a folded panel. Cached guests are sufficient for reads
362
+ // and input, but not for the user's request to open an address in this conversation's sidebar.
363
+ if (entry?.guest !== undefined && url === undefined) return entry.guest
361
364
  if (options?.initialize === false) {
362
365
  throw new BrowserPanelNotDisplayedError('this view has no attached guest yet', PANEL_INITIALIZING)
363
366
  }
@@ -374,12 +377,19 @@ export class DesktopBridgeViewHost implements ElectronBrowserViewHost {
374
377
  // conversation's own panel by id through the renderer, rather than by pressing the shell's
375
378
  // shortcut or clicking its card, both of which the shell delivers to whatever it displays.
376
379
  const owner = entry?.owner ?? this.owner
380
+ if (url !== undefined && this.protocol < 3
381
+ && [...this.views.entries()].some(([id, view]) => id !== viewId && view.owner === owner && view.guest !== undefined)) {
382
+ throw new Error('dsh-builtin-browser: this desktop bridge needs an update for separate sidebar tabs; use Repair and restart in Browser settings')
383
+ }
377
384
  // A command that must not present anything (issue #46: the live preview) takes a read-only path.
378
385
  // 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
379
386
  // and wrong for "let me look at it". A page that is not on screen therefore reports as a display
380
387
  // state, and the preview route turns that into the panel's paused state.
381
- const quiet = this.isQuiet()
382
- if (options?.present === false || quiet) {
388
+ if (options?.present === false) {
389
+ // A logical view without a binding cannot borrow a neighbouring tab for a preview.
390
+ if (this.protocol >= 3) {
391
+ throw new BrowserPanelNotDisplayedError('this view has no attached guest yet', PANEL_INITIALIZING)
392
+ }
383
393
  // `list` and NOT `ensureSidebar`. This is deliberate and it is the whole fix: every version of
384
394
  // `ensureSidebar` can drive the shell — the current one asks the renderer to display the
385
395
  // conversation, and the pre-#37 one literally pressed the sidebar shortcut and typed into the
@@ -391,25 +401,24 @@ export class DesktopBridgeViewHost implements ElectronBrowserViewHost {
391
401
  ? listed.sidebar.filter(page => page !== null && typeof page === 'object' && page.type === 'webview')
392
402
  : []
393
403
  const wanted = url !== undefined && url !== '' ? url : undefined
394
- const matchedUrl = pages.find(page => wanted !== undefined && page.url === wanted)
395
- const match = quiet && wanted !== undefined
396
- ? matchedUrl
397
- : pages.find(page => wanted !== undefined && typeof page.url === 'string' && page.url.startsWith(wanted)) ?? pages[0]
404
+ const samePage = (url: string, wanted: string): boolean => url === wanted || url.startsWith(`${wanted}?`) || url.startsWith(`${wanted}#`)
405
+ const match = pages.find(page => wanted !== undefined && typeof page.url === 'string' && samePage(page.url, wanted)) ?? pages[0]
398
406
  const id = match !== undefined ? Number(match.id) : Number.NaN
399
407
  if (!Number.isFinite(id) || id <= 0) {
400
408
  throw new BrowserPanelNotDisplayedError(
401
- quiet
402
- ? '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'
403
- : 'the preview asked for this conversation\'s page without presenting it, and no page is attached '
404
- + `(the shell holds ${pages.length})`,
409
+ 'the preview asked for this conversation\'s page without presenting it, and no page is attached '
410
+ + `(the shell holds ${pages.length})`,
405
411
  )
406
412
  }
407
- this.views.set(viewId, { guest: id, owner })
413
+ stillOwned()
414
+ entry.guest = id
408
415
  return id
409
416
  }
410
417
  const ask = (): Promise<Record<string, unknown>> => this.connection.call({
411
418
  op: 'ensureSidebar',
412
419
  owner,
420
+ viewId,
421
+ ...entry?.guest === undefined ? {} : { guestId: entry.guest },
413
422
  ...url !== undefined && url !== '' ? { url } : {},
414
423
  }, 30_000)
415
424
  let answer = await ask()
@@ -434,8 +443,10 @@ export class DesktopBridgeViewHost implements ElectronBrowserViewHost {
434
443
  || String(value.error ?? '').includes('can only attach'))
435
444
  for (let attempt = 0; attempt < PANEL_DISPLAY_RETRIES && displayRefusal(answer); attempt += 1) {
436
445
  await new Promise(resolve => setTimeout(resolve, PANEL_DISPLAY_RETRY_MS))
446
+ stillOwned()
437
447
  answer = await ask()
438
448
  }
449
+ stillOwned()
439
450
  if (answer.ok !== true) {
440
451
  // Reachable only after the retries above have run out, and the code still decides — not the
441
452
  // wording:
@@ -444,7 +455,7 @@ export class DesktopBridgeViewHost implements ElectronBrowserViewHost {
444
455
  // A missing guest within a time budget is still initialization, including on old bridges
445
456
  // that only returned text. It is not evidence that this shell uses an undrivable iframe.
446
457
  const code = String(answer.code ?? '')
447
- const detail = String(answer.error)
458
+ const detail = String(answer.error ?? answer.code ?? 'unknown sidebar failure')
448
459
  if (code === PANEL_NOT_DISPLAYED) throw new BrowserPanelNotDisplayedError(detail)
449
460
  if (code === PANEL_INITIALIZING || (code === '' && detail.includes('produced no page'))) {
450
461
  throw new BrowserPanelNotDisplayedError(detail, PANEL_INITIALIZING)
@@ -456,7 +467,7 @@ export class DesktopBridgeViewHost implements ElectronBrowserViewHost {
456
467
  if (!Number.isFinite(id) || id <= 0) {
457
468
  throw new Error('dsh-builtin-browser: the sidebar reported no browser page for this conversation')
458
469
  }
459
- this.views.set(viewId, { guest: id, owner })
470
+ entry.guest = id
460
471
  return id
461
472
  }
462
473
 
@@ -470,13 +481,21 @@ export class DesktopBridgeViewHost implements ElectronBrowserViewHost {
470
481
  const navigateUrl = (method: string, params?: Record<string, unknown>): string | undefined =>
471
482
  method === 'Page.navigate' ? String((params as { url?: unknown })?.url ?? '') : undefined
472
483
  const run = async (guest: number, method: string, params?: Record<string, unknown>): Promise<Record<string, unknown>> => {
473
- const answer = await this.connection.call({ op: 'cdp', id: guest, method, params })
484
+ const owner = this.views.get(viewId)?.owner ?? this.owner
485
+ const answer = await this.connection.call({ op: 'cdp', id: guest, method, params, owner })
474
486
  if (answer.ok !== true) throw new Error(`dsh-builtin-browser: sidebar command failed: ${String(answer.error)}`)
475
487
  // The bridge forwards whatever CDP answered; the seam expects an object.
476
488
  return (answer.result ?? {}) as Record<string, unknown>
477
489
  }
478
490
  return {
479
491
  id: viewId,
492
+ download: async (url: string, savePath: string) => {
493
+ if (this.protocol < 3) throw new Error('dsh-builtin-browser: repair and restart the desktop bridge for sidebar downloads')
494
+ const guest = await this.guestFor(viewId)
495
+ const owner = this.views.get(viewId)?.owner ?? this.owner
496
+ const answer = await this.connection.call({ op: 'download', id: guest, owner, url, savePath }, 60_000)
497
+ if (answer.ok !== true) throw new Error(`dsh-builtin-browser: sidebar download failed: ${String(answer.error)}`)
498
+ },
480
499
  sendCommand: async (method: string, params?: Record<string, unknown>, options?: CommandOptions) => {
481
500
  // No liveness probe up front. Checking first cost a whole round-trip on
482
501
  // every command; instead the command runs and its failure is what triggers
@@ -526,13 +545,10 @@ export class DesktopBridgeViewHost implements ElectronBrowserViewHost {
526
545
  * it must not fail the navigation that has already happened.
527
546
  * @param handle - the view to bring forward.
528
547
  */
529
- showView(handle: ElectronViewHandle, _label?: string, options?: { readonly quiet?: boolean }): void {
530
- // Quiet mode (`ui.quiet`) means "do not take my screen". On this carrier showing a page means
531
- // asking the shell to switch the displayed conversation — precisely the takeover the switch
532
- // forbids. So honour it by asking for nothing: a page that is already displayed keeps working,
533
- // and one that is not fails with the documented display-state error instead of moving the
534
- // user's view. Measured before this: the setting was on and every call still switched.
535
- if (options?.quiet === true) return
548
+ showView(handle: ElectronViewHandle, _label?: string, options?: { readonly quiet?: boolean; readonly select?: boolean }): void {
549
+ // Selecting a sidebar tab only changes the task's pane. The bridge never activates the
550
+ // desktop window, so explicit tab selection works in quiet mode as well.
551
+ if (options?.quiet === true && options.select !== true) return
536
552
  // `owner` is required: the bridge refuses to bring forward a guest held by another session.
537
553
  // It comes from the view, not the process — with several conversations live, a process-wide
538
554
  // owner would raise the wrong conversation's tab.
@@ -541,7 +557,7 @@ export class DesktopBridgeViewHost implements ElectronBrowserViewHost {
541
557
  // showActive also runs before a view has navigated; do not materialize a blank page just to
542
558
  // present it. Once materialized, only the shell's numeric guest id can name its tab.
543
559
  if (guest === undefined) return
544
- void this.connection.call({ op: 'showTab', viewId: guest, owner }, 5_000).catch(() => undefined)
560
+ void this.connection.call({ op: 'showTab', viewId: guest, logicalViewId: handle.id, owner }, 5_000).catch(() => undefined)
545
561
  }
546
562
 
547
563
 
@@ -619,7 +635,7 @@ export class DesktopBridgeViewHost implements ElectronBrowserViewHost {
619
635
  */
620
636
  async collapse(): Promise<void> {
621
637
  try {
622
- await this.connection.call({ op: 'collapseSidebar' }, 10_000)
638
+ await this.connection.call({ op: 'collapseSidebar', owner: this.owner }, 10_000)
623
639
  } catch {
624
640
  // Presentation only; failing to fold is never worth an error.
625
641
  }
@@ -23,8 +23,16 @@
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'
27
28
 
29
+ // Electron's patched fs opens an ASAR as a virtual directory. Identity needs the raw archive
30
+ // header and file offsets, including when this reader runs in the Desktop's Node-mode worker.
31
+ const archiveFs: Pick<typeof import('node:fs'), 'openSync' | 'readSync' | 'closeSync' | 'existsSync'> = (() => {
32
+ try { return createRequire(import.meta.url)('original-fs') as typeof import('node:fs') }
33
+ catch { return { openSync, readSync, closeSync, existsSync } }
34
+ })()
35
+
28
36
  /** The identity rule, as data. */
29
37
  interface IdentityRule {
30
38
  readonly packageNames: readonly string[]
@@ -116,13 +124,13 @@ interface AsarEntry {
116
124
  function readAsarHeader(archive: string): { header: { files?: Record<string, AsarEntry> }; contentBase: number } | { error: string } {
117
125
  let fd: number | undefined
118
126
  try {
119
- fd = openSync(archive, 'r')
127
+ fd = archiveFs.openSync(archive, 'r')
120
128
  const outer = Buffer.alloc(8)
121
- if (readSync(fd, outer, 0, 8, 0) !== 8) return { error: 'the archive header is truncated' }
129
+ if (archiveFs.readSync(fd, outer, 0, 8, 0) !== 8) return { error: 'the archive header is truncated' }
122
130
  const headerSize = outer.readUInt32LE(4)
123
131
  if (headerSize < 8 || headerSize > 64 * 1024 * 1024) return { error: `implausible archive header size (${headerSize})` }
124
132
  const header = Buffer.alloc(headerSize)
125
- if (readSync(fd, header, 0, headerSize, 8) !== headerSize) return { error: 'the archive header is truncated' }
133
+ if (archiveFs.readSync(fd, header, 0, headerSize, 8) !== headerSize) return { error: 'the archive header is truncated' }
126
134
  const jsonLength = header.readUInt32LE(4)
127
135
  if (jsonLength <= 0 || jsonLength > headerSize - 8) return { error: 'the archive header has an implausible JSON length' }
128
136
  return { header: JSON.parse(header.toString('utf8', 8, 8 + jsonLength)), contentBase: 8 + headerSize }
@@ -130,7 +138,7 @@ function readAsarHeader(archive: string): { header: { files?: Record<string, Asa
130
138
  return { error: `the archive header could not be read: ${String(error)}` }
131
139
  } finally {
132
140
  if (fd !== undefined) {
133
- try { closeSync(fd) } catch { /* already closed */ }
141
+ try { archiveFs.closeSync(fd) } catch { /* already closed */ }
134
142
  }
135
143
  }
136
144
  }
@@ -167,15 +175,15 @@ export function readAsarFile(archive: string, path: string): Buffer | undefined
167
175
  if (typeof entry.offset !== 'string' || typeof entry.size !== 'number' || entry.size < 0) return undefined
168
176
  let fd: number | undefined
169
177
  try {
170
- fd = openSync(archive, 'r')
178
+ fd = archiveFs.openSync(archive, 'r')
171
179
  const buffer = Buffer.alloc(entry.size)
172
- const read = readSync(fd, buffer, 0, entry.size, parsed.contentBase + Number(entry.offset))
180
+ const read = archiveFs.readSync(fd, buffer, 0, entry.size, parsed.contentBase + Number(entry.offset))
173
181
  return read === entry.size ? buffer : undefined
174
182
  } catch {
175
183
  return undefined
176
184
  } finally {
177
185
  if (fd !== undefined) {
178
- try { closeSync(fd) } catch { /* already closed */ }
186
+ try { archiveFs.closeSync(fd) } catch { /* already closed */ }
179
187
  }
180
188
  }
181
189
  }
@@ -197,7 +205,7 @@ export function readDesktopIdentity(installRoot: string): DesktopIdentity | Iden
197
205
 
198
206
  let archivePresent: boolean
199
207
  try {
200
- archivePresent = existsSync(archive)
208
+ archivePresent = archiveFs.existsSync(archive)
201
209
  } catch {
202
210
  return { ok: false, reason: `cannot inspect ${archive}` }
203
211
  }
@@ -223,7 +231,8 @@ export function readDesktopIdentity(installRoot: string): DesktopIdentity | Iden
223
231
  const manifestPath = join(appDir, 'package.json')
224
232
  try {
225
233
  manifestText = readFileSync(manifestPath, 'utf8')
226
- } catch {
234
+ } catch (error) {
235
+ console.error(`[dsh-browser] cannot read the package manifest at ${manifestPath}: ${String(error)}`)
227
236
  return { ok: false, reason: `${manifestPath} is missing; a directory without a package manifest is not a DSH Desktop install` }
228
237
  }
229
238
  mainPresent = existsSync(join(appDir, ...rule.mainEntry.split('/')))
@@ -202,12 +202,15 @@ export async function ensureElectronRuntime(deps: ProvisionDeps = defaultDeps())
202
202
  if (script === undefined) {
203
203
  return record({ status: 'failed', detail: 'the installed electron package has no install.js; reinstall the plugin in this profile' })
204
204
  }
205
+ // Resolve the installed Electron version once: each call re-runs createRequire,
206
+ // require.resolve and a synchronous package.json read + parse.
207
+ const version = electronVersion()
205
208
  latest = {
206
209
  state: 'preparing',
207
- detail: `downloading Electron ${electronVersion()} (one time, about a minute)`,
210
+ detail: `downloading Electron ${version} (one time, about a minute)`,
208
211
  at: new Date().toISOString(),
209
212
  }
210
- deps.log(`preparing Electron ${electronVersion()} in the background (a missing runtime needs a download)`)
213
+ deps.log(`preparing Electron ${version} in the background (a missing runtime needs a download)`)
211
214
  // The bound has to be a REFERENCED timer, and it has to be cleared when the race finishes.
212
215
  //
213
216
  // A first version unref'd it — "do not keep the process alive for a download" — which is exactly