dsh-builtin-browser 1.0.1 → 1.0.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 (222) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/README.md +1 -1
  3. package/assets/browser-panel-locales.mjs +37 -5
  4. package/assets/browser-policy.d.mts +29 -0
  5. package/assets/browser-policy.mjs +40 -0
  6. package/desktop-bridge/desktop-discovery.d.mts +1 -1
  7. package/desktop-bridge/desktop-discovery.mjs +59 -9
  8. package/desktop-bridge/desktop-identity.json +12 -0
  9. package/desktop-bridge/install.mjs +14 -7
  10. package/desktop-bridge/plugin-browser-bridge.js +19 -7
  11. package/docs/acceptance-2026-11-27.md +67 -0
  12. package/docs/architecture.md +1 -1
  13. package/docs/development.md +33 -4
  14. package/docs/dsh-0.2.3-host-patch-task.md +34 -0
  15. package/docs/hardcoding-audit.md +28 -8
  16. package/docs/known-issues.md +26 -0
  17. package/docs/limitations.md +6 -2
  18. package/docs/tool-reference.md +1 -1
  19. package/docs/v1.1.0-bu-data-batching-task.md +66 -0
  20. package/docs/v1.1.0-compat-hardcoding-task.md +85 -0
  21. package/dsh-host-patch/README.md +4 -0
  22. package/dsh-host-patch/apply.mjs +61 -13
  23. package/dsh-host-patch/rc3-revision9.json.gz +0 -0
  24. package/dsh-host-patch/rc5-revision9.json.gz +0 -0
  25. package/dsh-host-patch/tauri/desktop-main.cjs +62 -0
  26. package/dsh-host-patch/tauri/sidebar-session.cjs +104 -0
  27. package/dsh-host-patch/tauri-revision1.json +39 -0
  28. package/dsh-host-patch/tauri.json +43 -0
  29. package/dsh-host-patch/v023-alpha2.json +153 -0
  30. package/lib/browser/anti-bot.js +215 -0
  31. package/lib/browser/deep-dom.js +39 -0
  32. package/lib/browser/runtime.js +15 -0
  33. package/lib/browser/takeover-target.js +13 -6
  34. package/lib/browser/types.js +30 -1
  35. package/lib/browser-electron/authenticated-route.js +16 -2
  36. package/lib/browser-electron/automatic-maintenance.js +16 -10
  37. package/lib/browser-electron/bridge-connection.js +3 -8
  38. package/lib/browser-electron/bridge-install.js +2 -1
  39. package/lib/browser-electron/bridge-status.js +55 -26
  40. package/lib/browser-electron/desktop-bridge-host.js +7 -6
  41. package/lib/browser-electron/desktop-identity.js +28 -5
  42. package/lib/browser-electron/desktop-shell.js +64 -0
  43. package/lib/browser-electron/electron-provision.js +105 -18
  44. package/lib/browser-electron/entry.js +129 -44
  45. package/lib/browser-electron/extension-browser.js +4 -4
  46. package/lib/browser-electron/foreground-watch.js +134 -0
  47. package/lib/browser-electron/guest-cookie-jar.js +13 -13
  48. package/lib/browser-electron/guest-route.js +181 -32
  49. package/lib/browser-electron/guest-runtime.js +61 -10
  50. package/lib/browser-electron/guest-storage.js +2 -2
  51. package/lib/browser-electron/history-store.js +1 -5
  52. package/lib/browser-electron/host-main.js +8 -4
  53. package/lib/browser-electron/host-patch-maintenance.js +14 -8
  54. package/lib/browser-electron/maintenance-route.js +2 -1
  55. package/lib/browser-electron/missing-system-browser.js +5 -9
  56. package/lib/browser-electron/preferred-browser.js +7 -3
  57. package/lib/browser-electron/preview-route.js +9 -13
  58. package/lib/browser-electron/process-ownership.js +1 -1
  59. package/lib/browser-electron/profile-command.js +2 -1
  60. package/lib/browser-electron/profile-extension.js +5 -0
  61. package/lib/browser-electron/profile-lease.js +152 -47
  62. package/lib/browser-electron/provider-core.js +527 -0
  63. package/lib/browser-electron/provider-interaction.js +963 -0
  64. package/lib/browser-electron/provider-media.js +518 -0
  65. package/lib/browser-electron/provider-navigation.js +301 -0
  66. package/lib/browser-electron/provider-observation.js +623 -0
  67. package/lib/browser-electron/provider-tabs.js +372 -0
  68. package/lib/browser-electron/provider.js +150 -3301
  69. package/lib/browser-electron/reference-route.js +9 -18
  70. package/lib/browser-electron/remote-host.js +79 -34
  71. package/lib/browser-electron/runtime-status.js +56 -6
  72. package/lib/browser-electron/settings-store.js +3 -6
  73. package/lib/browser-electron/sidebar-only-host.js +1 -1
  74. package/lib/browser-electron/system-browser.js +539 -172
  75. package/lib/browser-electron/tauri-host.js +208 -0
  76. package/lib/browser-electron/virtual-cursor.js +23 -13
  77. package/lib/browser-reference/service.js +22 -4
  78. package/lib/browser-reference/web-sources.js +1 -1
  79. package/lib/client.js +43409 -0
  80. package/lib/compat/host-features.js +75 -0
  81. package/lib/reference-source.js +1 -1
  82. package/lib/reference-text.js +23 -1
  83. package/lib/takeover-protocol.js +1 -1
  84. package/lib/tool-browser/block-recovery.js +69 -0
  85. package/lib/tool-browser/code-tool.js +170 -19
  86. package/lib/tool-browser/code-worker.js +115 -20
  87. package/lib/tool-browser/errors.js +34 -0
  88. package/lib/tool-browser/index.js +66 -3593
  89. package/lib/tool-browser/page-probe.js +227 -28
  90. package/lib/tool-browser/panel-page.js +2 -1
  91. package/lib/tool-browser/probe-client.js +157 -0
  92. package/lib/tool-browser/screenshot-annotations.js +108 -0
  93. package/lib/tool-browser/state.js +337 -0
  94. package/lib/tool-browser/takeover.js +1 -1
  95. package/lib/tool-browser/tools-debug.js +862 -0
  96. package/lib/tool-browser/tools-interaction.js +993 -0
  97. package/lib/tool-browser/tools-navigation.js +807 -0
  98. package/lib/tool-browser/tools-observation.js +461 -0
  99. package/lib/tool-browser/tools-reference.js +293 -0
  100. package/lib/web-guest.js +1 -0
  101. package/package.json +16 -36
  102. package/scripts/build-client.mjs +305 -0
  103. package/scripts/build.mjs +15 -12
  104. package/scripts/fix-exports.mjs +6 -16
  105. package/scripts/install-electron.mjs +55 -5
  106. package/scripts/pack.mjs +99 -0
  107. package/scripts/publish-manifest.mjs +56 -0
  108. package/scripts/verify-exports.mjs +26 -15
  109. package/skills/dsh-builtin-browser/SKILL.md +27 -2
  110. package/skills/dsh-builtin-browser/references/batch.md +15 -0
  111. package/src/browser/anti-bot.ts +251 -0
  112. package/src/browser/deep-dom.ts +40 -0
  113. package/src/browser/runtime.ts +18 -0
  114. package/src/browser/takeover-target.ts +16 -7
  115. package/src/browser/types.ts +56 -3
  116. package/src/browser-electron/authenticated-route.ts +29 -4
  117. package/src/browser-electron/automatic-maintenance.ts +23 -13
  118. package/src/browser-electron/bridge-connection.ts +11 -10
  119. package/src/browser-electron/bridge-install.ts +2 -1
  120. package/src/browser-electron/bridge-status.ts +61 -22
  121. package/src/browser-electron/desktop-bridge-host.ts +9 -7
  122. package/src/browser-electron/desktop-identity.ts +38 -5
  123. package/src/browser-electron/desktop-shell.ts +100 -0
  124. package/src/browser-electron/electron-provision.ts +104 -18
  125. package/src/browser-electron/entry.ts +1378 -1299
  126. package/src/browser-electron/extension-browser.ts +11 -4
  127. package/src/browser-electron/foreground-watch.ts +142 -0
  128. package/src/browser-electron/guest-cookie-jar.ts +3 -2
  129. package/src/browser-electron/guest-route.ts +180 -32
  130. package/src/browser-electron/guest-runtime.ts +61 -10
  131. package/src/browser-electron/guest-storage.ts +5 -2
  132. package/src/browser-electron/history-store.ts +3 -6
  133. package/src/browser-electron/host-main.ts +8 -4
  134. package/src/browser-electron/host-patch-maintenance.ts +18 -9
  135. package/src/browser-electron/maintenance-route.ts +2 -1
  136. package/src/browser-electron/missing-system-browser.ts +11 -10
  137. package/src/browser-electron/preferred-browser.ts +13 -3
  138. package/src/browser-electron/preview-route.ts +9 -12
  139. package/src/browser-electron/process-ownership.ts +9 -3
  140. package/src/browser-electron/profile-command.ts +2 -1
  141. package/src/browser-electron/profile-extension.ts +5 -0
  142. package/src/browser-electron/profile-lease.ts +131 -35
  143. package/src/browser-electron/provider-core.ts +1107 -0
  144. package/src/browser-electron/provider-interaction.ts +1034 -0
  145. package/src/browser-electron/provider-media.ts +589 -0
  146. package/src/browser-electron/provider-navigation.ts +323 -0
  147. package/src/browser-electron/provider-observation.ts +664 -0
  148. package/src/browser-electron/provider-tabs.ts +372 -0
  149. package/src/browser-electron/provider.ts +158 -4063
  150. package/src/browser-electron/reference-route.ts +598 -608
  151. package/src/browser-electron/remote-host.ts +118 -42
  152. package/src/browser-electron/runtime-status.ts +80 -13
  153. package/src/browser-electron/settings-store.ts +10 -6
  154. package/src/browser-electron/sidebar-only-host.ts +4 -2
  155. package/src/browser-electron/system-browser.ts +537 -184
  156. package/src/browser-electron/tauri-host.ts +194 -0
  157. package/src/browser-electron/virtual-cursor.ts +24 -14
  158. package/src/browser-reference/service.ts +38 -7
  159. package/src/browser-reference/web-sources.ts +4 -1
  160. package/src/client/apply-guard.ts +22 -0
  161. package/src/client/browser/BrowserController.ts +3 -3
  162. package/src/client/browser/IframeImpl.ts +182 -176
  163. package/src/client/browser/frame-history.ts +125 -0
  164. package/src/client/browser/frame-state.ts +27 -0
  165. package/src/client/browser/web-reference-source.ts +5 -1
  166. package/src/client/definition.tsx +36 -30
  167. package/src/client/electron/ElectronWebViewImpl.ts +20 -13
  168. package/src/client/electron/ElectronWebviewPresentation.ts +4 -2
  169. package/src/client/electron/NativeChildPresentation.ts +11 -3
  170. package/src/client/electron/NativeViewPage.ts +19 -5
  171. package/src/client/index.ts +333 -293
  172. package/src/client/locales.ts +9 -6
  173. package/src/client/reference/client/plugin.ts +21 -2
  174. package/src/client/reference/client/production/ReferenceCapsules.tsx +3 -3
  175. package/src/client/reference/client/production/assembly.ts +4 -28
  176. package/src/client/reference/client/production/availability.ts +0 -2
  177. package/src/client/reference/client/production/composer-attachments.ts +44 -0
  178. package/src/client/reference/client/production/draft-adapter.ts +4 -0
  179. package/src/client/reference/client/production/http-transport.ts +0 -5
  180. package/src/client/reference/client/production/production-submission.ts +50 -290
  181. package/src/client/reference/client/production/protocol.ts +7 -4
  182. package/src/client/reference/client/production/runtime.ts +41 -86
  183. package/src/client/reference/client/production/source-marker.ts +49 -13
  184. package/src/client/reference/client/production/user-text-rule.ts +10 -1
  185. package/src/client/reference/client/reveal.ts +3 -1
  186. package/src/client/reference/client/session-schedule.ts +36 -0
  187. package/src/client/settings/index.ts +8 -0
  188. package/src/client/settings/mount-guard.ts +31 -0
  189. package/src/client/settings/panel.ts +163 -52
  190. package/src/client/startpage/controller.ts +3 -6
  191. package/src/client/view/BrowserBody.tsx +2 -1
  192. package/src/client/view/IframePresentation.ts +37 -16
  193. package/src/client/view/StartPage.tsx +2 -1
  194. package/src/compat/host-features.ts +92 -0
  195. package/src/reference-source.ts +1 -1
  196. package/src/reference-text.ts +23 -1
  197. package/src/takeover-protocol.ts +11 -2
  198. package/src/tool-browser/block-recovery.ts +85 -0
  199. package/src/tool-browser/code-tool.ts +173 -19
  200. package/src/tool-browser/code-worker.ts +101 -15
  201. package/src/tool-browser/errors.ts +40 -0
  202. package/src/tool-browser/index.ts +66 -3534
  203. package/src/tool-browser/page-probe.ts +229 -28
  204. package/src/tool-browser/panel-page.ts +3 -1
  205. package/src/tool-browser/probe-client.ts +183 -0
  206. package/src/tool-browser/screenshot-annotations.ts +131 -0
  207. package/src/tool-browser/state.ts +375 -0
  208. package/src/tool-browser/takeover.ts +3 -2
  209. package/src/tool-browser/tools-debug.ts +806 -0
  210. package/src/tool-browser/tools-interaction.ts +956 -0
  211. package/src/tool-browser/tools-navigation.ts +786 -0
  212. package/src/tool-browser/tools-observation.ts +474 -0
  213. package/src/tool-browser/tools-reference.ts +294 -0
  214. package/src/web-guest.ts +35 -34
  215. package/dist/client.cjs +0 -43167
  216. package/dist/client.d.cts +0 -516
  217. package/dist/client.d.mts +0 -516
  218. package/dist/index.cjs +0 -92
  219. package/dist/index.d.mts +0 -2960
  220. package/dist/index.mjs +0 -24
  221. package/lib/browser-reference/submission-receipts.js +0 -139
  222. package/src/browser-reference/submission-receipts.ts +0 -122
