scaffold.ts 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744
  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; workspace-context
  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 } from 'node:fs'
  26. import { mkdir, mkdtemp, readFile, readdir, realpath, rm, utimes, 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 'cordis'
  33. import Loader from '@cordisjs/plugin-loader'
  34. import Include, { type PatchOptions } from '@cordisjs/plugin-include'
  35. import { scrubRequestHeaders } from '@deepseek-ai/dsh-acp-snapshot'
  36. import {
  37. addHarnessSourceSection,
  38. assertEntriesLoaded,
  39. composeEntries,
  40. healProfilesModuleFallback,
  41. loadOverlayPatches,
  42. } from '@deepseek-ai/dsh-app-boot'
  43. import { dshHomePath } from '@deepseek-ai/dsh-paths'
  44. import {
  45. WELCOME_NOTICE_ACK_FIELD, WELCOME_NOTICE_SETTINGS_NAMESPACE, WELCOME_NOTICE_VERSION,
  46. } from '@deepseek-ai/dsh-client-ui-settings-general'
  47. import { settingsNamespace } from '@deepseek-ai/dsh-settings'
  48. import { LlmAdapter } from '@deepseek-ai/dsh-llm'
  49. import type {
  50. LlmModelInfo, LlmProviderInfo, LlmResolvedModelInfo, StreamChunk,
  51. } from '@deepseek-ai/dsh-llm'
  52. import type { ReplayHandle } from '@deepseek-ai/dsh-llm-replay'
  53. import { installLlmReplay, parseSessionLog } from '@deepseek-ai/dsh-llm-replay'
  54. import SessionStore, {
  55. packChunkRuns,
  56. SESSION_FORMAT_VERSION,
  57. SessionId,
  58. type Session,
  59. type SessionEvent,
  60. type SessionHeader,
  61. } from '@deepseek-ai/dsh-session'
  62. import SessionPersistenceJsonl from '@deepseek-ai/dsh-session-persistence-jsonl'
  63. import * as ToolCordis from '@deepseek-ai/dsh-tool-cordis'
  64. // Empty type imports carry the httpServer/agents/sessionPersistence Context merges.
  65. import type {} from '@deepseek-ai/dsh-host-webserver'
  66. import type {} from '@deepseek-ai/dsh-agent'
  67. import { REPO_ROOT, requireDist } from './support.ts'
  68. /** Snapshot mode for the lane, from $DSH_SNAPSHOT (same vocabulary as the other snapshot suites). */
  69. export type WebSnapshotMode = 'replay' | 'record' | 'refresh'
  70. /**
  71. * Resolve and validate the lane's snapshot mode.
  72. * @returns the active mode; unset/empty selects replay.
  73. */
  74. export function webSnapshotMode(): WebSnapshotMode {
  75. const value = process.env.DSH_SNAPSHOT
  76. if (value === undefined || value === '' || value === 'replay') return 'replay'
  77. if (value === 'record' || value === 'refresh') return value
  78. throw new Error(`DSH_SNAPSHOT must be replay, record, or refresh; got ${JSON.stringify(value)}`)
  79. }
  80. /** The shipped composition under test: the dsh-base and dsh-web-app bundle patches over the empty profile root. */
  81. const BASE_PATCH_PATH = join(REPO_ROOT, 'packages/bundle/base/cordis.patch.yml')
  82. const WEB_PATCH_PATH = join(REPO_ROOT, 'packages/bundle/web-app/cordis.patch.yml')
  83. /** The installation anchor whose dependency surface the profile module fallback mirrors. */
  84. const INSTALL_ANCHOR = join(REPO_ROOT, 'apps/cli/package.json')
  85. // Replay publishes the provider catalog the gateway routes to (providers
  86. // mode, never catch-all: with llm-deepseek disabled no adapter exists, so a
  87. // catch-all would leave resolveModelInfo unroutable and compact-basic's
  88. // post-step pressure check would warn every step). The published
  89. // contextWindow keeps that pressure path provably inert for small fixtures.
  90. const REPLAY_PROVIDERS = [{
  91. id: 'deepseek-official',
  92. name: 'DeepSeek',
  93. models: [{ id: 'deepseek-v4-flash', name: 'DeepSeek-V4-Flash', contextWindow: 128_000 }],
  94. }]
  95. /**
  96. * The routes a shipped composition always has, with no ability to stream.
  97. * A fixture-less keyless scenario issues no model calls, but its tree must
  98. * still answer `listProviders()` — surfaces legitimately gate on whether any
  99. * adapter serves a session's route, and an empty registry is a test artifact,
  100. * not a product state.
  101. */
  102. class RouteOnlyAdapter extends LlmAdapter {
  103. constructor(private readonly providers: typeof REPLAY_PROVIDERS) {
  104. super()
  105. }
  106. override providerInfo(provider: string): LlmProviderInfo {
  107. return { id: provider, name: this.providers.find(entry => entry.id === provider)?.name ?? provider }
  108. }
  109. override listModels(provider: string): Promise<readonly LlmModelInfo[]> {
  110. return Promise.resolve((this.providers.find(entry => entry.id === provider)?.models ?? [])
  111. .map(model => ({ provider, id: model.id, name: model.name })))
  112. }
  113. override resolveModel(provider: string, model: string): Promise<LlmResolvedModelInfo> {
  114. const listed = this.providers.find(entry => entry.id === provider)?.models
  115. .find(entry => entry.id === model)
  116. return Promise.resolve({
  117. provider,
  118. id: model,
  119. name: listed?.name ?? model,
  120. ...listed?.contextWindow === undefined ? {} : { contextWindow: listed.contextWindow },
  121. })
  122. }
  123. override async *stream(): AsyncIterable<StreamChunk> {
  124. throw new Error(
  125. 'web e2e scaffold: a model call was issued by a scenario that declared no replay fixture'
  126. + ' — pass replayFixture, or keep the scenario free of model calls',
  127. )
  128. }
  129. }
  130. function replayProviders(contextWindow: number | undefined): typeof REPLAY_PROVIDERS {
  131. if (contextWindow === undefined) return REPLAY_PROVIDERS
  132. return REPLAY_PROVIDERS.map(provider => ({
  133. ...provider,
  134. models: provider.models.map(model => ({ ...model, contextWindow })),
  135. }))
  136. }
  137. /** A booted web scaffold: real composition, mode-selected model backend, temp world. */
  138. export interface WebScaffold {
  139. /** The active snapshot mode this scaffold booted under. */
  140. mode: WebSnapshotMode
  141. /** Browser-facing origin for the bound test server. */
  142. baseUrl: string
  143. /** Settled root context (the in-process barrier seam; headless event subscription is its sanctioned use). */
  144. ctx: Context
  145. /** Temp project directory sessions run in (bash/fs tool cwd). */
  146. workspaceCwd: string
  147. /** Temp persistence root (seeded sessions land here through the real API). */
  148. persistenceRoot: string
  149. /** Isolated harness home the settings/credentials rows write ($DSH_HOME double). */
  150. harnessHome: string
  151. /** Await a settled turn end: in-process turn/end, then the agent's idle flip (which follows the persistence flush). */
  152. whenTurnSettled(timeoutMs?: number): Promise<SessionId>
  153. /** Tear everything down; asserts the replay fixture was fully consumed first (replay/refresh). */
  154. close(): Promise<void>
  155. }
  156. /** Options for {@link launchWebScaffold}. */
  157. export interface LaunchOptions {
  158. /**
  159. * Optional product overlay applied after the shipped Web surface and before
  160. * the scaffold's hermetic test patches, matching the launcher's `--patch`
  161. * ordering.
  162. */
  163. extraOverlayPath?: string
  164. /**
  165. * Replay fixture (session.jsonl) served by the inserted dsh-llm-replay row
  166. * in replay/refresh modes; ignored in record mode (the real adapter
  167. * answers). Omit for scenarios issuing no model calls — a stray stream then
  168. * fails loud with NO_ADAPTER (llm-deepseek is disabled and no replay row
  169. * mounts).
  170. */
  171. replayFixture?: string
  172. /**
  173. * Recorded child logs assigned in child creation order. Each child owns its
  174. * own positional replay cursor across initial and continuation turns.
  175. */
  176. replayChildFixtures?: string[]
  177. /**
  178. * Optional replay.override.json sidecar (whole-script replacement or
  179. * `{ patches }` augmentation) for throw/hang scenarios not expressible as
  180. * recorded chunks; replay/refresh only.
  181. */
  182. replayOverride?: string
  183. /** Per-chunk replay pacing (ms) so the browser observes genuinely incremental SSE; replay/refresh only. */
  184. paceMs?: number
  185. /** Synthetic model capacity for UI scenarios whose seeded history must remain uncompacted. */
  186. replayContextWindow?: number
  187. /**
  188. * Tool presentation mode patched onto the shipped `tools` row (`code`
  189. * collapses the wire to run_code + the SDK prompt section). Omit for the
  190. * yml default. The code runtime row is always in the tree, so no extra
  191. * insertion is needed.
  192. */
  193. toolsMode?: 'native' | 'code' | 'both'
  194. /**
  195. * Insert the opt-in self-referential Cordis tools into the shipped tree.
  196. * Record and replay use the same tool surface, so captured request headers
  197. * remain reconstructable without making the tools a product default.
  198. */
  199. cordisTools?: boolean
  200. /**
  201. * Keep the shipped DeepSeek adapter mounted while masking the process
  202. * environment's DEEPSEEK_API_KEY for this scaffold lifetime. This is the
  203. * keyless first-run configuration lane; the default disables the adapter.
  204. */
  205. deepSeekMissingCredential?: boolean
  206. /**
  207. * Patch the shipped DeepSeek search row to a deterministic endpoint and
  208. * credential reference. Browser search scenarios keep the real provider and
  209. * credentials seam while avoiding external search traffic and ambient keys.
  210. */
  211. deepSeekSearch?: {
  212. /** Anthropic-compatible base URL; the provider appends `/messages`. */
  213. baseURL: string
  214. /** Credential reference resolved by the shipped search provider. */
  215. apiKeyEnv: string
  216. }
  217. /** Leave the current welcome notice unacknowledged; ordinary scenarios publish it as complete before browser boot. */
  218. welcomeNoticePending?: boolean
  219. /**
  220. * Browse through a trusted non-loopback hostname that the browser resolves
  221. * to loopback (for example `*.localhost`). The test server stays bound to
  222. * 127.0.0.1; a non-resolving authority fails before Host trust is exercised.
  223. */
  224. remoteAuthority?: string
  225. }
  226. /** Dispose the booted tree and remove both owned temp roots, reporting every independent cleanup failure. */
  227. async function cleanupScaffoldWorld(ctx: Context, workspaceCwd: string, persistenceRoot: string): Promise<unknown[]> {
  228. const failures: unknown[] = []
  229. await Promise.resolve(ctx.fiber.dispose()).catch((error: unknown) => failures.push(error))
  230. await rm(workspaceCwd, { recursive: true, force: true }).catch((error: unknown) => failures.push(error))
  231. await rm(persistenceRoot, { recursive: true, force: true }).catch((error: unknown) => failures.push(error))
  232. return failures
  233. }
  234. /**
  235. * Boot the real web composition under the current snapshot mode.
  236. * @param options - replay fixture selection and pacing.
  237. * @returns the running scaffold.
  238. */
  239. export async function launchWebScaffold(options: LaunchOptions = {}): Promise<WebScaffold> {
  240. requireDist()
  241. const mode = webSnapshotMode()
  242. const browserHost = options.remoteAuthority ?? '127.0.0.1'
  243. if (mode === 'record') {
  244. // Both owning vitest configs (web unconditionally, snapshot in record
  245. // mode) load the repo-root .env before this file runs.
  246. if (process.env.DEEPSEEK_API_KEY === undefined || process.env.DEEPSEEK_API_KEY.length === 0) {
  247. throw new Error('web e2e record mode needs DEEPSEEK_API_KEY (env or repo-root .env)')
  248. }
  249. }
  250. if (mode === 'record' && options.deepSeekMissingCredential === true) {
  251. throw new Error('deepSeekMissingCredential is a keyless replay/refresh option')
  252. }
  253. const maskDeepSeekCredential = mode !== 'record' && options.deepSeekMissingCredential === true
  254. const originalDeepSeekCredential = process.env.DEEPSEEK_API_KEY
  255. let credentialEnvironmentRestored = false
  256. const restoreCredentialEnvironment = (): void => {
  257. if (credentialEnvironmentRestored || !maskDeepSeekCredential) return
  258. credentialEnvironmentRestored = true
  259. if (originalDeepSeekCredential === undefined) {
  260. Reflect.deleteProperty(process.env, 'DEEPSEEK_API_KEY')
  261. } else {
  262. process.env.DEEPSEEK_API_KEY = originalDeepSeekCredential
  263. }
  264. }
  265. const workspaceCwd = await realpath(await mkdtemp(join(tmpdir(), 'dsh-web-e2e-ws-')))
  266. // Isolated harness home: the settings/credentials rows resolve $DSH_HOME
  267. // paths at load, and an in-process boot must NEVER touch the developer's
  268. // real ~/.dsh document or credential file.
  269. const harnessHome = join(workspaceCwd, '.dsh-home')
  270. let persistenceRoot: string
  271. try {
  272. persistenceRoot = await mkdtemp(join(tmpdir(), 'dsh-web-e2e-sessions-'))
  273. } catch (error) {
  274. const failures: unknown[] = [error]
  275. await rm(workspaceCwd, { recursive: true, force: true }).catch((cleanupError: unknown) => failures.push(cleanupError))
  276. if (failures.length > 1) throw new AggregateError(failures, 'web scaffold temp-root setup failed')
  277. throw error
  278. }
  279. if (maskDeepSeekCredential) Reflect.deleteProperty(process.env, 'DEEPSEEK_API_KEY')
  280. // The include patch set — the same layer stack the profile boot composes
  281. // (bundle patches in dsh.profile.bundles order), applied over the SAME empty root (a
  282. // patch id that stops matching a row fails the boot sweep loudly instead of
  283. // drifting).
  284. const basePatches = loadOverlayPatches('web e2e scaffold', BASE_PATCH_PATH)
  285. const surfacePatches = loadOverlayPatches('web e2e scaffold', WEB_PATCH_PATH)
  286. const extraOverlayPatches = options.extraOverlayPath === undefined
  287. ? []
  288. : loadOverlayPatches('web e2e scaffold', options.extraOverlayPath)
  289. const composedRows = composeEntries([basePatches, surfacePatches, extraOverlayPatches])
  290. const webRuntimeConfig = composedRows.find(row => row.id === 'web-runtime')?.config as {
  291. surfaceContext?: boolean
  292. } | undefined
  293. const surfaceContext = webRuntimeConfig?.surfaceContext !== false
  294. const patches: PatchOptions[] = [
  295. ...basePatches,
  296. ...surfacePatches,
  297. ...extraOverlayPatches,
  298. { id: 'session-persistence-jsonl', config: { root: persistenceRoot } },
  299. { id: 'session-query-sqlite', config: { path: ':memory:', openAt: 'first-search' } },
  300. // storage-json's yml root is anchored to the real $DSH_HOME; pin the row
  301. // to an absolute temp root (removed with the workspace at close) so tests
  302. // never write the user's harness home.
  303. { id: 'storage-json', config: { root: join(workspaceCwd, '.dsh-storages') } },
  304. // Skill discovery is model-visible input. Pin every host-level root inside
  305. // the owned temp world so ~/.dsh, ~/.agents, and a bundled-root env setting
  306. // cannot change replay requests or conversation goldens. Project roots stay
  307. // enabled against the same empty temp workspace, preserving the real seam.
  308. {
  309. id: 'skill-local',
  310. config: {
  311. dshHome: join(workspaceCwd, '.dsh-home'),
  312. agentsHome: join(workspaceCwd, '.agents-home'),
  313. bundledSkillDir: join(workspaceCwd, '.bundled-skills'),
  314. watch: false,
  315. },
  316. },
  317. // fs/bash cwd default to process.cwd(); the gateway injects the same
  318. // value into session.cwd — chdir below anchors all three to the temp
  319. // workspace, keeping the composition untouched.
  320. { id: 'workspace-context', disabled: true },
  321. { id: 'session-title-llm', disabled: true },
  322. // Fixture sessions must never leave the process: the shipped row defaults
  323. // to the production OTLP endpoint (or whatever DSH_TELEMETRY_OTLP_URL
  324. // names in the ambient environment).
  325. { id: 'telemetry-otel', disabled: true },
  326. {
  327. id: 'webserver',
  328. config: { host: '127.0.0.1', port: 0 },
  329. },
  330. // The bundle's web-runtime row resolves the same built dist under test
  331. // (apps/web IS @deepseek-ai/dsh-frontend); only the URL line is silenced.
  332. // Preserve the composed surface-context choice because a patch replaces
  333. // the row's complete config.
  334. { id: 'web-runtime', config: { mode: 'production', printUrl: false, surfaceContext } },
  335. ...options.remoteAuthority === undefined
  336. ? []
  337. : [{ id: 'connection', config: { trustedHosts: [options.remoteAuthority] } }],
  338. { id: 'settings', config: { dshHome: harnessHome } },
  339. { id: 'credentials', config: { dshHome: harnessHome } },
  340. // The shipped directory-picker row is the -auto chooser, which resolves
  341. // the interaction from the RUNNING host (display, SSH launch, bind). The
  342. // lane's goldens are interaction-specific (workspace-management drives
  343. // the in-app browse dialog), so pin -browse deterministically on every
  344. // host: patch `name` is an assertion, not an override, hence the
  345. // disable+insert pair.
  346. { id: 'directory-picker', disabled: true },
  347. { insert: [{ id: 'directory-picker-browse', name: '@deepseek-ai/dsh-host-directory-picker-browse' }] },
  348. ...options.toolsMode === undefined ? [] : [{ id: 'tools', config: { mode: options.toolsMode } }],
  349. ...options.cordisTools === true
  350. ? [{ insert: [{ id: 'tool-cordis', name: 'cordis:tool-cordis' }] }]
  351. : [],
  352. ...options.deepSeekSearch === undefined
  353. ? []
  354. : [{
  355. id: 'web-search-deepseek',
  356. config: {
  357. apiKeyEnv: options.deepSeekSearch.apiKeyEnv,
  358. baseURL: options.deepSeekSearch.baseURL,
  359. },
  360. }],
  361. ...mode === 'record' || options.deepSeekMissingCredential === true
  362. ? []
  363. : [{ id: 'llm-deepseek', disabled: true }],
  364. ]
  365. // Sessions inherit the gateway's process.cwd() default; run the boot from
  366. // the temp workspace so tool cwd, session cwd, and fixtures agree.
  367. const originalCwd = process.cwd()
  368. const ctx = new Context()
  369. let port = 0
  370. let replayHandle: ReplayHandle | undefined
  371. try {
  372. process.chdir(workspaceCwd)
  373. // The production resolution shape: an empty profile root inside the temp
  374. // harness home, with bare plugin names resolving through the flat module
  375. // fallback the launcher heals under <home>/profiles.
  376. healProfilesModuleFallback(INSTALL_ANCHOR, harnessHome)
  377. const profileDir = join(harnessHome, 'profiles', 'scaffold')
  378. await mkdir(profileDir, { recursive: true })
  379. const rootConfig = join(profileDir, 'cordis.yml')
  380. await writeFile(rootConfig, '[]\n')
  381. ctx.baseUrl = pathToFileURL(profileDir).href + '/'
  382. // This direct Loader harness supplies the same root-path capability as app-boot.
  383. ctx.provide('dshHomePath', dshHomePath)
  384. await ctx.plugin(Loader)
  385. ctx.loader.builtins.include = Include
  386. // The shipped CLI deliberately has no dependency on this opt-in package.
  387. // Keep the Loader row real without broadening the product installation.
  388. if (options.cordisTools === true) ctx.loader.builtins['tool-cordis'] = ToolCordis
  389. if (surfaceContext) {
  390. ctx.inject(['systemPrompt'], (promptCtx) => { addHarnessSourceSection(promptCtx, REPO_ROOT) })
  391. }
  392. await ctx.loader.create({
  393. name: 'cordis:include',
  394. config: { path: pathToFileURL(rootConfig).href, patches },
  395. })
  396. await ctx.loader.await()
  397. assertEntriesLoaded(ctx, 'web e2e scaffold')
  398. if (options.welcomeNoticePending !== true) {
  399. await ctx.settings.mutate(settingsNamespace(WELCOME_NOTICE_SETTINGS_NAMESPACE), [{
  400. op: 'set', path: [WELCOME_NOTICE_ACK_FIELD], value: WELCOME_NOTICE_VERSION,
  401. }])
  402. }
  403. const boundPort = ctx.get('httpServer')?.port
  404. if (boundPort === undefined) {
  405. throw new Error('web e2e scaffold: httpServer service missing after settled boot')
  406. }
  407. port = boundPort
  408. // Fill the open llm seam on the settled root ctx. Ordinary keyless modes
  409. // disable llm-deepseek; the first-run lane keeps it mounted but has no
  410. // replay fixture and never streams. The direct install, unlike the plugin
  411. // row, returns the ReplayHandle for the teardown consumption check.
  412. if (mode !== 'record' && options.replayFixture !== undefined) {
  413. replayHandle = installLlmReplay(ctx, {
  414. file: options.replayFixture,
  415. providers: replayProviders(options.replayContextWindow),
  416. ...(options.replayOverride === undefined ? {} : { overrideFile: options.replayOverride }),
  417. ...(options.replayChildFixtures === undefined ? {} : { childFiles: options.replayChildFixtures }),
  418. ...(options.paceMs === undefined ? {} : { paceMs: options.paceMs }),
  419. })
  420. } else if (mode !== 'record' && options.deepSeekMissingCredential !== true) {
  421. // No fixture and no shipped adapter would leave the tree with ZERO
  422. // provider routes — a state no product composition has, and one the
  423. // composer now correctly refuses to type into. Register the same routes
  424. // a fixture would, with streaming that still fails loud: the scenario
  425. // issues no model calls, and one that slipped in must not pass quietly.
  426. ctx.effect(() => ctx.llm.registerAdapter(
  427. replayProviders(options.replayContextWindow).map(provider => provider.id),
  428. new RouteOnlyAdapter(replayProviders(options.replayContextWindow)),
  429. ), 'web e2e scaffold: route-only adapter')
  430. }
  431. } catch (error) {
  432. if (process.cwd() !== originalCwd) process.chdir(originalCwd)
  433. const cleanupFailures = await cleanupScaffoldWorld(ctx, workspaceCwd, persistenceRoot)
  434. restoreCredentialEnvironment()
  435. if (cleanupFailures.length > 0) {
  436. throw new AggregateError([error, ...cleanupFailures], 'web scaffold setup failed and cleanup was incomplete')
  437. }
  438. throw error
  439. } finally {
  440. if (process.cwd() !== originalCwd) process.chdir(originalCwd)
  441. }
  442. return {
  443. harnessHome,
  444. mode,
  445. baseUrl: `http://${browserHost}:${port}`,
  446. ctx,
  447. workspaceCwd,
  448. persistenceRoot,
  449. // Barrier stack: the in-process turn/end identifies the session, its
  450. // explicit flush makes the transcript durable, and the caller's browser
  451. // settled-poll comes last because host completion strictly precedes render.
  452. whenTurnSettled(timeoutMs = mode === 'record' ? 180_000 : 30_000): Promise<SessionId> {
  453. return new Promise<SessionId>((resolveSettled, reject) => {
  454. const timer = setTimeout(() => {
  455. off()
  456. reject(new Error(`no turn/end within ${timeoutMs}ms`))
  457. }, timeoutMs)
  458. const off = ctx.on('session/event', (session: Session, event: SessionEvent) => {
  459. if (event.type !== 'turn/end') return
  460. clearTimeout(timer)
  461. off()
  462. ctx.sessions.flush(session)
  463. .then(() => { resolveSettled(session.id) }, reject)
  464. })
  465. })
  466. },
  467. async close(): Promise<void> {
  468. const failures: unknown[] = []
  469. // Fixture-consumption check first, while the run's binding state is
  470. // still authoritative — a scenario that drove fewer model calls than
  471. // recorded fails here instead of drifting green.
  472. try {
  473. replayHandle?.assertConsumed()
  474. } catch (error) {
  475. failures.push(error)
  476. }
  477. try {
  478. failures.push(...await cleanupScaffoldWorld(ctx, workspaceCwd, persistenceRoot))
  479. } finally {
  480. restoreCredentialEnvironment()
  481. }
  482. if (failures.length > 0) throw new AggregateError(failures, 'web scaffold teardown failed')
  483. },
  484. }
  485. }
  486. /**
  487. * Serialize a live session to the canonical raw session-JSONL layout — the
  488. * in-memory record-mode harvest, so the on-disk zstd default never matters.
  489. */
  490. function rawSessionLog(session: Session): string {
  491. return [
  492. JSON.stringify({ type: 'session', ...session.header }),
  493. ...packChunkRuns(session.events).map(record => JSON.stringify(record)),
  494. '',
  495. ].join('\n')
  496. }
  497. /**
  498. * Record-mode fixture write-back: harvest the live session, scrub request
  499. * headers to {{system}}/{{tools}} (TODO(web-header-pin): the web lane pins no
  500. * header class — a deliberate deviation logged in the Agent Note's deferred
  501. * work), tokenize the run-local session id, cwd, and browser RPC id
  502. * ({{sessionId}}/{{cwd}}/{{rpcId}}, the committed fixture convention —
  503. * re-records then diff only on real content), and write the fixture.
  504. * @param scaffold - the record-mode scaffold.
  505. * @param sessionId - the driven session.
  506. * @param fixturePath - the committed session.jsonl / seed.jsonl target.
  507. */
  508. export async function recordFixture(scaffold: WebScaffold, sessionId: SessionId, fixturePath: string): Promise<void> {
  509. const agent = scaffold.ctx.agents.get(sessionId)
  510. if (agent === undefined) throw new Error(`record harvest: no live agent for ${sessionId}`)
  511. const tokenized = scrubRequestHeaders(rawSessionLog(agent.session))
  512. .split(sessionId).join('{{sessionId}}')
  513. .split(scaffold.workspaceCwd).join('{{cwd}}')
  514. .replace(/"rpcId":"[^"]+"/g, '"rpcId":"{{rpcId}}"')
  515. await writeFile(fixturePath, tokenized)
  516. }
  517. /**
  518. * The user prompts recorded in a fixture, in order — the single source tying
  519. * spec drive steps to recorded reality so script and fixture cannot drift.
  520. * @param fixtureText - raw session.jsonl contents.
  521. * @returns the recorded user prompt texts.
  522. */
  523. export function fixtureUserPrompts(fixtureText: string): string[] {
  524. return parseSessionLog(fixtureText).flatMap((event) => {
  525. if (event.type !== 'user/message' || event.data.source.kind !== 'user') return []
  526. const text = event.data.content.filter(block => block.type === 'text').map(block => block.text).join('')
  527. return text.length > 0 ? [text] : []
  528. })
  529. }
  530. /**
  531. * Seed a recorded session fixture into the scaffold's persistence root
  532. * through the REAL backend API (throwaway Context + SessionStore + JSONL
  533. * plugin — the semantic-checkpoint precedent), never raw file writes: no
  534. * knowledge of bucket hashing, filename encoding, or compression, and
  535. * malformed shapes fail loud at seed time. The fixture's tokenized identity
  536. * ({{sessionId}}/{{cwd}}) is realized for this world before parsing.
  537. * @param scaffold - the target scaffold.
  538. * @param fixtureText - raw recorded session.jsonl contents.
  539. * @param id - the seeded session id (stable for deterministic goldens).
  540. * @returns the seeded id.
  541. */
  542. /**
  543. * Realize a recorded seed fixture against one scaffold: substitute the
  544. * `{{sessionId}}`/`{{cwd}}` placeholders and rewrite the recorded cwd to the
  545. * scaffold's workspace. Idempotent, so a caller may realize early (e.g. to
  546. * price content exactly as the host will fold it) and still pass the result
  547. * through {@link seedSession}.
  548. * @param scaffold - the booted scaffold whose workspace the seed targets.
  549. * @param fixtureText - the committed seed fixture text.
  550. * @param id - the session id the seed is realized for.
  551. * @returns the realized fixture text.
  552. */
  553. export function realizeSeedFixture(scaffold: WebScaffold, fixtureText: string, id: string): string {
  554. const realized = fixtureText
  555. .split('{{sessionId}}').join(id)
  556. .split('{{cwd}}').join(scaffold.workspaceCwd)
  557. const fixtureCwd = (JSON.parse(realized.split('\n', 1)[0]!) as { cwd?: string }).cwd
  558. return fixtureCwd === undefined
  559. ? realized
  560. : realized.split(fixtureCwd).join(scaffold.workspaceCwd)
  561. }
  562. export async function seedSession(scaffold: WebScaffold, fixtureText: string, id: string): Promise<SessionId> {
  563. const events = parseSessionLog(realizeSeedFixture(scaffold, fixtureText, id))
  564. if (events.length === 0) throw new Error('seed fixture has no events')
  565. const last = events[events.length - 1]!
  566. // An open final turn would be mutated by resume's crash repair on first
  567. // open; a committed seed must be a closed recording.
  568. if (last.type !== 'turn/end') throw new Error(`seed fixture must end in turn/end, got ${last.type}`)
  569. const meta: SessionHeader = {
  570. version: SESSION_FORMAT_VERSION,
  571. id: SessionId(id),
  572. createdAt: Date.now() - 60_000,
  573. cwd: scaffold.workspaceCwd,
  574. delegationDepth: 0,
  575. }
  576. const seeder = new Context()
  577. try {
  578. await seeder.plugin(SessionStore)
  579. // Same root as the booted tree with the plugin's own default compression,
  580. // so the host's directory-scan list() sees one consistent encoding.
  581. await seeder.plugin(SessionPersistenceJsonl, { root: scaffold.persistenceRoot })
  582. await seeder.sessionPersistence.create(meta)
  583. await seeder.sessionPersistence.append(meta.id, events)
  584. // Deterministic sidebar order: cold summaries take updatedAt from mtime.
  585. const located = seeder.sessionPersistence.locate(meta)
  586. if (located !== undefined) {
  587. const backdated = new Date(meta.createdAt)
  588. await utimes(located.path, backdated, backdated)
  589. }
  590. } finally {
  591. await seeder.fiber.dispose()
  592. }
  593. return meta.id
  594. }
  595. /**
  596. * Normalize an aria snapshot: uuid, cwd, workspace-basename, duration, and
  597. * decode-throughput volatility collapse to stable tokens.
  598. *
  599. * Throughput needs a token for the same reason durations do, and no fixture
  600. * can supply one: the figure divides a replayed step's output tokens by the
  601. * wall time the local run took to stream them, so it moves between two runs
  602. * on one machine (measured 69 → 70 tok/s) and swings wildly on a fast replay
  603. * (26333 tok/s for a 3 ms stream).
  604. */
  605. function normalizeAria(snapshot: string, workspaceCwd: string): string {
  606. // The session heading renders the workspace's basename, not the full
  607. // path, so both spellings must collapse to the token.
  608. const base = workspaceCwd.split('/').pop()!
  609. return snapshot
  610. .split(workspaceCwd).join('{{cwd}}')
  611. .split(base).join('{{workspace}}')
  612. .replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi, '{{uuid}}')
  613. // The optional space in `\d+m ?\d+s` covers both minute spellings: the
  614. // stats line's compact `2m42s` and the message-chrome template's `2m 42s`.
  615. .replace(
  616. /~\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,
  617. duration => duration.startsWith('~') ? duration : '{{duration}}',
  618. )
  619. .replace(
  620. /约\d+(?:年(?:\d+个月)?|个月(?:\d+天)?)|\d+(?:天(?:\d+小时(?:\d+分\d+秒)?)?|小时\d+分\d+秒|分\d+秒|(?:\.\d+)?秒)/g,
  621. duration => duration.startsWith('约') ? duration : '{{duration}}',
  622. )
  623. .replace(/\d+(?:\.\d+)?(?= tok\/s(?!\w))/g, '{{throughput}}')
  624. // Message IconActions clocks widen by calendar day/year; collapse every
  625. // shape so goldens stay stable across midnight and year boundaries.
  626. .replace(/\d{4}年\d{1,2}月\d{1,2}日 \d{2}:\d{2}/g, '{{clock}}')
  627. .replace(/\d{1,2}月\d{1,2}日 \d{2}:\d{2}/g, '{{clock}}')
  628. .replace(/(?<!\d)\d{1,2}:\d{2}:\d{2}(?:\.\d+)?(?:\s*[AP]M)?(?!\d)/gi, '{{clock}}')
  629. .replace(/(?<!\d)\d{2}:\d{2}(?!\d)/g, '{{clock}}')
  630. }
  631. /**
  632. * Capture the region's aria snapshot at a settled milestone: poll until two
  633. * consecutive normalized captures are equal — a single-shot capture races the
  634. * last React commits.
  635. * @param page - the page under test.
  636. * @param selector - the region locator selector.
  637. * @param workspaceCwd - normalization input.
  638. * @returns the stable normalized snapshot.
  639. */
  640. export async function captureStableAria(page: Page, selector: string, workspaceCwd: string): Promise<string> {
  641. const region = page.locator(selector).first()
  642. let previous = normalizeAria(await region.ariaSnapshot(), workspaceCwd)
  643. await expect.poll(async () => {
  644. const current = normalizeAria(await region.ariaSnapshot(), workspaceCwd)
  645. const stable = current === previous
  646. previous = current
  647. return stable
  648. }, { timeout: 5_000, message: 'aria snapshot did not stabilize' }).toBe(true)
  649. return previous
  650. }
  651. /**
  652. * Compare a normalized golden, or rewrite it under refresh. Refresh is the
  653. * ONLY writer: a missing golden in replay mode fails with the healing command
  654. * instead of silently self-bootstrapping.
  655. * @param goldenPath - the committed ui.expected.md path.
  656. * @param actual - the stable normalized snapshot.
  657. * @param mode - the active snapshot mode.
  658. */
  659. export async function compareOrRefreshGolden(goldenPath: string, actual: string, mode: WebSnapshotMode): Promise<void> {
  660. const payload = `${actual}\n`
  661. if (mode === 'refresh') {
  662. await writeFile(goldenPath, payload)
  663. return
  664. }
  665. if (!existsSync(goldenPath)) {
  666. throw new Error(`missing golden ${goldenPath} — run DSH_SNAPSHOT=refresh pnpm run test:web to generate it`)
  667. }
  668. expect(payload).toBe(await readFile(goldenPath, 'utf8'))
  669. }
  670. /**
  671. * Fixture-inventory guard: the scenario directory holds exactly the expected
  672. * files and every committed JSONL is a scrub fixed-point without a run-local
  673. * browser RPC id.
  674. * @param dir - the scenario snapshot directory.
  675. * @param expected - the exact expected file inventory.
  676. */
  677. export async function assertFixtureInventory(dir: string, expected: string[]): Promise<void> {
  678. const entries = (await readdir(dir)).sort()
  679. expect(entries).toEqual([...expected].sort())
  680. for (const entry of entries.filter(name => name.endsWith('.jsonl'))) {
  681. const content = await readFile(join(dir, entry), 'utf8')
  682. expect(scrubRequestHeaders(content), `${dir}/${entry} carries request-header bulk`).toBe(content)
  683. expect(content, `${dir}/${entry} carries a run-local rpcId`)
  684. .not.toMatch(/"rpcId":"(?!\{\{rpcId\}\})[^"]+"/)
  685. }
  686. }
  687. /**
  688. * Console tripwires: reconnect/gap-repair self-healing or a pageerror must
  689. * fail the scenario, not mask a dead wire behind eventual consistency.
  690. * @param page - the page under test.
  691. * @returns live warning/pageerror collectors to assert empty at scenario end.
  692. */
  693. export function watchConsole(page: Page): { warnings: string[]; pageErrors: string[] } {
  694. const warnings: string[] = []
  695. const pageErrors: string[] = []
  696. page.on('console', (message) => {
  697. const text = message.text()
  698. if (/connection lost|gap repair|discontinuous/i.test(text)) warnings.push(text)
  699. })
  700. page.on('pageerror', (error) => { pageErrors.push(String(error)) })
  701. return { warnings, pageErrors }
  702. }
  703. /**
  704. * Remove only connection-loss warnings emitted after an intentional reload.
  705. * Earlier warnings and all gap-repair/discontinuity warnings remain fatal.
  706. * @param tripwire - the live console-warning collector.
  707. * @param warningStart - warning count captured immediately before reloading.
  708. */
  709. export function acknowledgeReloadConnectionLoss(
  710. tripwire: ReturnType<typeof watchConsole>,
  711. warningStart: number,
  712. ): void {
  713. const reloadWarnings = tripwire.warnings.splice(warningStart)
  714. tripwire.warnings.push(...reloadWarnings.filter(text => !/connection lost/i.test(text)))
  715. }