scaffold.ts 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955
  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 dsh-base and dsh-web-app bundle
  4. // patches over the empty profile root through the vendored Loader (the same
  5. // layer stack the profile boot composes), patched the
  6. // snapshot way — so a real chromium exercises the real HTTP uplink/WebSocket
  7. // downlink, api-gateway, agent loop, tools, and persistence. Modes ride $DSH_SNAPSHOT:
  8. // replay (default, keyless: normally disables the llm-deepseek row and
  9. // inserts dsh-llm-replay in providers mode), record (real adapter + key,
  10. // harvests fixtures from live session memory), refresh (keyless replay that
  11. // rewrites goldens). A first-run option keeps the real adapter mounted while
  12. // masking its credential, without making a model call.
  13. //
  14. // Composition divergences from `dsh web`, all deliberate, all via include
  15. // patches after the shipped bundle layers, over the SAME tree (never a
  16. // second yml): temp persistenceRoot; host-level skill roots confined to the
  17. // temp workspace while project skill discovery remains real; agent-instructions
  18. // disabled (recorded fixtures must not embed this repo's AGENTS.md);
  19. // session-title-llm disabled (its fire-and-forget title call would race the
  20. // loop for the session's replay cursor); webserver pinned to port 0 with the
  21. // built dist; ordinary keyless modes disable llm-deepseek and fill the open
  22. // llm seam post-boot with installLlmReplay on the settled root ctx
  23. // (the plugin-row path discards the ReplayHandle; the direct install keeps
  24. // assertConsumed for the teardown fixture-consumption check).
  25. import { existsSync, readFileSync } from 'node:fs'
  26. import { mkdir, mkdtemp, readFile, readdir, realpath, rm, writeFile } from 'node:fs/promises'
  27. import { tmpdir } from 'node:os'
  28. import { join } from 'node:path'
  29. import { pathToFileURL } from 'node:url'
  30. import type { Page } from 'playwright'
  31. import { expect } from 'vitest'
  32. import { Context } from '@deepseek-ai/cordis'
  33. import Loader from '@deepseek-ai/cordis-plugin-loader'
  34. import Include, { type PatchOptions } from '@deepseek-ai/cordis-plugin-include'
  35. import Group from '@deepseek-ai/cordis-plugin-group'
  36. import { scrubRequestHeaders, stabilizeFixtureMessageIds } from '@deepseek-ai/dsh-acp-snapshot'
  37. import {
  38. assertEntriesLoaded,
  39. composeEntries,
  40. healProfilesModuleFallback,
  41. loadOverlayPatches,
  42. } from '@deepseek-ai/dsh-app-boot'
  43. import { dshHomePath } from '@deepseek-ai/dsh-home-paths'
  44. import { settingsNamespace } from '@deepseek-ai/dsh-settings'
  45. import { LlmAdapter } from '@deepseek-ai/dsh-llm'
  46. import type {
  47. LlmModelInfo, LlmProviderInfo, LlmResolvedModelInfo, StreamChunk,
  48. } from '@deepseek-ai/dsh-llm'
  49. import type { ReplayHandle } from '@deepseek-ai/dsh-llm-replay'
  50. import { installLlmReplay, parseSessionLog } from '@deepseek-ai/dsh-llm-replay'
  51. import SessionStore, {
  52. packChunkRuns,
  53. SESSION_FORMAT_VERSION,
  54. SessionId,
  55. type Session,
  56. type SessionEvent,
  57. type SessionHeader,
  58. } from '@deepseek-ai/dsh-session'
  59. import JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl'
  60. // Empty type imports carry the webServer/agents/sessionPersistence Context merges.
  61. import type {} from '@deepseek-ai/dsh-host-webserver'
  62. import type {} from '@deepseek-ai/dsh-agent'
  63. import { provideCmdline } from '@deepseek-ai/dsh-cmdline'
  64. import { REPO_ROOT, requireDist } from './support.ts'
  65. // Host-side web e2e cannot import a browser package: doing so would pull that
  66. // package's complete TS project into this graph. Mirrored from
  67. // packages/client/ui-settings-models/src/onboarding-copy.ts; drift makes the
  68. // default pre-acknowledgement stop suppressing the notice and fails loudly.
  69. // import {
  70. // WELCOME_NOTICE_ACK_FIELD, WELCOME_NOTICE_SETTINGS_NAMESPACE,
  71. // WELCOME_NOTICE_VERSION, WELCOME_NOTICE_COPY,
  72. // } from '@deepseek-ai/dsh-client-ui-settings-models'
  73. export const WELCOME_NOTICE_SETTINGS_NAMESPACE = 'ui-onboarding'
  74. export const WELCOME_NOTICE_ACK_FIELD = 'welcomeNoticeVersion'
  75. export const WELCOME_NOTICE_VERSION = '2026-08-13.1'
  76. export const WELCOME_NOTICE_COPY = {
  77. zh: {
  78. title: '内测声明',
  79. body: 'DeepSeek Harness 目前的 0.1 版本仍处在面向 Harness 开发者进行测试的阶段,还有许多地方需要持续改进和打磨,希望听取广大开发者的反馈建议。预计 DeepSeek Harness 的核心插件以及基础 API 都会在接下来的一段时间内快速迭代、持续演化。\n\n我们期待与全球开发者一起,在开源、开放、可复用、可组合的基础设施之上,共同探索智能上限。欢迎全球 Harness 开发者加入 DSH 插件生态。',
  80. continueLabel: '继续',
  81. },
  82. } as const
  83. /** Snapshot mode for the lane, from $DSH_SNAPSHOT (same vocabulary as the other snapshot suites). */
  84. export type WebSnapshotMode = 'replay' | 'record' | 'refresh'
  85. /**
  86. * Resolve and validate the lane's snapshot mode.
  87. * @returns the active mode; unset/empty selects replay.
  88. */
  89. export function webSnapshotMode(): WebSnapshotMode {
  90. const value = process.env.DSH_SNAPSHOT
  91. if (value === undefined || value === '' || value === 'replay') return 'replay'
  92. if (value === 'record' || value === 'refresh') return value
  93. throw new Error(`DSH_SNAPSHOT must be replay, record, or refresh; got ${JSON.stringify(value)}`)
  94. }
  95. /** The shipped composition under test: the dsh-base and dsh-web-app bundle patches over the empty profile root. */
  96. const BASE_PATCH_PATH = join(REPO_ROOT, 'packages/bundle/base/cordis.patch.yml')
  97. const WEB_PATCH_PATH = join(REPO_ROOT, 'packages/bundle/web-app/cordis.patch.yml')
  98. /** The installation anchor whose dependency surface the profile module fallback mirrors. */
  99. const INSTALL_ANCHOR = join(REPO_ROOT, 'apps/cli/package.json')
  100. /** The deployment's own agent-preset root, shipped beside the app's config. */
  101. const SHIPPED_PRESET_DIR = join(REPO_ROOT, 'apps/cli/config/agent-presets')
  102. // Replay publishes the provider catalog the gateway routes to (providers
  103. // mode, never catch-all: with llm-deepseek disabled no adapter exists, so a
  104. // catch-all would leave resolveModelInfo unroutable and compaction-basic's
  105. // post-step pressure check would warn every step). The published
  106. // contextWindow keeps that pressure path provably inert for small fixtures.
  107. const REPLAY_PROVIDERS = [{
  108. id: 'deepseek-official',
  109. name: 'DeepSeek',
  110. models: [{ id: 'deepseek-v4-flash', name: 'DeepSeek-V4-Flash', contextWindow: 128_000 }],
  111. }]
  112. /**
  113. * The routes a shipped composition always has, with no ability to stream.
  114. * A fixture-less keyless scenario issues no model calls, but its tree must
  115. * still answer `listProviders()` — surfaces legitimately gate on whether any
  116. * adapter serves a session's route, and an empty registry is a test artifact,
  117. * not a product state.
  118. */
  119. class RouteOnlyAdapter extends LlmAdapter {
  120. constructor(private readonly providers: typeof REPLAY_PROVIDERS) {
  121. super()
  122. }
  123. override providerInfo(provider: string): LlmProviderInfo {
  124. return { id: provider, name: this.providers.find(entry => entry.id === provider)?.name ?? provider }
  125. }
  126. override listModels(provider: string): Promise<readonly LlmModelInfo[]> {
  127. return Promise.resolve((this.providers.find(entry => entry.id === provider)?.models ?? [])
  128. .map(model => ({ provider, id: model.id, name: model.name })))
  129. }
  130. override resolveModel(provider: string, model: string): Promise<LlmResolvedModelInfo> {
  131. const listed = this.providers.find(entry => entry.id === provider)?.models
  132. .find(entry => entry.id === model)
  133. return Promise.resolve({
  134. provider,
  135. id: model,
  136. name: listed?.name ?? model,
  137. ...listed?.contextWindow === undefined ? {} : { contextWindow: listed.contextWindow },
  138. })
  139. }
  140. override async *stream(): AsyncIterable<StreamChunk> {
  141. throw new Error(
  142. 'web e2e scaffold: a model call was issued by a scenario that declared no replay fixture'
  143. + ' — pass replayFixture, or keep the scenario free of model calls',
  144. )
  145. }
  146. }
  147. function replayProviders(contextWindow: number | undefined): typeof REPLAY_PROVIDERS {
  148. if (contextWindow === undefined) return REPLAY_PROVIDERS
  149. return REPLAY_PROVIDERS.map(provider => ({
  150. ...provider,
  151. models: provider.models.map(model => ({ ...model, contextWindow })),
  152. }))
  153. }
  154. /** A booted web scaffold: real composition, mode-selected model backend, temp world. */
  155. export interface WebScaffold {
  156. /** The active snapshot mode this scaffold booted under. */
  157. mode: WebSnapshotMode
  158. /** Browser-facing origin for the bound test server. */
  159. baseUrl: string
  160. /** Settled root context (the in-process readiness barrier; headless event subscription is its sanctioned use). */
  161. ctx: Context
  162. /** Temp project directory sessions run in (shell/fs tool cwd). */
  163. workspaceCwd: string
  164. /** Temp persistence root (seeded sessions land here through the real API). */
  165. persistenceRoot: string
  166. /** Isolated harness home the settings/credentials rows write ($DSH_HOME double). */
  167. harnessHome: string
  168. /** Await a settled turn end: in-process turn/end, then the agent's idle flip (which follows the persistence flush). */
  169. whenTurnSettled(timeoutMs?: number): Promise<SessionId>
  170. /**
  171. * Tear everything down; asserts the replay fixture was fully consumed first
  172. * (replay/refresh), unless booted with replayProvidersOnly (whose fixture
  173. * is validated call-free at boot).
  174. */
  175. close(): Promise<void>
  176. }
  177. /** Options for {@link launchWebScaffold}. */
  178. export interface LaunchOptions {
  179. /**
  180. * Optional product overlay applied after the shipped Web surface and before
  181. * the scaffold's hermetic test patches, matching the launcher's `--patch`
  182. * ordering.
  183. */
  184. extraOverlayPath?: string
  185. /**
  186. * Replay fixture (session.jsonl) served by the inserted dsh-llm-replay row
  187. * in replay/refresh modes; ignored in record mode (the real adapter
  188. * answers). Omit for scenarios issuing no model calls — a stray stream then
  189. * fails loud with NO_ADAPTER (llm-deepseek is disabled and no replay row
  190. * mounts). With {@link replayProvidersOnly}, the fixture must record no
  191. * model calls (its header alone mounts the catalog).
  192. */
  193. replayFixture?: string
  194. /**
  195. * Mount the replay provider catalog (the model directory the UI shows)
  196. * without consuming any recorded script: for scenarios that never call a
  197. * model but need the real provider/model labels rendered. Requires
  198. * {@link replayFixture} whose log records no model calls, and rejects
  199. * {@link replayOverride} and {@link replayChildFixtures}; the teardown
  200. * consumption check is skipped for this mode. `replayFixture` without this
  201. * flag keeps the consumption check.
  202. */
  203. replayProvidersOnly?: boolean
  204. /**
  205. * Recorded child logs assigned in child creation order. Each child owns its
  206. * own positional replay cursor across initial and continuation turns.
  207. */
  208. replayChildFixtures?: string[]
  209. /**
  210. * Optional replay.override.json sidecar (whole-script replacement or
  211. * `{ patches }` augmentation) for throw/hang scenarios not expressible as
  212. * recorded chunks; replay/refresh only.
  213. */
  214. replayOverride?: string
  215. /** Per-chunk replay pacing (ms) so the browser observes genuinely incremental SSE; replay/refresh only. */
  216. paceMs?: number
  217. /** Synthetic model capacity for UI scenarios whose seeded history must remain uncompacted. */
  218. replayContextWindow?: number
  219. /**
  220. * Tool presentation mode patched onto the shipped `tools` row (`code`
  221. * collapses the wire to run_code + the SDK prompt section). Omit for the
  222. * yml default. The code runtime row is always in the tree, so no extra
  223. * insertion is needed.
  224. */
  225. toolsMode?: 'native' | 'code' | 'both'
  226. /**
  227. * Insert the opt-in model-facing Cordis tool provider into the shipped tree.
  228. * Record and replay use the same tool surface, so captured request headers
  229. * remain reconstructable without making the tools a product default.
  230. */
  231. cordisTools?: boolean
  232. /**
  233. * Keep the shipped DeepSeek adapter mounted while masking the process
  234. * environment's DEEPSEEK_API_KEY for this scaffold lifetime. This is the
  235. * keyless first-run configuration lane; the default disables the adapter.
  236. */
  237. deepSeekMissingCredential?: boolean
  238. /** Leave the current welcome notice pending; ordinary scenarios pre-acknowledge it before browser boot. */
  239. welcomeNoticePending?: boolean
  240. /**
  241. * Patch the shipped DeepSeek search row to a deterministic endpoint and
  242. * credential reference. Browser search scenarios keep the real provider and
  243. * credentials seam while avoiding external search traffic and ambient keys.
  244. */
  245. deepSeekSearch?: {
  246. /** Anthropic-compatible base URL; the provider appends `/messages`. */
  247. baseURL: string
  248. /** Credential reference resolved by the shipped search provider. */
  249. apiKeyEnv: string
  250. }
  251. /**
  252. * Replace the roster the scaffold mounts by default (the shipped directory
  253. * at `system` trust, default `standard`). Supply this only to change WHICH
  254. * presets a scenario sees — a writable user root, a different default —
  255. * never to turn the roster on: without one every session composes an agent
  256. * with no tools, no persona, and no token meter, which is not a shape the
  257. * product ever boots in. The patch lands after the default, so it wins.
  258. */
  259. agentPresets?: {
  260. /** Roots to discover, in precedence order; the shipped directory is `system`. */
  261. roots: { path: string; trust: 'system' | 'user' }[]
  262. /** The preset a session that names none is composed from. */
  263. default: string
  264. }
  265. /**
  266. * Mount the shipped telemetry row in FULL mode against this exporter URL
  267. * instead of disabling it. Used to pin a real backend disclosure in
  268. * assembled coverage; point the URL at a local dead endpoint so no record
  269. * leaves the process.
  270. */
  271. telemetryUrl?: string
  272. /**
  273. * Browse through a trusted non-loopback hostname that the browser resolves
  274. * to loopback (for example `*.localhost`). The test server stays bound to
  275. * 127.0.0.1; a non-resolving authority fails before Host trust is exercised.
  276. */
  277. remoteAuthority?: string
  278. /** Reuse an existing harness home so a second Host can verify user settings across origins. */
  279. harnessHome?: string
  280. }
  281. /** Dispose the booted tree and remove both owned temp roots, reporting every independent cleanup failure. */
  282. async function cleanupScaffoldWorld(ctx: Context, workspaceCwd: string, persistenceRoot: string): Promise<unknown[]> {
  283. const failures: unknown[] = []
  284. await Promise.resolve(ctx.fiber.dispose()).catch((error: unknown) => failures.push(error))
  285. await rm(workspaceCwd, { recursive: true, force: true }).catch((error: unknown) => failures.push(error))
  286. await rm(persistenceRoot, { recursive: true, force: true }).catch((error: unknown) => failures.push(error))
  287. return failures
  288. }
  289. /**
  290. * Boot the real web composition under the current snapshot mode.
  291. * @param options - replay fixture selection and pacing.
  292. * @returns the running scaffold.
  293. */
  294. export async function launchWebScaffold(options: LaunchOptions = {}): Promise<WebScaffold> {
  295. requireDist()
  296. const mode = webSnapshotMode()
  297. const browserHost = options.remoteAuthority ?? '127.0.0.1'
  298. if (mode === 'record') {
  299. // Both owning vitest configs (web unconditionally, snapshot in record
  300. // mode) load the repo-root .env before this file runs.
  301. if (process.env.DEEPSEEK_API_KEY === undefined || process.env.DEEPSEEK_API_KEY.length === 0) {
  302. throw new Error('web e2e record mode needs DEEPSEEK_API_KEY (env or repo-root .env)')
  303. }
  304. }
  305. if (mode === 'record' && options.deepSeekMissingCredential === true) {
  306. throw new Error('deepSeekMissingCredential is a keyless replay/refresh option')
  307. }
  308. const maskDeepSeekCredential = mode !== 'record' && options.deepSeekMissingCredential === true
  309. const originalDeepSeekCredential = process.env.DEEPSEEK_API_KEY
  310. let credentialEnvironmentRestored = false
  311. const restoreCredentialEnvironment = (): void => {
  312. if (credentialEnvironmentRestored || !maskDeepSeekCredential) return
  313. credentialEnvironmentRestored = true
  314. if (originalDeepSeekCredential === undefined) {
  315. Reflect.deleteProperty(process.env, 'DEEPSEEK_API_KEY')
  316. } else {
  317. process.env.DEEPSEEK_API_KEY = originalDeepSeekCredential
  318. }
  319. }
  320. const workspaceCwd = await realpath(await mkdtemp(join(tmpdir(), 'dsh-web-e2e-ws-')))
  321. // Isolated harness home: the settings/credentials rows resolve $DSH_HOME
  322. // paths at load, and an in-process boot must NEVER touch the developer's
  323. // real ~/.dsh document or credential file.
  324. const harnessHome = options.harnessHome ?? join(workspaceCwd, '.dsh-home')
  325. // Skill discovery is model-visible input, and its roots now resolve inside a
  326. // PRESET — a subtree this lane's include patches cannot reach, because the
  327. // roster mounts it directly per session rather than as a row of the booted
  328. // tree. The row's documented fallback is the environment, so pin that: the
  329. // whole scaffold lifetime, not just the boot, since presets mount when a
  330. // session is created. Without this a developer's real ~/.dsh/skills silently
  331. // enters replay requests and goldens while CI sees none. `DSH_HOME` follows
  332. // the resolved harness home so a scaffold sharing another's home — the
  333. // cross-port persistence scenario — pins the same roots the settings and
  334. // credentials rows were configured with.
  335. const skillRootEnvironment = {
  336. DSH_HOME: harnessHome,
  337. DSH_AGENTS_HOME: join(workspaceCwd, '.agents-home'),
  338. DSH_BUNDLED_SKILL_DIR: join(workspaceCwd, '.bundled-skills'),
  339. }
  340. const originalSkillRootEnvironment = Object.fromEntries(
  341. Object.keys(skillRootEnvironment).map(key => [key, process.env[key]]),
  342. )
  343. let skillRootEnvironmentRestored = false
  344. const restoreSkillRootEnvironment = (): void => {
  345. if (skillRootEnvironmentRestored) return
  346. skillRootEnvironmentRestored = true
  347. for (const [key, value] of Object.entries(originalSkillRootEnvironment)) {
  348. if (value === undefined) Reflect.deleteProperty(process.env, key)
  349. else process.env[key] = value
  350. }
  351. }
  352. Object.assign(process.env, skillRootEnvironment)
  353. let persistenceRoot: string
  354. try {
  355. persistenceRoot = await mkdtemp(join(tmpdir(), 'dsh-web-e2e-sessions-'))
  356. } catch (error) {
  357. const failures: unknown[] = [error]
  358. await rm(workspaceCwd, { recursive: true, force: true }).catch((cleanupError: unknown) => failures.push(cleanupError))
  359. restoreSkillRootEnvironment()
  360. if (failures.length > 1) throw new AggregateError(failures, 'web scaffold temp-root setup failed')
  361. throw error
  362. }
  363. if (maskDeepSeekCredential) Reflect.deleteProperty(process.env, 'DEEPSEEK_API_KEY')
  364. // The include patch set — the same layer stack the profile boot composes
  365. // (bundle patches in dsh.profile.bundles order), applied over the SAME empty root (a
  366. // patch id that stops matching a row fails the boot sweep loudly instead of
  367. // drifting).
  368. const basePatches = loadOverlayPatches('web e2e scaffold', BASE_PATCH_PATH)
  369. const surfacePatches = loadOverlayPatches('web e2e scaffold', WEB_PATCH_PATH)
  370. const extraOverlayPatches = options.extraOverlayPath === undefined
  371. ? []
  372. : loadOverlayPatches('web e2e scaffold', options.extraOverlayPath)
  373. const composedRows = composeEntries([basePatches, surfacePatches, extraOverlayPatches])
  374. const webRuntimeConfig = composedRows.find(row => row.id === 'web-runtime')?.config as {
  375. surfaceContext?: boolean
  376. } | undefined
  377. const surfaceContext = webRuntimeConfig?.surfaceContext !== false
  378. const patches: PatchOptions[] = [
  379. ...basePatches,
  380. ...surfacePatches,
  381. ...extraOverlayPatches,
  382. // The roster's `roots` is an assembly fact AppCLIEntry resolves and patches
  383. // in, exactly like `distIndex` on the webserver row — the shipped preset
  384. // directory sits beside the composition that names it, and no config author
  385. // chooses it. This lane boots the shipped tree WITHOUT AppCLIEntry, so it
  386. // has to supply the same fact or the roster resolves nothing and every
  387. // session composes an agent with no tools, no persona, and no token meter.
  388. // Only the shipped root: a developer's own `~/.dsh/.agent-presets` must not be
  389. // able to change a golden.
  390. {
  391. id: 'agent-presets',
  392. config: {
  393. default: 'standard',
  394. roots: [{ path: SHIPPED_PRESET_DIR, trust: 'system' }],
  395. includeUserRoot: false,
  396. },
  397. },
  398. { id: 'session-persistence-jsonl', config: { root: persistenceRoot } },
  399. // Content search is enabled here although the shipped bundles default it
  400. // off (`openAt: never`, pinned by apps/cli/tests/lazy-search-startup):
  401. // the seeded-session scenarios navigate by content search, and these e2e
  402. // runs are the assembled coverage for the opt-in search path.
  403. { id: 'session-query-sqlite', config: { path: ':memory:', openAt: 'first-search' } },
  404. // storage-json's yml root is anchored to the real $DSH_HOME; pin the row
  405. // to an absolute temp root (removed with the workspace at close) so tests
  406. // never write the user's harness home.
  407. { id: 'storage-json', config: { root: join(workspaceCwd, '.dsh-storages') } },
  408. // Skill discovery is model-visible input. Pin every host-level root inside
  409. // the owned temp world so ~/.dsh, ~/.agents, and a bundled-root env setting
  410. // cannot change replay requests or conversation goldens. Project roots stay
  411. // enabled against the same empty temp workspace, preserving the real seam.
  412. {
  413. id: 'skill-filesystem',
  414. config: {
  415. dshHome: join(workspaceCwd, '.dsh-home'),
  416. agentsHome: join(workspaceCwd, '.agents-home'),
  417. bundledSkillDir: join(workspaceCwd, '.bundled-skills'),
  418. watch: false,
  419. },
  420. },
  421. // fs/bash cwd default to process.cwd(); the gateway injects the same
  422. // value into session.cwd — chdir below anchors all three to the temp
  423. // workspace, keeping the composition untouched.
  424. { id: 'agent-instructions', disabled: true },
  425. { id: 'session-title-llm', disabled: true },
  426. // Fixture sessions must never leave the process: the shipped row defaults
  427. // to the production OTLP endpoint (or whatever DSH_TELEMETRY_OTLP_URL
  428. // names in the ambient environment). A scenario that pins a real backend
  429. // disclosure passes a local dead endpoint instead of disabling the row.
  430. options.telemetryUrl === undefined
  431. ? { id: 'session-telemetry-otel', disabled: true }
  432. : {
  433. id: 'session-telemetry-otel',
  434. config: {
  435. mode: 'FULL',
  436. exporter: { url: options.telemetryUrl },
  437. shutdownTimeoutMillis: 1_000,
  438. },
  439. },
  440. {
  441. id: 'webserver',
  442. config: { host: '127.0.0.1', port: 0 },
  443. },
  444. // The bundle's web-runtime row resolves the same built dist under test
  445. // (apps/web IS @deepseek-ai/dsh-web-frontend); only the URL line is silenced.
  446. // Preserve the composed surface-context choice because a patch replaces
  447. // the row's complete config.
  448. { id: 'web-runtime', config: { printUrl: false, surfaceContext } },
  449. ...options.remoteAuthority === undefined
  450. ? []
  451. : [{ id: 'connection', config: { trustedHosts: [options.remoteAuthority] } }],
  452. { id: 'settings', config: { dshHome: harnessHome } },
  453. { id: 'credentials', config: { dshHome: harnessHome } },
  454. // The shipped directory-picker row is the -auto chooser, which resolves
  455. // the interaction from the RUNNING host (display, SSH launch, bind). The
  456. // lane's goldens are interaction-specific (workspace-management drives
  457. // the in-app browse dialog), so pin -browse deterministically on every
  458. // host: patch `name` is an assertion, not an override, hence the
  459. // disable+insert pair.
  460. { id: 'directory-picker', disabled: true },
  461. { insert: [
  462. { id: 'directory-picker-browse', name: '@deepseek-ai/dsh-host-directory-picker-browse' },
  463. { id: 'ui-directory-picker-browse', name: '@deepseek-ai/dsh-client-ui-directory-picker-browse' },
  464. ] },
  465. ...options.agentPresets === undefined
  466. ? []
  467. // Never the derived harness-home root: a developer's own presets must not
  468. // be able to change a golden, whatever roots a scenario asks for.
  469. : [{ id: 'agent-presets', config: { ...options.agentPresets, includeUserRoot: false } }],
  470. ...options.toolsMode === undefined ? [] : [{ id: 'tools', config: { mode: options.toolsMode } }],
  471. // The shipped Web bundle already owns both runners and the Cordis UI. This
  472. // scenario adds only the model-facing tools that exercise those services.
  473. ...options.cordisTools === true
  474. ? [{ insert: [
  475. { id: 'tool-cordis', name: '@deepseek-ai/dsh-tool-cordis' },
  476. ] }]
  477. : [],
  478. ...options.deepSeekSearch === undefined
  479. ? []
  480. : [{
  481. id: 'web-search-deepseek',
  482. config: {
  483. apiKeyEnv: options.deepSeekSearch.apiKeyEnv,
  484. baseURL: options.deepSeekSearch.baseURL,
  485. },
  486. }],
  487. ...mode === 'record' || options.deepSeekMissingCredential === true
  488. ? []
  489. : [{ id: 'llm-deepseek', disabled: true }],
  490. ]
  491. // Sessions inherit the gateway's process.cwd() default; run the boot from
  492. // the temp workspace so tool cwd, session cwd, and fixtures agree.
  493. const originalCwd = process.cwd()
  494. const ctx = new Context()
  495. let port = 0
  496. let replayHandle: ReplayHandle | undefined
  497. try {
  498. process.chdir(workspaceCwd)
  499. // The production module-resolution setup: an empty profile root inside the temp
  500. // harness home, with bare plugin names resolving through the flat module
  501. // fallback the launcher heals under <home>/profiles.
  502. healProfilesModuleFallback(INSTALL_ANCHOR, harnessHome)
  503. const profileDir = join(harnessHome, 'profiles', 'scaffold')
  504. await mkdir(profileDir, { recursive: true })
  505. const rootConfig = join(profileDir, 'cordis.yml')
  506. await writeFile(rootConfig, '[]\n')
  507. ctx.baseUrl = pathToFileURL(profileDir).href + '/'
  508. // This direct Loader harness supplies the same root-path capability as app-boot.
  509. ctx.provide('dshHomePath', dshHomePath)
  510. // A host with no command line still provides one: the web bundle's startup
  511. // row releases the rows waiting on it, and with no arguments each starts on
  512. // the values this scaffold composed above. An exit request can only come
  513. // from a rejected argument, which a fixed empty list has none of.
  514. provideCmdline(ctx, {
  515. args: [],
  516. exit: (code) => {
  517. throw new Error(`web e2e scaffold: the web app requested exit ${String(code)} with no arguments to reject`)
  518. },
  519. })
  520. await ctx.plugin(Loader)
  521. ctx.loader.builtins.include = Include
  522. // `cordis:group` beside it, exactly as `boot()` registers it: a group row is
  523. // how a preset gives one `isolate` realm to a provider and its consumers,
  524. // and a preset resolving package names from its own directory cannot reach
  525. // `@deepseek-ai/cordis-plugin-group` by name.
  526. ctx.loader.builtins.group = Group
  527. await ctx.loader.create({
  528. name: 'cordis:include',
  529. config: { path: pathToFileURL(rootConfig).href, patches },
  530. })
  531. await ctx.loader.await()
  532. assertEntriesLoaded(ctx, 'web e2e scaffold')
  533. if (options.welcomeNoticePending !== true) {
  534. await ctx.settings.mutate(settingsNamespace(WELCOME_NOTICE_SETTINGS_NAMESPACE), [{
  535. op: 'set', path: [WELCOME_NOTICE_ACK_FIELD], value: WELCOME_NOTICE_VERSION,
  536. }])
  537. }
  538. const boundPort = ctx.get('webServer')?.port
  539. if (boundPort === undefined) {
  540. throw new Error('web e2e scaffold: webServer service missing after settled boot')
  541. }
  542. port = boundPort
  543. // Fill the open llm seam on the settled root ctx. Ordinary keyless modes
  544. // disable llm-deepseek; the first-run lane keeps it mounted but has no
  545. // replay fixture and never streams. The direct install, unlike the plugin
  546. // row, returns the ReplayHandle for the teardown consumption check.
  547. if (options.replayProvidersOnly) {
  548. if (options.replayFixture === undefined) {
  549. throw new Error('replayProvidersOnly requires replayFixture (its file supplies the header)')
  550. }
  551. const fixtureText = readFileSync(options.replayFixture, 'utf8')
  552. // The consumption check is skipped for this mode, so no script source
  553. // may carry callable entries: reject override/child sources outright
  554. // and any call-bearing fixture.
  555. if (options.replayOverride !== undefined || options.replayChildFixtures !== undefined) {
  556. throw new Error('replayProvidersOnly cannot combine with replayOverride or replayChildFixtures')
  557. }
  558. // A fixture without a session header row must not mount the catalog
  559. // silently: the consumption-skip assumes the header-only shape.
  560. let headerType: unknown
  561. try {
  562. headerType = (JSON.parse(fixtureText.trimStart().split('\n', 1)[0] ?? '') as { type?: unknown }).type
  563. } catch {
  564. headerType = undefined
  565. }
  566. if (headerType !== 'session') {
  567. throw new Error('replayProvidersOnly fixture must open with a session header row')
  568. }
  569. const recorded = parseSessionLog(fixtureText)
  570. const hasModelCall = recorded.some(event => (
  571. event.type === 'assistant/chunk' || event.type === 'request/header' || event.type === 'tool/call'
  572. ))
  573. if (hasModelCall) {
  574. throw new Error('replayProvidersOnly fixture must record no model calls')
  575. }
  576. }
  577. if (mode !== 'record' && options.replayFixture !== undefined) {
  578. replayHandle = installLlmReplay(ctx, {
  579. file: options.replayFixture,
  580. providers: replayProviders(options.replayContextWindow),
  581. ...(options.replayOverride === undefined ? {} : { overrideFile: options.replayOverride }),
  582. ...(options.replayChildFixtures === undefined ? {} : { childFiles: options.replayChildFixtures }),
  583. ...(options.paceMs === undefined ? {} : { paceMs: options.paceMs }),
  584. })
  585. } else if (mode !== 'record' && options.deepSeekMissingCredential !== true) {
  586. // No fixture and no shipped adapter would leave the tree with ZERO
  587. // provider routes — a state no product composition has, and one the
  588. // composer refuses to type into. Register the same routes
  589. // a fixture would, with streaming that still fails loud: the scenario
  590. // issues no model calls, and one that slipped in must not pass quietly.
  591. ctx.effect(() => ctx.llm.registerAdapter(
  592. replayProviders(options.replayContextWindow).map(provider => provider.id),
  593. new RouteOnlyAdapter(replayProviders(options.replayContextWindow)),
  594. ), 'web e2e scaffold: route-only adapter')
  595. }
  596. } catch (error) {
  597. if (process.cwd() !== originalCwd) process.chdir(originalCwd)
  598. const cleanupFailures = await cleanupScaffoldWorld(ctx, workspaceCwd, persistenceRoot)
  599. restoreCredentialEnvironment()
  600. restoreSkillRootEnvironment()
  601. if (cleanupFailures.length > 0) {
  602. throw new AggregateError([error, ...cleanupFailures], 'web scaffold setup failed and cleanup was incomplete')
  603. }
  604. throw error
  605. } finally {
  606. if (process.cwd() !== originalCwd) process.chdir(originalCwd)
  607. }
  608. return {
  609. harnessHome,
  610. mode,
  611. baseUrl: `http://${browserHost}:${port}`,
  612. ctx,
  613. workspaceCwd,
  614. persistenceRoot,
  615. // Barrier stack: the in-process turn/end identifies the session, its
  616. // explicit flush makes the transcript durable, and the caller's browser
  617. // settled-poll comes last because host completion strictly precedes render.
  618. whenTurnSettled(timeoutMs = mode === 'record' ? 180_000 : 30_000): Promise<SessionId> {
  619. return new Promise<SessionId>((resolveSettled, reject) => {
  620. const timer = setTimeout(() => {
  621. off()
  622. reject(new Error(`no turn/end within ${timeoutMs}ms`))
  623. }, timeoutMs)
  624. const off = ctx.on('session/event', (session: Session, event: SessionEvent) => {
  625. if (event.type !== 'turn/end') return
  626. clearTimeout(timer)
  627. off()
  628. ctx.sessions.flush(session)
  629. .then(() => { resolveSettled(session.id) }, reject)
  630. })
  631. })
  632. },
  633. async close(): Promise<void> {
  634. const failures: unknown[] = []
  635. // Fixture-consumption check first, while the run's binding state is
  636. // still authoritative — a scenario that drove fewer model calls than
  637. // recorded fails here instead of drifting green. Skipped for
  638. // replayProvidersOnly, whose fixture is validated call-free at boot.
  639. if (!options.replayProvidersOnly) {
  640. try {
  641. replayHandle?.assertConsumed()
  642. } catch (error) {
  643. failures.push(error)
  644. }
  645. }
  646. try {
  647. failures.push(...await cleanupScaffoldWorld(ctx, workspaceCwd, persistenceRoot))
  648. } finally {
  649. restoreCredentialEnvironment()
  650. restoreSkillRootEnvironment()
  651. }
  652. if (failures.length > 0) throw new AggregateError(failures, 'web scaffold teardown failed')
  653. },
  654. }
  655. }
  656. /**
  657. * Serialize a live session to the canonical raw session-JSONL layout — the
  658. * in-memory record-mode harvest, so the on-disk zstd default never matters.
  659. */
  660. function rawSessionLog(session: Session): string {
  661. return [
  662. JSON.stringify({ type: 'session', ...session.header }),
  663. ...packChunkRuns(session.events).map(record => JSON.stringify(record)),
  664. '',
  665. ].join('\n')
  666. }
  667. /**
  668. * Record-mode fixture write-back: harvest the live session, scrub request
  669. * headers to {{system}}/{{tools}} (TODO(web-header-pin): the web lane pins no
  670. * header class — a deliberate deviation logged in the Agent Note's deferred
  671. * work), tokenize the run-local session id, cwd, and browser RPC id
  672. * ({{sessionId}}/{{cwd}}/{{rpcId}}, the committed fixture convention —
  673. * re-records then diff only on real content), and write the fixture.
  674. * @param scaffold - the record-mode scaffold.
  675. * @param sessionId - the driven session.
  676. * @param fixturePath - the committed session.jsonl / seed.jsonl target.
  677. */
  678. export async function recordFixture(scaffold: WebScaffold, sessionId: SessionId, fixturePath: string): Promise<void> {
  679. const agent = scaffold.ctx.agents.get(sessionId)
  680. if (agent === undefined) throw new Error(`record harvest: no live agent for ${sessionId}`)
  681. const fresh = scrubRequestHeaders(rawSessionLog(agent.session))
  682. .split(sessionId).join('{{sessionId}}')
  683. .split(scaffold.workspaceCwd).join('{{cwd}}')
  684. .replace(/"rpcId":"[^"]+"/g, '"rpcId":"{{rpcId}}"')
  685. const existing = existsSync(fixturePath) ? await readFile(fixturePath, 'utf8') : ''
  686. const stable = stabilizeFixtureMessageIds([fresh], [existing])[0]
  687. if (stable === undefined) throw new Error('record harvest: no stabilized fixture')
  688. await writeFile(fixturePath, stable)
  689. }
  690. /**
  691. * The user prompts recorded in a fixture, in order — the single source tying
  692. * spec drive steps to recorded reality so script and fixture cannot drift.
  693. * @param fixtureText - raw session.jsonl contents.
  694. * @returns the recorded user prompt texts.
  695. */
  696. export function fixtureUserPrompts(fixtureText: string): string[] {
  697. return parseSessionLog(fixtureText).flatMap((event) => {
  698. if (event.type !== 'user/message' || event.data.source.kind !== 'user') return []
  699. const text = event.data.content.filter(block => block.type === 'text').map(block => block.text).join('')
  700. return text.length > 0 ? [text] : []
  701. })
  702. }
  703. /**
  704. * Seed a recorded session fixture into the scaffold's persistence root
  705. * through the REAL backend API (throwaway Context + SessionStore + JSONL
  706. * plugin — the semantic-checkpoint precedent), never raw file writes: no
  707. * knowledge of bucket hashing, filename encoding, or compression, and
  708. * malformed session events fail loud at seed time. The fixture's tokenized identity
  709. * ({{sessionId}}/{{cwd}}) is realized for this world before parsing.
  710. * @param scaffold - the target scaffold.
  711. * @param fixtureText - raw recorded session.jsonl contents.
  712. * @param id - the seeded session id (stable for deterministic goldens).
  713. * @param agentPreset - the preset the recorded session was composed from,
  714. * for scenarios asserting what a resumed session reports running.
  715. * @returns the seeded id.
  716. */
  717. /**
  718. * Realize a recorded seed fixture against one scaffold: substitute the
  719. * `{{sessionId}}`/`{{cwd}}` placeholders and rewrite the recorded cwd to the
  720. * scaffold's workspace. Idempotent, so a caller may realize early (e.g. to
  721. * price content exactly as the host will fold it) and still pass the result
  722. * through {@link seedSession}.
  723. * @param scaffold - the booted scaffold whose workspace the seed targets.
  724. * @param fixtureText - the committed seed fixture text.
  725. * @param id - the session id the seed is realized for.
  726. * @returns the realized fixture text.
  727. */
  728. export function realizeSeedFixture(scaffold: WebScaffold, fixtureText: string, id: string): string {
  729. const realized = fixtureText
  730. .split('{{sessionId}}').join(id)
  731. .split('{{cwd}}').join(scaffold.workspaceCwd)
  732. const fixtureCwd = (JSON.parse(realized.split('\n', 1)[0]!) as { cwd?: string }).cwd
  733. return fixtureCwd === undefined
  734. ? realized
  735. : realized.split(fixtureCwd).join(scaffold.workspaceCwd)
  736. }
  737. export async function seedSession(
  738. scaffold: WebScaffold,
  739. fixtureText: string,
  740. id: string,
  741. agentPreset?: string,
  742. ): Promise<SessionId> {
  743. const events = parseSessionLog(realizeSeedFixture(scaffold, fixtureText, id))
  744. if (events.length === 0) throw new Error('seed fixture has no events')
  745. const last = events[events.length - 1]!
  746. // An open final turn would be mutated by resume's crash repair on first
  747. // open; a committed seed must be a closed recording.
  748. if (last.type !== 'turn/end') throw new Error(`seed fixture must end in turn/end, got ${last.type}`)
  749. const meta: SessionHeader = {
  750. version: SESSION_FORMAT_VERSION,
  751. id: SessionId(id),
  752. createdAt: Date.now() - 60_000,
  753. cwd: scaffold.workspaceCwd,
  754. delegationDepth: 0,
  755. ...agentPreset === undefined ? {} : { agentPreset },
  756. }
  757. await persistSeedSession(scaffold, meta, events)
  758. return meta.id
  759. }
  760. /** Seed one materialized cold Session whose log has no turn/start event. */
  761. export async function seedBlankSession(
  762. scaffold: WebScaffold,
  763. id: string,
  764. cwd: string,
  765. ): Promise<SessionId> {
  766. const meta: SessionHeader = {
  767. version: SESSION_FORMAT_VERSION,
  768. id: SessionId(id),
  769. createdAt: Date.now() - 60_000,
  770. cwd,
  771. delegationDepth: 0,
  772. }
  773. await persistSeedSession(scaffold, meta, [{
  774. type: 'session/end-seed',
  775. seq: 0,
  776. time: meta.createdAt,
  777. data: {},
  778. }])
  779. return meta.id
  780. }
  781. /** Materialize one detached Session fixture through the shipped JSONL provider. */
  782. async function persistSeedSession(
  783. scaffold: WebScaffold,
  784. meta: SessionHeader,
  785. events: readonly SessionEvent[],
  786. ): Promise<void> {
  787. const seeder = new Context()
  788. try {
  789. await seeder.plugin(SessionStore)
  790. // Same root as the booted tree with the plugin's own default compression,
  791. // so the host's directory-scan list() sees one consistent encoding.
  792. await seeder.plugin(JsonlSessionPersistence, { root: scaffold.persistenceRoot })
  793. await seeder.sessionPersistence.create(meta)
  794. await seeder.sessionPersistence.append(meta.id, events)
  795. } finally {
  796. await seeder.fiber.dispose()
  797. }
  798. }
  799. /**
  800. * Normalize an aria snapshot: uuid, cwd, workspace-basename, duration,
  801. * decode-throughput, and path-sensitive compaction estimates collapse to
  802. * stable tokens.
  803. *
  804. * Throughput needs a token for the same reason durations do, and no fixture
  805. * can supply one: the figure divides a replayed step's output tokens by the
  806. * wall time the local run took to stream them, so it moves between two runs
  807. * on one machine (measured 69 → 70 tok/s) and swings wildly on a fast replay
  808. * (26333 tok/s for a 3 ms stream).
  809. */
  810. function normalizeAria(snapshot: string, workspaceCwd: string): string {
  811. // The session heading renders the workspace's basename, not the full
  812. // path, so both spellings must collapse to the token.
  813. const base = workspaceCwd.split('/').pop()!
  814. return snapshot
  815. .split(workspaceCwd).join('{{cwd}}')
  816. .split(base).join('{{workspace}}')
  817. .replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi, '{{uuid}}')
  818. // The optional space in `\d+m ?\d+s` covers both minute spellings: the
  819. // stats line's compact `2m42s` and the message-chrome template's `2m 42s`.
  820. .replace(
  821. /~\d+(?:y(?: \d+mo)?|mo(?: \d+d)?)|\b(?:\d+d(?: \d+h(?: \d+m \d+s)?)?|\d+h \d+m \d+s|\d+m ?\d+s|\d+(?:\.\d+)?s|\d+(?:\.\d+)?ms)\b/g,
  822. duration => duration.startsWith('~') ? duration : '{{duration}}',
  823. )
  824. .replace(
  825. /约\d+(?:年(?:\d+个月)?|个月(?:\d+天)?)|\d+(?:天(?:\d+小时(?:\d+分\d+秒)?)?|小时\d+分\d+秒|分\d+秒|(?:\.\d+)?秒)/g,
  826. duration => duration.startsWith('约') ? duration : '{{duration}}',
  827. )
  828. .replace(/\d+(?:\.\d+)?(?= tok\/s(?!\w))/g, '{{throughput}}')
  829. // Seeded compaction prices realized file paths, whose length differs
  830. // between local worktrees and CI scratch directories.
  831. .replace(/(Compacted \d+ history items \(~)\d+( tokens\))/g, '$1{{tokens}}$2')
  832. // Message IconActions clocks widen by calendar day/year; collapse every
  833. // format so goldens stay stable across midnight and year changes.
  834. .replace(/\d{4}年\d{1,2}月\d{1,2}日 \d{2}:\d{2}/g, '{{clock}}')
  835. .replace(/\d{1,2}月\d{1,2}日 \d{2}:\d{2}/g, '{{clock}}')
  836. .replace(/(?<!\d)\d{1,2}:\d{2}:\d{2}(?:\.\d+)?(?:\s*[AP]M)?(?!\d)/gi, '{{clock}}')
  837. .replace(/(?<!\d)\d{2}:\d{2}(?!\d)/g, '{{clock}}')
  838. }
  839. /**
  840. * Capture the region's aria snapshot at a settled milestone: poll until two
  841. * consecutive normalized captures are equal — a single-shot capture races the
  842. * last React commits.
  843. * @param page - the page under test.
  844. * @param selector - the region locator selector.
  845. * @param workspaceCwd - normalization input.
  846. * @returns the stable normalized snapshot.
  847. */
  848. export async function captureStableAria(page: Page, selector: string, workspaceCwd: string): Promise<string> {
  849. const region = page.locator(selector).first()
  850. let previous = normalizeAria(await region.ariaSnapshot(), workspaceCwd)
  851. await expect.poll(async () => {
  852. const current = normalizeAria(await region.ariaSnapshot(), workspaceCwd)
  853. const stable = current === previous
  854. previous = current
  855. return stable
  856. }, { timeout: 5_000, message: 'aria snapshot did not stabilize' }).toBe(true)
  857. return previous
  858. }
  859. /**
  860. * Compare a normalized golden, or rewrite it under refresh. Refresh is the
  861. * ONLY writer: a missing golden in replay mode fails with the healing command
  862. * instead of silently self-bootstrapping.
  863. * @param goldenPath - the committed ui.expected.md path.
  864. * @param actual - the stable normalized snapshot.
  865. * @param mode - the active snapshot mode.
  866. */
  867. export async function compareOrRefreshGolden(goldenPath: string, actual: string, mode: WebSnapshotMode): Promise<void> {
  868. const payload = `${actual}\n`
  869. if (mode === 'refresh') {
  870. await writeFile(goldenPath, payload)
  871. return
  872. }
  873. if (!existsSync(goldenPath)) {
  874. throw new Error(`missing golden ${goldenPath} — run DSH_SNAPSHOT=refresh pnpm run test:web to generate it`)
  875. }
  876. expect(payload).toBe(await readFile(goldenPath, 'utf8'))
  877. }
  878. /**
  879. * Fixture-inventory guard: the scenario directory holds exactly the expected
  880. * files and every committed JSONL is a scrub fixed-point without a run-local
  881. * browser RPC id.
  882. * @param dir - the scenario snapshot directory.
  883. * @param expected - the exact expected file inventory.
  884. */
  885. export async function assertFixtureInventory(dir: string, expected: string[]): Promise<void> {
  886. const entries = (await readdir(dir)).sort()
  887. expect(entries).toEqual([...expected].sort())
  888. for (const entry of entries.filter(name => name.endsWith('.jsonl'))) {
  889. const content = await readFile(join(dir, entry), 'utf8')
  890. expect(scrubRequestHeaders(content), `${dir}/${entry} carries request-header bulk`).toBe(content)
  891. expect(content, `${dir}/${entry} carries a run-local rpcId`)
  892. .not.toMatch(/"rpcId":"(?!\{\{rpcId\}\})[^"]+"/)
  893. }
  894. }
  895. /**
  896. * Console tripwires: reconnect/gap-repair self-healing or a pageerror must
  897. * fail the scenario, not mask a dead wire behind eventual consistency.
  898. * @param page - the page under test.
  899. * @returns live warning/pageerror collectors to assert empty at scenario end.
  900. */
  901. export function watchConsole(page: Page): { warnings: string[]; pageErrors: string[] } {
  902. const warnings: string[] = []
  903. const pageErrors: string[] = []
  904. page.on('console', (message) => {
  905. const text = message.text()
  906. if (/connection lost|gap repair|discontinuous/i.test(text)) warnings.push(text)
  907. })
  908. page.on('pageerror', (error) => { pageErrors.push(String(error)) })
  909. return { warnings, pageErrors }
  910. }
  911. /**
  912. * Remove only connection-loss warnings emitted after an intentional reload.
  913. * Earlier warnings and all gap-repair/discontinuity warnings remain fatal.
  914. * @param tripwire - the live console-warning collector.
  915. * @param warningStart - warning count captured immediately before reloading.
  916. */
  917. export function acknowledgeReloadConnectionLoss(
  918. tripwire: ReturnType<typeof watchConsole>,
  919. warningStart: number,
  920. ): void {
  921. const reloadWarnings = tripwire.warnings.splice(warningStart)
  922. tripwire.warnings.push(...reloadWarnings.filter(text => !/connection lost/i.test(text)))
  923. }