@@ -0,0 +1,194 @@
1
+ /**
2
+ * DSH Tauri (dsh-tauri/deepseek-harness-desktop) as a sidebar host.
3
+ *
4
+ * DSH Tauri does not run DeepSeek Harness Desktop's `lib/main.js`: its Electron main process is
5
+ * electron-rs, staged in `runtime/<platform>-<arch>` beside an `electron-rs.json` whose identifier
6
+ * names the app. Its sidebar guests get an in-memory partition, so the sidebar host patch
7
+ * (`dsh-host-patch/tauri.json`) targets `runtime/browser.cjs` there. The plugin's own Node process
8
+ * is that same Electron binary in Node mode, so a running Tauri is recognised from `process.execPath`.
9
+ * @module dsh-browser/browser-electron/tauri-host
10
+ */
11
+ import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
12
+ import { basename, dirname, join } from 'node:path'
13
+ import { fileURLToPath } from 'node:url'
14
+ import { dshHome } from './paths.ts'
15
+ import { registeredInstallLocations } from '../../desktop-bridge/desktop-discovery.mjs'
16
+
17
+ const { hostPatchStatus }: { hostPatchStatus: (directory: string) => TauriHostPatch } = await import(new URL('../../dsh-host-patch/apply.mjs', import.meta.url).href)
18
+
19
+ interface TauriRule {
20
+ readonly identifiers: readonly string[]
21
+ readonly metadata: string
22
+ readonly runtimeRoots: readonly string[]
23
+ readonly installNames: readonly string[]
24
+ readonly registryName: string
25
+ }
26
+
27
+ /** One DSH Tauri electron-rs runtime directory. */
28
+ export interface TauriRuntime {
29
+ /** The install root, when the runtime sits at one of the rule's runtime roots. */
30
+ readonly root?: string
31
+ /** `runtime/<platform>-<arch>`: the directory the host patch is applied to. */
32
+ readonly runtime: string
33
+ readonly identifier: string
34
+ readonly appName?: string
35
+ readonly running: boolean
36
+ }
37
+
38
+ /** Host patch state of a Tauri runtime, as `dsh-host-patch/apply.mjs` reports it. */
39
+ export interface TauriHostPatch {
40
+ readonly status: string
41
+ readonly reason?: string
42
+ }
43
+
44
+ /**
45
+ * Read the Tauri part of the shared identity rule.
46
+ * @returns the rule, or undefined when it cannot be read.
47
+ */
48
+ export function readTauriRule(): TauriRule | undefined {
49
+ try {
50
+ const rule = (JSON.parse(readFileSync(new URL('../../desktop-bridge/desktop-identity.json', import.meta.url), 'utf8')) as { tauri?: TauriRule }).tauri
51
+ const strings = (value: unknown): value is readonly string[] => Array.isArray(value) && value.length > 0 && value.every(item => typeof item === 'string' && item !== '')
52
+ if (rule === undefined || !strings(rule.identifiers) || !strings(rule.runtimeRoots) || !strings(rule.installNames)
53
+ || typeof rule.metadata !== 'string' || typeof rule.registryName !== 'string') return undefined
54
+ return rule
55
+ } catch {
56
+ return undefined
57
+ }
58
+ }
59
+
60
+ function metadataOf(directory: string, rule: TauriRule): { identifier: string; appName?: string; target?: string; arch?: string } | undefined {
61
+ try {
62
+ const value = JSON.parse(readFileSync(join(directory, rule.metadata), 'utf8')) as Record<string, unknown>
63
+ if (typeof value.identifier !== 'string' || !rule.identifiers.includes(value.identifier)) return undefined
64
+ return {
65
+ identifier: value.identifier,
66
+ ...typeof value.appName === 'string' ? { appName: value.appName } : {},
67
+ ...typeof value.target === 'string' ? { target: value.target } : {},
68
+ ...typeof value.arch === 'string' ? { arch: value.arch } : {},
69
+ }
70
+ } catch {
71
+ return undefined
72
+ }
73
+ }
74
+
75
+ function rootOf(runtime: string, rule: TauriRule): string | undefined {
76
+ for (const base of [...rule.runtimeRoots].sort((a, b) => b.split('/').length - a.split('/').length)) {
77
+ const parts = base.split('/')
78
+ let directory = dirname(runtime)
79
+ let matches = true
80
+ for (const part of [...parts].reverse()) {
81
+ if (basename(directory) !== part) { matches = false; break }
82
+ directory = dirname(directory)
83
+ }
84
+ if (matches) return directory
85
+ }
86
+ return undefined
87
+ }
88
+
89
+ /**
90
+ * The Tauri runtime this process runs from, when the plugin is hosted by DSH Tauri. On macOS the
91
+ * Electron binary sits in `<runtime>/<name>.app/Contents/MacOS/`, beside which electron-rs keeps
92
+ * `electron-rs.json` and `runtime/`, so the directory holding the `.app` is the runtime.
93
+ * @param execPath - the running executable.
94
+ * @returns the runtime, or undefined outside DSH Tauri.
95
+ */
96
+ export function runningTauriRuntime(execPath: string = process.execPath): TauriRuntime | undefined {
97
+ const rule = readTauriRule()
98
+ if (rule === undefined) return undefined
99
+ const binary = dirname(execPath)
100
+ const bundle = basename(binary) === 'MacOS' && basename(dirname(binary)) === 'Contents' && dirname(dirname(binary)).endsWith('.app')
101
+ ? dirname(dirname(dirname(binary))) : undefined
102
+ const runtime = [binary, bundle].find(directory => directory !== undefined && metadataOf(directory, rule) !== undefined)
103
+ if (runtime === undefined) return undefined
104
+ const metadata = metadataOf(runtime, rule)!
105
+ const root = rootOf(runtime, rule)
106
+ return { ...root === undefined ? {} : { root }, runtime, identifier: metadata.identifier, ...metadata.appName === undefined ? {} : { appName: metadata.appName }, running: true }
107
+ }
108
+
109
+ /**
110
+ * The runtime of a DSH Tauri install root that matches this machine.
111
+ * @param root - a candidate install directory.
112
+ * @param platform - the platform the runtime must target.
113
+ * @param arch - the architecture the runtime must target.
114
+ * @returns the runtime, or undefined when the directory is not DSH Tauri.
115
+ */
116
+ export function tauriRuntimeOf(root: string, platform: string = process.platform, arch: string = process.arch): TauriRuntime | undefined {
117
+ const rule = readTauriRule()
118
+ if (rule === undefined) return undefined
119
+ for (const base of rule.runtimeRoots) {
120
+ const directory = join(root, ...base.split('/'))
121
+ let entries: string[] = []
122
+ try { entries = readdirSync(directory, { withFileTypes: true }).filter(entry => entry.isDirectory()).map(entry => entry.name) } catch { continue }
123
+ for (const name of entries) {
124
+ const runtime = join(directory, name)
125
+ const metadata = metadataOf(runtime, rule)
126
+ if (metadata === undefined) continue
127
+ if ((metadata.target !== undefined && metadata.target !== platform) || (metadata.arch !== undefined && metadata.arch !== arch)) continue
128
+ return { root, runtime, identifier: metadata.identifier, ...metadata.appName === undefined ? {} : { appName: metadata.appName }, running: false }
129
+ }
130
+ }
131
+ return undefined
132
+ }
133
+
134
+ /**
135
+ * Find DSH Tauri: the running host first, then the usual install locations.
136
+ * @param options - discovery overrides for tests.
137
+ * @returns the runtime, or undefined when no DSH Tauri is found.
138
+ */
139
+ export function findTauriRuntime(options: {
140
+ readonly execPath?: string
141
+ readonly localAppData?: string
142
+ readonly registry?: () => readonly string[]
143
+ } = {}): TauriRuntime | undefined {
144
+ const running = runningTauriRuntime(options.execPath)
145
+ if (running !== undefined) return running
146
+ const rule = readTauriRule()
147
+ if (rule === undefined) return undefined
148
+ const bases = options.localAppData !== undefined ? [options.localAppData]
149
+ : [process.env.LOCALAPPDATA, join(process.env.LOCALAPPDATA ?? '', 'Programs'), process.env.ProgramFiles, process.env['ProgramFiles(x86)']]
150
+ .filter((base): base is string => typeof base === 'string' && base !== '' && base !== 'Programs')
151
+ const candidates = [
152
+ ...[process.env.DSH_DESKTOP_PATH, process.env.DSH_DESKTOP_APP].filter((path): path is string => typeof path === 'string' && path !== ''),
153
+ ...bases.flatMap(base => rule.installNames.map(name => join(base, name))),
154
+ ]
155
+ for (const candidate of candidates) {
156
+ if (!existsSync(candidate)) continue
157
+ const found = tauriRuntimeOf(candidate)
158
+ if (found !== undefined) return found
159
+ }
160
+ let registered: readonly string[] = []
161
+ try { registered = (options.registry ?? (() => registeredInstallLocations(process.platform, undefined, rule.registryName)))() } catch {}
162
+ for (const candidate of registered) {
163
+ const found = tauriRuntimeOf(candidate)
164
+ if (found !== undefined) return found
165
+ }
166
+ return undefined
167
+ }
168
+
169
+ /**
170
+ * Read the sidebar host patch state of a Tauri runtime without writing.
171
+ * @param runtime - the runtime directory.
172
+ * @returns the patch status.
173
+ */
174
+ export function tauriHostPatchStatus(runtime: string): TauriHostPatch {
175
+ try { return hostPatchStatus(runtime) } catch (error) { return { status: 'anchors mismatch', reason: String(error) } }
176
+ }
177
+
178
+ /**
179
+ * Name this plugin's package to the Tauri host patch, which starts its `dsh.desktop.main` (the sidebar
180
+ * bridge) inside electron-rs: Tauri has no Desktop main-extension loader to find it in the profile.
181
+ * @param home - the DSH home the host patch reads.
182
+ * @param root - this plugin's package directory.
183
+ * @returns the pointer file path.
184
+ */
185
+ export function publishTauriDesktopMain(home: string = dshHome(), root: string = fileURLToPath(new URL('../../', import.meta.url))): string {
186
+ const file = join(home, 'dsh-builtin-browser-desktop-main.json')
187
+ const text = JSON.stringify({ root }) + '\n'
188
+ try { if (readFileSync(file, 'utf8') === text) return file } catch { /* absent */ }
189
+ const temporary = `${file}.${process.pid}.tmp`
190
+ mkdirSync(home, { recursive: true })
191
+ writeFileSync(temporary, text, { mode: 0o600 })
192
+ renameSync(temporary, file)
193
+ return file
194
+ }
@@ -12,6 +12,10 @@
12
12
  * `<style>` element would be subject to the page's `style-src` CSP, an
