scaffold.ts 32 KB

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