1
0

scaffold.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  1. // Shared scaffold for the keyless browser e2e lane (Agent Note:
  2. // .agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.md).
  3. // Boots the REAL web composition — the shipped base plus web overlay through
  4. // the vendored Loader (the same include boot AppCLIEntry drives), patched the
  5. // snapshot way — so a real chromium exercises the real HTTP/SSE wire, the
  6. // api-gateway, agent loop, tools, and persistence. Modes ride $DSH_SNAPSHOT:
  7. // replay (default, keyless: llm-deepseek row disabled, dsh-llm-replay row
  8. // inserted in providers mode), record (real adapter + key, harvests fixtures
  9. // from live session memory), refresh (keyless replay that rewrites goldens).
  10. //
  11. // Composition divergences from `dsh web`, all deliberate, all via include
  12. // patches after the shipped surface overlay: temp persistenceRoot;
  13. // workspace-context disabled (recorded fixtures must not embed this repo's
  14. // AGENTS.md); session-title-llm disabled (its fire-and-forget title call
  15. // would race the loop for the session's replay cursor); webserver pinned to
  16. // port 0 with the built dist; keyless modes disable llm-deepseek and fill
  17. // the open llm seam post-boot with installLlmReplay on the settled root ctx
  18. // (the plugin-row path discards the ReplayHandle; the direct install keeps
  19. // assertConsumed for the teardown fixture-consumption check).
  20. import { existsSync } from 'node:fs'
  21. import { mkdtemp, readFile, readdir, realpath, rm, utimes, writeFile } from 'node:fs/promises'
  22. import { tmpdir } from 'node:os'
  23. import { join, resolve } from 'node:path'
  24. import { pathToFileURL } from 'node:url'
  25. import type { Page } from 'playwright'
  26. import { expect } from 'vitest'
  27. import { Context } from 'cordis'
  28. import Loader from '@cordisjs/plugin-loader'
  29. import Include, { type PatchOptions } from '@cordisjs/plugin-include'
  30. import { scrubRequestHeaders } from '@deepseek-ai/dsh-acp-snapshot'
  31. import { assertEntriesLoaded, loadOverlayPatches } from '@deepseek-ai/dsh-app-boot'
  32. import type { ReplayHandle } from '@deepseek-ai/dsh-llm-replay'
  33. import { installLlmReplay, parseSessionLog } from '@deepseek-ai/dsh-llm-replay'
  34. import SessionStore, {
  35. packChunkRuns,
  36. SESSION_FORMAT_VERSION,
  37. SessionId,
  38. type Session,
  39. type SessionEvent,
  40. type SessionHeader,
  41. } from '@deepseek-ai/dsh-session'
  42. import SessionPersistenceJsonl from '@deepseek-ai/dsh-session-persistence-jsonl'
  43. import * as ToolCordis from '@deepseek-ai/dsh-tool-cordis'
  44. // Empty type imports carry the httpServer/agents/sessionPersistence Context merges.
  45. import type {} from '@deepseek-ai/dsh-host-webserver'
  46. import type {} from '@deepseek-ai/dsh-agent'
  47. import { DIST_INDEX, REPO_ROOT, requireDist } from './support.ts'
  48. /** Snapshot mode for the lane, from $DSH_SNAPSHOT (same vocabulary as the ACP/TUI suites). */
  49. export type WebSnapshotMode = 'replay' | 'record' | 'refresh'
  50. /**
  51. * Resolve and validate the lane's snapshot mode.
  52. * @returns the active mode; unset/empty selects replay.
  53. */
  54. export function webSnapshotMode(): WebSnapshotMode {
  55. const value = process.env.DSH_SNAPSHOT
  56. if (value === undefined || value === '' || value === 'replay') return 'replay'
  57. if (value === 'record' || value === 'refresh') return value
  58. throw new Error(`DSH_SNAPSHOT must be replay, record, or refresh; got ${JSON.stringify(value)}`)
  59. }
  60. /** The shipped composition under test: apps/cli's shared base and web overlay. */
  61. const CONFIG_PATH = join(REPO_ROOT, 'apps/cli/config/base.cordis.yml')
  62. const WEB_OVERLAY_PATH = join(REPO_ROOT, 'apps/cli/config/web.cordis.yml')
  63. // Replay publishes the provider catalog the gateway routes to (providers
  64. // mode, never catch-all: with llm-deepseek disabled no adapter exists, so a
  65. // catch-all would leave resolveModelInfo unroutable and compact-basic's
  66. // post-step pressure check would warn every step). The published
  67. // contextWindow keeps that pressure path provably inert for small fixtures.
  68. const REPLAY_PROVIDERS = [{
  69. id: 'deepseek',
  70. name: 'DeepSeek',
  71. models: [{ id: 'deepseek-v4-flash', name: 'DeepSeek-V4-Flash', contextWindow: 128_000 }],
  72. }]
  73. /** A booted web scaffold: real composition, mode-selected model backend, temp world. */
  74. export interface WebScaffold {
  75. /** The active snapshot mode this scaffold booted under. */
  76. mode: WebSnapshotMode
  77. /** Browser-facing origin (http://127.0.0.1:<bound port>). */
  78. baseUrl: string
  79. /** Settled root context (the in-process barrier seam; headless event subscription is its sanctioned use). */
  80. ctx: Context
  81. /** Temp project directory sessions run in (bash/fs tool cwd). */
  82. workspaceCwd: string
  83. /** Temp persistence root (seeded sessions land here through the real API). */
  84. persistenceRoot: string
  85. /** Await a settled turn end: in-process turn/end, then the agent's idle flip (which follows the persistence flush). */
  86. whenTurnSettled(timeoutMs?: number): Promise<SessionId>
  87. /** Tear everything down; asserts the replay fixture was fully consumed first (replay/refresh). */
  88. close(): Promise<void>
  89. }
  90. /** Options for {@link launchWebScaffold}. */
  91. export interface LaunchOptions {
  92. /**
  93. * Replay fixture (session.jsonl) served by the inserted dsh-llm-replay row
  94. * in replay/refresh modes; ignored in record mode (the real adapter
  95. * answers). Omit for scenarios issuing no model calls — a stray stream then
  96. * fails loud with NO_ADAPTER (llm-deepseek is disabled and no replay row
  97. * mounts).
  98. */
  99. replayFixture?: string
  100. /**
  101. * Optional replay.override.json sidecar (whole-script replacement or
  102. * `{ patches }` augmentation) for throw/hang scenarios not expressible as
  103. * recorded chunks; replay/refresh only.
  104. */
  105. replayOverride?: string
  106. /** Per-chunk replay pacing (ms) so the browser observes genuinely incremental SSE; replay/refresh only. */
  107. paceMs?: number
  108. /**
  109. * Tool presentation mode patched onto the shipped `tools` row (`code`
  110. * collapses the wire to run_code + the SDK prompt section). Omit for the
  111. * yml default. The code runtime row is always in the tree, so no extra
  112. * insertion is needed.
  113. */
  114. toolsMode?: 'native' | 'code' | 'both'
  115. /**
  116. * Insert the opt-in self-referential Cordis tools into the shipped tree.
  117. * Record and replay use the same tool surface, so captured request headers
  118. * remain reconstructable without making the tools a product default.
  119. */
  120. cordisTools?: boolean
  121. }
  122. /** Dispose the booted tree and remove both owned temp roots, reporting every independent cleanup failure. */
  123. async function cleanupScaffoldWorld(ctx: Context, workspaceCwd: string, persistenceRoot: string): Promise<unknown[]> {
  124. const failures: unknown[] = []
  125. await Promise.resolve(ctx.fiber.dispose()).catch((error: unknown) => failures.push(error))
  126. await rm(workspaceCwd, { recursive: true, force: true }).catch((error: unknown) => failures.push(error))
  127. await rm(persistenceRoot, { recursive: true, force: true }).catch((error: unknown) => failures.push(error))
  128. return failures
  129. }
  130. /**
  131. * Boot the real web composition under the current snapshot mode.
  132. * @param options - replay fixture selection and pacing.
  133. * @returns the running scaffold.
  134. */
  135. export async function launchWebScaffold(options: LaunchOptions = {}): Promise<WebScaffold> {
  136. requireDist()
  137. const mode = webSnapshotMode()
  138. if (mode === 'record') {
  139. // Both owning vitest configs (web unconditionally, snapshot in record
  140. // mode) load the repo-root .env before this file runs.
  141. if (process.env.DEEPSEEK_API_KEY === undefined || process.env.DEEPSEEK_API_KEY.length === 0) {
  142. throw new Error('web e2e record mode needs DEEPSEEK_API_KEY (env or repo-root .env)')
  143. }
  144. }
  145. const workspaceCwd = await realpath(await mkdtemp(join(tmpdir(), 'dsh-web-e2e-ws-')))
  146. let persistenceRoot: string
  147. try {
  148. persistenceRoot = await mkdtemp(join(tmpdir(), 'dsh-web-e2e-sessions-'))
  149. } catch (error) {
  150. const failures: unknown[] = [error]
  151. await rm(workspaceCwd, { recursive: true, force: true }).catch((cleanupError: unknown) => failures.push(cleanupError))
  152. if (failures.length > 1) throw new AggregateError(failures, 'web scaffold temp-root setup failed')
  153. throw error
  154. }
  155. // The include patch set — the same mechanism AppCLIEntry and the ACP
  156. // snapshot overlay use, applied over the SAME shipped tree (a patch id that
  157. // stops matching a row fails the boot sweep loudly instead of drifting).
  158. const surfacePatches = loadOverlayPatches('web e2e scaffold', WEB_OVERLAY_PATH)
  159. const patches: PatchOptions[] = [
  160. ...surfacePatches,
  161. { id: 'session-persistence-jsonl', config: { root: persistenceRoot } },
  162. // storage-json's './.storages' yml default is cwd-relative and resolves
  163. // per write; the scaffold restores the original cwd after boot, so the
  164. // row gets an absolute temp root (removed with the workspace at close).
  165. { id: 'storage-json', config: { root: join(workspaceCwd, '.dsh-storages') } },
  166. // fs/bash cwd default to process.cwd(); the gateway injects the same
  167. // value into session.cwd — chdir below anchors all three to the temp
  168. // workspace, keeping the composition untouched.
  169. { id: 'workspace-context', disabled: true },
  170. { id: 'session-title-llm', disabled: true },
  171. { id: 'webserver', config: { host: '127.0.0.1', port: 0, distIndex: DIST_INDEX } },
  172. ...options.toolsMode === undefined ? [] : [{ id: 'tools', config: { mode: options.toolsMode } }],
  173. ...options.cordisTools === true
  174. ? [{ insert: [{ id: 'tool-cordis', name: 'cordis:tool-cordis' }] }]
  175. : [],
  176. ...mode === 'record' ? [] : [{ id: 'llm-deepseek', disabled: true }],
  177. ]
  178. // Sessions inherit the gateway's process.cwd() default; run the boot from
  179. // the temp workspace so tool cwd, session cwd, and fixtures agree.
  180. const originalCwd = process.cwd()
  181. const ctx = new Context()
  182. let port = 0
  183. let replayHandle: ReplayHandle | undefined
  184. try {
  185. process.chdir(workspaceCwd)
  186. ctx.baseUrl = pathToFileURL(join(resolve(CONFIG_PATH), '..')).href + '/'
  187. await ctx.plugin(Loader)
  188. ctx.loader.builtins.include = Include
  189. // The shipped CLI deliberately has no dependency on this opt-in package.
  190. // Keep the Loader row real without broadening the product installation.
  191. if (options.cordisTools === true) ctx.loader.builtins['tool-cordis'] = ToolCordis
  192. await ctx.loader.create({
  193. name: 'cordis:include',
  194. config: { path: pathToFileURL(resolve(CONFIG_PATH)).href, patches },
  195. })
  196. await ctx.loader.await()
  197. assertEntriesLoaded(ctx, 'web e2e scaffold')
  198. const boundPort = ctx.get('httpServer')?.port
  199. if (boundPort === undefined) {
  200. throw new Error('web e2e scaffold: httpServer service missing after settled boot')
  201. }
  202. port = boundPort
  203. // Fill the open llm seam on the settled root ctx (llm-deepseek is disabled
  204. // in keyless modes; a scenario with no fixture leaves the seam empty so a
  205. // stray stream fails loud with NO_ADAPTER). The direct install, unlike the
  206. // plugin row, returns the ReplayHandle for the teardown consumption check.
  207. if (mode !== 'record' && options.replayFixture !== undefined) {
  208. replayHandle = installLlmReplay(ctx, {
  209. file: options.replayFixture,
  210. providers: REPLAY_PROVIDERS,
  211. ...(options.replayOverride === undefined ? {} : { overrideFile: options.replayOverride }),
  212. ...(options.paceMs === undefined ? {} : { paceMs: options.paceMs }),
  213. })
  214. }
  215. } catch (error) {
  216. if (process.cwd() !== originalCwd) process.chdir(originalCwd)
  217. const cleanupFailures = await cleanupScaffoldWorld(ctx, workspaceCwd, persistenceRoot)
  218. if (cleanupFailures.length > 0) {
  219. throw new AggregateError([error, ...cleanupFailures], 'web scaffold setup failed and cleanup was incomplete')
  220. }
  221. throw error
  222. } finally {
  223. if (process.cwd() !== originalCwd) process.chdir(originalCwd)
  224. }
  225. return {
  226. mode,
  227. baseUrl: `http://127.0.0.1:${port}`,
  228. ctx,
  229. workspaceCwd,
  230. persistenceRoot,
  231. // Barrier stack: the in-process turn/end identifies the session, then
  232. // agent.whenIdle() covers the persistence flush (the idle flip follows
  233. // the flush), and the caller's browser settled-poll comes last because
  234. // host completion strictly precedes render.
  235. whenTurnSettled(timeoutMs = mode === 'record' ? 180_000 : 30_000): Promise<SessionId> {
  236. return new Promise<SessionId>((resolveSettled, reject) => {
  237. const timer = setTimeout(() => {
  238. off()
  239. reject(new Error(`no turn/end within ${timeoutMs}ms`))
  240. }, timeoutMs)
  241. const off = ctx.on('session/event', (session: { id: SessionId }, event: SessionEvent) => {
  242. if (event.type !== 'turn/end') return
  243. clearTimeout(timer)
  244. off()
  245. const agent = ctx.agents.get(session.id)
  246. if (agent === undefined) {
  247. reject(new Error(`turn/end for ${session.id} but no live agent`))
  248. return
  249. }
  250. agent.whenIdle().then(() => { resolveSettled(session.id) }, reject)
  251. })
  252. })
  253. },
  254. async close(): Promise<void> {
  255. const failures: unknown[] = []
  256. // Fixture-consumption check first, while the run's binding state is
  257. // still authoritative — a scenario that drove fewer model calls than
  258. // recorded fails here instead of drifting green.
  259. try {
  260. replayHandle?.assertConsumed()
  261. } catch (error) {
  262. failures.push(error)
  263. }
  264. failures.push(...await cleanupScaffoldWorld(ctx, workspaceCwd, persistenceRoot))
  265. if (failures.length > 0) throw new AggregateError(failures, 'web scaffold teardown failed')
  266. },
  267. }
  268. }
  269. /**
  270. * Serialize a live session to the canonical raw session-JSONL layout — the
  271. * in-memory record-mode harvest, so the on-disk zstd default never matters.
  272. */
  273. function rawSessionLog(session: Session): string {
  274. return [
  275. JSON.stringify({ type: 'session', ...session.header }),
  276. ...packChunkRuns(session.events).map(record => JSON.stringify(record)),
  277. '',
  278. ].join('\n')
  279. }
  280. /**
  281. * Record-mode fixture write-back: harvest the live session, scrub request
  282. * headers to {{system}}/{{tools}} (TODO(web-header-pin): the web lane pins no
  283. * header class — a deliberate deviation logged in the Agent Note's deferred
  284. * work), tokenize the run-local session id, cwd, and browser RPC id
  285. * ({{sessionId}}/{{cwd}}/{{rpcId}}, the committed fixture convention —
  286. * re-records then diff only on real content), and write the fixture.
  287. * @param scaffold - the record-mode scaffold.
  288. * @param sessionId - the driven session.
  289. * @param fixturePath - the committed session.jsonl / seed.jsonl target.
  290. */
  291. export async function recordFixture(scaffold: WebScaffold, sessionId: SessionId, fixturePath: string): Promise<void> {
  292. const agent = scaffold.ctx.agents.get(sessionId)
  293. if (agent === undefined) throw new Error(`record harvest: no live agent for ${sessionId}`)
  294. const tokenized = scrubRequestHeaders(rawSessionLog(agent.session))
  295. .split(sessionId).join('{{sessionId}}')
  296. .split(scaffold.workspaceCwd).join('{{cwd}}')
  297. .replace(/"rpcId":"[^"]+"/g, '"rpcId":"{{rpcId}}"')
  298. await writeFile(fixturePath, tokenized)
  299. }
  300. /**
  301. * The user prompts recorded in a fixture, in order — the single source tying
  302. * spec drive steps to recorded reality so script and fixture cannot drift.
  303. * @param fixtureText - raw session.jsonl contents.
  304. * @returns the recorded user prompt texts.
  305. */
  306. export function fixtureUserPrompts(fixtureText: string): string[] {
  307. return parseSessionLog(fixtureText).flatMap((event) => {
  308. if (event.type !== 'user/message' || event.data.source.kind !== 'user') return []
  309. const text = event.data.content.filter(block => block.type === 'text').map(block => block.text).join('')
  310. return text.length > 0 ? [text] : []
  311. })
  312. }
  313. /**
  314. * Seed a recorded session fixture into the scaffold's persistence root
  315. * through the REAL backend API (throwaway Context + SessionStore + JSONL
  316. * plugin — the semantic-checkpoint precedent), never raw file writes: no
  317. * knowledge of bucket hashing, filename encoding, or compression, and
  318. * malformed shapes fail loud at seed time. The fixture's tokenized identity
  319. * ({{sessionId}}/{{cwd}}) is realized for this world before parsing.
  320. * @param scaffold - the target scaffold.
  321. * @param fixtureText - raw recorded session.jsonl contents.
  322. * @param id - the seeded session id (stable for deterministic goldens).
  323. * @returns the seeded id.
  324. */
  325. export async function seedSession(scaffold: WebScaffold, fixtureText: string, id: string): Promise<SessionId> {
  326. const realized = fixtureText
  327. .split('{{sessionId}}').join(id)
  328. .split('{{cwd}}').join(scaffold.workspaceCwd)
  329. const fixtureCwd = (JSON.parse(realized.split('\n', 1)[0]!) as { cwd?: string }).cwd
  330. const rewritten = fixtureCwd === undefined
  331. ? realized
  332. : realized.split(fixtureCwd).join(scaffold.workspaceCwd)
  333. const events = parseSessionLog(rewritten)
  334. if (events.length === 0) throw new Error('seed fixture has no events')
  335. const last = events[events.length - 1]!
  336. // An open final turn would be mutated by resume's crash repair on first
  337. // open; a committed seed must be a closed recording.
  338. if (last.type !== 'turn/end') throw new Error(`seed fixture must end in turn/end, got ${last.type}`)
  339. const meta: SessionHeader = {
  340. version: SESSION_FORMAT_VERSION,
  341. id: SessionId(id),
  342. createdAt: Date.now() - 60_000,
  343. cwd: scaffold.workspaceCwd,
  344. delegationDepth: 0,
  345. }
  346. const seeder = new Context()
  347. try {
  348. await seeder.plugin(SessionStore)
  349. // Same root as the booted tree with the plugin's own default compression,
  350. // so the host's directory-scan list() sees one consistent encoding.
  351. await seeder.plugin(SessionPersistenceJsonl, { root: scaffold.persistenceRoot })
  352. await seeder.sessionPersistence.create(meta)
  353. await seeder.sessionPersistence.append(meta.id, events)
  354. // Deterministic sidebar order: cold summaries take updatedAt from mtime.
  355. const located = seeder.sessionPersistence.locate(meta)
  356. if (located !== undefined) {
  357. const backdated = new Date(meta.createdAt)
  358. await utimes(located.path, backdated, backdated)
  359. }
  360. } finally {
  361. await seeder.fiber.dispose()
  362. }
  363. return meta.id
  364. }
  365. /**
  366. * Normalize an aria snapshot: uuid, cwd, workspace-basename, and duration
  367. * volatility collapse to stable tokens.
  368. */
  369. function normalizeAria(snapshot: string, workspaceCwd: string): string {
  370. // The header breadcrumb renders the workspace's basename, not the full
  371. // path, so both spellings must collapse to the token.
  372. const base = workspaceCwd.split('/').pop()!
  373. return snapshot
  374. .split(workspaceCwd).join('{{cwd}}')
  375. .split(base).join('{{workspace}}')
  376. .replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi, '{{uuid}}')
  377. .replace(/\b\d+(?:\.\d+)?(?:ms|s|秒)\b/g, '{{duration}}')
  378. // Message IconActions clocks widen by calendar day/year; collapse every
  379. // shape so goldens stay stable across midnight and year boundaries.
  380. .replace(/\d{4}年\d{1,2}月\d{1,2}日 \d{2}:\d{2}/g, '{{clock}}')
  381. .replace(/\d{1,2}月\d{1,2}日 \d{2}:\d{2}/g, '{{clock}}')
  382. .replace(/(?<!\d)\d{2}:\d{2}(?!\d)/g, '{{clock}}')
  383. }
  384. /**
  385. * Capture the region's aria snapshot at a settled milestone: poll until two
  386. * consecutive normalized captures are equal — a single-shot capture races the
  387. * last React commits.
  388. * @param page - the page under test.
  389. * @param selector - the region locator selector.
  390. * @param workspaceCwd - normalization input.
  391. * @returns the stable normalized snapshot.
  392. */
  393. export async function captureStableAria(page: Page, selector: string, workspaceCwd: string): Promise<string> {
  394. const region = page.locator(selector).first()
  395. let previous = normalizeAria(await region.ariaSnapshot(), workspaceCwd)
  396. await expect.poll(async () => {
  397. const current = normalizeAria(await region.ariaSnapshot(), workspaceCwd)
  398. const stable = current === previous
  399. previous = current
  400. return stable
  401. }, { timeout: 5_000, message: 'aria snapshot did not stabilize' }).toBe(true)
  402. return previous
  403. }
  404. /**
  405. * Compare a normalized golden, or rewrite it under refresh. Refresh is the
  406. * ONLY writer: a missing golden in replay mode fails with the healing command
  407. * instead of silently self-bootstrapping.
  408. * @param goldenPath - the committed ui.expected.md path.
  409. * @param actual - the stable normalized snapshot.
  410. * @param mode - the active snapshot mode.
  411. */
  412. export async function compareOrRefreshGolden(goldenPath: string, actual: string, mode: WebSnapshotMode): Promise<void> {
  413. const payload = `${actual}\n`
  414. if (mode === 'refresh') {
  415. await writeFile(goldenPath, payload)
  416. return
  417. }
  418. if (!existsSync(goldenPath)) {
  419. throw new Error(`missing golden ${goldenPath} — run DSH_SNAPSHOT=refresh pnpm run test:web to generate it`)
  420. }
  421. expect(payload).toBe(await readFile(goldenPath, 'utf8'))
  422. }
  423. /**
  424. * Fixture-inventory guard (the TUI afterAll shape): the scenario directory
  425. * holds exactly the expected files and every committed JSONL is a scrub
  426. * fixed-point without a run-local browser RPC id.
  427. * @param dir - the scenario snapshot directory.
  428. * @param expected - the exact expected file inventory.
  429. */
  430. export async function assertFixtureInventory(dir: string, expected: string[]): Promise<void> {
  431. const entries = (await readdir(dir)).sort()
  432. expect(entries).toEqual([...expected].sort())
  433. for (const entry of entries.filter(name => name.endsWith('.jsonl'))) {
  434. const content = await readFile(join(dir, entry), 'utf8')
  435. expect(scrubRequestHeaders(content), `${dir}/${entry} carries request-header bulk`).toBe(content)
  436. expect(content, `${dir}/${entry} carries a run-local rpcId`)
  437. .not.toMatch(/"rpcId":"(?!\{\{rpcId\}\})[^"]+"/)
  438. }
  439. }
  440. /**
  441. * Console tripwires: reconnect/gap-repair self-healing or a pageerror must
  442. * fail the scenario, not mask a dead wire behind eventual consistency.
  443. * @param page - the page under test.
  444. * @returns live warning/pageerror collectors to assert empty at scenario end.
  445. */
  446. export function watchConsole(page: Page): { warnings: string[]; pageErrors: string[] } {
  447. const warnings: string[] = []
  448. const pageErrors: string[] = []
  449. page.on('console', (message) => {
  450. const text = message.text()
  451. if (/connection lost|gap repair|discontinuous/i.test(text)) warnings.push(text)
  452. })
  453. page.on('pageerror', (error) => { pageErrors.push(String(error)) })
  454. return { warnings, pageErrors }
  455. }
  456. /**
  457. * Remove only connection-loss warnings emitted after an intentional reload.
  458. * Earlier warnings and all gap-repair/discontinuity warnings remain fatal.
  459. * @param tripwire - the live console-warning collector.
  460. * @param warningStart - warning count captured immediately before reloading.
  461. */
  462. export function acknowledgeReloadConnectionLoss(
  463. tripwire: ReturnType<typeof watchConsole>,
  464. warningStart: number,
  465. ): void {
  466. const reloadWarnings = tripwire.warnings.splice(warningStart)
  467. tripwire.warnings.push(...reloadWarnings.filter(text => !/connection lost/i.test(text)))
  468. }