13
13
  * injected script is not. Injected page feedback must never be silently
14
14
  * dropped by a strict CSP.
15
+ * - The overlay mounts inside a closed shadow root (keyed via a Symbol on the
16
+ * host node) and translates an inner stage wrapper so neither `innerText`,
17
+ * deep-DOM shadow-root walkers (`content(markdown)`, `findText`, `anti-bot`),
18
+ * nor top-document attribute `MutationObserver`s (`wait_idle`) observe it.
15
19
  * - Every call is best-effort: feedback is never allowed to fail an operation.
16
20
  * @module dsh-browser/browser-electron/virtual-cursor
17
21
  */
@@ -20,7 +24,7 @@
20
24
  export type CursorAction = 'move' | 'click'
21
25
 
22
26
  /** Element id of the overlay root, stable so repeat calls update one node. */
23
- const CURSOR_ID = '__dsh_agent_cursor__'
27
+ export const CURSOR_ID = '__dsh_agent_cursor__'
24
28
 
25
29
  /**
26
30
  * Where the overlay was last placed, so an unchanged position is not repainted.
@@ -64,30 +68,36 @@ export function cursorNeedsPaint<TView>(handle: TView, x: number, y: number, act
64
68
  export function cursorScript(x: number, y: number, action: CursorAction, label?: string): string {
65
69
  return `(() => {
66
70
  const id = ${JSON.stringify(CURSOR_ID)}
71
+ const key = Symbol.for('__dsh_agent_cursor_shadow__')
67
72
  let root = document.getElementById(id)
68
73
  if (!root) {
69
74
  root = document.createElement('div')
70
75
  root.id = id
71
76
  root.setAttribute('aria-hidden', 'true')
72
- root.style.cssText = 'position:fixed;left:0;top:0;width:0;height:0;z-index:2147483647;pointer-events:none;transition:transform 190ms cubic-bezier(.22,.85,.24,1);will-change:transform'
77
+ root.style.cssText = 'position:fixed;left:0;top:0;width:0;height:0;z-index:2147483647;pointer-events:none'
73
78
  const svg = '<svg width="22" height="22" viewBox="0 0 22 22" style="position:absolute;left:-2px;top:-2px;filter:drop-shadow(0 1px 2px rgba(0,0,0,.45))">'
74
79
  + '<path d="M4 2 L4 18 L8.4 13.8 L11.2 19.6 L13.8 18.4 L11 12.8 L17 12.6 Z" fill="#ffffff" stroke="#111111" stroke-width="1.4" stroke-linejoin="round"/></svg>'
75
80
  const ripple = '<span data-dsh-role="ripple" style="position:absolute;left:0;top:0;width:34px;height:34px;margin:-17px 0 0 -17px;border-radius:50%;border:2px solid rgba(64,160,255,.9);opacity:0"></span>'
76
81
  // The bubble sits below-right of the pointer tip and is capped in width so a long
77
82
  // label cannot cover the page it is describing.
78
83
  const bubble = '<span data-dsh-role="bubble" style="position:absolute;left:18px;top:16px;max-width:280px;padding:3px 8px;border-radius:5px;background:rgba(17,17,17,.92);color:#fff;font:12px/1.45 -apple-system,Segoe UI,Roboto,sans-serif;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;opacity:0;box-shadow:0 1px 3px rgba(0,0,0,.4)"></span>'
79
- root.innerHTML = svg + ripple + bubble
84
+ const stage = '<div data-dsh-role="stage" style="position:fixed;left:0;top:0;width:0;height:0;pointer-events:none;transition:transform 190ms cubic-bezier(.22,.85,.24,1);will-change:transform">' + svg + ripple + bubble + '</div>'
85
+ const parts = typeof root.attachShadow === 'function' ? root.attachShadow({ mode: 'closed' }) : root
86
+ parts.innerHTML = stage
87
+ root[key] = parts
80
88
  ;(document.body || document.documentElement).appendChild(root)
81
89
  }
82
- root.style.transform = 'translate(${x}px, ${y}px)'
83
- ${action === 'click' ? `const ripple = root.querySelector('[data-dsh-role="ripple"]')
90
+ const parts = root[key] || root
91
+ const stage = parts.querySelector('[data-dsh-role="stage"]') || root
92
+ stage.style.transform = 'translate(${x}px, ${y}px)'
93
+ ${action === 'click' ? `const ripple = parts.querySelector('[data-dsh-role="ripple"]')
84
94
  if (ripple && typeof ripple.animate === 'function') {
85
95
  ripple.animate(
86
96
  [{ transform: 'scale(.25)', opacity: 0.95 }, { transform: 'scale(1.6)', opacity: 0 }],
87
97
  { duration: 550, easing: 'ease-out' },
88
98
  )
89
99
  }` : ''}
90
- ${label !== undefined && label !== '' ? `const bubble = root.querySelector('[data-dsh-role="bubble"]')
100
+ ${label !== undefined && label !== '' ? `const bubble = parts.querySelector('[data-dsh-role="bubble"]')
91
101
  if (bubble) {
92
102
  bubble.textContent = ${JSON.stringify(label)}
93
103
  if (typeof bubble.animate === 'function') {
@@ -122,10 +132,10 @@ export function forgetCursor<TView>(handle: TView): void {
122
132
  /**
123
133
  * Draw (or move) the pointer overlay on one view's page.
124
134
  *
125
- * Fire-and-forget: a page that is mid-navigation, cross-origin-blocked, or
126
- * otherwise unable to answer must not turn a successful operation into a
127
- * failure, and the navigation that just committed may still be replacing the
128
- * document this call would have painted into.
135
+ * Best-effort: a page that is mid-navigation, cross-origin-blocked, or otherwise
136
+ * unable to answer must not turn a successful operation into a failure. Returns
137
+ * a settled promise so callers like click() can optionally wait briefly for the
138
+ * paint before dispatching mouse events without racing the press/release pair.
129
139
  * @param handle - the view to paint into.
130
140
  * @param x - viewport x in CSS pixels.
131
141
  * @param y - viewport y in CSS pixels.
@@ -141,12 +151,12 @@ export function paintCursor<TView>(
141
151
  evaluate: (handle: TView, expression: string) => Promise<unknown>,
142
152
  label?: string,
143
153
  force = false,
144
- ): void {
145
- if (!Number.isFinite(x) || !Number.isFinite(y)) return
154
+ ): Promise<void> {
155
+ if (!Number.isFinite(x) || !Number.isFinite(y)) return Promise.resolve()
146
156
  const roundedX = Math.round(x)
147
157
  const roundedY = Math.round(y)
148
- if (!cursorNeedsPaint(handle, roundedX, roundedY, action, force)) return
158
+ if (!cursorNeedsPaint(handle, roundedX, roundedY, action, force)) return Promise.resolve()
149
159
  const key = handle as unknown as object
150
160
  if (key !== null && typeof key === 'object') lastPlaced.set(key, { x: roundedX, y: roundedY, action })
151
- void evaluate(handle, cursorScript(roundedX, roundedY, action, label)).catch(() => {})
161
+ return Promise.resolve(evaluate(handle, cursorScript(roundedX, roundedY, action, label))).then(() => undefined, () => undefined)
152
162
  }
@@ -18,6 +18,7 @@
18
18
  import { createHash, randomUUID } from 'node:crypto'
19
19
  import { referenceOwnerKey } from '../reference-owner.ts'
20
20
  import { webReferenceSources, type WebReferenceSources } from './web-sources.ts'
21
+ import { fetchGuestResource } from '../browser-electron/guest-route.ts'
21
22
  import { sameReferenceDocument as samePage } from '../reference-page.ts'
22
23
  import { isReferenceText, normalizeReferenceText, MAX_REFERENCE_TEXT, referenceTextContent, renderReferenceText } from '../reference-text.ts'
23
24
  import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
@@ -96,6 +97,8 @@ export interface ReferenceHost {
96
97
  exists(sessionId: string): boolean
97
98
  /** Save one URL to a local file with the session's cookies, when the carrier can. */
