dsh-builtin-browser 0.5.2 → 0.5.4

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 (38) hide show
  1. package/CHANGELOG.md +145 -0
  2. package/README.en.md +77 -68
  3. package/README.md +69 -89
  4. package/client.js +147 -15
  5. package/desktop-bridge/desktop-identity.json +9 -0
  6. package/desktop-bridge/install.mjs +220 -1
  7. package/desktop-bridge/plugin-browser-bridge.js +5 -0
  8. package/docs/README.md +1 -1
  9. package/docs/architecture.md +1 -1
  10. package/docs/limitations.md +19 -1
  11. package/docs/tool-reference.md +2 -1
  12. package/lib/browser-electron/bridge-status.d.ts +5 -3
  13. package/lib/browser-electron/bridge-status.js +53 -9
  14. package/lib/browser-electron/desktop-bridge-host.d.ts +25 -25
  15. package/lib/browser-electron/desktop-bridge-host.js +67 -40
  16. package/lib/browser-electron/desktop-identity.d.ts +58 -0
  17. package/lib/browser-electron/desktop-identity.js +236 -0
  18. package/lib/browser-electron/electron-provision.d.ts +59 -0
  19. package/lib/browser-electron/electron-provision.js +176 -0
  20. package/lib/browser-electron/entry.js +12 -0
  21. package/lib/browser-electron/host-main.js +68 -14
  22. package/lib/browser-electron/provider.d.ts +53 -3
  23. package/lib/browser-electron/provider.js +26 -5
  24. package/lib/browser-electron/remote-host.d.ts +3 -3
  25. package/lib/browser-electron/remote-host.js +25 -11
  26. package/lib/browser-electron/settings-store.d.ts +19 -0
  27. package/lib/browser-electron/settings-store.js +5 -1
  28. package/package.json +2 -3
  29. package/src/browser-electron/bridge-status.ts +56 -10
  30. package/src/browser-electron/desktop-bridge-host.ts +70 -41
  31. package/src/browser-electron/desktop-identity.ts +260 -0
  32. package/src/browser-electron/electron-provision.ts +208 -0
  33. package/src/browser-electron/entry.ts +12 -0
  34. package/src/browser-electron/host-main.ts +62 -12
  35. package/src/browser-electron/provider.ts +73 -8
  36. package/src/browser-electron/remote-host.ts +26 -12
  37. package/src/browser-electron/settings-store.ts +24 -1
  38. package/src/types/electron-shim.d.ts +8 -0
