dsh-builtin-browser 0.5.4 → 0.5.6

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 (36) hide show
  1. package/CHANGELOG.md +63 -1
  2. package/README.en.md +5 -3
  3. package/README.md +4 -2
  4. package/client.js +300 -4
  5. package/docs/development.md +10 -0
  6. package/docs/user-guide.md +16 -4
  7. package/lib/browser-electron/bridge-connection.d.ts +8 -0
  8. package/lib/browser-electron/bridge-connection.js +8 -0
  9. package/lib/browser-electron/bridge-endpoint.d.ts +30 -0
  10. package/lib/browser-electron/bridge-endpoint.js +123 -0
  11. package/lib/browser-electron/desktop-bridge-host.d.ts +23 -23
  12. package/lib/browser-electron/desktop-bridge-host.js +35 -35
  13. package/lib/browser-electron/electron-provision.d.ts +34 -1
  14. package/lib/browser-electron/electron-provision.js +52 -9
  15. package/lib/browser-electron/entry.js +62 -1
  16. package/lib/browser-electron/json-reply.d.ts +21 -0
  17. package/lib/browser-electron/json-reply.js +17 -0
  18. package/lib/browser-electron/preview-route.js +1 -12
  19. package/lib/browser-electron/remote-host.js +6 -5
  20. package/lib/browser-electron/runtime-route.d.ts +57 -0
  21. package/lib/browser-electron/runtime-route.js +66 -0
  22. package/lib/browser-electron/runtime-status.d.ts +102 -0
  23. package/lib/browser-electron/runtime-status.js +86 -0
  24. package/package.json +2 -2
  25. package/scripts/consumer-install-check.mjs +72 -0
  26. package/scripts/verify-runtime-status.mjs +165 -0
  27. package/src/browser-electron/bridge-connection.ts +9 -0
  28. package/src/browser-electron/bridge-endpoint.ts +139 -0
  29. package/src/browser-electron/desktop-bridge-host.ts +35 -35
  30. package/src/browser-electron/electron-provision.ts +73 -8
  31. package/src/browser-electron/entry.ts +67 -1
  32. package/src/browser-electron/json-reply.ts +32 -0
  33. package/src/browser-electron/preview-route.ts +1 -12
  34. package/src/browser-electron/remote-host.ts +6 -5
  35. package/src/browser-electron/runtime-route.ts +106 -0
  36. package/src/browser-electron/runtime-status.ts +186 -0