98
99
  download?(sessionId: string, url: string, savePath: string, signal?: AbortSignal): Promise<void>
100
+ /** Save one image a Web sidebar page loaded, fetched the way the guest proxy loaded it; a frozen Web capture has no browser session. */
101
+ fetchWebImage?(url: string, savePath: string, web: WebImageContext, signal?: AbortSignal): Promise<void>
99
102
  /**
100
103
  * Capture a clipped, read-only visible-region screenshot. Optional: a host
101
104
  * without this capability keeps the source-image / rasterised-image paths.
@@ -105,6 +108,18 @@ export interface ReferenceHost {
105
108
  newId?(): string
106
109
  }
107
110
 
111
+ type ImagePolicy = {
112
+ readonly verifyImageVersion: boolean
113
+ readonly allowVisibleSnapshot: boolean
114
+ /** Set for a frozen Web capture: its images come from the page's own URLs, never a browser session. */
115
+ readonly web?: WebImageContext
116
+ }
117
+
118
+ type WebImageContext = {
119
+ /** The Host the capture reached DSH on: the guest proxy refuses it as a target, so this fetch does too. */
120
+ readonly dshHost?: string
121
+ }
122
+
108
123
  type MaterializedAsset = {
109
124
  assetKey: string
110
125
  representation: 'source-image' | 'rasterized-image' | 'visible-snapshot'
@@ -167,6 +182,8 @@ export interface CaptureOutcome {
167
182
 
168
183
  /** What the caller wants captured. */
169
184
  export interface CaptureRequest {
185
+ /** The Host header the capture request reached DSH on; a frozen Web capture never fetches its images from it. */
186
+ readonly dshHost?: string
170
187
  readonly sourcePageId?: string
171
188
  /** The DSH session that owns the reference. */
172
189
  readonly sessionId: string
@@ -492,6 +509,7 @@ export class BrowserReferenceService {
492
509
  if (request.sourcePageId !== undefined && (!fromFrozen || !this.webSources?.owns(sessionId, request.sourcePageId))) {
493
510
  return { failures: [{ kind: 'reference', reason: 'web-source-not-owned' }] }
494
511
  }
512
+ const webImages = fromFrozen && request.sourcePageId !== undefined
495
513
  if (!fromFrozen && !this.host.exists(browserSessionId)) {
496
514
  return { failures: [{ kind: 'reference', reason: 'session-unavailable' }] }
497
515
  }
@@ -586,6 +604,7 @@ export class BrowserReferenceService {
586
604
  } else if (kind === 'image') {
587
605
  const imagePart = await this.imagePart(browserSessionId, event as RawCaptureEvent, nextPartId, signal, {
588
606
  verifyImageVersion: request.verifyImageVersion !== false,
607
+ ...webImages ? { web: request.dshHost === undefined ? {} : { dshHost: request.dshHost } } : {},
589
608
  allowVisibleSnapshot: request.allowVisibleSnapshot !== false,
590
609
  })
591
610
  if ('reason' in imagePart) failures.push(imagePart)
@@ -595,6 +614,7 @@ export class BrowserReferenceService {
595
614
  // A cell image is one image, not "whatever region is selected"; a
596
615
  // masked visible snapshot of the table would misreport it.
597
616
  verifyImageVersion: request.verifyImageVersion !== false,
617
+ ...webImages ? { web: request.dshHost === undefined ? {} : { dshHost: request.dshHost } } : {},
598
618
  allowVisibleSnapshot: false,
599
619
  })
600
620
  if ('reason' in tablePart) failures.push(tablePart)
@@ -851,7 +871,7 @@ export class BrowserReferenceService {
851
871
  event: RawCaptureEvent,
852
872
  nextPartId: () => string,
853
873
  signal?: AbortSignal,
854
- policy: { readonly verifyImageVersion: boolean; readonly allowVisibleSnapshot: boolean } = {
874
+ policy: ImagePolicy = {
855
875
  verifyImageVersion: true, allowVisibleSnapshot: true,
856
876
  },
857
877
  ): Promise<ImageReferencePart | CaptureFailure> {
@@ -923,10 +943,16 @@ export class BrowserReferenceService {
923
943
  sessionId: string,
924
944
  image: { readonly urls: readonly string[]; readonly path?: readonly number[]; readonly selector?: string },
925
945
  signal?: AbortSignal,
926
- policy: { readonly verifyImageVersion: boolean; readonly allowVisibleSnapshot: boolean } = {
946
+ policy: ImagePolicy = {
927
947
  verifyImageVersion: true, allowVisibleSnapshot: true,
928
948
  },
929
949
  ): Promise<MaterializedAsset | { reason: string; detail?: Record<string, unknown> }> {
950
+ const web = policy.web
951
+ const { download, fetchWebImage } = this.host
952
+ const fetchImage: ((url: string, savePath: string) => Promise<void>) | undefined = web === undefined
953
+ ? download && ((url, savePath) => download.call(this.host, sessionId, url, savePath, signal))
954
+ : fetchWebImage && ((url, savePath) => fetchWebImage.call(this.host, url, savePath, web, signal))
955
+ let webFailure: string | undefined
930
956
  let versionChangedUrl = ''
931
957
  for (const url of image.urls) {
932
958
  if (/^data:image\//i.test(url)) {
@@ -937,15 +963,15 @@ export class BrowserReferenceService {
937
963
  }
938
964
  continue
939
965
  }
940
- if (/^https?:/i.test(url) && this.host.download !== undefined) {
966
+ if (/^https?:/i.test(url) && fetchImage !== undefined) {
941
967
  const temp = join(this.assetDir, '.tmp', `${randomUUID()}.bin`)
942
968
  mkdirSync(dirname(temp), { recursive: true })
943
969
  try {
944
- await this.host.download(sessionId, url, temp, signal)
970
+ await fetchImage(url, temp)
945
971
  const bytes = readFileSync(temp)
946
972
  if (bytes.length > 0 && bytes.length <= this.options.maxImageBytes) {
947
973
  let status: VersionStatus = 'unverifiable'
948
- if (policy.verifyImageVersion) {
974
+ if (policy.verifyImageVersion && web === undefined) {
949
975
  try {
950
976
  const probe = await this.run<unknown>(sessionId, versionProbeScript(), [{ url }], signal)
951
977
  status = compareImageVersion(probe, bytes)
@@ -963,12 +989,14 @@ export class BrowserReferenceService {
963
989
  const saved = this.saveAsset(bytes, url, 'source-image', { versionStatus: status })
964
990
  if (saved !== undefined) return { ...saved, versionStatus: status }
965
991
  }
966
- } catch { /* the page-side raster below is the next honest attempt */ } finally {
992
+ } catch (error) { webFailure = messageOf(error) } finally {
967
993
  try { rmSync(temp, { force: true }) } catch { /* temp file already gone */ }
968
994
  }
969
995
  }
970
996
  }
971
997
 
998
+ // Nothing can rasterize or screenshot a page that has no browser session.
999
+ if (web !== undefined) return { reason: 'image-unavailable', detail: { web: webFailure ?? (fetchImage === undefined ? 'no-web-image-fetch' : 'no-image-bytes') } }
972
1000
  let rasterReason: string | undefined
973
1001
  try {
974
1002
  const raster = await this.run<RawRasterResult>(sessionId, rasterizeScript(), [{
@@ -1093,7 +1121,7 @@ export class BrowserReferenceService {
1093
1121
  event: RawCaptureEvent,
1094
1122
  nextPartId: () => string,
1095
1123
  signal?: AbortSignal,
1096
- policy: { readonly verifyImageVersion: boolean; readonly allowVisibleSnapshot: boolean } = {
1124
+ policy: ImagePolicy = {
1097
1125
  verifyImageVersion: true, allowVisibleSnapshot: false,
1098
1126
  },
1099
1127
  ): Promise<{ part: TableReferencePart; cellImages: ImageReferencePart[]; failures: CaptureFailure[] } | CaptureFailure> {
@@ -1310,6 +1338,9 @@ export function createReferenceService(
1310
1338
  download: async (sessionId, url, savePath, signal) => {
1311
1339
  await browser.download(sessionId, { url, savePath }, signal)
1312
1340
  },
1341
+ fetchWebImage: async (url, savePath, web, signal) => {
1342
+ writeFileSync(savePath, await fetchGuestResource(url, { ...web, maxBytes: rest.maxImageBytes ?? 20 * 1024 * 1024, ...signal === undefined ? {} : { signal } }))
1343
+ },
1313
1344
  ...visibleCapture !== undefined ? { captureVisible: visibleCapture } : {},
1314
1345
  }, store ?? new ReferenceStore(), { webSources: webReferenceSources(browser), ...rest })
1315
1346
  }
@@ -25,7 +25,10 @@ interface Source {
25
25
  /** App-owned iframe leases; no guest can register or acknowledge a command. */
26
26
  export class WebReferenceSources {
27
27
  private readonly leases = new Map<string, Source>()
28
- constructor(private readonly timeoutMs = 8_000) {}
28
+ private readonly timeoutMs: number
29
+ constructor(timeoutMs = 8_000) {
30
+ this.timeoutMs = timeoutMs
31
+ }
29
32
 
30
33
  private prune(): void {
31
34
  for (const [lease, source] of this.leases) {
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Apply-once guard for the client half (issue #132).
3
+ *
4
+ * The host can hand the same context to `apply()` more than once — two rows resolving the same
5
+ * bundle, or a bundle loaded twice — and the second registration used to throw somewhere in the
6
+ * middle of `apply`, taking every later registration (including the settings section) with it.
7
+ * Refusing the second pass up front turns that into one warning and one intact panel.
8
+ *
9
+ * A WeakSet keyed by the context object is deliberate: it is per module instance, so a genuinely
10
+ * new bundle (the self-update path) gets an empty set and still registers, while the same bundle
11
+ * applied twice to the same context does not.
12
+ */
13
+
14
+ /** Decide whether this context still needs the client registrations. */
15
+ export function createApplyGuard(): (ctx: object) => boolean {
16
+ const applied = new WeakSet<object>()
17
+ return ctx => {
18
+ if (applied.has(ctx)) return false
19
+ applied.add(ctx)
20
+ return true
21
+ }
22
+ }
@@ -69,9 +69,9 @@ export class BrowserController implements HostObservable<BrowserControllerState>
69
69
  private readonly journal: BrowserInitializationJournal
70
70
  private readonly sessionId: string
71
71
  private readonly occurrenceId: string
72
-
73
- /** @param options - identity, persistence, page factory and source-tab navigation. */
74
- constructor(private readonly options: BrowserControllerOptions) {
72
+ private readonly options: BrowserControllerOptions
73
+ constructor(options: BrowserControllerOptions) {
74
+ this.options = options
75
75
  this.actions = options.actions
76
76
  this.journal = options.journal ?? createBrowserInitializationJournal()
77
77
  this.sessionId = options.sessionId ?? ''