@@ -66,7 +66,7 @@
66
66
  * and nothing started from outside survives the exit far enough to install afterwards (issue #36).
67
67
  * --restart asks for confirmation on a console; add --yes for an unattended run.
68
68
  */
69
- import { copyFileSync, existsSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
69
+ import { closeSync, copyFileSync, existsSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
70
70
  import { execFileSync, spawn } from 'node:child_process'
71
71
  import { dirname, join } from 'node:path'
72
72
 
@@ -435,6 +435,215 @@ function installCliCompatibility() {
435
435
  console.log(` cli runtime resolution: ${patchHostCli()}`)
436
436
  }
437
437
 
438
+ // ---------------------------------------------------------------------------
439
+ // Identity — before anything is stopped, deleted, extracted, renamed or written.
440
+ //
441
+ // Reported as issue #40. The check used to be "resources/app/lib/main.js or resources/app.asar
442
+ // exists", which is the shape of EVERY Electron app. Measured: a throwaway app whose package.json
443
+ // said `unrelated-meeting-app` was accepted, had its entry file rewritten and the bridge copied in;
444
+ // and a second sample lost its `resources/app` directory to the packed-layout rebuild before the
445
+ // archive was found to be invalid.
446
+ //
447
+ // The rule now lives in `desktop-identity.json`, shared with the plugin's status reader, and the
448
+ // order is the point: identity first, then the archive is VALIDATED, and only then may this script
449
+ // close the app or delete a tree.
450
+ // ---------------------------------------------------------------------------
451
+
452
+ /**
453
+ * The identity rule (accepted package names and the main entry), from the JSON next to this file.
454
+ * @returns the rule, or undefined after printing why it cannot be trusted.
455
+ */
456
+ function readIdentityRule() {
457
+ try {
458
+ const raw = JSON.parse(readFileSync(new URL('./desktop-identity.json', import.meta.url), 'utf8'))
459
+ const names = raw.packageNames
460
+ const mainEntry = raw.mainEntry
461
+ if (!Array.isArray(names) || names.length === 0 || names.some(name => typeof name !== 'string')
462
+ || typeof mainEntry !== 'string' || mainEntry === '') {
463
+ console.error('desktop-identity.json is malformed: expected packageNames[] and mainEntry')
464
+ return undefined
465
+ }
466
+ return { packageNames: names, mainEntry }
467
+ } catch (error) {
468
+ console.error(`desktop-identity.json could not be read: ${String(error)}`)
469
+ return undefined
470
+ }
471
+ }
472
+
473
+ /**
474
+ * Read one file out of an asar archive without extracting anything.
475
+ *
476
+ * Identity has to come from the archive when one exists: Electron loads it in preference to the
477
+ * sibling directory, and a desktop update leaves that older extraction behind, so verifying the
478
+ * directory would verify bytes nobody runs.
479
+ * @param archive - the archive path.
480
+ * @param entryPath - slash-separated path inside the archive.
481
+ * @returns the bytes, or undefined when the entry is missing or unreadable.
482
+ */
483
+ function readAsarEntry(archive, entryPath) {
484
+ let fd
485
+ try {
486
+ const parsed = readAsarHeader(archive)
487
+ fd = parsed.fd
488
+ let node
489
+ let files = parsed.header.files
490
+ for (const part of entryPath.split('/')) {
491
+ if (files === undefined) return undefined
492
+ node = files[part]
493
+ if (node === undefined) return undefined
494
+ files = node.files
495
+ }
496
+ if (node.files !== undefined || node.unpacked === true) return undefined
497
+ const size = Number(node.size)
498
+ const offset = Number(node.offset)
499
+ if (!Number.isFinite(size) || !Number.isFinite(offset) || size < 0) return undefined
500
+ const buffer = Buffer.alloc(size)
501
+ const read = readSync(fd, buffer, 0, size, parsed.contentBase + offset)
502
+ return read === size ? buffer : undefined
503
+ } catch {
504
+ return undefined
505
+ } finally {
506
+ if (fd !== undefined) {
507
+ try { closeSync(fd) } catch { /* already closed */ }
508
+ }
509
+ }
510
+ }
511
+
512
+ /**
513
+ * Validate the archive the shell will actually load: it must parse, carry a DSH Desktop manifest and
514
+ * the declared main entry, and every `unpacked` entry must exist beside it with the size the header
515
+ * claims. Read-only.
516
+ * @param archive - the archive path.
517
+ * @returns `{ ok: true }`, or `{ ok: false, reason }`.
518
+ */
519
+ function validateArchive(archive) {
520
+ let parsed
521
+ try {
522
+ parsed = readAsarHeader(archive)
523
+ } catch (error) {
524
+ return { ok: false, reason: `the archive header cannot be read: ${String(error)}` }
525
+ }
526
+ const { fd, header, contentBase } = parsed
527
+ try {
528
+ const fileSize = statSync(archive).size
529
+ const problems = []
530
+ const walk = (node, prefix) => {
531
+ for (const [name, entry] of Object.entries(node.files ?? {})) {
532
+ const relativePath = prefix === '' ? name : `${prefix}/${name}`
533
+ if (entry.files !== undefined) {
534
+ walk(entry, relativePath)
535
+ continue
536
+ }
537
+ const size = Number(entry.size)
538
+ if (!Number.isFinite(size) || size < 0) {
539
+ problems.push(`${relativePath}: implausible size ${String(entry.size)}`)
540
+ continue
541
+ }
542
+ if (entry.unpacked === true) {
543
+ const source = join(`${archive}.unpacked`, ...relativePath.split('/'))
544
+ if (!existsSync(source)) {
545
+ problems.push(`${relativePath}: listed as unpacked but ${source} is missing`)
546
+ continue
547
+ }
548
+ if (statSync(source).size !== size) problems.push(`${relativePath}: unpacked size does not match the header`)
549
+ continue
550
+ }
551
+ const offset = Number(entry.offset)
552
+ if (!Number.isFinite(offset) || contentBase + offset + size > fileSize) {
553
+ problems.push(`${relativePath}: content lies outside the archive`)
554
+ }
555
+ }
556
+ }
557
+ walk(header, '')
558
+ if (problems.length > 0) {
559
+ return { ok: false, reason: `the archive is not usable: ${problems.slice(0, 5).join('; ')}` }
560
+ }
561
+ const rule = readIdentityRule()
562
+ if (rule === undefined) return { ok: false, reason: 'the identity rule is unavailable' }
563
+ let node
564
+ let files = header.files
565
+ for (const part of rule.mainEntry.split('/')) {
566
+ if (files === undefined) { node = undefined; break }
567
+ node = files[part]
568
+ files = node?.files
569
+ }
570
+ if (node === undefined) return { ok: false, reason: `the archive has no ${rule.mainEntry}` }
571
+ return { ok: true }
572
+ } catch (error) {
573
+ return { ok: false, reason: `the archive cannot be validated: ${String(error)}` }
574
+ } finally {
575
+ try { closeSync(fd) } catch { /* already closed */ }
576
+ }
577
+ }
578
+
579
+ /**
580
+ * Whether a directory is a DSH Desktop install, by the shared identity rule.
581
+ *
582
+ * Every uncertainty refuses: this answer gates stopping the app, deleting a tree and writing files.
583
+ * @param root - the install directory to verify.
584
+ * @returns `{ ok: true, layout, packageName, version }`, or `{ ok: false, reason }`.
585
+ */
586
+ function verifyDesktopIdentity(root) {
587
+ const rule = readIdentityRule()
588
+ if (rule === undefined) return { ok: false, reason: 'the identity rule is unavailable' }
589
+ const resources = join(root, 'resources')
590
+ const archive = join(resources, 'app.asar')
591
+ const appDir = join(resources, 'app')
592
+ const archivePresent = existsSync(archive)
593
+ const layout = archivePresent ? 'packed' : 'unpacked'
594
+
595
+ let manifestText
596
+ if (archivePresent) {
597
+ const bytes = readAsarEntry(archive, 'package.json')
598
+ if (bytes === undefined) {
599
+ return { ok: false, reason: `${archive} exists but its package.json cannot be read` }
600
+ }
601
+ manifestText = bytes.toString('utf8')
602
+ } else {
603
+ const manifestPath = join(appDir, 'package.json')
604
+ if (!existsSync(manifestPath)) {
605
+ return { ok: false, reason: `neither ${manifestPath} nor ${archive} exists` }
606
+ }
607
+ manifestText = readFileSync(manifestPath, 'utf8')
608
+ }
609
+
610
+ let manifest
611
+ try {
612
+ manifest = JSON.parse(manifestText)
613
+ } catch {
614
+ return { ok: false, reason: 'the package manifest is not valid JSON' }
615
+ }
616
+ const name = typeof manifest.name === 'string' ? manifest.name : ''
617
+ if (!rule.packageNames.includes(name)) {
618
+ return {
619
+ ok: false,
620
+ reason: `the app calls itself ${name === '' ? '(no name)' : JSON.stringify(name)}, which is not one of `
621
+ + `${rule.packageNames.join(' / ')} — a generic Electron layout is not proof of identity`,
622
+ }
623
+ }
624
+ const mainPresent = archivePresent
625
+ ? readAsarEntry(archive, rule.mainEntry) !== undefined
626
+ : existsSync(join(appDir, ...rule.mainEntry.split('/')))
627
+ if (!mainPresent) {
628
+ return { ok: false, reason: `${rule.mainEntry} is not present under ${archivePresent ? archive : appDir}` }
629
+ }
630
+ return {
631
+ ok: true,
632
+ layout,
633
+ packageName: name,
634
+ version: typeof manifest.version === 'string' ? manifest.version : undefined,
635
+ }
636
+ }
637
+
638
+ const identity = verifyDesktopIdentity(installRoot)
639
+ if (!identity.ok) {
640
+ console.error(`refusing to touch ${installRoot}`)
641
+ console.error(` ${identity.reason}`)
642
+ console.error('Pass the installation directory of DSH Desktop as the first argument.')
643
+ console.error('Nothing was stopped, deleted, extracted or written.')
644
+ process.exit(1)
645
+ }
646
+
438
647
  // `--restart` closes the shell BEFORE anything else, because the archive cannot be moved while the
439
648
  // shell holds it (EBUSY), and because there is no safe way to wait across the exit from outside —
440
649
  // both arrangements measured in issue #36 died at that moment. Doing it here keeps the whole
@@ -569,6 +778,16 @@ if (revert) {
569
778
  }
570
779
 
571
780
  if (packedLayout) {
781
+ // Validate BEFORE the tree is deleted. Reported as issue #40: with an invalid archive and an
782
+ // existing extraction, this script removed `resources/app` and only then discovered the archive
783
+ // was unusable — leaving the app directory gone for no gain. The check is read-only and cheap
784
+ // (header walk plus a stat per unpacked entry), so it belongs on this side of the deletion.
785
+ const checked = validateArchive(asarPath)
786
+ if (!checked.ok) {
787
+ console.error(`refusing to rebuild from an archive that cannot be verified: ${checked.reason}`)
788
+ console.error('Nothing was deleted; the archive and the existing directory are untouched.')
789
+ process.exit(1)
790
+ }
572
791
  const stale = existsSync(appDir)
573
792
  const started = Date.now()
574
793
  console.log(stale
@@ -507,6 +507,11 @@ async function handle(request) { const op = String(request?.op ?? '')
507
507
  }
508
508
 
509
509
  // Already has a page: reuse it. This is the common case after the first open of a session.
510
+ //
511
+ // A read-only caller (the live preview, issue #46) does NOT come through here at all: it uses the
512
+ // `list` op instead, because this one can drive the shell — that is the difference between "show
513
+ // me the page" and "let me look at it", and keeping the preview off this path is what stops a
514
+ // read-only action from moving the reader's layout.
510
515
  const first = await ask(url !== '')
511
516
  if (first.guestId !== null) {
512
517
  claims.set(first.guestId, owner)
package/docs/README.md CHANGED
@@ -6,7 +6,7 @@
6
6
  | --- | --- |
7
7
  | 了解插件为什么存在、与无头方案的区别 | [为什么做共享真实浏览器](why-browser.md) |
8
8
  | 安装、配置、日常使用与常见问题 | [用户指南](user-guide.md) |
9
- | 全部 34 个工具的参数、输出与示例 | [工具参考](tool-reference.md) |
9
+ | 全部 35 个工具的参数、输出与示例 | [工具参考](tool-reference.md) |
10
10
  | 了解 seam / provider / 工具三层与自托管实现 | [架构说明](architecture.md) |
11
11
  | 知道哪些事**做不到**、以及为什么 | [已知限制](limitations.md) |
12
12
  | 构建、测试、复验宿主兼容性 | [开发](development.md) |
@@ -37,7 +37,7 @@ agent (dsh_browser_* 工具)
37
37
 
38
38
  ### 工具层(`src/tool-browser/`)
39
39
 
40
- 34 个 `dsh_browser_*` 工具,按**调用方任务**(`exec.agent.id`)维护独立浏览器会话:
40
+ 35 个 `dsh_browser_*` 工具,按**调用方任务**(`exec.agent.id`)维护独立浏览器会话:
41
41
 
42
42
  - 会话缓存 `sessionsByTask`:同一任务复用同一会话,并发首开去重;
43
43
  - `dsh_browser_reset_session` 关闭本任务会话并遗忘映射(即使 close 抛错也清除,下次调用重建);
@@ -6,7 +6,7 @@
6
6
 
7
7
  - JPEG 在**自托管**与**本机 Chrome / Edge** 上可用;**桌面端侧栏**走外壳的 `webContents.debugger`,其 Electron 的 CDP JPEG 编码会挂起,因此该载体下请求 JPEG 会返回 PNG。
8
8
  - 降采样(`maxWidth`/`maxHeight`)**三种载体都支持**(经 CDP `clip.scale`,或自托管走原生 `capturePage`)。
9
- - 自托管截图优先走 Electron 原生 `capturePage`(CDP `captureScreenshot` 在多视图下会挂起);截图前自动把目标标签置顶。
9
+ - 自托管截图优先走 Electron 原生 `capturePage`(CDP `captureScreenshot` 在多视图下会挂起);截图前自动把目标标签置顶 —— 除非开启**安静模式**,那时不碰窗口(见下)。
10
10
  - `fullPage` 在部分主机的**软件合成**下不稳定 —— 请求 `fullPage` 时**原生 `capturePage` 路径被整体跳过**(它没有捕获滚动区以外内容的能力),因此**三种载体都走 CDP 的 `captureBeyondViewport`**。也就是说 `fullPage` 的不稳定性与载体无关,任何载体都可能碰到;只有视口截图才优先走原生路径。
11
11
 
12
12
  ## 验证与登录
@@ -63,6 +63,24 @@
63
63
  - 新视图创建前会先有界加载 `about:blank`(3 秒上限,保证视图一存在就有可响应的渲染进程),宿主侧命令另有 20s 有界超时。
64
64
  - 子进程 stderr 与退出码/信号落到 `$DSH_HOME/logs/dsh-builtin-browser-host.log`;写之前若该文件已超过 2 MiB,则**丢弃旧内容、只写入一行带时间戳的轮转记录**(形如 `<ISO 时间戳> log rotated: previous content exceeded 2097152 bytes and was discarded`)—— 旧内容就此消失不留副本,但那一行证明"曾发生过轮转",纯 `dsh web` 自托管可据此自助排查崩溃循环。
65
65
 
66
+ ## 安静模式(`ui.quiet`)
67
+
68
+ 默认关闭。默认契约是"人机共享同一个窗口":每次操作把窗口带到前面,用户能直接看见 agent 在做什么。开启后,自托管的 Electron 载体改成"能操作,但不接管屏幕":
69
+
70
+ | 操作 | 默认 | 安静模式 |
71
+ | --- | --- | --- |
72
+ | 截图 | 显示 / 还原 / 聚焦窗口,再 `capturePage` | 不碰窗口;窗口不可见时直接走 CDP `Page.captureScreenshot` |
73
+ | 输入(点击 / 输入 / 按键) | `show()` + `moveTop()` + 聚焦 | 最小化则 `restore()`,不可见则 `showInactive()`;不激活应用、不抢键盘焦点、不 `moveTop()` |
74
+ | 标签切换 / 导航 | 同输入,把窗口置前 | 只换窗口内可见的标签,最小化的窗口保持最小化 |
75
+
76
+ 它不是"不显示窗口"。合成输入(CDP `Input.*`)仍需要视图有**显示表面**,Chromium 对没有表面的视图会静默丢弃输入 —— 所以点击/输入可能把最小化的窗口恢复成可见,但不会成为 key window,也不会盖在用户正在用的窗口上。截图和导航没有这个约束,因此是安静模式下完全不动窗口的操作。
77
+
78
+ 边界:
79
+
80
+ - **只作用于自托管 Electron 载体**(插件的 `host-main` 子进程)。桌面端侧栏由外壳承载,`ui.quiet` 不改变外壳的展示策略;安装版 Chrome / Edge 载体各自管理自己的窗口。
81
+ - 用户主动操作(点工具栏、切标签)不受影响 —— 它们本来就发生在那个窗口里。
82
+ - 窗口完全不可见时,安静模式仍会让它出现在屏幕上(只是不聚焦)。要"连出现都不要",请在截图之外使用非视觉能力(snapshot / a11y / content),它们本来就不需要显示表面。
83
+
66
84
  ## 不提供的东西
67
85
 
68
86
  - **无痕模式(`privateMode`)未实现**:它需要 Electron 的 session 分区能力,属于宿主层,本插件不承诺。
@@ -1,6 +1,6 @@
1
1
  # 工具参考
2
2
 
3
- 全部 34 个 `dsh_browser_*` 工具。守卫列:✅ 表示该动作受 `dsh_browser_restrict` 白名单约束;**「– 豁免」表示无论白名单怎么写都不拦截**(豁免集合为 `READ_ONLY_TOOLS`,`src/tool-browser/index.ts` 导出:**只观察的工具** —— `snapshot`/`a11y`/`content`/`scrape`/`screenshot`/`get_value`/`wait`/`challenge`/`list_tabs`/`session`/`history`/`visited` —— 加上 **解除限制 / 从坏状态恢复的工具** `restrict`/`reset_session`/`reset`;`restrict` 在其中,否则限制到空的任务再也解不开);**「–」表示该工具只观察、不做动作**,故没有可拦的东西。两者之外的工具都受白名单约束 —— 例如 `dsh_browser_close_tab`、`dsh_browser_auth` 都不属于豁免集合(`dsh_browser_auth` 的 `restore` 会向任意域写 cookie,是动作,不是观察)。
3
+ 全部 35 个 `dsh_browser_*` 工具。守卫列:✅ 表示该动作受 `dsh_browser_restrict` 白名单约束;**「– 豁免」表示无论白名单怎么写都不拦截**(豁免集合为 `READ_ONLY_TOOLS`,`src/tool-browser/index.ts` 导出:**只观察的工具** —— `snapshot`/`a11y`/`content`/`scrape`/`screenshot`/`get_value`/`wait`/`challenge`/`list_tabs`/`session`/`history`/`visited` —— 加上 **解除限制 / 从坏状态恢复的工具** `restrict`/`reset_session`/`reset`;`restrict` 在其中,否则限制到空的任务再也解不开);**「–」表示该工具只观察、不做动作**,故没有可拦的东西。两者之外的工具都受白名单约束 —— 例如 `dsh_browser_close_tab`、`dsh_browser_auth` 都不属于豁免集合(`dsh_browser_auth` 的 `restore` 会向任意域写 cookie,是动作,不是观察)。
4
4
 
5
5
  ## 页面与导航
6
6
 
@@ -19,6 +19,7 @@
19
19
  | --- | --- | --- | --- | --- |
20
20
  | `dsh_browser_execute` | `script`(必填), `args?` | `{ ok, value? / exception? }` | ✅ | 在页面执行 JS;脚本以 `return` 开头或作为表达式;`args` 以 `arguments[0..n]` 传入。**返回值上限 50 000 字符**,超出时结果里写明"截断于 50 000 / 实际 N 字符"(要完整内容请让表达式返回更小的值)。受设置「Agent 能做什么 → 允许在页面里执行脚本」门控,关闭后一律被拒(`BROWSER_EXECUTE_DISABLED`),且没有任何工具能把它打开 |
21
21
  | `dsh_browser_click` | `target?`(css/text/xpath), `x?`, `y?`(target 与坐标二选一) | `{ clicked }` | ✅ | 语义目标点击:按 `target` 定位、滚动到视口中央再点中心;或视口坐标点击(配合截图做视觉定位) |
22
+ | `dsh_browser_click_sequence` | `points`(必填,`{x,y}[]`), `intervalMs?`(默认 40) | `{ clicked, failedAt?, error? }` | ✅ | 一次调用打一串**视口坐标**点击:只 `present()` 一次,每点走 `mouseMoved`/`mousePressed`/`mouseReleased`;点间默认 40 ms(低于此值页面会把两次按下读成双击或丢弃)。**首点失败即停**并回报 `failedAt`。用于 canvas 页面——它们不采信脚本派发的 `MouseEvent`/`PointerEvent`/`element.click()`,只认 `isTrusted` 的真实输入(实测:sudoku.com 一盘 84 点一次打完) |
22
23
  | `dsh_browser_type` | `text`(必填), `target?` | `{ typed }` | ✅ | 输入文本;传 `target` 先聚焦该元素(CDP `Input.insertText`) |
23
24
  | `dsh_browser_key` | `key`(必填,枚举) | `{ pressed }` | ✅ | 按命名按键:Enter/Tab/Escape/Backspace/Delete/方向键/Home/End/PageUp/PageDown/Space |
24
25
  | `dsh_browser_scroll` | `deltaX?`, `deltaY?`, `selector?`, `toTop?`, `toBottom?` | `{ scrolled }` | ✅ | 滚动页面:像素增量 / 选择器定位 / 顶部底部 |
@@ -1,9 +1,11 @@
1
1
  /**
2
2
  * Find the desktop install to report on.
3
3
  *
4
- * The same shape probe the installer uses, repeated here because the two run in different processes
5
- * and neither can import the other: the product directory is `DeepSeek Harness` on some builds and
6
- * `DSH Desktop` on others, and the shape that identifies an install is stable across both.
4
+ * Reported as issue #40: this used to probe for a *generic* Electron layout and return the first
5
+ * directory that had one. Any Electron app has that layout, so a stranger's app was reported as
6
+ * "DSH Desktop, bridge missing" — together with a ready-to-run installer command aimed at it. The
7
+ * probe now verifies the same identity the installer does (see `desktop-identity.js`), so the
8
+ * answer is about DSH Desktop and nothing else.
7
9
  * @param localAppData - the base directory; defaults to the environment's.
8
10
  * @returns the install directory, or undefined when nothing matches.
9
11
  */
@@ -18,12 +18,16 @@
18
18
  */
19
19
  import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
20
20
  import { join } from 'node:path';
21
+ import { fileURLToPath } from 'node:url';
22
+ import { readDesktopIdentity } from './desktop-identity.js';
21
23
  /**
22
24
  * Find the desktop install to report on.
23
25
  *
24
- * The same shape probe the installer uses, repeated here because the two run in different processes
25
- * and neither can import the other: the product directory is `DeepSeek Harness` on some builds and
26
- * `DSH Desktop` on others, and the shape that identifies an install is stable across both.
26
+ * Reported as issue #40: this used to probe for a *generic* Electron layout and return the first
27
+ * directory that had one. Any Electron app has that layout, so a stranger's app was reported as
28
+ * "DSH Desktop, bridge missing" — together with a ready-to-run installer command aimed at it. The
29
+ * probe now verifies the same identity the installer does (see `desktop-identity.js`), so the
30
+ * answer is about DSH Desktop and nothing else.
27
31
  * @param localAppData - the base directory; defaults to the environment's.
28
32
  * @returns the install directory, or undefined when nothing matches.
29
33
  */
@@ -31,11 +35,10 @@ export function findDesktopInstall(localAppData = process.env.LOCALAPPDATA ?? ''
31
35
  if (localAppData === '')
32
36
  return undefined;
33
37
  const programs = join(localAppData, 'Programs');
34
- const looksInstalled = (candidate) => existsSync(join(candidate, 'resources', 'app', 'lib', 'main.js'))
35
- || existsSync(join(candidate, 'resources', 'app.asar'));
38
+ const isDesktop = (candidate) => readDesktopIdentity(candidate).ok;
36
39
  for (const named of ['DSH Desktop', 'DeepSeek Harness']) {
37
40
  const candidate = join(programs, named);
38
- if (looksInstalled(candidate))
41
+ if (isDesktop(candidate))
39
42
  return candidate;
40
43
  }
41
44
  try {
@@ -43,7 +46,7 @@ export function findDesktopInstall(localAppData = process.env.LOCALAPPDATA ?? ''
43
46
  if (!entry.isDirectory())
44
47
  continue;
45
48
  const candidate = join(programs, entry.name);
46
- if (looksInstalled(candidate))
49
+ if (isDesktop(candidate))
47
50
  return candidate;
48
51
  }
49
52
  }
@@ -54,6 +57,28 @@ export function findDesktopInstall(localAppData = process.env.LOCALAPPDATA ?? ''
54
57
  }
55
58
  /** The marker the installer inserts into the shell's main.js. */
56
59
  const MARKER = '// dsh-builtin-browser: hand the plugin a way to drive the sidebar';
60
+ /**
61
+ * The installer script inside THIS plugin package.
62
+ *
63
+ * Reported as issue #40, fourth item: the panel told users to run
64
+ * `node desktop-bridge/install.mjs "<root>" --restart`, which assumes the reader is standing in a
65
+ * source checkout. Anyone who installed the plugin from npm or the market has no such relative path —
66
+ * the file lives inside the installed package, and there is nowhere sensible for them to run the
67
+ * command from. Resolving it from this module's own location is the difference between a hint and an
68
+ * instruction that works.
69
+ * @returns the absolute path, or undefined when the package layout is unexpected.
70
+ */
71
+ function installerScriptPath() {
72
+ try {
73
+ // lib/browser-electron/bridge-status.js → <package>/desktop-bridge/install.mjs
74
+ const url = new URL('../../desktop-bridge/install.mjs', import.meta.url);
75
+ const path = fileURLToPath(url);
76
+ return safeExists(path) ? path : undefined;
77
+ }
78
+ catch {
79
+ return undefined;
80
+ }
81
+ }
57
82
  /**
58
83
  * The command a user should run for this state, quoted so it survives a path with spaces.
59
84
  * @param installRoot - the install directory, or undefined when none was found.
@@ -62,7 +87,11 @@ const MARKER = '// dsh-builtin-browser: hand the plugin a way to drive the sideb
62
87
  function repairCommand(installRoot) {
63
88
  if (installRoot === undefined)
64
89
  return undefined;
65
- return `node desktop-bridge/install.mjs "${installRoot}" --restart`;
90
+ const script = installerScriptPath();
91
+ // No absolute path means the package is laid out in a way this module cannot navigate; the bare
92
+ // relative form is still better than nothing, but it is the fallback, not the default.
93
+ const runner = script === undefined ? 'desktop-bridge/install.mjs' : `"${script}"`;
94
+ return `node ${runner} "${installRoot}" --restart`;
66
95
  }
67
96
  /**
68
97
  * Read the bridge's state from an install directory.
@@ -78,15 +107,30 @@ export function readBridgeStatus(installRoot) {
78
107
  const mainPath = join(appDir, 'lib', 'main.js');
79
108
  const archivePath = join(resources, 'app.asar');
80
109
  const backupPath = `${mainPath}.before-bridge`;
110
+ // Identity first, and before any other reading. Two reasons, both measured in issue #40: a
111
+ // stranger's app must not be reported as DSH Desktop, and this status also carries a *command* —
112
+ // pointing that command at a directory whose identity was never verified is how the installer got
113
+ // aimed at an application that merely looked like Electron.
114
+ const identity = readDesktopIdentity(installRoot);
115
+ if (!identity.ok) {
116
+ return {
117
+ state: 'missing',
118
+ present: false,
119
+ installRoot,
120
+ archivePresent: safeExists(archivePath),
121
+ detail: `not a DSH Desktop install: ${identity.reason}`,
122
+ };
123
+ }
81
124
  const archivePresent = safeExists(archivePath);
82
125
  const mainPresent = safeExists(mainPath);
83
126
  if (!mainPresent && !archivePresent) {
127
+ // Unreachable once identity has passed (identity requires the loaded main entry), kept as the
128
+ // fail-closed branch for a tree that changed between the two reads.
84
129
  return {
85
130
  state: 'missing',
86
131
  present: false,
87
132
  installRoot,
88
133
  archivePresent,
89
- command: repairCommand(installRoot),
90
134
  detail: 'not a DSH Desktop install: no resources/app/lib/main.js and no resources/app.asar',
91
135
  };
92
136
  }
@@ -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
@@ -32,8 +32,8 @@ export declare function bridgeEndpointPath(): string;
32
32
  *
33
33
  * Thrown instead of a plain Error so callers can distinguish "the panel did not render" from "the
34
34
  * browser broke", which is exactly the distinction issue #37 says was missing. The plugin no longer
35
- * waits for a human to show the conversation — the client half asks the shell to (`openSession`) and
36
- * this host retries while it renders — so reaching here means the shell did not render it at all.
35
+ * waits for a human to show the conversation 鈥?the client half asks the shell to (`openSession`) and
36
+ * this host retries while it renders 鈥?so reaching here means the shell did not render it at all.
37
37
  */
38
38
  export declare class BrowserPanelNotDisplayedError extends Error {
39
39
  readonly code = "panel-not-displayed";
@@ -47,7 +47,7 @@ export declare class BrowserPanelNotDisplayedError extends Error {
47
47
  *
48
48
  * One sidebar exists per shell window, so every view this host hands out refers
49
49
  * to the same guest: the provider keeps its tab bookkeeping, and the tabs simply
50
- * share the visible page. That is the intended behaviour for this carrier — the
50
+ * share the visible page. That is the intended behaviour for this carrier 鈥?the
51
51
  * point is a single page both parties can see.
52
52
  */
53
53
  export declare class DesktopBridgeViewHost implements ElectronBrowserViewHost {
@@ -56,7 +56,7 @@ export declare class DesktopBridgeViewHost implements ElectronBrowserViewHost {
56
56
  * One entry per view this host handed out: the conversation it serves, and the guest backing it.
57
57
  *
58
58
  * The conversation belongs to the ENTRY, not to this host. A single plugin process serves every
59
- * conversation — DSH runs them all through one host instance — so an owner held on the host
59
+ * conversation 鈥?DSH runs them all through one host instance 鈥?so an owner held on the host
60
60
  * would be one conversation's id applied to all of them, and a page could still land in
61
61
  * another's sidebar however carefully the bridge checked it.
62
62
  */
@@ -66,7 +66,7 @@ export declare class DesktopBridgeViewHost implements ElectronBrowserViewHost {
66
66
  *
67
67
  * Every DSH session is its own plugin process, and the sidebar is one surface they all share.
68
68
  * A session can only see its own `views` map, so before the bridge kept a ledger it adopted
69
- * whichever tab it found — including one another session had opened, which is how a URL from
69
+ * whichever tab it found 鈥?including one another session had opened, which is how a URL from
70
70
  * one session appeared in another's sidebar. The id is per process, so two sessions never
71
71
  * collide and one session's tabs are never handed to another; it is deliberately not the DSH
72
72
  * session id, which this layer has no access to and does not need.
@@ -74,17 +74,17 @@ export declare class DesktopBridgeViewHost implements ElectronBrowserViewHost {
74
74
  * The whole ledger rests on that premise, so it was measured rather than assumed: with two
75
75
  * sessions running, the desktop had TWO host processes (plus one main, two renderers and a
76
76
  * gpu/utility pair). If sessions ever shared a process, every owner check in the bridge would
77
- * compare equal and the bleed would return in a new shape — so a change to how DSH spawns
77
+ * compare equal and the bleed would return in a new shape 鈥?so a change to how DSH spawns
78
78
  * sessions invalidates this file, not just this comment.
79
79
  *
80
80
  * It is now the CONVERSATION id rather than an invented uuid, read from the plugin's ctx by the
81
81
  * same path DSH's own desktop host uses. That matters because the shell keeps one sidebar per
82
82
  * conversation and writes its session id onto each sidebar container (on the React fiber,
83
- * measured on the running app) — so the bridge can only answer "is this sidebar mine" if it has
83
+ * measured on the running app) 鈥?so the bridge can only answer "is this sidebar mine" if it has
84
84
  * a comparable id. With an invented uuid it never could, which is how a command came to be typed
85
85
  * into another conversation's address bar.
86
86
  *
87
- * Falls back to a random uuid when the host cannot supply one — an older DSH, or a non-desktop
87
+ * Falls back to a random uuid when the host cannot supply one 鈥?an older DSH, or a non-desktop
88
88
  * composition. That is no worse than before: the bridge then knows only "this process", and it
89
89
  * refuses to operate on a sidebar it cannot prove is its own.
90
90
  */
@@ -94,8 +94,8 @@ export declare class DesktopBridgeViewHost implements ElectronBrowserViewHost {
94
94
  * conversation each belongs to.
95
95
  *
96
96
  * The provider destroys its view handles before it asks for a release, so the mapping is dropped
97
- * by then — keeping the guest ids here is what lets us close only our own tabs when several
98
- * conversations are running (requirements §4: each session gets its own page). The owner rides
97
+ * by then 鈥?keeping the guest ids here is what lets us close only our own tabs when several
98
+ * conversations are running (requirements 搂4: each session gets its own page). The owner rides
99
99
  * along for the same reason it does in {@link views}: a release names one conversation.
100
100
  */
101
101
  private readonly orphaned;
@@ -107,7 +107,7 @@ export declare class DesktopBridgeViewHost implements ElectronBrowserViewHost {
107
107
  * handler is stored anyway so the interface contract holds (a caller may register
108
108
  * one and must not be surprised) and so a future bridge operation can deliver it
109
109
  * without changing the provider. Consequently no user-action event is emitted while
110
- * the desktop sidebar is the carrier — by design, not by omission.
110
+ * the desktop sidebar is the carrier 鈥?by design, not by omission.
111
111
  */
112
112
  private userActionHandler;
113
113
  /** Told when the shell behind this bridge exits; see `onLost`. */
@@ -151,8 +151,8 @@ export declare class DesktopBridgeViewHost implements ElectronBrowserViewHost {
151
151
  * Every page this conversation's sidebar panel currently holds.
152
152
  *
153
153
  * The shell owns page creation inside the panel: a link the user or the agent clicks may open a
154
- * new page, and nothing tells the provider. Those pages are real — they are what the human sees
155
- * — but without this the tab model reports only the ones the provider created, so the rest are
154
+ * new page, and nothing tells the provider. Those pages are real 鈥?they are what the human sees
155
+ * 鈥?but without this the tab model reports only the ones the provider created, so the rest are
156
156
  * invisible to `dsh_browser_list_tabs` and unclosable through `dsh_browser_close_tab`.
157
157
  *
158
158
  * The bridge's `list` already answers with the sidebar guests, which is the same information, so
@@ -163,14 +163,14 @@ export declare class DesktopBridgeViewHost implements ElectronBrowserViewHost {
163
163
  * Every sidebar page this conversation holds that THIS HOST did not open.
164
164
  *
165
165
  * The shell owns page creation inside the panel: a link the user or the agent clicks may open a
166
- * new page, and nothing tells the provider. Those pages are real — they are what the human sees
167
- * — but without this the tab model reports only the ones the provider created, so the rest are
166
+ * new page, and nothing tells the provider. Those pages are real 鈥?they are what the human sees
167
+ * 鈥?but without this the tab model reports only the ones the provider created, so the rest are
168
168
  * invisible to `dsh_browser_list_tabs` and unclosable through `dsh_browser_close_tab`.
169
169
  *
170
170
  * Pages this host opened are EXCLUDED here rather than deduplicated by the caller, because the
171
171
  * caller cannot do it: the provider knows a tab by its own id and the carrier knows a page by the
172
172
  * guest id, and the two never match. The first version returned everything and relied on the
173
- * caller to filter, which reported the same page twice — the mapping that makes the match
173
+ * caller to filter, which reported the same page twice 鈥?the mapping that makes the match
174
174
  * possible exists only here.
175
175
  * @returns the panel's pages that are not ours, or an empty list when the bridge cannot answer.
176
176
  */
@@ -178,7 +178,7 @@ export declare class DesktopBridgeViewHost implements ElectronBrowserViewHost {
178
178
  /**
179
179
  * Close one sidebar page by the id {@link listPages} reported.
180
180
  *
181
- * The bridge closes sidebar pages by TITLE, and only the ones the caller owns — that is what
181
+ * The bridge closes sidebar pages by TITLE, and only the ones the caller owns 鈥?that is what
182
182
  * stopped one conversation's teardown from destroying another's page. So the title is looked up
183
183
  * through the same listing, and a page that no longer appears is treated as already gone rather
184
184
  * than as an error: the caller asked for it to be closed, and it is.
@@ -188,8 +188,8 @@ export declare class DesktopBridgeViewHost implements ElectronBrowserViewHost {
188
188
  /**
189
189
  * The guest backing a view, materialized on first use.
190
190
  *
191
- * The conversation that called owns exactly one sidebar page on this carrier — a human and the
192
- * agent look at the same page — so every view resolves to that conversation's own guest, and the
191
+ * The conversation that called owns exactly one sidebar page on this carrier 鈥?a human and the
192
+ * agent look at the same page 鈥?so every view resolves to that conversation's own guest, and the
193
193
  * page does not multiply behind the provider's own tab bookkeeping.
194
194
  *
195
195
  * A cached guest is used as-is: probing it first cost a round-trip on every command, so liveness
@@ -210,8 +210,8 @@ export declare class DesktopBridgeViewHost implements ElectronBrowserViewHost {
210
210
  * This used to be empty, on the reasoning that the sidebar is already on screen so there is
211
211
  * nothing to show. That confused "the sidebar is visible" with "this page is the one being
212
212
  * looked at": opening a page left it behind whatever the human had in front, which is issue
213
- * #23. The other two carriers both do this — the self-hosted window re-adds the view and the
214
- * system browser calls `Page.bringToFront` — so this carrier was the odd one out.
213
+ * #23. The other two carriers both do this 鈥?the self-hosted window re-adds the view and the
214
+ * system browser calls `Page.bringToFront` 鈥?so this carrier was the odd one out.
215
215
  *
216
216
  * Best-effort by design: the tab strip belongs to the shell's renderer, and failing to raise
217
217
  * it must not fail the navigation that has already happened.
@@ -220,11 +220,11 @@ export declare class DesktopBridgeViewHost implements ElectronBrowserViewHost {
220
220
  showView(handle: ElectronViewHandle): void;
221
221
  onUserAction(handler: (action: BrowserUserAction) => void): void;
222
222
  /**
223
- * Release the sidebar's browser pages (requirements §3, `ui.closeWithSession`).
223
+ * Release the sidebar's browser pages (requirements 搂3, `ui.closeWithSession`).
224
224
  *
225
225
  * Destroying our own view handles is not enough on this carrier: the sidebar
226
226
  * belongs to the shell and would happily keep the page (and its renderer) alive.
227
- * Closing the tabs is what actually ends the page — and only the page: cookies
227
+ * Closing the tabs is what actually ends the page 鈥?and only the page: cookies
228
228
  * live in the partition, history on disk, so both survive.
229
229
  * @param owner - the conversation whose pages to close. Omit to close every conversation's,
230
230
  * which is only correct from a teardown that is itself global.