dsh-builtin-browser 0.4.14 → 0.5.1

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 (56) hide show
  1. package/CHANGELOG.md +72 -0
  2. package/README.en.md +17 -9
  3. package/README.md +48 -10
  4. package/client.js +410 -6
  5. package/desktop-bridge/install-and-start.cmd +36 -0
  6. package/desktop-bridge/install.mjs +166 -3
  7. package/desktop-bridge/plugin-browser-bridge.js +133 -11
  8. package/docs/development.md +19 -0
  9. package/docs/limitations.md +7 -3
  10. package/docs/user-guide.md +46 -18
  11. package/lib/browser/runtime.d.ts +21 -2
  12. package/lib/browser/runtime.js +30 -0
  13. package/lib/browser/types.d.ts +54 -0
  14. package/lib/browser-electron/bridge-status.d.ts +41 -0
  15. package/lib/browser-electron/bridge-status.js +164 -0
  16. package/lib/browser-electron/desktop-bridge-host.d.ts +15 -2
  17. package/lib/browser-electron/desktop-bridge-host.js +75 -44
  18. package/lib/browser-electron/entry.js +130 -11
  19. package/lib/browser-electron/file-write.d.ts +2 -0
  20. package/lib/browser-electron/file-write.js +39 -0
  21. package/lib/browser-electron/history-store.d.ts +8 -19
  22. package/lib/browser-electron/history-store.js +37 -58
  23. package/lib/browser-electron/host-main.js +15 -22
  24. package/lib/browser-electron/preview-route.d.ts +89 -0
  25. package/lib/browser-electron/preview-route.js +172 -0
  26. package/lib/browser-electron/provider.d.ts +62 -3
  27. package/lib/browser-electron/provider.js +246 -12
  28. package/lib/browser-electron/remote-host.js +5 -1
  29. package/lib/browser-electron/rpc-input.d.ts +4 -0
  30. package/lib/browser-electron/rpc-input.js +11 -0
  31. package/lib/browser-electron/runtime-diagnostics.d.ts +12 -0
  32. package/lib/browser-electron/runtime-diagnostics.js +29 -0
  33. package/lib/browser-electron/settings-store.d.ts +15 -2
  34. package/lib/browser-electron/settings-store.js +25 -5
  35. package/lib/browser-electron/system-browser.d.ts +18 -0
  36. package/lib/browser-electron/system-browser.js +158 -37
  37. package/lib/tool-browser/index.js +10 -1
  38. package/package.json +8 -3
  39. package/scripts/install-electron.mjs +66 -0
  40. package/scripts/verify-preview-route.mjs +150 -0
  41. package/src/browser/runtime.ts +36 -0
  42. package/src/browser/types.ts +55 -0
  43. package/src/browser-electron/bridge-status.ts +180 -0
  44. package/src/browser-electron/desktop-bridge-host.ts +75 -41
  45. package/src/browser-electron/entry.ts +119 -11
  46. package/src/browser-electron/file-write.ts +31 -0
  47. package/src/browser-electron/history-store.ts +36 -57
  48. package/src/browser-electron/host-main.ts +16 -18
  49. package/src/browser-electron/preview-route.ts +222 -0
  50. package/src/browser-electron/provider.ts +286 -16
  51. package/src/browser-electron/remote-host.ts +5 -1
  52. package/src/browser-electron/rpc-input.ts +13 -0
  53. package/src/browser-electron/runtime-diagnostics.ts +38 -0
  54. package/src/browser-electron/settings-store.ts +37 -5
  55. package/src/browser-electron/system-browser.ts +149 -32
  56. package/src/tool-browser/index.ts +13 -1
