scaffold.ts 33 KB

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