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,372 @@
1
+ import { randomUUID } from 'node:crypto'
2
+ import type { BrowserSessionId, BrowserTab } from '../browser/types.ts'
3
+ import { BrowserError } from '../browser/types.ts'
4
+ import { browserSessionHandle, resolveSessionHandle, resolveTabHandle, sessionWireId, tabWireId, type BrowserTabWireId } from '../browser/handles.ts'
5
+ import type { CarrierPage } from '../browser/types.ts'
6
+ import { ProviderCore, type ElectronViewHandle, type Tab, type Session } from './provider-core.ts'
7
+
8
+ export abstract class ProviderTabs extends ProviderCore {
9
+ /**
10
+ * Bind the page the human has open in this conversation's sidebar into a session.
11
+ *
12
+ * Why this is the whole entry: the sidebar page is the shell's, opened by a person
13
+ * through the address bar, so no session of ours names it and nothing injects the
14
+ * selection bar into it. The shell DOES expose the panel's pages by conversation id
15
+ * (`listPages`), and can hand one over (`adoptPage`) — the same pair the tools use
16
+ * for `dsh_browser_list_tabs`. Doing it on a timer means the bar appears on a page
17
+ * the human opened themselves, which is the only entry they actually take.
18
+ *
19
+ * Rescans are spaced by one idle tick, not five: the listing crosses the
20
+ * bridge, and a page the human just opened must get its entry within a
21
+ * couple of seconds rather than five.
22
+ */
23
+ protected async adoptSidebarPageForReference(): Promise<void> {
24
+ const configured = this.config.referenceLabel
25
+ const label = typeof configured === 'function' ? configured() : configured
26
+ this.referenceScan.label = label
27
+ if (label === undefined || label === '') return
28
+ if (this.host.listPages === undefined || this.host.adoptPage === undefined) {
29
+ this.referenceScan.lastError = 'this carrier cannot list or adopt a page it did not open'
30
+ return
31
+ }
32
+ if (this.referenceScanCountdown > 0) { this.referenceScanCountdown -= 1; return }
33
+ // One idle tick between scans: a page the human opens must get its entry
34
+ // within a couple of seconds (measured: the shell creates the guest, then
35
+ // the next scan adopts it). The listing is a local bridge call, not a
36
+ // network request, so this is cheap.
37
+ this.referenceScanCountdown = 1
38
+ let session = this.referenceSession === undefined ? undefined : this.sessions.get(this.referenceSession)
39
+ if (session?.label !== label) session = undefined
40
+ const candidate: Session = session ?? {
41
+ id: sessionWireId(browserSessionHandle(label, randomUUID())), label,
42
+ tabs: [], activeIndex: 0, history: [], nextSeq: 1,
43
+ }
44
+ let pages: readonly CarrierPage[]
45
+ try {
46
+ // `requireRunning` is what keeps a scan from launching the human's
47
+ // installed browser: only a carrier that is already up can have pages.
48
+ pages = await this.host.listPages(this.carrierScope(candidate), { requireRunning: true })
49
+ } catch (error) {
50
+ this.referenceScan.lastError = error instanceof Error ? error.message : String(error)
51
+ return
52
+ }
53
+ this.referenceScan.pages = pages.length
54
+ const live = pages.filter(candidate => /^https?:\/\//iu.test(candidate.url))
55
+ // NOT pruned. The host's listing already EXCLUDES the pages this process
56
+ // adopted (that exclusion is what keeps `listTabs` from reporting one page
57
+ // twice), so "absent from the listing" means "already adopted" as often as
58
+ // it means "closed". Dropping those tabs would lose the bar on every page
59
+ // the human switches away from and re-adopt it under a new handle on the
60
+ // way back. A closed page's handle simply stops answering, and the pump
61
+ // already skips a tab it cannot evaluate.
62
+ if (live.length === 0) {
63
+ this.referenceScan.lastError = 'no http page is open in this conversation\'s sidebar'
64
+ return
65
+ }
66
+ let refused: string | undefined
67
+ for (const page of live) {
68
+ const tabId = this.carrierTab(candidate, page.id)
69
+ const existing = session?.tabs.find(tab => tab.id === tabId)
70
+ if (existing !== undefined) {
71
+ // A navigation changes the URL of a page we already hold.
72
+ if (existing.url !== page.url) existing.url = page.url
73
+ continue
74
+ }
75
+ try {
76
+ // The owner is passed so the adopted view is released with THIS
77
+ // conversation and not swept up by, or lost to, another one.
78
+ const handle = await this.host.adoptPage(this.carrierTab(candidate, page.id), this.carrierScope(candidate))
79
+ if (session === undefined) {
80
+ session = candidate
81
+ this.sessions.set(session.id, session)
82
+ this.referenceSession = session.id
83
+ }
84
+ // Append only: discovery must never switch the page the human is
85
+ // looking at, nor open a tab they did not ask for.
86
+ session.tabs.push({ id: tabId, handle, url: page.url })
87
+ } catch (error) {
88
+ refused = error instanceof Error ? error.message : String(error)
89
+ }
90
+ }
91
+ if (session !== undefined) {
92
+ session.activeIndex = Math.min(session.activeIndex, Math.max(0, session.tabs.length - 1))
93
+ }
94
+ this.referenceScan.lastError = session === undefined
95
+ ? refused ?? 'no page could be adopted'
96
+ : refused
97
+ }
98
+
99
+ /**
100
+ * Bind the carrier page that already shows this URL, if there is one.
101
+ *
102
+ * Compare the part of a URL that says WHICH page it is: scheme, host, path and query. A hash is a
103
+ * position inside a document, and a trailing slash is spelling, so neither makes a different page.
104
+ * @param s - the session to bind the page into.
105
+ * @param url - the URL being opened.
106
+ * @returns whether an existing page was taken over.
107
+ */
108
+ protected async adoptMatchingPage(s: Session, url: string, target: Tab, navigation: symbol, signal?: AbortSignal): Promise<boolean> {
109
+ if (this.host.adoptPage === undefined || this.host.listPages === undefined) return false
110
+ const wanted = this.comparableUrl(url)
111
+ if (wanted === undefined) return false
112
+ let pages: readonly CarrierPage[]
113
+ try {
114
+ pages = await this.host.listPages(this.carrierScope(s))
115
+ } catch {
116
+ // A listing must not turn "nothing to reuse" into "open failed".
117
+ return false
118
+ }
119
+ this.checkNavigation(target, navigation)
120
+ const match = pages.find(page => this.comparableUrl(page.url) === wanted)
121
+ if (match === undefined) return false
122
+ let handle: ElectronViewHandle
123
+ try {
124
+ handle = await this.host.adoptPage(this.carrierTab(s, match.id), this.carrierScope(s))
125
+ } catch {
126
+ // The page went away between listing and adopting: fall through to an ordinary navigation.
127
+ return false
128
+ }
129
+ if (target.navigation !== navigation) {
130
+ this.host.destroyView(handle, { keepPage: true })
131
+ this.checkNavigation(target, navigation)
132
+ }
133
+ const tab: Tab = { id: this.carrierTab(s, match.id), handle, url: match.url, navigation, navigationAbort: target.navigationAbort }
134
+ delete target.navigationAbort
135
+ s.tabs.push(tab)
136
+ s.activeIndex = s.tabs.length - 1
137
+ const document = await this.documentIdentity(handle, signal, () => { this.checkNavigation(tab, navigation) })
138
+ await this.settleDocument(handle, document, signal, { frameId: document.id, loaderId: document.loaderId },
139
+ () => { this.checkNavigation(tab, navigation) })
140
+ this.showActive(s, true)
141
+ return true
142
+ }
143
+
144
+ /** The parts of a URL that decide identity, or undefined when it cannot be parsed. */
145
+ private comparableUrl(url: string): string | undefined {
146
+ if (url === '' || url === 'about:blank') return undefined
147
+ try {
148
+ const parsed = new URL(url)
149
+ return `${parsed.protocol}//${parsed.host}${parsed.pathname.replace(/\/+$/, '')}${parsed.search}`
150
+ } catch {
151
+ return undefined
152
+ }
153
+ }
154
+
155
+ /** List the session's tabs with their titles. */
156
+ async listTabs(session: BrowserSessionId): Promise<readonly BrowserTab[]> {
157
+ const s = this.session(session)
158
+ const result: BrowserTab[] = []
159
+ for (let i = 0; i < s.tabs.length; i++) {
160
+ const tab = s.tabs[i]
161
+ if (tab === undefined) continue // defensive: array can shift under concurrency
162
+ // A tab we know has never navigated is NOT probed: its view has committed no document, so
163
+ // the round trip can only answer nothing — and it is the round trip that costs. A tab that
164
+ // HAS navigated is re-read, because the page may have moved itself since; a read that fails
165
+ // keeps the last accepted URL rather than reporting the tab as blank.
166
+ const liveUrl = tab.failure !== undefined ? tab.url : tab.url === '' ? '' : await this.currentUrl(tab.handle).catch(() => tab.url)
167
+ if (liveUrl !== '') tab.url = liveUrl
168
+ result.push({
169
+ id: tab.id,
170
+ url: liveUrl,
171
+ active: i === s.activeIndex,
172
+ })
173
+ }
174
+ // Pages the CARRIER holds that this provider never created.
175
+ //
176
+ // A sidebar panel and an installed browser both open pages on their own: a click on a link
177
+ // that targets a new page, or any `window.open`, produces a page nothing tells us about.
178
+ // Reporting only our own tabs made those invisible to this tool and unclosable through
179
+ // `dsh_browser_close_tab`, so they accumulated for the life of the browser. Measured on the
180
+ // sidebar carrier: three clicks produced three webview guests while this listed one tab.
181
+ //
182
+ // Hosts exclude pages already attached to provider views.
183
+ const pages = await this.host.listPages?.(this.carrierScope(s)) ?? []
184
+ for (const page of pages) {
185
+ // A page with no URL is a blank one the carrier opened for itself. Listing it would invite a
186
+ // caller to act on nothing, and the blank normalisation already closes those.
187
+ if (page.url === '' || page.url === 'about:blank') continue
188
+ result.push({ id: this.carrierTab(s, page.id), url: page.url, active: false })
189
+ }
190
+ return result
191
+ }
192
+
193
+ /** Switch to a tab by id, making its view visible. */
194
+ async switchTab(session: BrowserSessionId, tabId: BrowserTabWireId, options?: { readonly user?: boolean }): Promise<void> {
195
+ const user = options?.user === true
196
+ const s = this.session(session)
197
+ // A page the carrier owns. Before this, switching to one threw "not open in this session" —
198
+ // while `dsh_browser_list_tabs` was happily listing it, so the two tools disagreed and the
199
+ // page the human was looking at could not be reached (reported as a defect).
200
+ const carrierId = this.carrierId(s, tabId)
201
+ if (carrierId !== undefined) {
202
+ const existing = s.tabs.findIndex(tab => tab.id === tabId)
203
+ if (existing !== -1) {
204
+ await this.host.presentView?.(s.tabs[existing]!.handle, s.label, { quiet: this.isQuiet(), select: true, ...user ? { user } : {} })
205
+ s.activeIndex = existing
206
+ this.showActive(s, true, user)
207
+ return
208
+ }
209
+ const id = carrierId
210
+ if (this.host.adoptPage === undefined) {
211
+ throw new BrowserError(
212
+ 'browser: this carrier cannot hand over a page it opened itself, so that page cannot be driven. '
213
+ + 'Open the URL through dsh_browser_open instead — that creates a page this plugin owns.',
214
+ 'BROWSER_TAB_NOT_FOUND',
215
+ )
216
+ }
217
+ const pages = await this.host.listPages?.(this.carrierScope(s)).catch(() => []) ?? []
218
+ const page = pages.find(candidate => candidate.id === id)
219
+ const handle = await this.host.adoptPage(id, this.carrierScope(s))
220
+ try {
221
+ // An adopted guest already has a document. Marking it as our never-opened
222
+ // blank view makes the first snapshot/a11y return without reading it.
223
+ const url = page?.url || await this.currentUrl(handle)
224
+ if (url === '') throw new BrowserError('browser: the adopted page did not report its document URL', 'BROWSER_TAB_NOT_FOUND')
225
+ const tab: Tab = { id: tabId, handle, url }
226
+ await this.host.presentView?.(handle, s.label, { quiet: this.isQuiet(), select: true, ...user ? { user } : {} })
227
+ s.tabs.push(tab)
228
+ s.activeIndex = s.tabs.length - 1
229
+ this.showActive(s, true, user)
230
+ } catch (error) {
231
+ this.host.destroyView(handle, { keepPage: true })
232
+ throw error
233
+ }
234
+ return
235
+ }
236
+ const found = this.locateTab(session, tabId)
237
+ found.s.activeIndex = found.index
238
+ this.showActive(found.s, true, user)
239
+ }
240
+
241
+ /** Close one tab; closing the active tab activates the next. */
242
+ async closeTab(session: BrowserSessionId, tabId: BrowserTabWireId): Promise<void> {
243
+ const current = this.session(session)
244
+ const carrierId = this.carrierId(current, tabId)
245
+ // A page the carrier owns rather than a view we created. It was reported by `listTabs` under
246
+ // this prefix, so closing it here is what keeps the two tools consistent — a page that can be
247
+ // listed must be closable, or the listing reads as a contradiction.
248
+ if (carrierId !== undefined) {
249
+ const id = carrierId
250
+ if (this.host.closePage === undefined) {
251
+ return Promise.reject(new BrowserError(
252
+ 'browser: this carrier does not expose the pages it opens on its own, so that page cannot be closed',
253
+ 'BROWSER_TAB_NOT_FOUND',
254
+ ))
255
+ }
256
+ await this.host.closePage(id, this.carrierScope(current))
257
+ if (!this.session(session).tabs.some(tab => tab.id === tabId)) return
258
+ }
259
+ const found = this.locateTab(session, tabId)
260
+ const s = found.s
261
+ const index = found.index
262
+ const removed = s.tabs[index]
263
+ if (removed !== undefined) {
264
+ s.tabs.splice(index, 1)
265
+ this.destroyTab(removed, { keepPage: carrierId !== undefined })
266
+ }
267
+ if (s.tabs.length === 0) {
268
+ // Session keeps one blank tab so it stays usable.
269
+ this.newTab(s)
270
+ } else if (index < s.activeIndex) {
271
+ // Closing a tab before the active one shifts the array left; keep the
272
+ // same tab active by decrementing the index.
273
+ s.activeIndex -= 1
274
+ } else if (index === s.activeIndex) {
275
+ // The active tab itself was closed; activate the next tab (the one that
276
+ // shifted into its place), or the last one when the closed tab was the
277
+ // last.
278
+ s.activeIndex = Math.min(index, s.tabs.length - 1)
279
+ }
280
+ this.showActive(s)
281
+ return Promise.resolve()
282
+ }
283
+
284
+ /**
285
+ * Find a canonical tab within the calling session.
286
+ */
287
+ private locateTab(session: BrowserSessionId, tabId: string): { s: Session; index: number } {
288
+ const s = this.session(session)
289
+ resolveTabHandle(resolveSessionHandle(session), tabId)
290
+ const own = s.tabs.findIndex(tab => tab.id === tabId)
291
+ if (own >= 0) return { s, index: own }
292
+ const ownIds = s.tabs.map(t => t.id).join(', ') || '(none)'
293
+ throw new BrowserError(
294
+ `browser: tab "${tabId}" is not open in this session (session tabs: ${ownIds})`,
295
+ 'BROWSER_TAB_UNKNOWN',
296
+ )
297
+ }
298
+
299
+ /** Close every tab and reset to one blank tab. */
300
+ reset(session: BrowserSessionId): Promise<void> {
301
+ const s = this.session(session)
302
+ for (const tab of s.tabs) this.destroyTab(tab)
303
+ s.tabs.length = 0
304
+ this.newTab(s)
305
+ s.activeIndex = 0
306
+ this.showActive(s)
307
+ return Promise.resolve()
308
+ }
309
+
310
+ /** Look up a session or throw the unknown-session error. */
311
+ protected session(session: BrowserSessionId): Session {
312
+ const existing = this.sessions.get(session)
313
+ if (existing === undefined) {
314
+ throw new BrowserError(`browser: session "${session}" is not open`, 'BROWSER_SESSION_UNKNOWN')
315
+ }
316
+ return existing
317
+ }
318
+
319
+ /** The active tab of a session. */
320
+ protected activeTab(s: Session): Tab {
321
+ if (this.carrierLaunchError !== undefined) throw this.carrierLaunchError
322
+ const tab = s.tabs[s.activeIndex]
323
+ if (tab === undefined) throw new BrowserError('browser: session has no active tab', 'BROWSER_TAB_UNKNOWN')
324
+ if (tab.failure !== undefined) throw tab.failure
325
+ return tab
326
+ }
327
+
328
+ /** Append a fresh tab and make it active. */
329
+ protected newTab(s: Session): void {
330
+ const id = tabWireId({ ...resolveSessionHandle(s.id), tab: randomUUID() })
331
+ const handle = this.host.createView(id)
332
+ // Same window as the session's other tabs.
333
+ this.host.groupView?.(handle, s.id, s.label)
334
+ s.tabs.push({ id, handle, url: '' })
335
+ s.activeIndex = s.tabs.length - 1
336
+ this.showActive(s)
337
+ }
338
+
339
+ protected carrierScope(s: Session): BrowserSessionId {
340
+ return s.id
341
+ }
342
+
343
+ protected carrierTab(s: Session, id: string): BrowserTabWireId {
344
+ const scope = resolveSessionHandle(s.id)
345
+ return tabWireId(resolveTabHandle(scope, id))
346
+ }
347
+
348
+ private carrierId(s: Session, id: BrowserTabWireId): BrowserTabWireId | undefined {
349
+ const tab = resolveTabHandle(resolveSessionHandle(s.id), id).tab
350
+ if (!tab.startsWith('page:') && this.host.closePage === undefined) return undefined
351
+ return id
352
+ }
353
+
354
+ protected destroyTab(tab: Tab, options?: { readonly keepPage?: boolean }): void {
355
+ tab.navigationAbort?.abort(new BrowserError('browser: the navigation guest was closed', 'BROWSER_GUEST_CLOSED'))
356
+ this.host.destroyView(tab.handle, options)
357
+ }
358
+
359
+ /** Find a session's tab by its backing view id (toolbar actions carry view ids). */
360
+ protected tabByViewId(s: Session, viewId: string): Tab | undefined {
361
+ return s.tabs.find(tab => tab.handle.id === viewId)
362
+ }
363
+
364
+ /**
365
+ * Whether a session is still live. The human closing a window ends its session
366
+ * (see {@link handleViewClosed}), so callers that cache ids must ask first.
367
+ * @param session - the session id to test.
368
+ */
369
+ exists(session: BrowserSessionId): boolean {
370
+ return this.sessions.has(session)
371
+ }
372
+ }