scaffold.ts 31 KB

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