dsh-codex-style-computer-use 2.3.5 → 3.1.0

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.
@@ -0,0 +1,807 @@
1
+ // scripts/verify-browser-integration.mjs — the end-to-end acceptance run for browser control.
2
+ //
3
+ // WHAT THIS IS. One script, one path: it launches its own headless Chromium with the REAL
4
+ // unpacked extension from this checkout, pairs the extension the way a human does, and then
5
+ // drives the user's existing tab through the real engine over the real relay. Nothing is
6
+ // mocked — no stub bridge, no stub page, no stub browser. If a dependency or a browser build
7
+ // is missing, the run FAILS and names it; it never skips and never substitutes something else.
8
+ //
9
+ // ISOLATION. Everything it touches is disposable and its own:
10
+ // * a brand-new Chrome profile inside a scratch directory this script creates, so the
11
+ // user's profile, cookies, history and running browser are never reached;
12
+ // * only this extension is loaded (`--disable-extensions-except` + `--load-extension`);
13
+ // no system extension is installed and nothing is sent off the machine;
14
+ // * the test site is a throwaway server on 127.0.0.1 with an OS-chosen port, and the
15
+ // "login" is a synthetic HttpOnly cookie with a value regenerated every run;
16
+ // * the bridge listens on port 0 (an OS-chosen port) unless --port pins one.
17
+ //
18
+ // PAIRING IS A HUMAN STEP, SIMULATED — NEVER FORGED. The extension is never handed a token by
19
+ // this script: it asks to pair, the script reads the six-digit code out of the extension's own
20
+ // popup, waits until the host setup page shows that SAME code in exactly one row, and clicks the
21
+ // real allow button of that row. The one browser setting it changes is the port, through the
22
+ // extension's own popup — the same control a user would use — and it never injects a token,
23
+ // never hand-writes `pairing.json`, and never writes `chrome.storage` directly.
24
+ //
25
+ // USAGE (the coordinator runs commands; this file never runs itself):
26
+ //
27
+ // node scripts/verify-browser-integration.mjs
28
+ // node scripts/verify-browser-integration.mjs --work-dir D:\tmp\e2e --chrome "C:\...\chrome.exe"
29
+ // node scripts/verify-browser-integration.mjs --preflight
30
+ //
31
+ // OPTIONS
32
+ // --chrome <absolute path> Chrome/Chromium to drive. Default: playwright-core's own build,
33
+ // or DSH_BROWSER_E2E_CHROME. Must be a full Chromium build: the
34
+ // headless shell cannot load extensions.
35
+ // --work-dir <path> scratch root. Default: DSH_BROWSER_E2E_WORKDIR, else os.tmpdir().
36
+ // This script still creates a fresh random subdirectory inside it,
37
+ // because on Windows a profile directly under the default temp
38
+ // path can trip Chromium's ProcessSingleton.
39
+ // --port <n> bridge port. Default 0 (OS-chosen).
40
+ // --timeout <ms> watchdog for the whole run. Default 300000.
41
+ // --keep keep the scratch directory, for inspecting a failure.
42
+ // --preflight check Node, the runtime and the extension, then exit.
43
+ //
44
+ // EXIT: 0 only when every assertion below held.
45
+ //
46
+ // Authorization is exercised, not assumed: every engine call carries a real `pageAccess` guard from
47
+ // `lib/browser/access.js`, obtained by citing the tab the way a user's @ does, and the run asserts
48
+ // that an uncited reference yields no guard and that the guard refuses the DSH control surface.
49
+ //
50
+ // WHAT THIS RUN DOES **NOT** COVER — stated here so a green run is never read as more than it is:
51
+ // * The real DSH host process. Loading the package into a profile, the same-origin HTTP route
52
+ // (`/api/computer-use/browser/…`), per-session authorization scoping and the settings client
53
+ // all need a running DSH with its own services. Those are exercised in the coordinator's
54
+ // separate host harness, and their pure logic is unit-tested in build/test-browser-host.mjs
55
+ // (in the reviewed gate). Here the host layer is only checked for being constructible and
56
+ // wired to this bridge.
57
+ // * Annotation, WebMCP, network capture and app management: this partition does not implement
58
+ // them, so there is nothing to verify.
59
+ // * A visible (headed) window. The run asserts it is headless instead, because a verifier must
60
+ // not put a window on the user's screen.
61
+
62
+ import assert from 'node:assert/strict'
63
+ import { createServer } from 'node:http'
64
+ import { createServer as createNetServer } from 'node:net'
65
+ import { existsSync } from 'node:fs'
66
+ import { randomBytes } from 'node:crypto'
67
+ import { mkdir, mkdtemp, readFile, rm, stat } from 'node:fs/promises'
68
+ import os from 'node:os'
69
+ import path from 'node:path'
70
+ import { fileURLToPath, pathToFileURL } from 'node:url'
71
+ import { chromium } from 'playwright-core'
72
+
73
+ const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
74
+ const EXTENSION_DIR = path.join(ROOT, 'lib/browser/extension')
75
+ const { BrowserBridge } = await import(pathToFileURL(path.join(ROOT, 'lib/browser/bridge.js')).href)
76
+ const { BrowserEngine } = await import(pathToFileURL(path.join(ROOT, 'lib/browser/engine.js')).href)
77
+ const { BrowserAccess } = await import(pathToFileURL(path.join(ROOT, 'lib/browser/access.js')).href)
78
+
79
+ const argv = process.argv.slice(2)
80
+ const option = name => {
81
+ const index = argv.indexOf(`--${name}`)
82
+ return index < 0 ? undefined : argv[index + 1]
83
+ }
84
+ const KEEP = argv.includes('--keep')
85
+ const PREFLIGHT_ONLY = argv.includes('--preflight')
86
+ const RUN_TIMEOUT_MS = Number(option('timeout') ?? 300_000)
87
+ const BRIDGE_PORT = Number(option('port') ?? 0)
88
+ const WORK_ROOT = path.resolve(option('work-dir') ?? process.env.DSH_BROWSER_E2E_WORKDIR ?? os.tmpdir())
89
+
90
+ // One run, one synthetic identity. The cookie value is the only secret here, and the point of
91
+ // the cookie check below is that it never reaches a tool result.
92
+ const RUN_ID = randomBytes(6).toString('hex')
93
+ const SESSION_SECRET = randomBytes(18).toString('hex')
94
+ const ACCOUNT = 'qa-user'
95
+
96
+ const delay = ms => new Promise(resolve => setTimeout(resolve, ms))
97
+
98
+ /**
99
+ * The phase currently running.
100
+ *
101
+ * WHY THIS EXISTS: the run has a hard watchdog, and when it fired the log said only "the run
102
+ * exceeded 300000 ms" — nothing about WHICH phase was stuck, so a sporadic hang could not be
103
+ * attributed from the log. Every major phase now announces itself, and both the watchdog and the
104
+ * failure path report the phase they died in.
105
+ */
106
+ let STAGE = 'startup'
107
+ function stage (name) {
108
+ STAGE = name
109
+ console.log(`INFO stage ${name}`)
110
+ }
111
+
112
+ // Per-phase ceilings. Each is well inside the global watchdog, so a stuck phase fails with its own
113
+ // name instead of consuming the whole budget and reporting "exceeded 300000 ms".
114
+ const STARTUP_TIMEOUT_MS = Math.min(120_000, Math.floor(RUN_TIMEOUT_MS / 2))
115
+ const TOOL_TIMEOUT_MS = Math.min(90_000, Math.floor(RUN_TIMEOUT_MS / 3))
116
+ const PAIR_TIMEOUT_MS = Math.min(60_000, Math.floor(RUN_TIMEOUT_MS / 4))
117
+
118
+ /**
119
+ * Await `promise`, but never longer than `ms`.
120
+ *
121
+ * THE POINT: a verifier must FAIL with a diagnosis, not vanish behind a global watchdog. Several
122
+ * awaits in a run like this have no useful default ceiling — `context.newPage()` and
123
+ * `context.close()` on a wedged browser, a server `close()` waiting for live keep-alive sockets,
124
+ * `page.evaluate()` on an unresponsive renderer — and each of them can hold the process open until
125
+ * the watchdog fires with no idea of where it stopped.
126
+ */
127
+ async function bounded (promise, ms, what) {
128
+ let timer
129
+ const expiry = new Promise((_, reject) => {
130
+ timer = setTimeout(() => reject(new Error(`timed out after ${ms} ms during "${STAGE}": ${what}`)), ms)
131
+ })
132
+ try {
133
+ return await Promise.race([promise, expiry])
134
+ } finally {
135
+ clearTimeout(timer)
136
+ }
137
+ }
138
+
139
+ async function waitFor (probe, what, timeout = 30_000) {
140
+ const deadline = Date.now() + timeout
141
+ let last
142
+ while (Date.now() < deadline) {
143
+ try {
144
+ const value = await probe()
145
+ if (value) return value
146
+ } catch (error) { last = error }
147
+ await delay(100)
148
+ }
149
+ throw new Error(`timed out after ${timeout} ms during "${STAGE}" waiting for ${what}${last ? `: ${last.message}` : ''}`)
150
+ }
151
+
152
+ /**
153
+ * Run a direct browser-page interaction under a ceiling.
154
+ *
155
+ * The assertions in this run read the page itself (`evaluate`, `locator(...).textContent()`) as the
156
+ * independent witness for what a tool did. Every one of those awaits the renderer, and a wedged
157
+ * renderer — the exact failure a watchdog is supposed to report — leaves them pending for ever.
158
+ * They are not retried or softened; they simply may not outlive the phase budget.
159
+ */
160
+ function ui (operation, what) {
161
+ return bounded(Promise.resolve().then(operation), TOOL_TIMEOUT_MS, what)
162
+ }
163
+
164
+ const escapeRegExp = value => String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
165
+
166
+ /**
167
+ * The CDP commands that actually DRIVE a page.
168
+ *
169
+ * A refusal check must not demand "no CDP at all": detecting a stale snapshot legitimately reads
170
+ * the live document first (`Runtime.evaluate` / `Runtime.callFunctionOn`), and a stray
171
+ * `Runtime.releaseObject` is bookkeeping, not an effect. What must never happen is an INPUT
172
+ * command — a click, a keystroke, a file attach or a navigation. This list mirrors the engine's
173
+ * own `commandSent` filter, so a real dispatch cannot slip past it.
174
+ *
175
+ * ONLY EXISTENCE IS EVER ASSERTED FROM THIS, never a count. One user-level Playwright click
176
+ * becomes several `Input.dispatchMouseEvent` commands (mouseMoved, mousePressed, mouseReleased),
177
+ * and `commandSent` forwards only the method name without params, so the packets cannot be
178
+ * regrouped back into gestures. How many times the user's action really ran is measured in the
179
+ * page (`#save` listener) and on the fixture server, which are the only honest witnesses.
180
+ */
181
+ const DRIVING = /^(?:Input\.(?:dispatchMouseEvent|dispatchKeyEvent|insertText|dispatchTouchEvent|dispatchDragEvent)|DOM\.setFileInputFiles|Page\.(?:navigate|navigateToHistoryEntry))$/
182
+
183
+ const drivingCommands = entries => entries.filter(entry => DRIVING.test(entry.command))
184
+
185
+ /** The `[ref=eN]` an accessible snapshot prints for one role/name pair. */
186
+ function refFor (content, role, name) {
187
+ const pattern = new RegExp(`${escapeRegExp(role)} "${escapeRegExp(name)}" \\[ref=(e\\d+)\\]`)
188
+ return pattern.exec(String(content ?? ''))?.[1]
189
+ }
190
+
191
+ /** The `[ref=fNeN]` a snapshot prints for a control inside an iframe. */
192
+ function frameRefFor (content, role, name) {
193
+ const pattern = new RegExp(`${escapeRegExp(role)} "${escapeRegExp(name)}" \\[ref=(f\\d+e\\d+)\\]`)
194
+ return pattern.exec(String(content ?? ''))?.[1]
195
+ }
196
+
197
+ function pngSize (buffer) {
198
+ assert.equal(buffer.subarray(0, 8).toString('hex'), '89504e470d0a1a0a', 'a capture must be a PNG')
199
+ assert.equal(buffer.subarray(12, 16).toString('ascii'), 'IHDR', 'the PNG must start with an IHDR chunk')
200
+ return { width: buffer.readUInt32BE(16), height: buffer.readUInt32BE(20) }
201
+ }
202
+
203
+ // ---------------------------------------------------------------------------------------------
204
+ // the throwaway site: synthetic login, a real form, an iframe, a long page and a second page
205
+ // ---------------------------------------------------------------------------------------------
206
+
207
+ const html = (title, body, script = '') =>
208
+ `<!doctype html><meta charset="utf-8"><title>${title}</title>` +
209
+ '<style>body{font:15px/1.6 system-ui,sans-serif;margin:24px}' +
210
+ 'button{font:inherit;padding:6px 12px}</style>' +
211
+ `${body}${script ? `<script>${script}</script>` : ''}`
212
+
213
+ function buildSite () {
214
+ const state = { signedIn: 0, mutations: 0 }
215
+ const isSignedIn = request => String(request.headers.cookie ?? '').split(/;\s*/)
216
+ .some(pair => pair === `e2e_session=${SESSION_SECRET}`)
217
+
218
+ const routes = {
219
+ '/': () => html('DSH Browser E2E',
220
+ `<h1>Browser integration fixture</h1>
221
+ <p id="account">__ACCOUNT__</p>
222
+ <label>Name <input id="name" autocomplete="off"></label>
223
+ <button id="save">Save</button> <output id="out"></output>
224
+ <p id="live"></p>
225
+ <iframe id="frame" src="/frame" width="420" height="120"></iframe>`,
226
+ `window.saveClicks = 0;
227
+ document.querySelector('#save').onclick = () => {
228
+ // The page and the server each count the effect, so "nothing happened" can be proved
229
+ // outside the tool result.
230
+ window.saveClicks += 1;
231
+ document.querySelector('#out').textContent = 'Saved ' + document.querySelector('#name').value;
232
+ fetch('/mutate?via=save').catch(() => {});
233
+ };
234
+ document.querySelector('#live').textContent = 'LIVE-' + Math.random().toString(16).slice(2, 12);`),
235
+ '/second': () => html('Second fixture page',
236
+ `<h1>Unrelated tab</h1><label>Note <input id="note" autocomplete="off"></label>
237
+ <button id="mark">Mark</button> <output id="marked"></output>`,
238
+ `document.querySelector('#mark').onclick = () => {
239
+ document.querySelector('#marked').textContent = 'Marked ' + document.querySelector('#note').value;
240
+ };`),
241
+ '/frame': () => html('Frame fixture',
242
+ `<button id="frame-btn" onclick="this.textContent='Frame clicked'">Frame button</button>`),
243
+ '/long': () => html('Long fixture page',
244
+ `<h1>Long list</h1><ul>${Array.from({ length: 200 },
245
+ (_, index) => `<li>Row ${String(index + 1).padStart(3, '0')} — pagination line ${RUN_ID}</li>`).join('')}</ul>`),
246
+ }
247
+
248
+ const server = createServer((request, response) => {
249
+ const { pathname } = new URL(request.url ?? '/', 'http://127.0.0.1')
250
+ // The synthetic login: the site issues its own HttpOnly cookie and renders from it.
251
+ // Page script cannot read the value, and neither can any tool.
252
+ if (!String(request.headers.cookie ?? '').includes('e2e_session=')) {
253
+ response.setHeader('Set-Cookie', `e2e_session=${SESSION_SECRET}; HttpOnly; Path=/; SameSite=Lax`)
254
+ }
255
+ // A server-side counter of real mutations: a click that landed cannot hide here.
256
+ if (pathname === '/mutate') {
257
+ state.mutations += 1
258
+ response.writeHead(204).end()
259
+ return
260
+ }
261
+ const authenticated = isSignedIn(request)
262
+ if (authenticated) state.signedIn += 1
263
+ const render = routes[pathname]
264
+ if (!render) { response.writeHead(404).end('not found'); return }
265
+ response.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' })
266
+ response.end(render().replace('__ACCOUNT__',
267
+ authenticated ? `Signed in as ${ACCOUNT}` : 'Not signed in'))
268
+ })
269
+ return { server, state }
270
+ }
271
+
272
+ // ---------------------------------------------------------------------------------------------
273
+ // extension plumbing
274
+ // ---------------------------------------------------------------------------------------------
275
+
276
+ /** The id of the extension the browser actually loaded. */
277
+ async function extensionId (context) {
278
+ // A browser that launched without our extension never emits the event, so the wait is bounded
279
+ // rather than relying on Playwright's own default.
280
+ const worker = context.serviceWorkers()[0] ??
281
+ await bounded(context.waitForEvent('serviceworker', { timeout: 30_000 }), 35_000,
282
+ 'the extension service worker to register')
283
+ return new URL(worker.url()).host
284
+ }
285
+
286
+ /** Point the extension at this run's bridge port through its own popup, as a user would. */
287
+ async function setExtensionPort (context, id, port) {
288
+ const popup = await bounded(context.newPage(), 30_000, 'the extension popup page')
289
+ try {
290
+ await bounded(popup.goto(`chrome-extension://${id}/popup.html`, { waitUntil: 'domcontentloaded' }), 30_000,
291
+ 'the extension popup to open')
292
+ await bounded(popup.locator('details > summary').first().click(), 30_000, 'the popup connection settings to expand')
293
+ await bounded(popup.fill('#port', String(port)), 30_000, 'the popup port field')
294
+ await bounded(popup.click('#save-port'), 30_000, 'the popup port save button')
295
+ await bounded(popup.waitForFunction(value => document.querySelector('#port')?.value === String(value), port),
296
+ 30_000, 'the popup to store the port')
297
+ } finally {
298
+ // Closing the popup is itself unbounded by default; a control page that hangs must not stop the
299
+ // run from reporting.
300
+ await bounded(popup.close(), 15_000, 'the extension popup to close').catch(() => {})
301
+ }
302
+ }
303
+
304
+ /**
305
+ * The six-digit code the extension is currently showing.
306
+ *
307
+ * The popup refreshes its status on load and only keeps polling while it is visible; a
308
+ * background tab may therefore never update. Reopening it until the code appears is what a
309
+ * user glancing at the toolbar repeatedly would do, and it cannot fabricate a code.
310
+ */
311
+ async function readExtensionCode (context, id) {
312
+ const deadline = Date.now() + 30_000
313
+ let last
314
+ while (Date.now() < deadline) {
315
+ const popup = await bounded(context.newPage(), 30_000, 'a popup page to read the pairing code')
316
+ try {
317
+ await bounded(popup.goto(`chrome-extension://${id}/popup.html`, { waitUntil: 'domcontentloaded' }), 30_000,
318
+ 'the popup to open while reading the code')
319
+ const value = ((await bounded(popup.locator('#code').textContent().catch(() => ''), 15_000,
320
+ 'the pairing code to be readable')) ?? '').trim()
321
+ if (/^\d{6}$/.test(value)) return value
322
+ last = `the popup showed "${value}"`
323
+ } finally {
324
+ await bounded(popup.close(), 15_000, 'the popup to close').catch(() => {})
325
+ }
326
+ await delay(300)
327
+ }
328
+ throw new Error(`the extension never displayed a six-digit pairing code (${last}) during "${STAGE}". ` +
329
+ 'It never reached this bridge — check that the popup port was saved and that the bridge is listening.')
330
+ }
331
+
332
+ /**
333
+ * Approve the pending request the way a human does: find the setup row that shows the code the
334
+ * extension is displaying, then click that row's allow button.
335
+ */
336
+ async function approve (context, bridge, code) {
337
+ const page = await bounded(context.newPage(), 30_000, 'the setup page')
338
+ try {
339
+ await bounded(page.goto(bridge.approvalUrl('setup'), { waitUntil: 'domcontentloaded' }), 30_000,
340
+ 'the setup page to open')
341
+ const row = page.locator('li').filter({ hasText: code })
342
+ await waitFor(async () => (await row.count()) === 1, `exactly one setup row showing code ${code}`, 20_000)
343
+ const allow = row.first().locator('button[value="allow"]')
344
+ // The page enables it after exchanging its one-time invitation; clicking a disabled button
345
+ // would silently do nothing.
346
+ await waitFor(async () => allow.isEnabled().catch(() => false), 'the setup allow button to enable', 20_000)
347
+ await bounded(Promise.all([
348
+ page.waitForNavigation({ waitUntil: 'domcontentloaded' }).catch(() => {}),
349
+ allow.click(),
350
+ ]), 30_000, 'the approval to be submitted')
351
+ } finally {
352
+ await bounded(page.close(), 15_000, 'the setup page to close').catch(() => {})
353
+ }
354
+ }
355
+
356
+ // ---------------------------------------------------------------------------------------------
357
+ // the run
358
+ // ---------------------------------------------------------------------------------------------
359
+
360
+ let scratch, site, bridge, context
361
+ const toolOutputs = []
362
+ const sent = []
363
+
364
+ const watchdog = setTimeout(() => {
365
+ console.error(`FAIL the run exceeded ${RUN_TIMEOUT_MS} ms during stage "${STAGE}"`)
366
+ console.log(JSON.stringify({ suite: 'verify-browser-integration', ok: false, stage: STAGE,
367
+ error: `watchdog: the run exceeded ${RUN_TIMEOUT_MS} ms` }))
368
+ process.exit(2)
369
+ }, RUN_TIMEOUT_MS)
370
+ watchdog.unref?.()
371
+
372
+ try {
373
+ stage('preflight')
374
+ const manifest = JSON.parse(await readFile(path.join(EXTENSION_DIR, 'manifest.json'), 'utf8'))
375
+ assert.equal(manifest.manifest_version, 3, 'the companion extension must be Manifest V3')
376
+ for (const permission of ['debugger', 'tabs', 'storage']) {
377
+ assert.ok(manifest.permissions.includes(permission), `the extension must request "${permission}"`)
378
+ }
379
+ const configuredChrome = option('chrome') ?? process.env.DSH_BROWSER_E2E_CHROME
380
+ if (configuredChrome !== undefined) {
381
+ assert.ok(path.isAbsolute(configuredChrome),
382
+ `--chrome / DSH_BROWSER_E2E_CHROME must be an absolute path, got "${configuredChrome}"`)
383
+ assert.ok(existsSync(configuredChrome), `the configured Chrome executable does not exist: ${configuredChrome}`)
384
+ }
385
+ // Playwright's registry is the fallback; a runtime with no browser installed throws here, so
386
+ // the message below (not Playwright's) is what the operator reads.
387
+ let registered
388
+ try { registered = chromium.executablePath() } catch { registered = undefined }
389
+ const chrome = configuredChrome ?? registered
390
+ assert.ok(chrome && existsSync(chrome),
391
+ 'no Chrome/Chromium build was found. Pass --chrome "<absolute path to chrome.exe>" (or set ' +
392
+ 'DSH_BROWSER_E2E_CHROME). The bundled headless shell cannot load an extension, so a full ' +
393
+ `Chromium or Chrome for Testing build is required.${registered ? ` Playwright reported ${registered}, which does not exist.` : ''}`)
394
+ assert.ok((await stat(chrome)).size > 1_000_000, `the Chrome executable looks truncated: ${chrome}`)
395
+ console.log(`INFO chrome ${chrome}`)
396
+ console.log(`INFO extension ${EXTENSION_DIR}`)
397
+
398
+ if (PREFLIGHT_ONLY) {
399
+ console.log('PREFLIGHT OK: Node, playwright-core, the extension and Chrome are all present.')
400
+ console.log(JSON.stringify({ suite: 'verify-browser-integration', mode: 'preflight', ok: true, chrome }))
401
+ process.exitCode = 0
402
+ } else {
403
+ stage('fixture')
404
+ const fixture = buildSite()
405
+ site = fixture.server
406
+ const sitePort = await bounded(
407
+ new Promise(resolve => site.listen(0, '127.0.0.1', () => resolve(site.address().port))),
408
+ 10_000, 'the fixture server to bind a loopback port')
409
+ const siteUrl = `http://127.0.0.1:${sitePort}`
410
+
411
+ await mkdir(WORK_ROOT, { recursive: true })
412
+ scratch = await mkdtemp(path.join(WORK_ROOT, 'dsh-browser-e2e-'))
413
+
414
+ stage('bridge-start')
415
+ bridge = new BrowserBridge({
416
+ home: path.join(scratch, 'bridge'),
417
+ port: BRIDGE_PORT,
418
+ extensionSource: EXTENSION_DIR,
419
+ idleTimeoutMs: 5_000,
420
+ })
421
+ bridge.playwright = { chromium }
422
+ await bounded(bridge.start(), STARTUP_TIMEOUT_MS, 'the bridge to start listening')
423
+ console.log(`INFO bridge 127.0.0.1:${bridge.port}`)
424
+
425
+ const profile = path.join(scratch, 'profile')
426
+ await mkdir(profile)
427
+
428
+ stage('browser-launch')
429
+ context = await bounded(chromium.launchPersistentContext(profile, {
430
+ headless: true,
431
+ executablePath: chrome,
432
+ // Playwright disables extensions by default; the unpacked extension needs them back on.
433
+ ignoreDefaultArgs: ['--disable-extensions'],
434
+ viewport: { width: 1280, height: 720 },
435
+ args: [
436
+ '--headless=new',
437
+ `--disable-extensions-except=${EXTENSION_DIR}`,
438
+ `--load-extension=${EXTENSION_DIR}`,
439
+ `--explicitly-allowed-ports=${sitePort},${bridge.port}`,
440
+ ],
441
+ }), STARTUP_TIMEOUT_MS, 'the browser to launch')
442
+ const browserVersion = await bounded(
443
+ (context.pages()[0] ?? await bounded(context.newPage(), STARTUP_TIMEOUT_MS, 'an initial page'))
444
+ .evaluate(() => navigator.userAgent),
445
+ STARTUP_TIMEOUT_MS, 'the browser to answer about itself')
446
+ assert.match(browserVersion, /HeadlessChrome/, `the run must be headless so no window appears: ${browserVersion}`)
447
+
448
+ stage('extension-load')
449
+ const id = await extensionId(context)
450
+ console.log(`INFO extension id ${id}`)
451
+
452
+ // Two ordinary tabs already exist, as they would in the user's browser.
453
+ stage('tabs')
454
+ const page = context.pages()[0] ?? await bounded(context.newPage(), STARTUP_TIMEOUT_MS, 'the fixture tab')
455
+ await bounded(page.goto(`${siteUrl}/`, { waitUntil: 'domcontentloaded' }), STARTUP_TIMEOUT_MS, 'the fixture page to load')
456
+ const anonymous = await ui(() => page.locator('#account').textContent(), 'the fixture page to render')
457
+ // The first request is what issues the HttpOnly cookie; the next one presents it.
458
+ await bounded(page.reload({ waitUntil: 'domcontentloaded' }), STARTUP_TIMEOUT_MS, 'the fixture page to reload')
459
+ assert.equal(anonymous, 'Not signed in', 'the first visit must be anonymous before the cookie exists')
460
+ assert.equal(await ui(() => page.locator('#account').textContent(), 'the authenticated page to render'),
461
+ `Signed in as ${ACCOUNT}`,
462
+ 'presenting the synthetic HttpOnly cookie must authenticate the fixture page')
463
+ const second = await bounded(context.newPage(), STARTUP_TIMEOUT_MS, 'the second fixture tab')
464
+ await bounded(second.goto(`${siteUrl}/second`, { waitUntil: 'domcontentloaded' }), STARTUP_TIMEOUT_MS,
465
+ 'the second fixture page to load')
466
+ const marker = await ui(() => page.locator('#live').textContent(), 'the per-load marker to render')
467
+ assert.match(marker, /^LIVE-/, 'the fixture must generate a per-load marker')
468
+
469
+ // ---- pairing: code from the extension popup, matched on the host setup page ------------
470
+ stage('pair')
471
+ await setExtensionPort(context, id, bridge.port)
472
+ await waitFor(() => bridge.pairings.list()[0], 'the extension to ask this bridge to pair', PAIR_TIMEOUT_MS)
473
+ const shown = await readExtensionCode(context, id)
474
+ // Compare against the CURRENT pending set, not a captured snapshot: the extension may drop and
475
+ // re-request pairing, which mints a new code and is not a failure.
476
+ const pending = bridge.pairings.list().find(entry => entry.code === shown)
477
+ assert.ok(pending, `the code the extension shows (${shown}) must be pending on this bridge; ` +
478
+ `pending now: ${JSON.stringify(bridge.pairings.list())}`)
479
+ await approve(context, bridge, shown)
480
+ await waitFor(() => bridge.profiles.size === 1, 'the extension to connect after approval', PAIR_TIMEOUT_MS)
481
+ assert.equal(bridge.pairings.list().length, 0, 'an approved request must be consumed, not left pending')
482
+
483
+ // ---- discovery: the user's own tabs, exactly once each ---------------------------------
484
+ stage('discovery')
485
+ const tabs = await waitFor(() => {
486
+ const rows = bridge.list()
487
+ return rows.some(row => row.url === `${siteUrl}/`) && rows.some(row => row.url === `${siteUrl}/second`)
488
+ ? rows : undefined
489
+ }, 'the open fixture tabs to appear in the inventory', PAIR_TIMEOUT_MS)
490
+ const [mainTab] = tabs.filter(row => row.url === `${siteUrl}/`)
491
+ const [secondTab] = tabs.filter(row => row.url === `${siteUrl}/second`)
492
+ assert.ok(mainTab && secondTab, `both fixture tabs must be listed: ${JSON.stringify(tabs)}`)
493
+ assert.match(mainTab.ref, /^dsh-browser:\/\/[a-z0-9-]+\/\d+$/i, 'inventory rows carry dsh-browser refs')
494
+ assert.equal(tabs.filter(row => row.url === `${siteUrl}/`).length, 1, 'each tab is listed exactly once')
495
+ assert.equal(tabs.some(row => row.url.includes(`:${bridge.port}/`)), false,
496
+ 'the bridge\'s own setup page must never be offered as a tab')
497
+ const ref = mainTab.ref
498
+ const tabId = mainTab.id
499
+ const windowId = mainTab.windowId
500
+
501
+ // ---- the engine, over the real relay ---------------------------------------------------
502
+ stage('engine')
503
+ const engine = new BrowserEngine(bridge, { artifactDir: path.join(scratch, 'captures') })
504
+ bridge.on('commandSent', (target, command) => sent.push({ target, command }))
505
+
506
+ // AUTHORIZATION IS PART OF THE RUN, NOT SKIPPED. The engine only enforces the conversation's
507
+ // grant when it is handed a `pageAccess` guard (engine.js uses `pageAccess?.` everywhere), so a
508
+ // run that omits it would prove the transport but silently skip the authorization path. This
509
+ // uses the partition's real BrowserAccess: the human "cites" the tab with @, and every read/act
510
+ // then carries the guard that pins the page, the origin and the abort signal.
511
+ const access = new BrowserAccess({ bridge, guardedPorts: [bridge.port] })
512
+ const sessionId = `verify-${RUN_ID}`
513
+ const cited = access.cite({ sessionId, refs: [ref, secondTab.ref],
514
+ text: `@[fixture](${ref}) @[second](${secondTab.ref})` })
515
+ assert.deepEqual([...cited.granted].sort(), [ref, secondTab.ref].sort(), 'both cited tabs must be granted')
516
+ assert.deepEqual(cited.refused, [])
517
+ const guard = access.pageAccess({ sessionId, ref })
518
+ const secondGuard = access.pageAccess({ sessionId, ref: secondTab.ref })
519
+ assert.equal(guard.ref, ref)
520
+ assert.equal(guard.signal.aborted, false)
521
+ // A reference that was never cited has no guard, which is what makes an omission detectable.
522
+ assert.throws(() => access.pageAccess({ sessionId, ref: `${ref}9` }), /revoked/i,
523
+ 'an uncited reference must not produce a usable guard')
524
+ // The guard itself refuses the DSH control surface: a tab sitting on this bridge's own port is
525
+ // never a browser target, and the engine would be driving it through this exact guard.
526
+ assert.throws(() => guard.assertUrl(`http://127.0.0.1:${bridge.port}/setup`),
527
+ /DSH control surface|never a browser target/i,
528
+ 'the bridge\'s own setup page must be refused by the granted guard')
529
+ assert.equal(guard.assertUrl(`${siteUrl}/`), true, 'the cited fixture page must remain admissible')
530
+
531
+ const tool = async run => {
532
+ // Every engine call goes through a real relay to a real browser, so a wedged renderer or a
533
+ // dropped socket can leave one pending forever. Bound it to the phase budget and name the
534
+ // stage in the error.
535
+ const result = await bounded(run(), TOOL_TIMEOUT_MS, 'an engine tool call')
536
+ toolOutputs.push(JSON.stringify(result ?? null))
537
+ return result
538
+ }
539
+
540
+ // read: real live DOM, not a cached fixture
541
+ stage('read')
542
+ const read = await tool(() => engine.read(ref, { limit: 8000, pageAccess: guard }, guard.signal))
543
+ assert.equal(read.tab, ref)
544
+ assert.equal(read.url, `${siteUrl}/`)
545
+ assert.match(read.content, new RegExp(marker), 'the read must contain the live per-load marker')
546
+ assert.match(read.content, /Browser integration fixture/)
547
+
548
+ // the HttpOnly login cookie works for the site and never shows up in a tool value
549
+ assert.ok(fixture.state.signedIn > 0, 'the fixture must have authenticated a request by cookie')
550
+ assert.equal(await ui(() => page.evaluate(() => document.cookie), 'the page cookie store to be readable'), '',
551
+ 'the session cookie is HttpOnly, so page script must not be able to read it')
552
+ for (const value of toolOutputs) {
553
+ assert.equal(value.includes(SESSION_SECRET), false, 'no tool value may contain the cookie value')
554
+ assert.equal(value.includes('e2e_session'), false, 'no tool value may contain the cookie name')
555
+ }
556
+
557
+ // act: fill + click, dispatched to the browser, then verified in the page and by a re-read
558
+ stage('act')
559
+ const nameRef = refFor(read.content, 'textbox', 'Name')
560
+ const saveRef = refFor(read.content, 'button', 'Save')
561
+ assert.ok(nameRef && saveRef, `the snapshot must expose the form controls: ${read.content}`)
562
+ const acted = await tool(() => engine.act(ref, { snapshot: read.snapshot, pageAccess: guard, steps: [
563
+ { op: 'fill', ref: nameRef, value: 'E2E' },
564
+ { op: 'click', ref: saveRef },
565
+ ] }))
566
+ assert.equal(acted.completed.length, 2)
567
+ assert.equal(await ui(() => page.locator('#out').textContent(), 'the click to reach the page handler'), 'Saved E2E',
568
+ 'the click must run the page handler')
569
+ // The page's own listener and the fixture server are the authorities on "one click happened";
570
+ // the CDP stream is only checked for the existence of a mouse dispatch, never its packet count.
571
+ assert.equal(await ui(() => page.evaluate(() => window.saveClicks), 'the page click counter'), 1,
572
+ 'the handler must run exactly once')
573
+ await waitFor(() => fixture.state.mutations >= 1, 'the page\'s handler to reach the fixture server')
574
+ assert.match((await tool(() => engine.read(ref, { limit: 4000, pageAccess: guard }))).content, /Saved E2E/)
575
+ assert.equal(drivingCommands(sent).some(entry => entry.command === 'Input.dispatchMouseEvent'), true,
576
+ 'the click must have been dispatched to the browser, not simulated in-process')
577
+
578
+ // iframe
579
+ stage('iframe')
580
+ const framed = await tool(() => engine.read(ref, { limit: 8000, pageAccess: guard }))
581
+ assert.match(framed.content, /Frame button/, 'the read must include iframe content')
582
+ const framedRef = frameRefFor(framed.content, 'button', 'Frame button')
583
+ const framedStep = framedRef ? { op: 'click', ref: framedRef } : { op: 'click', frame: '#frame', selector: '#frame-btn' }
584
+ assert.equal((await tool(() => engine.act(ref, { snapshot: framed.snapshot, pageAccess: guard, steps: [framedStep] }))).completed.length, 1)
585
+ await waitFor(async () => (await page.frameLocator('#frame').locator('#frame-btn').textContent()) === 'Frame clicked',
586
+ 'the iframe handler to run', TOOL_TIMEOUT_MS)
587
+
588
+ // identity: same tab, same window, no tab created or closed
589
+ const after = bridge.list()
590
+ const nowMain = after.find(row => row.url === `${siteUrl}/`)
591
+ const nowSecond = after.find(row => row.url === `${siteUrl}/second`)
592
+ assert.ok(nowMain && nowSecond, `both tabs must still be listed: ${JSON.stringify(after)}`)
593
+ assert.equal(nowMain.id, tabId, 'the tab id must not change')
594
+ assert.equal(nowMain.windowId, windowId, 'the window must not change')
595
+ assert.equal(nowSecond.id, secondTab.id, 'the other tab keeps its id')
596
+ assert.equal(drivingCommands(sent).every(entry => entry.target === ref), true,
597
+ 'only the referenced tab may be driven')
598
+ assert.equal(sent.some(entry => /Target\.(createTarget|closeTarget)/.test(entry.command)), false,
599
+ 'the bridge may never open or close a tab')
600
+ assert.equal(page.isClosed(), false)
601
+
602
+ // state that must be preserved: an unsubmitted form and a second tab's own state
603
+ stage('state')
604
+ await ui(() => page.locator('#name').fill(`draft-${RUN_ID}`), 'the draft field to accept input')
605
+ await ui(() => second.locator('#note').fill(`second-${RUN_ID}`), 'the second tab field to accept input')
606
+ await tool(() => engine.read(ref, { limit: 4000, pageAccess: guard }))
607
+ await tool(() => engine.capture(ref, { pageAccess: guard }))
608
+ assert.match((await tool(() => engine.read(secondTab.ref, { limit: 4000, pageAccess: secondGuard }))).content, /Unrelated tab/)
609
+ assert.equal(await ui(() => page.locator('#name').inputValue(), 'the draft field value'),
610
+ `draft-${RUN_ID}`,
611
+ 'reading a tab must not reset an unsubmitted form field')
612
+ // `#out` still shows the result of the one click above: reading must not re-run the handler.
613
+ assert.equal(await ui(() => page.locator('#out').textContent(), 'the earlier click result'), 'Saved E2E',
614
+ 'reading a tab must not re-submit or re-run the page handler')
615
+ assert.equal(await ui(() => second.locator('#note').inputValue(), 'the second tab field value'),
616
+ `second-${RUN_ID}`,
617
+ 'working on one tab must not disturb another tab')
618
+ assert.equal(await ui(() => second.locator('#marked').textContent(), 'the second tab result area'), '',
619
+ 'the second form must stay unsubmitted')
620
+
621
+ // pagination through a cursor, without duplicating content
622
+ stage('pagination')
623
+ const before = await tool(() => engine.read(ref, { limit: 4000, pageAccess: guard }))
624
+ await tool(() => engine.act(ref, { snapshot: before.snapshot, pageAccess: guard,
625
+ steps: [{ op: 'navigate', value: `${siteUrl}/long` }] }))
626
+ const first = await tool(() => engine.read(ref, { limit: 600, pageAccess: guard }))
627
+ assert.ok(first.cursor, 'a 600-character read of a long page must return a cursor')
628
+ const chunks = [first.content]
629
+ let pages = 0
630
+ for (let cursor = first.cursor; cursor;) {
631
+ assert.ok(pages++ < 100, 'pagination must terminate')
632
+ const next = await tool(() => engine.read(ref, { cursor, pageAccess: guard }))
633
+ assert.equal(next.snapshot, first.snapshot, 'a cursor page must continue the same snapshot')
634
+ chunks.push(next.content)
635
+ cursor = next.cursor
636
+ }
637
+ const whole = chunks.join('')
638
+ assert.match(whole, /Row 001/)
639
+ assert.match(whole, /Row 200/, 'pagination must reach the end of the list')
640
+ assert.equal((whole.match(/Row 200/g) ?? []).length, 1, 'pagination must not repeat content')
641
+
642
+ // full-page PNG on disk
643
+ stage('capture')
644
+ const capture = await tool(() => engine.capture(ref, { fullPage: true, pageAccess: guard }))
645
+ assert.ok(path.isAbsolute(capture.path) && capture.path.endsWith('.png'))
646
+ const image = pngSize(await readFile(capture.path))
647
+ const viewport = await ui(() => page.evaluate(() => ({ width: innerWidth, height: innerHeight })),
648
+ 'the viewport size')
649
+ assert.equal(image.width, viewport.width)
650
+ assert.ok(image.height > viewport.height, `a full-page PNG must be taller than ${viewport.height} px, got ${image.height}`)
651
+
652
+ // a stale snapshot is refused, and nothing is DRIVEN (read-only CDP is expected)
653
+ stage('stale')
654
+ await bounded(page.goto(`${siteUrl}/`, { waitUntil: 'domcontentloaded' }), TOOL_TIMEOUT_MS, 'the fixture page to reset')
655
+ const stale = await tool(() => engine.read(ref, { limit: 4000, pageAccess: guard }))
656
+ await bounded(page.reload({ waitUntil: 'domcontentloaded' }), TOOL_TIMEOUT_MS, 'the fixture page to reload for the stale check')
657
+ const mutationsBefore = fixture.state.mutations
658
+ const clicksBefore = await ui(() => page.evaluate(() => window.saveClicks ?? 0), 'the pre-refusal click counter')
659
+ const sentBefore = sent.length
660
+ await assert.rejects(() => engine.act(ref, { snapshot: stale.snapshot, pageAccess: guard,
661
+ steps: [{ op: 'click', selector: '#save' }] }),
662
+ /stale/i, 'acting on a snapshot taken before the reload must be refused')
663
+ // 1. no INPUT command was dispatched. Reading the live document to detect staleness is not a
664
+ // side effect, so only driving commands are filtered out of this check.
665
+ assert.deepEqual(drivingCommands(sent.slice(sentBefore)), [],
666
+ 'a refused action must dispatch no input, file or navigation command')
667
+ // 2. the page itself is untouched: the handler did not run and the field kept its value.
668
+ assert.equal(await ui(() => page.locator('#out').textContent(), 'the result area after a refusal'), '',
669
+ 'a refused action must not have clicked anything')
670
+ assert.equal(await ui(() => page.locator('#name').inputValue(), 'the field value after a refusal'), '',
671
+ 'a refused action must not have typed anything')
672
+ assert.equal(await ui(() => page.evaluate(() => window.saveClicks ?? 0), 'the post-refusal click counter'),
673
+ clicksBefore,
674
+ 'the button handler must not have run for a refused action')
675
+ // 3. the server saw no mutation, which a click could not hide from.
676
+ await delay(200)
677
+ assert.equal(fixture.state.mutations, mutationsBefore,
678
+ 'a refused action must not reach the server')
679
+
680
+ // disconnect: in-flight work fails, the tab stays usable, the port is released
681
+ stage('disconnect')
682
+ const bridgePort = bridge.port
683
+ await bounded(bridge.close(), TOOL_TIMEOUT_MS, 'the bridge to close')
684
+ assert.equal(bridge.relays.size, 0, 'closing the bridge must drop every relay')
685
+ // The listener is gone, so the relay cannot be opened again: the read must fail rather than
686
+ // hand back a stale page. Which of the three real paths reports it depends on how far the
687
+ // teardown got (profile already dropped, socket closed, or connect refused), so all are accepted.
688
+ await assert.rejects(() => engine.read(ref, { limit: 2000, pageAccess: guard }),
689
+ /ECONNREFUSED|ECONNRESET|disconnect|offline|not connected|closed|stopped|WebSocket|socket hang up|authorized window|revoked/i,
690
+ 'a read after the bridge closes must fail instead of returning a page')
691
+ // Losing the browser profile revokes the conversation's grant, exactly as it does for a user who
692
+ // closes the browser window: the OLD guard must be dead, not merely unusable by luck.
693
+ await waitFor(() => guard.signal.aborted, 'the old conversation grant to be revoked on disconnect', TOOL_TIMEOUT_MS)
694
+ assert.equal(guard.signal.reason?.code, 'BROWSER_ACCESS_CHANGED',
695
+ 'a dropped browser profile must revoke with BROWSER_ACCESS_CHANGED')
696
+ assert.throws(() => guard.assertUrl(`${siteUrl}/`),
697
+ error => error?.code === 'BROWSER_ACCESS_CHANGED',
698
+ 'a revoked guard must refuse its own page rather than keep authorising it')
699
+ assert.equal(access.refs(sessionId).has(ref), false, 'the revoked tab must leave the session\'s grant set')
700
+ // An unsubmitted form field set BEFORE the disconnect must still be there afterwards: this is the
701
+ // user's own page and nothing in a reconnect may reload, reset or re-submit it.
702
+ const draftAcrossReconnect = `kept-${RUN_ID}`
703
+ await bounded(page.locator('#name').fill(draftAcrossReconnect), TOOL_TIMEOUT_MS, 'the draft field to accept input')
704
+ assert.equal(await ui(() => page.locator('#name').inputValue(), 'the pre-disconnect draft value'),
705
+ draftAcrossReconnect,
706
+ 'closing the bridge must leave the user\'s tab open and usable')
707
+ // The port probe is bounded: `listen` on a port still held never calls back, and an unbounded
708
+ // await there would burn the whole watchdog with no diagnosis.
709
+ const rebound = await bounded(new Promise(resolve => {
710
+ const probe = createNetServer()
711
+ probe.once('error', () => resolve(false))
712
+ probe.listen(bridgePort, '127.0.0.1', () => probe.close(() => resolve(true)))
713
+ }), TOOL_TIMEOUT_MS, 'the released bridge port to be re-bindable')
714
+ assert.equal(rebound, true, 'the bridge must release its port on close')
715
+
716
+ // reconnect: the already-paired extension comes back without pairing again
717
+ stage('reconnect')
718
+ bridge = new BrowserBridge({ home: path.join(scratch, 'bridge'), port: bridgePort,
719
+ extensionSource: EXTENSION_DIR, idleTimeoutMs: 5_000 })
720
+ bridge.playwright = { chromium }
721
+ bridge.on('commandSent', (target, command) => sent.push({ target, command }))
722
+ await bounded(bridge.start(), STARTUP_TIMEOUT_MS, 'the restarted bridge to listen')
723
+ // The extension retries with exponential backoff (up to 30 s), so give it room to come back.
724
+ await waitFor(() => bridge.list().some(row => row.ref === ref), 'the paired extension to reconnect', 75_000)
725
+ assert.equal(bridge.pairings.list().length, 0, 'an already-paired browser must not ask to pair again')
726
+
727
+ // The user cites the SAME tab again in the new conversation state. This is not a workaround for
728
+ // the revoked guard: authorization belongs to a live session bound to a live profile, so a new
729
+ // bridge (new profile, new AbortSignal) legitimately needs a new citation.
730
+ const nextAccess = new BrowserAccess({ bridge, guardedPorts: [bridge.port] })
731
+ const nextSession = `verify-${RUN_ID}-re`
732
+ const recitation = nextAccess.cite({ sessionId: nextSession, refs: [ref], text: `@[fixture](${ref})` })
733
+ assert.deepEqual(recitation.granted, [ref], 're-citing the same tab on the new bridge must grant it')
734
+ const nextGuard = nextAccess.pageAccess({ sessionId: nextSession, ref })
735
+ assert.equal(nextGuard.signal.aborted, false, 'the new grant must be live')
736
+
737
+ // A fresh engine for the new bridge: the previous one still names the closed one.
738
+ stage('reconnect-read')
739
+ const reconnected = new BrowserEngine(bridge, { artifactDir: path.join(scratch, 'captures') })
740
+ assert.match((await tool(() => reconnected.read(ref, { limit: 4000, pageAccess: nextGuard }))).content, /Browser integration fixture/,
741
+ 'the same tab reference must resolve after the bridge restarts')
742
+ assert.equal(await ui(() => page.locator('#name').inputValue(), 'the post-reconnect draft value'),
743
+ draftAcrossReconnect,
744
+ 'reconnecting must not reload or reset the page; the pre-disconnect draft must survive')
745
+
746
+ // The host layer this partition exposes to the plugin entry (lib/index.js): constructible and
747
+ // wired to a bridge. Route dispatch, DSH same-origin enforcement and per-session scoping need a
748
+ // real DSH process and its services, so they are NOT covered here — see the coverage note at
749
+ // the top of this file. A bridge of its own keeps this check independent of the live run, whose
750
+ // engine and relay must stay untouched until cleanup.
751
+ stage('host-wiring')
752
+ const { BrowserHost } = await import(pathToFileURL(path.join(ROOT, 'lib/browser/host.js')).href)
753
+ assert.equal(typeof BrowserHost, 'function', 'lib/browser/host.js must export the BrowserHost class')
754
+ const hostBridge = new BrowserBridge({ home: path.join(scratch, 'host-bridge'), port: 0,
755
+ extensionSource: EXTENSION_DIR })
756
+ const host = new BrowserHost({ bridge: hostBridge, ctx: {}, config: {}, log: null,
757
+ artifacts: path.join(scratch, 'captures') })
758
+ assert.equal(host.bridge, hostBridge, 'the host must drive the bridge it was given')
759
+ assert.equal(typeof host.list, 'function', 'the host must expose the tab list the sidebar shows')
760
+ assert.equal(typeof host.accessState, 'function', 'the host must expose per-session access state')
761
+ assert.equal(typeof host.close, 'function', 'the host must expose a shutdown entry')
762
+ host.close()
763
+
764
+ stage('done')
765
+ console.log(`\nPASS real browser: headless Chromium with the unpacked extension, human pairing, ` +
766
+ 'inventory discovery, read, DOM actions with verified results, iframe, pagination, full-page PNG, ' +
767
+ 'cookie isolation, form/tab state preserved, stale rejection, disconnect and reconnect.')
768
+ console.log(JSON.stringify({ suite: 'verify-browser-integration', ok: true, chrome, extension: EXTENSION_DIR }))
769
+ }
770
+ } catch (error) {
771
+ console.error(`\nFAILED during stage "${STAGE}": ${error?.message ?? error}`)
772
+ if (typeof error?.stack === 'string') console.error(error.stack.split('\n').slice(0, 6).join('\n'))
773
+ console.log(JSON.stringify({ suite: 'verify-browser-integration', ok: false, stage: STAGE,
774
+ error: String(error?.message ?? error) }))
775
+ process.exitCode = 1
776
+ } finally {
777
+ // CLEANUP IS BOUNDED PER STEP. A wedged browser or a keep-alive socket still held by the fixture
778
+ // server can make any of these never call back, and the whole point of this block is to leave the
779
+ // process able to report its own result — an unbounded `await` here is exactly how a run that
780
+ // already decided to fail dies at the watchdog with no output.
781
+ stage('cleanup')
782
+ try { if (bridge?.started) await bounded(bridge.close(), 20_000, 'the bridge to close') } catch { /* already closed */ }
783
+ try { if (context) await bounded(context.close(), 30_000, 'the browser to close') } catch { /* already closed */ }
784
+ try {
785
+ if (site?.listening) {
786
+ // `server.close` only stops accepting and waits for live sockets. The fixture page may still
787
+ // hold a keep-alive connection, so the callback can be postponed indefinitely; close idle
788
+ // connections first and give the rest a hard deadline.
789
+ site.closeIdleConnections?.()
790
+ site.closeAllConnections?.()
791
+ await bounded(new Promise(resolve => site.close(resolve)), 10_000, 'the fixture server to close')
792
+ }
793
+ } catch { /* already closed */ }
794
+ if (scratch) {
795
+ if (KEEP) console.log(`INFO kept ${scratch}`)
796
+ // Only the directory this run created, and only after proving where it is.
797
+ else if (path.dirname(path.resolve(scratch)) === path.resolve(WORK_ROOT) &&
798
+ path.basename(scratch).startsWith('dsh-browser-e2e-')) {
799
+ // Chromium can still hold its profile briefly after close(); that must not mask the result.
800
+ try { await bounded(rm(scratch, { recursive: true, force: true, maxRetries: 10, retryDelay: 300 }),
801
+ 60_000, 'the scratch directory to be removed') } catch (error) {
802
+ console.error(`WARN could not remove ${scratch}: ${error.message}`)
803
+ }
804
+ } else console.error(`WARN not removing an unexpected directory: ${scratch}`)
805
+ }
806
+ clearTimeout(watchdog)
807
+ }