@@ -0,0 +1,150 @@
1
+ // End-to-end: a real HTTP server behind the preview route, a real Chrome behind the capture.
2
+ //
3
+ // The unit tests prove the route's decisions. This proves the two halves join: an HTTP request that
4
+ // survives origin and switch checks reaches a passive capture of a page that is actually open, and
5
+ // what comes back is a JPEG a browser can paint.
6
+ import { createServer } from 'node:http'
7
+ import { spawn } from 'node:child_process'
8
+ import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'
9
+ import { tmpdir } from 'node:os'
10
+ import { join } from 'node:path'
11
+
12
+ import { handlePreviewFrame, PREVIEW_ROUTE } from '../lib/browser-electron/preview-route.js'
13
+
14
+ const sleep = ms => new Promise(r => setTimeout(r, ms))
15
+
16
+ async function connect(wsUrl) {
17
+ const socket = new WebSocket(wsUrl)
18
+ const pending = new Map()
19
+ let nextId = 1
20
+ await new Promise((resolve, reject) => {
21
+ socket.addEventListener('open', resolve, { once: true })
22
+ socket.addEventListener('error', reject, { once: true })
23
+ })
24
+ socket.addEventListener('message', event => {
25
+ const raw = typeof event.data === 'string' ? event.data
26
+ : Buffer.isBuffer(event.data) ? event.data.toString('utf8')
27
+ : event.data instanceof ArrayBuffer ? Buffer.from(event.data).toString('utf8') : ''
28
+ let message
29
+ try { message = JSON.parse(raw) } catch { return }
30
+ if (typeof message.id !== 'number') return
31
+ const entry = pending.get(message.id)
32
+ if (entry === undefined) return
33
+ pending.delete(message.id)
34
+ if (message.error !== undefined) entry.reject(new Error(JSON.stringify(message.error)))
35
+ else entry.resolve(message.result)
36
+ })
37
+ return {
38
+ send(method, params = {}, sessionId) {
39
+ const id = nextId++
40
+ return new Promise((resolve, reject) => {
41
+ pending.set(id, { resolve, reject })
42
+ socket.send(JSON.stringify({ id, method, params, ...sessionId === undefined ? {} : { sessionId } }))
43
+ setTimeout(() => { if (pending.delete(id)) reject(new Error(`${method} timed out`)) }, 20000).unref?.()
44
+ })
45
+ },
46
+ close() { try { socket.close() } catch {} },
47
+ }
48
+ }
49
+
50
+ const CHROME = 'C:/Program Files/Google/Chrome/Application/chrome.exe'
51
+ const profile = mkdtempSync(join(tmpdir(), 'dsh-e2e-preview-'))
52
+ const portFile = join(profile, 'DevToolsActivePort')
53
+ const child = spawn(CHROME, [
54
+ '--remote-debugging-port=0', `--user-data-dir=${profile}`,
55
+ '--no-first-run', '--no-default-browser-check', '--no-startup-window',
56
+ ], { stdio: 'ignore' })
57
+
58
+ let cdpPort = null
59
+ for (let i = 0; i < 300 && cdpPort === null; i++) {
60
+ if (existsSync(portFile)) {
61
+ const n = Number(readFileSync(portFile, 'utf8').split('\n')[0]?.trim())
62
+ if (Number.isInteger(n) && n > 0) cdpPort = n
63
+ }
64
+ if (cdpPort === null) await sleep(10)
65
+ }
66
+ if (cdpPort === null) { console.log(' no CDP endpoint'); child.kill(); process.exit(1) }
67
+
68
+ const version = await (await fetch(`http://127.0.0.1:${cdpPort}/json/version`)).json()
69
+ const client = await connect(version.webSocketDebuggerUrl)
70
+ console.log(` ${version.Browser}`)
71
+
72
+ // A page with something visible on it, then attach ONCE (the route captures repeatedly).
73
+ const { targetId } = await client.send('Target.createTarget', {
74
+ url: 'data:text/html,<body style="background:%23246"><h1 style="color:%23fff;font:48px sans-serif">live</h1></body>',
75
+ background: true,
76
+ })
77
+ await sleep(700)
78
+ const { sessionId } = await client.send('Target.attachToTarget', { targetId, flatten: true })
79
+ await client.send('Page.enable', {}, sessionId)
80
+
81
+ /** Stands in for the provider: same CDP call the real carrier makes, without presentation. */
82
+ const browser = {
83
+ exists: id => id === 'browser:e2e',
84
+ async capturePassive() {
85
+ const shot = await client.send('Page.captureScreenshot', {
86
+ format: 'jpeg', quality: 70, fromSurface: true, captureBeyondViewport: false,
87
+ }, sessionId)
88
+ const base64 = shot?.data ?? ''
89
+ if (base64 === '') throw new Error('empty')
90
+ return { dataUrl: `data:image/jpeg;base64,${base64}` }
91
+ },
92
+ }
93
+
94
+ const settingsOn = { get: () => ({ remoteView: { enabled: true } }) }
95
+ const settingsOff = { get: () => ({ remoteView: { enabled: false } }) }
96
+
97
+ let currentSettings = settingsOn
98
+ const server = createServer((req, res) => {
99
+ if (!req.url?.startsWith(PREVIEW_ROUTE)) { res.writeHead(404).end(); return }
100
+ void handlePreviewFrame(req, res, currentSettings, browser)
101
+ })
102
+ await new Promise(resolve => server.listen(0, '127.0.0.1', resolve))
103
+ const port = server.address().port
104
+ const base = `http://127.0.0.1:${port}`
105
+ const headers = { origin: base, referer: `${base}/` }
106
+ console.log(` preview server on ${base}`)
107
+
108
+ const fetchFrame = async (session, extra = {}) =>
109
+ fetch(`${base}${PREVIEW_ROUTE}?session=${encodeURIComponent(session)}`, { headers: { ...headers, ...extra } })
110
+
111
+ // 1. sharing off -> refused, and the body names no session
112
+ currentSettings = settingsOff
113
+ const offRes = await fetchFrame('browser:e2e')
114
+ const offBody = await offRes.text()
115
+ console.log(` sharing off : ${offRes.status} ${offBody}`)
116
+
117
+ // 2. sharing on, valid session -> a real JPEG
118
+ currentSettings = settingsOn
119
+ const t0 = Date.now()
120
+ const okRes = await fetchFrame('browser:e2e')
121
+ const bytes = Buffer.from(await okRes.arrayBuffer())
122
+ const ms = Date.now() - t0
123
+ console.log(` sharing on : ${okRes.status} ${okRes.headers.get('content-type')} ${bytes.length} bytes in ${ms} ms`)
124
+ console.log(` jpeg magic : ${bytes.subarray(0, 2).toString('hex')} ${bytes.subarray(0, 2).toString('hex') === 'ffd8' ? '(JPEG)' : '(NOT JPEG)'}`)
125
+ console.log(` cache-control : ${okRes.headers.get('cache-control')}`)
126
+
127
+ // 3. three more frames, to show repeated capture works and stays JPEG
128
+ let allJpeg = true
129
+ let total = 0
130
+ for (let i = 0; i < 3; i++) {
131
+ const r = await fetchFrame('browser:e2e')
132
+ const b = Buffer.from(await r.arrayBuffer())
133
+ total += b.length
134
+ if (b.subarray(0, 2).toString('hex') !== 'ffd8') allJpeg = false
135
+ await sleep(500)
136
+ }
137
+ console.log(` three more frames: ${allJpeg ? 'all JPEG' : 'NOT all JPEG'}, avg ${Math.round(total / 3)} bytes`)
138
+
139
+ // 4. an unknown session -> 404, even with sharing on
140
+ const badRes = await fetchFrame('view:whatever')
141
+ console.log(` unknown session : ${badRes.status} ${await badRes.text()}`)
142
+
143
+ console.log('')
144
+ console.log(` ok : ${offRes.status === 403 && okRes.status === 200 && allJpeg && badRes.status === 404}`)
145
+
146
+ server.close()
147
+ client.close()
148
+ try { child.kill() } catch {}
149
+ await sleep(600)
150
+ try { rmSync(profile, { recursive: true, force: true }) } catch {}
@@ -28,6 +28,7 @@ import type {
28
28
  BrowserHistoryEntry,
29
29
  BrowserNavigateRequest,
30
30
  BrowserOpenRequest,
31
+ BrowserPreviewFrame,
31
32
  BrowserProvider,
32
33
  BrowserScrapeRequest,
33
34
  BrowserScrapeResult,
@@ -88,6 +89,7 @@ export type {
88
89
  BrowserHistoryEntry,
89
90
  BrowserNavigateRequest,
90
91
  BrowserOpenRequest,
92
+ BrowserPreviewFrame,
91
93
  BrowserProvider,
92
94
  BrowserScreenshotRequest,
93
95
  BrowserScreenshotResult,
@@ -336,6 +338,27 @@ export class BrowserRuntime extends Service {
336
338
  return this.resolveProvider().screenshot(session, request, signal)
337
339
  }
338
340
 
341
+ /**
342
+ * Capture the active page without presenting it, through the selected provider.
343
+ *
344
+ * Optional throughout: a provider that cannot do this keeps working for every other tool, and the
345
+ * caller gets exactly one error code meaning "watching is not available here" — which the viewer
346
+ * renders as paused rather than as a failure of the browser.
347
+ * @param session - the session whose active page to capture.
348
+ * @param signal - cancellation for the wait, never for the capture itself.
349
+ * @returns the encoded frame.
350
+ */
351
+ async capturePassive(session: BrowserSessionId, signal?: AbortSignal): Promise<BrowserPreviewFrame> {
352
+ const provider = this.resolveProvider()
353
+ if (typeof provider.capturePassive !== 'function') {
354
+ throw new BrowserError(
355
+ 'browser: this carrier cannot provide a passive preview (watching is unavailable here)',
356
+ 'BROWSER_PREVIEW_UNAVAILABLE',
357
+ )
358
+ }
359
+ return provider.capturePassive(session, signal)
360
+ }
361
+
339
362
  /** Check for a human-verification challenge on the active tab. */
340
363
  async detectChallenge(session: BrowserSessionId, signal?: AbortSignal): Promise<BrowserChallenge> {
341
364
  return this.resolveProvider().detectChallenge(session, signal)
@@ -367,6 +390,19 @@ export class BrowserRuntime extends Service {
367
390
  return provider.exists === undefined ? true : provider.exists(session)
368
391
  }
369
392
 
393
+ /**
394
+ * The sessions a viewer may watch, through the selected provider.
395
+ *
396
+ * Empty when the provider cannot preview at all: a viewer then has nothing to offer, which is the
397
+ * honest answer rather than an error.
398
+ * @returns the live session ids.
399
+ */
400
+ watchableSessions(): readonly BrowserSessionId[] {
401
+ const provider = this.resolveProvider()
402
+ if (typeof provider.capturePassive !== 'function') return []
403
+ return provider.watchableSessions?.() ?? []
404
+ }
405
+
370
406
  /** Replay one recorded operation by sequence number through the provider. */
371
407
  async replay(session: BrowserSessionId, seq: number): Promise<void> {
372
408
  return this.resolveProvider().replay(session, seq)
@@ -381,6 +381,27 @@ export interface BrowserSnapshotResult {
381
381
  readonly truncated: boolean
382
382
  /** Human-verification challenge blocking the page, when one is detected. */
383
383
  readonly challenge?: BrowserChallenge
384
+ /**
385
+ * True when this is a blank page — no document to read, nothing to drive.
386
+ *
387
+ * Zero elements means two very different things: a page that genuinely has nothing interactive,
388
+ * and a browser that has not opened anything at all. Without this flag they look identical, so a
389
+ * caller can act on a blank page and get a success value back — reported as issue #37, where every
390
+ * tool after a carrier swap answered against `about:blank` while appearing to work.
391
+ *
392
+ * Set for `about:blank` and for a view that has never navigated. A caller seeing it should treat
393
+ * the page as absent, not as empty.
394
+ */
395
+ readonly blank?: boolean
396
+ /** A sentence a caller can show instead of reporting an empty page as a successful read. */
397
+ readonly note?: string
398
+ /**
399
+ * True when the page draws its interface on a canvas, so no DOM element exists to collect.
400
+ *
401
+ * Distinct from `blank`: the page is fully rendered and interactive, just not as elements. A
402
+ * caller must switch to a screenshot and coordinate input rather than conclude the page is empty.
403
+ */
404
+ readonly canvas?: boolean
384
405
  }
385
406
 
386
407
  /**
@@ -503,6 +524,18 @@ export interface BrowserTab {
503
524
  readonly active: boolean
504
525
  }
505
526
 
527
+ /**
528
+ * One passive preview frame: an encoded image plus its dimensions.
529
+ *
530
+ * The image is a data URL so it travels the existing JSON seam unchanged; the media type is part of
531
+ * the URL rather than a separate field because every consumer needs them together.
532
+ */
533
+ export interface BrowserPreviewFrame {
534
+ readonly dataUrl: string
535
+ readonly width?: number
536
+ readonly height?: number
537
+ }
538
+
506
539
  /** One page a carrier holds, whether or not this plugin created it. */
507
540
  export interface CarrierPage {
508
541
  /** Stable within one carrier session; used to address the page. */
@@ -620,6 +653,28 @@ export interface BrowserProvider {
620
653
  fillForm(session: BrowserSessionId, request: BrowserFillRequest, signal?: AbortSignal): Promise<BrowserFillResult>
621
654
  /** Capture the current page. Honor `signal` for cancellation. */
622
655
  screenshot(session: BrowserSessionId, request?: BrowserScreenshotRequest, signal?: AbortSignal): Promise<BrowserScreenshotResult>
656
+ /**
657
+ * Capture the active page WITHOUT presenting it, for a remote live view (issue #34).
658
+ *
659
+ * Optional, and it must stay optional: a third-party provider that cannot do this simply does not
660
+ * offer watching, while every existing tool keeps working. That is the design's requirement, not
661
+ * a convenience — a mandatory member would make every provider implement a feature most never
662
+ * need.
663
+ *
664
+ * The contract is narrower than {@link screenshot} in every direction: viewport only, no save
665
+ * path, no full page, and no side effects on what the host displays. A provider that would have to
666
+ * focus, restore, expand or recreate anything to produce a frame must throw
667
+ * BROWSER_PREVIEW_UNAVAILABLE instead — the viewer shows a paused state, it does not rearrange the
668
+ * host's screen.
669
+ */
670
+ capturePassive?(session: BrowserSessionId, signal?: AbortSignal): Promise<BrowserPreviewFrame>
671
+ /**
672
+ * The sessions a viewer may watch. Only meaningful alongside {@link capturePassive}.
673
+ *
674
+ * Exists because the provider names its sessions and the browser page cannot know one; served as
675
+ * ids only, so the panel can address a session without being told what is in it.
676
+ */
677
+ watchableSessions?(): readonly BrowserSessionId[]
623
678
  /** Download a URL to a local file. Honor `signal` for cancellation. */
624
679
  download(session: BrowserSessionId, request: BrowserDownloadRequest, signal?: AbortSignal): Promise<{ readonly path: string }>
625
680
  /** Export the session's cookies (login state). */
@@ -0,0 +1,180 @@
1
+ /**
2
+ * Whether the desktop bridge is installed, and what state its files are in.
3
+ *
4
+ * Reported as issue #36: when the bridge is missing the plugin only logs a warning, so a user who
5
+ * chose `channel: sidebar` sees "another window opened again" and has no way to connect that with
6
+ * "the bridge is not installed". This module answers the question the panel needs to show, from the
7
+ * install tree on disk rather than from anything the plugin remembers.
8
+ *
9
+ * The states are the three that actually occur:
10
+ *
11
+ * - `installed` — the shell's main.js carries our marker and the archive is still moved aside.
12
+ * - `missing` — no marker. Either never installed, or the shell was upgraded (which restores
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.
17
+ * @module dsh-browser/browser-electron/bridge-status
18
+ */
19
+ import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs'
20
+ import { join } from 'node:path'
21
+
22
+ /**
23
+ * Find the desktop install to report on.
24
+ *
25
+ * The same shape probe the installer uses, repeated here because the two run in different processes
26
+ * and neither can import the other: the product directory is `DeepSeek Harness` on some builds and
27
+ * `DSH Desktop` on others, and the shape that identifies an install is stable across both.
28
+ * @param localAppData - the base directory; defaults to the environment's.
29
+ * @returns the install directory, or undefined when nothing matches.
30
+ */
31
+ export function findDesktopInstall(localAppData = process.env.LOCALAPPDATA ?? ''): string | undefined {
32
+ if (localAppData === '') return undefined
33
+ const programs = join(localAppData, 'Programs')
34
+ const looksInstalled = (candidate: string): boolean => existsSync(join(candidate, 'resources', 'app', 'lib', 'main.js'))
35
+ || existsSync(join(candidate, 'resources', 'app.asar'))
36
+ for (const named of ['DSH Desktop', 'DeepSeek Harness']) {
37
+ const candidate = join(programs, named)
38
+ if (looksInstalled(candidate)) return candidate
39
+ }
40
+ try {
41
+ for (const entry of readdirSync(programs, { withFileTypes: true })) {
42
+ if (!entry.isDirectory()) continue
43
+ const candidate = join(programs, entry.name)
44
+ if (looksInstalled(candidate)) return candidate
45
+ }
46
+ } catch {
47
+ // No Programs directory: nothing to report on, which is a state rather than an error.
48
+ }
49
+ return undefined
50
+ }
51
+
52
+ /** The marker the installer inserts into the shell's main.js. */
53
+ const MARKER = '// dsh-builtin-browser: hand the plugin a way to drive the sidebar'
54
+
55
+ /** One reading of the install tree. */
56
+ export interface BridgeStatus {
57
+ /** `installed`, `missing` or `stale`; see the module comment for what each means. */
58
+ readonly state: 'installed' | 'missing' | 'stale'
59
+ /** Whether the install directory looks like a DSH Desktop install at all. */
60
+ readonly present: boolean
61
+ /** The directory that was inspected, when one was found. */
62
+ readonly installRoot?: string
63
+ /** Whether `resources/app.asar` exists — the archive the shell actually loads. */
64
+ readonly archivePresent: boolean
65
+ /** When the pre-bridge backup was written, if there is one. */
66
+ readonly backupAt?: string
67
+ /** A one-line explanation for the panel, in the plugin's own words. */
68
+ readonly detail: string
69
+ /**
70
+ * The command that installs or repairs the bridge.
71
+ *
72
+ * Shown rather than run. Executing it from a web request would mean a page can decide to close the
73
+ * desktop shell, and no amount of same-origin checking makes that a good idea; the user runs it.
74
+ */
75
+ readonly command?: string
76
+ }
77
+
78
+ /**
79
+ * The command a user should run for this state, quoted so it survives a path with spaces.
80
+ * @param installRoot - the install directory, or undefined when none was found.
81
+ * @returns the command line, or undefined when there is nothing useful to suggest.
82
+ */
83
+ function repairCommand(installRoot: string | undefined): string | undefined {
84
+ if (installRoot === undefined) return undefined
85
+ return `node desktop-bridge/install.mjs "${installRoot}" --restart`
86
+ }
87
+
88
+ /**
89
+ * Read the bridge's state from an install directory.
90
+ *
91
+ * Never throws: a caller showing this in a settings panel must get an answer even when the directory
92
+ * is unreadable or the user pointed at something that is not an install.
93
+ * @param installRoot - the desktop install directory.
94
+ * @returns the current state.
95
+ */
96
+ export function readBridgeStatus(installRoot: string): BridgeStatus {
97
+ const resources = join(installRoot, 'resources')
98
+ const appDir = join(resources, 'app')
99
+ const mainPath = join(appDir, 'lib', 'main.js')
100
+ const archivePath = join(resources, 'app.asar')
101
+ const backupPath = `${mainPath}.before-bridge`
102
+
103
+ const archivePresent = safeExists(archivePath)
104
+ const mainPresent = safeExists(mainPath)
105
+ if (!mainPresent && !archivePresent) {
106
+ return {
107
+ state: 'missing',
108
+ present: false,
109
+ installRoot,
110
+ archivePresent,
111
+ command: repairCommand(installRoot),
112
+ detail: 'not a DSH Desktop install: no resources/app/lib/main.js and no resources/app.asar',
113
+ }
114
+ }
115
+ let backupAt
116
+ try {
117
+ if (existsSync(backupPath)) backupAt = statSync(backupPath).mtime.toISOString()
118
+ } catch {
119
+ // A backup we cannot stat is simply not reported; it does not change the state.
120
+ }
121
+ if (archivePresent && !safeIncludes(mainPath, MARKER)) {
122
+ // The archive is what the shell loads, so an unpacked tree without our marker is not in effect
123
+ // even if it were patched.
124
+ return {
125
+ state: 'missing',
126
+ present: true,
127
+ installRoot,
128
+ archivePresent,
129
+ ...backupAt === undefined ? {} : { backupAt },
130
+ command: repairCommand(installRoot),
131
+ detail: 'packed layout with no bridge in the loaded tree: the bridge is not installed',
132
+ }
133
+ }
134
+ if (archivePresent) {
135
+ return {
136
+ state: 'stale',
137
+ present: true,
138
+ installRoot,
139
+ archivePresent,
140
+ ...backupAt === undefined ? {} : { backupAt },
141
+ command: repairCommand(installRoot),
142
+ detail: 'the archive is back alongside the patched tree, so the shell loads the archive: '
143
+ + 'a desktop update restored it. Re-run the installer to repair.',
144
+ }
145
+ }
146
+ if (!safeIncludes(mainPath, MARKER)) {
147
+ return {
148
+ state: 'missing',
149
+ present: true,
150
+ installRoot,
151
+ archivePresent,
152
+ ...backupAt === undefined ? {} : { backupAt },
153
+ command: repairCommand(installRoot),
154
+ detail: 'unpacked layout without the bridge patch: the bridge is not installed',
155
+ }
156
+ }
157
+ return {
158
+ state: 'installed',
159
+ present: true,
160
+ installRoot,
161
+ archivePresent,
162
+ ...backupAt === undefined ? {} : { backupAt },
163
+ command: repairCommand(installRoot),
164
+ detail: 'the shell loads the patched tree and the bridge is in it',
165
+ }
166
+ }
167
+
168
+ /** Whether a path exists, treating any error as absence. */
169
+ function safeExists(path: string): boolean {
170
+ try { return existsSync(path) } catch { return false }
171
+ }
172
+
173
+ /** Whether a file contains a string, treating any error as absence. */
174
+ function safeIncludes(path: string, needle: string): boolean {
175
+ try {
176
+ return existsSync(path) && statSync(path).isFile() && readFileSync(path, 'utf8').includes(needle)
177
+ } catch {
178
+ return false
179
+ }
180
+ }
@@ -39,12 +39,49 @@ export function bridgeEndpointPath(): string {
39
39
  return join(home, 'dsh-builtin-browser-bridge.json')
40
40
  }
41
41
 
42
+ /**
43
+ * The error code the bridge uses when the conversation's panel exists but the shell is not showing
44
+ * that conversation, so no webview has attached yet (issue #37).
45
+ *
46
+ * A display state, not a dead carrier. It must never reach `reportLost`, and it must never be
47
+ * retried as though a guest had vanished: retrying cannot attach a webview the shell has not
48
+ * rendered, and treating it as loss swapped the surface to a fresh self-hosted window whose page was
49
+ * blank — losing the page the user had open.
50
+ */
51
+ const PANEL_NOT_DISPLAYED = 'panel-not-displayed'
52
+
53
+ /**
54
+ * A failure worth showing as-is: the carrier is alive and this is a condition the user can change.
55
+ *
56
+ * Thrown instead of a plain Error so callers can distinguish "wait for the conversation to be shown"
57
+ * from "the browser broke", which is exactly the distinction issue #37 says was missing.
58
+ */
59
+ export class BrowserPanelNotDisplayedError extends Error {
60
+ readonly code = PANEL_NOT_DISPLAYED
61
+
62
+ /**
63
+ * @param detail - the bridge's own explanation, appended so the message says why.
64
+ */
65
+ constructor(detail: string) {
66
+ super(
67
+ 'dsh-builtin-browser: this conversation\'s sidebar page is not attached because the conversation '
68
+ + 'is not the one displayed. Show it and the page appears; nothing was lost. '
69
+ + `(${detail})`,
70
+ )
71
+ this.name = 'BrowserPanelNotDisplayedError'
72
+ }
73
+ }
74
+
42
75
  /**
43
76
  * Whether a command failed because the page is no longer there (as opposed to
44
77
  * failing on its own merits). Only these are worth retrying on a fresh guest.
45
78
  * @param error - the failure to classify.
46
79
  */
47
80
  function isGuestGone(error: unknown): boolean {
81
+ // "The conversation is not displayed" is NOT a vanished guest. It is listed here as a negative
82
+ // because retrying it wastes the only thing it can produce: the same answer, slower. Issue #37 was
83
+ // this classification being too broad.
84
+ if (error instanceof BrowserPanelNotDisplayedError) return false
48
85
  const message = error instanceof Error ? error.message : String(error)
49
86
  // The panel path reports its own failure when the renderer never produced a page, and that is the
50
87
  // same class as a vanished guest — worth one retry on a fresh panel — so it is listed here too.
@@ -250,26 +287,21 @@ export class DesktopBridgeViewHost implements ElectronBrowserViewHost {
250
287
  * possible exists only here.
251
288
  * @returns the panel's pages that are not ours, or an empty list when the bridge cannot answer.
252
289
  */
253
- async listPages(): Promise<readonly CarrierPage[]> {
254
- try {
255
- const answer = await this.connection.call({ op: 'list', owner: this.owner }, 5_000)
256
- const guests = Array.isArray(answer.sidebar) ? answer.sidebar : []
257
- const ours = new Set<number>()
258
- for (const view of this.views.values()) {
259
- if (typeof view.guest === 'number') ours.add(view.guest)
260
- }
261
- return guests
262
- .filter((guest): guest is { id: number; url?: unknown } => typeof guest?.id === 'number')
263
- .filter(guest => !ours.has(guest.id))
264
- .map(guest => ({
265
- id: String(guest.id),
266
- url: typeof guest.url === 'string' ? guest.url : '',
267
- }))
268
- } catch {
269
- // A bridge that cannot answer has a real problem, and the next command reports it. Failing
270
- // the tab LIST here would make a listing worse than the driving it exists to describe.
271
- return []
290
+ async listPages(owner: string = this.owner): Promise<readonly CarrierPage[]> {
291
+ const answer = await this.connection.call({ op: 'list', owner }, 5_000)
292
+ if (answer.ok !== true) throw new Error(String(answer.error ?? 'sidebar page listing failed'))
293
+ const guests = Array.isArray(answer.sidebar) ? answer.sidebar : []
294
+ const ours = new Set<number>()
295
+ for (const view of this.views.values()) {
296
+ if (typeof view.guest === 'number') ours.add(view.guest)
272
297
  }
298
+ return guests
299
+ .filter((guest): guest is { id: number; url?: unknown } => typeof guest?.id === 'number')
300
+ .filter(guest => !ours.has(guest.id))
301
+ .map(guest => ({
302
+ id: String(guest.id),
303
+ url: typeof guest.url === 'string' ? guest.url : '',
304
+ }))
273
305
  }
274
306
 
275
307
  /**
@@ -281,17 +313,13 @@ export class DesktopBridgeViewHost implements ElectronBrowserViewHost {
281
313
  * than as an error: the caller asked for it to be closed, and it is.
282
314
  * @param id - the sidebar guest id, as a string.
283
315
  */
284
- async closePage(id: string): Promise<void> {
316
+ async closePage(id: string, owner: string = this.owner): Promise<void> {
285
317
  const numeric = Number(id)
286
- if (!Number.isFinite(numeric)) throw new Error(`not a sidebar page id: ${id}`)
287
- const answer = await this.connection.call({ op: 'list', owner: this.owner }, 5_000)
288
- const guests = Array.isArray(answer.sidebar) ? answer.sidebar : []
289
- const title = guests
290
- .filter((guest): guest is { id: number; title?: unknown } => Number(guest?.id) === numeric)
291
- .map(guest => String(guest.title ?? ''))
292
- .find(candidate => candidate !== '')
293
- if (title === undefined) return
294
- await this.connection.call({ op: 'closeSidebarBrowser', titles: [title], owner: this.owner }, 10_000)
318
+ if (!Number.isSafeInteger(numeric) || numeric <= 0) throw new Error(`not a sidebar page id: ${id}`)
319
+ const answer = await this.connection.call({ op: 'closePage', id: numeric, owner }, 10_000)
320
+ if (answer.ok !== true || answer.closed !== 1) {
321
+ throw new Error(`dsh-builtin-browser: could not close sidebar page ${id}: ${String(answer.error ?? 'the shell did not close the requested page; refresh or upgrade the desktop bridge')}`)
322
+ }
295
323
  }
296
324
 
297
325
  /**
@@ -332,18 +360,20 @@ export class DesktopBridgeViewHost implements ElectronBrowserViewHost {
332
360
  ...url !== undefined && url !== '' ? { url } : {},
333
361
  }, 30_000)
334
362
  if (answer.ok !== true) {
335
- // A bridge that answers but cannot produce a page is as unusable as one that has exited, and
336
- // the difference matters here: `onLost` is what returns the surface to the self-hosted
337
- // browser. Without this the same failure repeats on every call until DSH is restarted — on a
338
- // shell whose sidebar panel is an iframe, that is every call forever. Reported as "installing
339
- // the bridge made it worse than not installing it": the carrier was switched to one that
340
- // cannot work, with no path back to the one that does.
363
+ // A bridge that answers but cannot produce a page is as usable as one that has exited ONLY when
364
+ // the panel can never work here. "The conversation is not displayed" is the opposite case: the
365
+ // panel is fine, the shell simply is not rendering it right now, and it will the moment the
366
+ // user shows that conversation (issue #37).
341
367
  //
342
- // `panel-unusable`, not `shell-exited`: the shell is alive and answered this very request. The
343
- // fallback's message used to announce an exiting shell unconditionally, which told the user
344
- // their desktop had crashed when it was running normally.
345
- if (String(answer.error).includes('produced no page')) this.reportLost('panel-unusable')
346
- throw new Error(`dsh-builtin-browser: sidebar unavailable (${String(answer.error)})`)
368
+ // So the code decides, not the wording:
369
+ // panel-not-displayed -> a transient display state; no loss, no retry, nothing swapped.
370
+ // produced no page -> this shell cannot drive a panel at all (an iframe shell, issue #30);
371
+ // fall back, because otherwise every call fails forever.
372
+ const code = String(answer.code ?? '')
373
+ const detail = String(answer.error)
374
+ if (code === PANEL_NOT_DISPLAYED) throw new BrowserPanelNotDisplayedError(detail)
375
+ if (detail.includes('produced no page')) this.reportLost('panel-unusable')
376
+ throw new Error(`dsh-builtin-browser: sidebar unavailable (${detail})`)
347
377
  }
348
378
  const id = Number(answer.id)
349
379
  if (!Number.isFinite(id) || id <= 0) {
@@ -424,7 +454,11 @@ export class DesktopBridgeViewHost implements ElectronBrowserViewHost {
424
454
  // It comes from the view, not the process — with several conversations live, a process-wide
425
455
  // owner would raise the wrong conversation's tab.
426
456
  const owner = this.views.get(handle.id)?.owner ?? this.owner
427
- void this.connection.call({ op: 'showTab', viewId: Number(handle.id), owner }, 5_000).catch(() => undefined)
457
+ const guest = this.views.get(handle.id)?.guest
458
+ // showActive also runs before a view has navigated; do not materialize a blank page just to
459
+ // present it. Once materialized, only the shell's numeric guest id can name its tab.
460
+ if (guest === undefined) return
461
+ void this.connection.call({ op: 'showTab', viewId: guest, owner }, 5_000).catch(() => undefined)
428
462
  }
429
463
 
430
464