@@ -0,0 +1,72 @@
1
+ // Consumer-layout install check for the packaged artifact.
2
+ //
3
+ // The promise this version is about ("it works once you install it") starts at INSTALL time: the
4
+ // tarball must install cleanly on a default pnpm profile, with no build-script approval and no
5
+ // network, and it must carry the files the readiness endpoints live in.
6
+ //
7
+ // Run: node scripts/consumer-install-check.mjs <tarball> <workdir>
8
+ import { execFileSync } from 'node:child_process'
9
+ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
10
+ import { join } from 'node:path'
11
+
12
+ const [tarball, workdir] = process.argv.slice(2)
13
+ if (!tarball || !workdir) {
14
+ console.error('usage: consumer-install-check.mjs <tarball> <workdir>')
15
+ process.exit(2)
16
+ }
17
+
18
+ const pnpm = process.env.DSH_PNPM ?? 'pnpm'
19
+ const node = process.execPath
20
+
21
+ rmSync(workdir, { recursive: true, force: true })
22
+ mkdirSync(workdir, { recursive: true })
23
+ writeFileSync(join(workdir, 'package.json'), JSON.stringify({ name: 'consumer', private: true, version: '1.0.0' }, null, 2))
24
+
25
+ const problems = []
26
+ let installOutput = ''
27
+ try {
28
+ installOutput = execFileSync(node, [pnpm, 'add', tarball], {
29
+ cwd: workdir,
30
+ encoding: 'utf8',
31
+ stdio: ['ignore', 'pipe', 'pipe'],
32
+ env: { ...process.env, npm_config_loglevel: 'info' },
33
+ })
34
+ } catch (error) {
35
+ installOutput = `${error.stdout ?? ''}${error.stderr ?? ''}`
36
+ problems.push(`install failed: ${String(error.message).split('\n')[0]}`)
37
+ }
38
+
39
+ // pnpm blocks dependency build scripts by default, and the whole point of moving the Electron
40
+ // download out of `postinstall` (issue #41) is that this never comes up again.
41
+ if (/Ignored build scripts/i.test(installOutput) || /ERR_PNPM_IGNORED_BUILDS/.test(installOutput)) {
42
+ problems.push('install reported ignored build scripts, which is issue #41 again')
43
+ }
44
+
45
+ const installed = join(workdir, 'node_modules', 'dsh-builtin-browser')
46
+ const manifestPath = join(installed, 'package.json')
47
+ if (!existsSync(manifestPath)) {
48
+ problems.push('the package was not installed')
49
+ } else {
50
+ const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'))
51
+ const scripts = Object.keys(manifest.scripts ?? {}).sort().join(',')
52
+ if (scripts !== 'build,prepack,test') problems.push(`unexpected scripts: ${scripts}`)
53
+ for (const lifecycle of ['preinstall', 'install', 'postinstall', 'prepare']) {
54
+ if (manifest.scripts?.[lifecycle] !== undefined) problems.push(`install-time hook "${lifecycle}" is back`)
55
+ }
56
+ if (manifest.bin?.['dsh-browser-install-electron'] !== 'scripts/install-electron.mjs') {
57
+ problems.push('the explicit provisioning command is missing from bin')
58
+ }
59
+ // The files the readiness endpoints are served from. A tarball that shipped an entry without them
60
+ // would fail at request time with a module-resolution error instead of a panel.
61
+ for (const file of [
62
+ 'lib/browser-electron/runtime-status.js',
63
+ 'lib/browser-electron/runtime-route.js',
64
+ 'desktop-bridge/install.mjs',
65
+ 'client.js',
66
+ ]) {
67
+ if (!existsSync(join(installed, file))) problems.push(`missing from the installed tree: ${file}`)
68
+ }
69
+ }
70
+
71
+ console.log(JSON.stringify({ tarball, workdir, problems }, null, 2))
72
+ process.exit(problems.length === 0 ? 0 : 1)
@@ -0,0 +1,165 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Readiness-route probe: do the two endpoints the settings panel reads actually get registered,
4
+ * and does the report they serve describe this machine?
5
+ *
6
+ * The unit tests cover the handlers and the report in isolation. What they cannot cover is the
7
+ * WIRING between them — `ctx.inject(['webServer'])`, the two `webServer.register` calls, and the
8
+ * deps that read the settings document and the install tree. That glue is exactly where this plugin
9
+ * has lost a surface before (a route that was never registered because a dependency name was wrong
10
+ * looks identical to a route that returned nothing), so it is checked here against the real host
11
+ * packages, over real HTTP, with no browser and no DSH restart.
12
+ *
13
+ * Usage:
14
+ * node scripts/verify-runtime-status.mjs # profile named by DSH_PROFILE, else the first
15
+ * DSH_PROFILE=desktop node scripts/verify-runtime-status.mjs
16
+ *
17
+ * It writes into a throwaway DSH_HOME, never the real one, and pins
18
+ * ELECTRON_SKIP_BINARY_DOWNLOAD so a probe can never start a 100 MB download.
19
+ */
20
+ import { createRequire } from 'node:module'
21
+ import { existsSync, mkdtempSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'
22
+ import { createServer } from 'node:http'
23
+ import { tmpdir } from 'node:os'
24
+ import { join } from 'node:path'
25
+ import { pathToFileURL } from 'node:url'
26
+
27
+ const REPO = new URL('..', import.meta.url)
28
+ const failures = []
29
+ const ok = (label, condition, detail = '') => {
30
+ console.log(` ${condition ? 'OK ' : 'FAIL'} ${label}${detail === '' ? '' : ` — ${detail}`}`)
31
+ if (!condition) failures.push(label)
32
+ }
33
+
34
+ /** The profile whose node_modules resolve the host packages. */
35
+ function findProfileRoot() {
36
+ const home = process.env.DSH_HOME ?? join(process.env.USERPROFILE ?? process.env.HOME ?? '', '.dsh')
37
+ const profiles = join(home, 'profiles')
38
+ if (!existsSync(profiles)) return undefined
39
+ const named = process.env.DSH_PROFILE
40
+ const candidates = named !== undefined && named !== ''
41
+ ? [named]
42
+ : readdirSync(profiles).filter(entry => existsSync(join(profiles, entry, 'package.json')))
43
+ for (const candidate of candidates) {
44
+ const manifest = join(profiles, candidate, 'package.json')
45
+ if (existsSync(manifest)) return { name: candidate, manifest }
46
+ }
47
+ return undefined
48
+ }
49
+
50
+ const profile = findProfileRoot()
51
+ if (profile === undefined) {
52
+ console.log('No DSH profile found under $DSH_HOME/profiles; nothing to verify.')
53
+ process.exit(0)
54
+ }
55
+
56
+ // A settings document of our own, so the probe can name a channel without touching the user's file.
57
+ const sandboxHome = mkdtempSync(join(tmpdir(), 'dsh-runtime-probe-'))
58
+ process.env.DSH_HOME = sandboxHome
59
+ // The whole point is that a probe never downloads: this reports `skipped`, which is also a state the
60
+ // panel has to render.
61
+ process.env.ELECTRON_SKIP_BINARY_DOWNLOAD = '1'
62
+
63
+ const require = createRequire(profile.manifest)
64
+ const load = async spec => import(pathToFileURL(require.resolve(spec)).href)
65
+ const cordis = await load('@deepseek-ai/cordis')
66
+
67
+ console.log(`Host: profile "${profile.name}" · sandbox DSH_HOME ${sandboxHome}`)
68
+ console.log('')
69
+
70
+ /** The host's web-server shape: exact paths, a handler, and an unsubscribe. */
71
+ class StubWebServer extends cordis.Service {
72
+ constructor(ctx) {
73
+ super(ctx, 'webServer')
74
+ this.routes = new Map()
75
+ }
76
+ register(spec, label) {
77
+ this.routes.set(spec.path, { handler: spec.handler, label })
78
+ return () => this.routes.delete(spec.path)
79
+ }
80
+ }
81
+
82
+ const root = new cordis.Context()
83
+ new StubWebServer(root)
84
+
85
+ const seam = await import(new URL('lib/browser/runtime.js', REPO).href)
86
+ new seam.default(root)
87
+ const entry = await import(new URL('lib/browser-electron/entry.js', REPO).href)
88
+ entry.apply(root, {})
89
+
90
+ const server = root.get('webServer')
91
+ // `ctx.inject([...], cb)` defers the callback until the dependency is available, which is a later
92
+ // turn of the loop — so the first read can legitimately see an empty route table. Poll briefly
93
+ // instead of asserting on a race; this is the difference between "not wired" and "not yet".
94
+ for (let waited = 0; waited < 2_000 && server.routes.size === 0; waited += 50) {
95
+ await new Promise(resolve => setTimeout(resolve, 50))
96
+ }
97
+ ok('the readiness routes are registered', server.routes.has('/dsh-builtin-browser/runtime-status')
98
+ && server.routes.has('/dsh-builtin-browser/runtime-provision'),
99
+ [...server.routes.keys()].join(', '))
100
+
101
+ // Serve exactly the handlers the plugin registered — no re-implementation in the probe.
102
+ const listener = createServer((req, res) => {
103
+ const route = server.routes.get(new URL(req.url, 'http://localhost').pathname)
104
+ if (route === undefined) { res.writeHead(404); res.end(); return }
105
+ void route.handler(req, res)
106
+ })
107
+ await new Promise(resolve => listener.listen(0, '127.0.0.1', resolve))
108
+ const base = `http://127.0.0.1:${listener.address().port}`
109
+
110
+ /** Headers a browser sends and a plain script does not — the admission rule keys off exactly these. */
111
+ const panelHeaders = { 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)', 'accept-language': 'zh-CN' }
112
+
113
+ try {
114
+ const read = await fetch(`${base}/dsh-builtin-browser/runtime-status`, { headers: panelHeaders })
115
+ const body = await read.json()
116
+ ok('GET answers 200', read.status === 200, String(read.status))
117
+ ok('the report names the channel the settings document holds', body.runtime?.channel === 'bundled', String(body.runtime?.channel))
118
+ ok('the report resolves it to a carrier', body.runtime?.carrier === 'bundled', String(body.runtime?.carrier))
119
+ ok('the runtime state is a state the panel can localize',
120
+ ['idle', 'preparing', 'present', 'ready', 'skipped', 'failed'].includes(body.runtime?.electron?.state),
121
+ String(body.runtime?.electron?.state))
122
+ ok('the download opt-out is honoured, or a runtime is already there',
123
+ body.runtime?.electron?.state !== 'preparing' && (body.runtime?.electron?.detail ?? '') !== '',
124
+ `${String(body.runtime?.electron?.state)}: ${body.runtime?.electron?.detail ?? ''}`)
125
+ ok('the bridge reading is one of the four states the panel knows',
126
+ ['installed', 'missing', 'stale', 'absent'].includes(body.runtime?.bridge?.state),
127
+ String(body.runtime?.bridge?.state))
128
+ ok('installed and running are reported separately',
129
+ typeof body.runtime?.bridge?.running === 'boolean' && typeof body.runtime?.bridge?.runningDetail === 'string',
130
+ `running=${String(body.runtime?.bridge?.running)} — ${body.runtime?.bridge?.runningDetail ?? ''}`)
131
+ ok('a runtime on disk is not described as "not asked for yet"',
132
+ body.runtime?.electron?.state !== 'present' || !/not been asked/.test(body.runtime?.electron?.detail ?? ''),
133
+ String(body.runtime?.electron?.detail ?? ''))
134
+ ok('readiness is one of ready/blocked/unknown',
135
+ ['ready', 'blocked', 'unknown'].includes(body.runtime?.readiness), String(body.runtime?.readiness))
136
+ ok('readiness agrees with the two readings it is derived from',
137
+ body.runtime?.readiness !== 'ready'
138
+ || (body.runtime?.carrier === 'sidebar'
139
+ ? body.runtime?.bridge?.state === 'installed' && body.runtime?.bridge?.running === true
140
+ : body.runtime?.electron?.state === 'present' || body.runtime?.electron?.state === 'ready'),
141
+ `carrier=${String(body.runtime?.carrier)} readiness=${String(body.runtime?.readiness)}`)
142
+
143
+ const scripted = await fetch(`${base}/dsh-builtin-browser/runtime-provision`, { method: 'POST' })
144
+ ok('a POST without browser headers is refused', scripted.status === 403, String(scripted.status))
145
+
146
+ const started = await fetch(`${base}/dsh-builtin-browser/runtime-provision`, { method: 'POST', headers: panelHeaders })
147
+ const startedBody = await started.json()
148
+ ok('the panel may start it and gets a state back', started.status === 200 && startedBody.provision !== undefined,
149
+ JSON.stringify(startedBody.provision ?? startedBody).slice(0, 120))
150
+ } catch (error) {
151
+ ok('the routes answer over HTTP', false, String(error && error.message))
152
+ } finally {
153
+ await new Promise(resolve => listener.close(resolve))
154
+ await root.stop?.()
155
+ }
156
+
157
+ console.log('')
158
+ if (failures.length === 0) {
159
+ console.log('VERDICT: the readiness routes are wired and answer on this host.')
160
+ } else {
161
+ console.log(`VERDICT: ${failures.length} failure(s):`)
162
+ for (const failure of failures) console.log(` - ${failure}`)
163
+ process.exitCode = 1
164
+ }
165
+ process.exit(process.exitCode ?? 0)
@@ -61,6 +61,15 @@ const REQUEST_ID_FIELD = 'bridgeRequestId'
61
61
  */
62
62
  const ENDPOINT_TTL_MS = 60_000
63
63
 
64
+ /**
65
+ * The same window, for the readiness report.
66
+ *
67
+ * Exported rather than re-stated: "the shell is gone" must mean one thing in this plugin. A second
68
+ * copy of the number would drift, and the drift would show up as a panel that says ready while every
69
+ * call times out — the exact failure this constant exists to prevent.
70
+ */
71
+ export const ENDPOINT_STALE_AFTER_MS = ENDPOINT_TTL_MS
72
+
64
73
  /**
65
74
  * A reusable connection to the bridge.
66
75
  *
@@ -0,0 +1,139 @@
1
+ /**
2
+ * Whether the desktop shell is RUNNING, as opposed to whether its bridge is installed.
3
+ *
4
+ * The two questions are constantly confused, and the confusion is the reason a user on
5
+ * `channel: sidebar` sees "another window opened instead" and cannot tell why:
6
+ *
7
+ * - `bridge-status.ts` reads the INSTALL TREE: does the shell's main entry carry our patch, and is
8
+ * the archive out of the way. It survives a reboot; it says nothing about a process.
9
+ * - This module reads the ENDPOINT the shell publishes while it runs: a port, a token, a pid and a
10
+ * refresh stamp. It says nothing about the install tree.
11
+ *
12
+ * "Installed" plus "not running" is the single most common broken state (the desktop app is simply
13
+ * closed), and a readiness report that stops at the install tree calls it ready — then every call
14
+ * dials a port nobody owns. So both readings are taken, and the sidebar carrier is only ready when
15
+ * BOTH are true.
16
+ *
17
+ * Two independent signals, because each alone has a false-positive:
18
+ * - the refresh stamp (the shell rewrites the file every ~15 s, so a stale stamp means a shell that
19
+ * exited and left its last write behind — a tombstone naming a dead port);
20
+ * - the pid, checked with signal 0 (kills nothing, and works across platforms).
21
+ * @module dsh-browser/browser-electron/bridge-endpoint
22
+ */
23
+ import { existsSync, readFileSync, statSync } from 'node:fs'
24
+
25
+ import { ENDPOINT_STALE_AFTER_MS } from './bridge-connection.js'
26
+ import { bridgeEndpointPath } from './desktop-bridge-host.js'
27
+
28
+ /** What the panel needs to know about the running shell. */
29
+ export interface BridgeEndpointState {
30
+ /** Whether a published endpoint file exists at all. */
31
+ readonly present: boolean
32
+ /** Whether the shell behind it looks alive right now: a fresh stamp AND a live pid. */
33
+ readonly alive: boolean
34
+ /** One line, already user-facing. */
35
+ readonly detail: string
36
+ /** When the shell said it last refreshed the file, ISO, when the file carries a stamp. */
37
+ readonly updatedAt?: string
38
+ }
39
+
40
+ /**
41
+ * Whether a pid is alive, without signalling it.
42
+ *
43
+ * Signal 0 performs the permission and existence checks and delivers nothing. `EPERM` means the
44
+ * process exists and belongs to someone else, which is still "alive" for this purpose.
45
+ * @param pid - the process id from the endpoint file.
46
+ * @returns whether that process exists.
47
+ */
48
+ function pidAlive(pid: number): boolean {
49
+ if (!Number.isSafeInteger(pid) || pid <= 0) return false
50
+ try {
51
+ process.kill(pid, 0)
52
+ return true
53
+ } catch (error) {
54
+ return (error as NodeJS.ErrnoException)?.code === 'EPERM'
55
+ }
56
+ }
57
+
58
+ /**
59
+ * Read the endpoint the shell publishes.
60
+ *
61
+ * Never throws: a settings panel must get an answer even when the file is mid-write, unreadable, or
62
+ * belongs to a shell that exited an hour ago.
63
+ * @param path - the endpoint file; defaults to the one location the shell writes.
64
+ * @param now - the clock, injected so a test can age a stamp without sleeping.
65
+ * @returns what the panel shows.
66
+ */
67
+ export function readBridgeEndpoint(
68
+ path: string = bridgeEndpointPath(),
69
+ now: number = Date.now(),
70
+ ): BridgeEndpointState {
71
+ if (!existsSync(path)) {
72
+ return {
73
+ present: false,
74
+ alive: false,
75
+ detail: 'no desktop shell has published a bridge endpoint',
76
+ }
77
+ }
78
+ let raw: { port?: unknown; token?: unknown; pid?: unknown; updatedAt?: unknown }
79
+ try {
80
+ raw = JSON.parse(readFileSync(path, 'utf8')) as typeof raw
81
+ } catch (error) {
82
+ return {
83
+ present: true,
84
+ alive: false,
85
+ detail: `the published endpoint is unreadable: ${String(error)}`,
86
+ }
87
+ }
88
+ const updatedAt = typeof raw.updatedAt === 'string' ? raw.updatedAt : undefined
89
+ const pid = typeof raw.pid === 'number' ? raw.pid : undefined
90
+
91
+ // A stamp older than the refresh window is a tombstone, not a slow shell (see
92
+ // ENDPOINT_STALE_AFTER_MS). An ABSENT stamp is not expired on purpose: an older bridge never wrote
93
+ // one, and that shell deserves to be checked by its pid instead of being declared gone.
94
+ if (updatedAt !== undefined) {
95
+ const at = Date.parse(updatedAt)
96
+ if (Number.isFinite(at)) {
97
+ const ageMs = now - at
98
+ if (ageMs > ENDPOINT_STALE_AFTER_MS) {
99
+ return {
100
+ present: true,
101
+ alive: false,
102
+ updatedAt,
103
+ detail: `the published endpoint has not been refreshed for ${Math.round(ageMs / 1000)}s, `
104
+ + 'so the shell that wrote it has most likely exited',
105
+ }
106
+ }
107
+ }
108
+ }
109
+ if (pid !== undefined && !pidAlive(pid)) {
110
+ return {
111
+ present: true,
112
+ alive: false,
113
+ ...updatedAt === undefined ? {} : { updatedAt },
114
+ detail: `the shell that published the endpoint (pid ${pid}) is not running`,
115
+ }
116
+ }
117
+ return {
118
+ present: true,
119
+ alive: true,
120
+ ...updatedAt === undefined ? {} : { updatedAt },
121
+ detail: 'a desktop shell is running and answering on its published endpoint',
122
+ }
123
+ }
124
+
125
+ /**
126
+ * The endpoint file's mtime, for diagnostics that want to say "written at".
127
+ *
128
+ * Separate and optional: the readiness report does not need it, and a caller that does can fail
129
+ * without disturbing anything else.
130
+ * @param path - the endpoint file.
131
+ * @returns the mtime as ISO, or undefined.
132
+ */
133
+ export function bridgeEndpointWrittenAt(path: string = bridgeEndpointPath()): string | undefined {
134
+ try {
135
+ return statSync(path).mtime.toISOString()
136
+ } catch {
137
+ return undefined
138
+ }
139
+ }
@@ -4,7 +4,7 @@
4
4
  *
5
5
  * WHY
6
6
  * The plugin runs inside the desktop's Node-mode host, where there is no Electron
7
- * API 鈥?which is why it self-hosts a whole browser today. The shell, however, can
7
+ * API — which is why it self-hosts a whole browser today. The shell, however, can
8
8
  * own views, and its sidebar already displays real web pages. This host borrows
9
9
  * that page over the shell's bridge (see apps/desktop/bridge/plugin-browser-bridge.js),
10
10
  * so the agent and the human end up on ONE page instead of two.
@@ -13,7 +13,7 @@
13
13
  * It implements the same `ElectronBrowserViewHost` seam the self-hosted host does,
14
14
  * so the provider, the tools, browsing history, the synthetic cursor and the
15
15
  * teardown rules are all unchanged: only the carrier differs. Everything is
16
- * lazily materialized 鈥?a fresh shell has no sidebar guest until something asks
16
+ * lazily materialized — a fresh shell has no sidebar guest until something asks
17
17
  * for a page, and the bridge creates one on demand.
18
18
  *
19
19
  * FALLBACK
@@ -46,7 +46,7 @@ export function bridgeEndpointPath(): string {
46
46
  * A display state, not a dead carrier. It must never reach `reportLost`, and it must never be
47
47
  * retried as though a guest had vanished: retrying cannot attach a webview the shell has not
48
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.
49
+ * blank — losing the page the user had open.
50
50
  */
51
51
  const PANEL_NOT_DISPLAYED = 'panel-not-displayed'
52
52
 
@@ -67,8 +67,8 @@ const PANEL_DISPLAY_RETRY_MS = 400
67
67
  *
68
68
  * Thrown instead of a plain Error so callers can distinguish "the panel did not render" from "the
69
69
  * browser broke", which is exactly the distinction issue #37 says was missing. The plugin no longer
70
- * waits for a human to show the conversation 鈥?the client half asks the shell to (`openSession`) and
71
- * this host retries while it renders 鈥?so reaching here means the shell did not render it at all.
70
+ * waits for a human to show the conversation — the client half asks the shell to (`openSession`) and
71
+ * this host retries while it renders — so reaching here means the shell did not render it at all.
72
72
  */
73
73
  export class BrowserPanelNotDisplayedError extends Error {
74
74
  readonly code = PANEL_NOT_DISPLAYED
@@ -78,7 +78,7 @@ export class BrowserPanelNotDisplayedError extends Error {
78
78
  */
79
79
  constructor(detail: string) {
80
80
  super(
81
- 'dsh-builtin-browser: this conversation\'s sidebar page did not attach 鈥?the shell was asked to '
81
+ 'dsh-builtin-browser: this conversation\'s sidebar page did not attach — the shell was asked to '
82
82
  + 'show this conversation and its panel still did not render. Nothing was lost, and the page '
83
83
  + 'appears as soon as the panel mounts. '
84
84
  + `(${detail})`,
@@ -99,7 +99,7 @@ function isGuestGone(error: unknown): boolean {
99
99
  if (error instanceof BrowserPanelNotDisplayedError) return false
100
100
  const message = error instanceof Error ? error.message : String(error)
101
101
  // The panel path reports its own failure when the renderer never produced a page, and that is the
102
- // same class as a vanished guest 鈥?worth one retry on a fresh panel 鈥?so it is listed here too.
102
+ // same class as a vanished guest — worth one retry on a fresh panel — so it is listed here too.
103
103
  return /guest \d+ is not available|sidebar unavailable|produced no page/i.test(message)
104
104
  }
105
105
 
@@ -108,7 +108,7 @@ function isGuestGone(error: unknown): boolean {
108
108
  *
109
109
  * One sidebar exists per shell window, so every view this host hands out refers
110
110
  * to the same guest: the provider keeps its tab bookkeeping, and the tabs simply
111
- * share the visible page. That is the intended behaviour for this carrier 鈥?the
111
+ * share the visible page. That is the intended behaviour for this carrier — the
112
112
  * point is a single page both parties can see.
113
113
  */
114
114
  export class DesktopBridgeViewHost implements ElectronBrowserViewHost {
@@ -117,7 +117,7 @@ export class DesktopBridgeViewHost implements ElectronBrowserViewHost {
117
117
  * One entry per view this host handed out: the conversation it serves, and the guest backing it.
118
118
  *
119
119
  * The conversation belongs to the ENTRY, not to this host. A single plugin process serves every
120
- * conversation 鈥?DSH runs them all through one host instance 鈥?so an owner held on the host
120
+ * conversation — DSH runs them all through one host instance — so an owner held on the host
121
121
  * would be one conversation's id applied to all of them, and a page could still land in
122
122
  * another's sidebar however carefully the bridge checked it.
123
123
  */
@@ -127,7 +127,7 @@ export class DesktopBridgeViewHost implements ElectronBrowserViewHost {
127
127
  *
128
128
  * Every DSH session is its own plugin process, and the sidebar is one surface they all share.
129
129
  * A session can only see its own `views` map, so before the bridge kept a ledger it adopted
130
- * whichever tab it found 鈥?including one another session had opened, which is how a URL from
130
+ * whichever tab it found — including one another session had opened, which is how a URL from
131
131
  * one session appeared in another's sidebar. The id is per process, so two sessions never
132
132
  * collide and one session's tabs are never handed to another; it is deliberately not the DSH
133
133
  * session id, which this layer has no access to and does not need.
@@ -135,17 +135,17 @@ export class DesktopBridgeViewHost implements ElectronBrowserViewHost {
135
135
  * The whole ledger rests on that premise, so it was measured rather than assumed: with two
136
136
  * sessions running, the desktop had TWO host processes (plus one main, two renderers and a
137
137
  * gpu/utility pair). If sessions ever shared a process, every owner check in the bridge would
138
- * compare equal and the bleed would return in a new shape 鈥?so a change to how DSH spawns
138
+ * compare equal and the bleed would return in a new shape — so a change to how DSH spawns
139
139
  * sessions invalidates this file, not just this comment.
140
140
  *
141
141
  * It is now the CONVERSATION id rather than an invented uuid, read from the plugin's ctx by the
142
142
  * same path DSH's own desktop host uses. That matters because the shell keeps one sidebar per
143
143
  * conversation and writes its session id onto each sidebar container (on the React fiber,
144
- * measured on the running app) 鈥?so the bridge can only answer "is this sidebar mine" if it has
144
+ * measured on the running app) — so the bridge can only answer "is this sidebar mine" if it has
145
145
  * a comparable id. With an invented uuid it never could, which is how a command came to be typed
146
146
  * into another conversation's address bar.
147
147
  *
148
- * Falls back to a random uuid when the host cannot supply one 鈥?an older DSH, or a non-desktop
148
+ * Falls back to a random uuid when the host cannot supply one — an older DSH, or a non-desktop
149
149
  * composition. That is no worse than before: the bridge then knows only "this process", and it
150
150
  * refuses to operate on a sidebar it cannot prove is its own.
151
151
  */
@@ -155,7 +155,7 @@ export class DesktopBridgeViewHost implements ElectronBrowserViewHost {
155
155
  * conversation each belongs to.
156
156
  *
157
157
  * The provider destroys its view handles before it asks for a release, so the mapping is dropped
158
- * by then 鈥?keeping the guest ids here is what lets us close only our own tabs when several
158
+ * by then — keeping the guest ids here is what lets us close only our own tabs when several
159
159
  * conversations are running (requirements 搂4: each session gets its own page). The owner rides
160
160
  * along for the same reason it does in {@link views}: a release names one conversation.
161
161
  */
@@ -168,7 +168,7 @@ export class DesktopBridgeViewHost implements ElectronBrowserViewHost {
168
168
  * handler is stored anyway so the interface contract holds (a caller may register
169
169
  * one and must not be surprised) and so a future bridge operation can deliver it
170
170
  * without changing the provider. Consequently no user-action event is emitted while
171
- * the desktop sidebar is the carrier 鈥?by design, not by omission.
171
+ * the desktop sidebar is the carrier — by design, not by omission.
172
172
  */
173
173
  private userActionHandler: ((action: BrowserUserAction) => void) | undefined
174
174
  /** Told when the shell behind this bridge exits; see `onLost`. */
@@ -232,7 +232,7 @@ export class DesktopBridgeViewHost implements ElectronBrowserViewHost {
232
232
  //
233
233
  // The sidebar browser renders as a <webview> only where the shell exposes
234
234
  // `dshDesktop.browser` and enables `webviewTag`. Where it renders as an <iframe> there is
235
- // no webContents, no `getWebContentsId()` and no CDP endpoint 鈥?and every tool here is
235
+ // no webContents, no `getWebContentsId()` and no CDP endpoint — and every tool here is
236
236
  // built on CDP, so adopting it means failing every call, with no path back to a carrier
237
237
  // that works. Reported on DSH Desktop 2.0.17 with both conditions measured.
238
238
  //
@@ -279,8 +279,8 @@ export class DesktopBridgeViewHost implements ElectronBrowserViewHost {
279
279
  * Every page this conversation's sidebar panel currently holds.
280
280
  *
281
281
  * The shell owns page creation inside the panel: a link the user or the agent clicks may open a
282
- * new page, and nothing tells the provider. Those pages are real 鈥?they are what the human sees
283
- * 鈥?but without this the tab model reports only the ones the provider created, so the rest are
282
+ * new page, and nothing tells the provider. Those pages are real — they are what the human sees
283
+ * — but without this the tab model reports only the ones the provider created, so the rest are
284
284
  * invisible to `dsh_browser_list_tabs` and unclosable through `dsh_browser_close_tab`.
285
285
  *
286
286
  * The bridge's `list` already answers with the sidebar guests, which is the same information, so
@@ -291,14 +291,14 @@ export class DesktopBridgeViewHost implements ElectronBrowserViewHost {
291
291
  * Every sidebar page this conversation holds that THIS HOST did not open.
292
292
  *
293
293
  * The shell owns page creation inside the panel: a link the user or the agent clicks may open a
294
- * new page, and nothing tells the provider. Those pages are real 鈥?they are what the human sees
295
- * 鈥?but without this the tab model reports only the ones the provider created, so the rest are
294
+ * new page, and nothing tells the provider. Those pages are real — they are what the human sees
295
+ * — but without this the tab model reports only the ones the provider created, so the rest are
296
296
  * invisible to `dsh_browser_list_tabs` and unclosable through `dsh_browser_close_tab`.
297
297
  *
298
298
  * Pages this host opened are EXCLUDED here rather than deduplicated by the caller, because the
299
299
  * caller cannot do it: the provider knows a tab by its own id and the carrier knows a page by the
300
300
  * guest id, and the two never match. The first version returned everything and relied on the
301
- * caller to filter, which reported the same page twice 鈥?the mapping that makes the match
301
+ * caller to filter, which reported the same page twice — the mapping that makes the match
302
302
  * possible exists only here.
303
303
  * @returns the panel's pages that are not ours, or an empty list when the bridge cannot answer.
304
304
  */
@@ -322,7 +322,7 @@ export class DesktopBridgeViewHost implements ElectronBrowserViewHost {
322
322
  /**
323
323
  * Close one sidebar page by the id {@link listPages} reported.
324
324
  *
325
- * The bridge closes sidebar pages by TITLE, and only the ones the caller owns 鈥?that is what
325
+ * The bridge closes sidebar pages by TITLE, and only the ones the caller owns — that is what
326
326
  * stopped one conversation's teardown from destroying another's page. So the title is looked up
327
327
  * through the same listing, and a page that no longer appears is treated as already gone rather
328
328
  * than as an error: the caller asked for it to be closed, and it is.
@@ -340,8 +340,8 @@ export class DesktopBridgeViewHost implements ElectronBrowserViewHost {
340
340
  /**
341
341
  * The guest backing a view, materialized on first use.
342
342
  *
343
- * The conversation that called owns exactly one sidebar page on this carrier 鈥?a human and the
344
- * agent look at the same page 鈥?so every view resolves to that conversation's own guest, and the
343
+ * The conversation that called owns exactly one sidebar page on this carrier — a human and the
344
+ * agent look at the same page — so every view resolves to that conversation's own guest, and the
345
345
  * page does not multiply behind the provider's own tab bookkeeping.
346
346
  *
347
347
  * A cached guest is used as-is: probing it first cost a round-trip on every command, so liveness
@@ -357,7 +357,7 @@ export class DesktopBridgeViewHost implements ElectronBrowserViewHost {
357
357
  // and `createView`'s sendCommand then discards the cache and calls back in here.
358
358
  if (entry?.guest !== undefined) return entry.guest
359
359
 
360
- // The conversation THIS VIEW serves 鈥?read from the view, never from the process.
360
+ // The conversation THIS VIEW serves — read from the view, never from the process.
361
361
  //
362
362
  // The difference is the whole bug. This host is one instance shared by every conversation, so
363
363
  // `this.owner` alone can only be "whichever conversation this process happens to name", and
@@ -370,7 +370,7 @@ export class DesktopBridgeViewHost implements ElectronBrowserViewHost {
370
370
  // shortcut or clicking its card, both of which the shell delivers to whatever it displays.
371
371
  const owner = entry?.owner ?? this.owner
372
372
  // A command that must not present anything (issue #46: the live preview) takes a read-only path.
373
- // 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
373
+ // 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
374
374
  // and wrong for "let me look at it". A page that is not on screen therefore reports as a display
375
375
  // state, and the preview route turns that into the panel's paused state.
376
376
  if (options?.present === false) {
@@ -410,14 +410,14 @@ export class DesktopBridgeViewHost implements ElectronBrowserViewHost {
410
410
  // panel-not-displayed - the conversation exists but is not the one on screen;
411
411
  // "is not mounted" - its surface store was not minted when the tab was placed.
412
412
  // Both are gone one render later. Measured, this is the whole difference between "the sidebar
413
- // works once I click over to that conversation" and "it works" 鈥?the page is real either way,
413
+ // works once I click over to that conversation" and "it works" — the page is real either way,
414
414
  // and failing the call while the shell is already switching away from it just reported a
415
415
  // problem the plugin had already fixed.
416
416
  const displayRefusal = (value: Record<string, unknown>): boolean =>
417
417
  value.ok !== true
418
418
  && (String(value.code ?? '') === PANEL_NOT_DISPLAYED
419
419
  || String(value.error ?? '').includes('not mounted')
420
- // Bridges installed before issue #37 send the same refusal with NO code 鈥?the installed copy
420
+ // Bridges installed before issue #37 send the same refusal with NO code — the installed copy
421
421
  // on this machine is one of them (`panel-not-displayed` appears nowhere in it). Reading only
422
422
  // the code therefore turned a retryable display state into a hard failure for exactly the
423
423
  // users who had the old bridge, which is the majority until it is reinstalled. The wording
@@ -428,7 +428,7 @@ export class DesktopBridgeViewHost implements ElectronBrowserViewHost {
428
428
  answer = await ask()
429
429
  }
430
430
  if (answer.ok !== true) {
431
- // Reachable only after the retries above have run out, and the code still decides 鈥?not the
431
+ // Reachable only after the retries above have run out, and the code still decides — not the
432
432
  // wording:
433
433
  // panel-not-displayed -> the shell was asked to show the conversation (client half's
434
434
  // `openSession`) and did not render it in ~1.6 s: no loss, no swap.
@@ -507,8 +507,8 @@ export class DesktopBridgeViewHost implements ElectronBrowserViewHost {
507
507
  * This used to be empty, on the reasoning that the sidebar is already on screen so there is
508
508
  * nothing to show. That confused "the sidebar is visible" with "this page is the one being
509
509
  * looked at": opening a page left it behind whatever the human had in front, which is issue
510
- * #23. The other two carriers both do this 鈥?the self-hosted window re-adds the view and the
511
- * system browser calls `Page.bringToFront` 鈥?so this carrier was the odd one out.
510
+ * #23. The other two carriers both do this — the self-hosted window re-adds the view and the
511
+ * system browser calls `Page.bringToFront` — so this carrier was the odd one out.
512
512
  *
513
513
  * Best-effort by design: the tab strip belongs to the shell's renderer, and failing to raise
514
514
  * it must not fail the navigation that has already happened.
@@ -516,7 +516,7 @@ export class DesktopBridgeViewHost implements ElectronBrowserViewHost {
516
516
  */
517
517
  showView(handle: ElectronViewHandle): void {
518
518
  // `owner` is required: the bridge refuses to bring forward a guest held by another session.
519
- // It comes from the view, not the process 鈥?with several conversations live, a process-wide
519
+ // It comes from the view, not the process — with several conversations live, a process-wide
520
520
  // owner would raise the wrong conversation's tab.
521
521
  const owner = this.views.get(handle.id)?.owner ?? this.owner
522
522
  const guest = this.views.get(handle.id)?.guest
@@ -539,7 +539,7 @@ export class DesktopBridgeViewHost implements ElectronBrowserViewHost {
539
539
  *
540
540
  * Destroying our own view handles is not enough on this carrier: the sidebar
541
541
  * belongs to the shell and would happily keep the page (and its renderer) alive.
542
- * Closing the tabs is what actually ends the page 鈥?and only the page: cookies
542
+ * Closing the tabs is what actually ends the page — and only the page: cookies
543
543
  * live in the partition, history on disk, so both survive.
544
544
  * @param owner - the conversation whose pages to close. Omit to close every conversation's,
545
545
  * which is only correct from a teardown that is itself global.
@@ -547,7 +547,7 @@ export class DesktopBridgeViewHost implements ElectronBrowserViewHost {
547
547
  */
548
548
  async releasePage(owner?: string): Promise<void> {
549
549
  // Only this conversation's tabs. The host is ONE instance shared by every conversation, so a
550
- // release that named none would close pages other conversations are still driving 鈥?"every
550
+ // release that named none would close pages other conversations are still driving — "every
551
551
  // webview currently visible" is precisely what must never be used here.
552
552
  const mine: number[] = []
553
553
  for (const [viewId, entry] of [...this.views]) {
@@ -569,7 +569,7 @@ export class DesktopBridgeViewHost implements ElectronBrowserViewHost {
569
569
  // `owner` is REQUIRED here now that the bridge filters `list` by it. Without it the bridge
570
570
  // falls back to a different owner, so the guests this session holds are filtered out of the
571
571
  // answer, `mine.includes(...)` matches nothing, the title list comes back empty and this
572
- // returns without closing anything 鈥?the page stayed open and the human had to close it by
572
+ // returns without closing anything — the page stayed open and the human had to close it by
573
573
  // hand. Adding the ledger to the bridge without updating this call site is exactly the kind
574
574
  // of half-change that made the ownership work take four rounds.
575
575
  const answer = await this.connection.call({ op: 'list', owner: owner ?? this.owner }, 5_000)