scaffold.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  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 apps/cli/cordis.yml through
  4. // the vendored Loader (the same include boot AppCLIEntry drives), patched the
  5. // snapshot way — so a real chromium exercises the real HTTP/SSE wire, the
  6. // api-gateway, agent loop, tools, and persistence. Modes ride $DSH_SNAPSHOT:
  7. // replay (default, keyless: llm-deepseek row disabled, dsh-llm-replay row
  8. // inserted in providers mode), record (real adapter + key, harvests fixtures
  9. // from live session memory), refresh (keyless replay that rewrites goldens).
  10. //
  11. // Composition divergences from `dsh web`, all deliberate, all via include
  12. // patches over the SAME tree (never a second yml): temp persistenceRoot;
  13. // workspace-context disabled (recorded fixtures must not embed this repo's
  14. // AGENTS.md); session-title-llm disabled (its fire-and-forget title call
  15. // would race the loop for the session's replay cursor); webserver pinned to
  16. // port 0 with the built dist; keyless modes disable llm-deepseek and fill
  17. // the open llm seam post-boot with installLlmReplay on the settled root ctx
  18. // (the plugin-row path discards the ReplayHandle; the direct install keeps
  19. // assertConsumed for the teardown fixture-consumption check).
  20. import { existsSync, readFileSync } from 'node:fs'
  21. import { mkdtemp, readFile, readdir, rm, utimes, writeFile } from 'node:fs/promises'
  22. import { tmpdir } from 'node:os'
  23. import { join, resolve } from 'node:path'
  24. import { pathToFileURL } from 'node:url'
  25. import type { Page } from 'playwright'
  26. import { expect } from 'vitest'
  27. import { Context } from 'cordis'
  28. import Loader from '@cordisjs/plugin-loader'
  29. import Include, { type PatchOptions } from '@cordisjs/plugin-include'
  30. import { scrubRequestHeaders } from '@deepseek-ai/dsh-acp-snapshot'
  31. import { assertEntriesLoaded } from '@deepseek-ai/dsh-app-boot'
  32. import type { ReplayHandle } from '@deepseek-ai/dsh-llm-replay'
  33. import { installLlmReplay, parseSessionLog } from '@deepseek-ai/dsh-llm-replay'
  34. import SessionStore, { SESSION_FORMAT_VERSION, SessionId } from '@deepseek-ai/dsh-session'
  35. import type { Session, SessionEvent, SessionHeader } from '@deepseek-ai/dsh-session'
  36. import SessionPersistenceJsonl from '@deepseek-ai/dsh-session-persistence-jsonl'
  37. // Empty type imports carry the httpServer/agents/sessionPersistence Context merges.
  38. import type {} from '@deepseek-ai/dsh-host-webserver'
  39. import type {} from '@deepseek-ai/dsh-agent'
  40. import { DIST_INDEX, REPO_ROOT, requireDist } from './support.ts'
  41. /** Snapshot mode for the lane, from $DSH_SNAPSHOT (same vocabulary as the ACP/TUI suites). */
  42. export type WebSnapshotMode = 'replay' | 'record' | 'refresh'
  43. /**
  44. * Resolve and validate the lane's snapshot mode.
  45. * @returns the active mode; unset/empty selects replay.
  46. */
  47. export function webSnapshotMode(): WebSnapshotMode {
  48. const value = process.env.DSH_SNAPSHOT
  49. if (value === undefined || value === '' || value === 'replay') return 'replay'
  50. if (value === 'record' || value === 'refresh') return value
  51. throw new Error(`DSH_SNAPSHOT must be replay, record, or refresh; got ${JSON.stringify(value)}`)
  52. }
  53. /** The shipped composition under test: apps/cli's config tree. */
  54. const CONFIG_PATH = join(REPO_ROOT, 'apps/cli/cordis.yml')
  55. // Replay publishes the provider catalog the gateway routes to (providers
  56. // mode, never catch-all: with llm-deepseek disabled no adapter exists, so a
  57. // catch-all would leave resolveModelContext unroutable and compact-basic's
  58. // post-step pressure check would warn every step). The published
  59. // contextWindow keeps that pressure path provably inert for small fixtures.
  60. const REPLAY_PROVIDERS = [{ id: 'deepseek', name: 'DeepSeek', models: [{ id: 'deepseek-v4-flash', contextWindow: 128_000 }] }]
  61. /** Repo-root .env → process.env for record mode (never overrides set vars); the smoke-real convention. */
  62. function loadRootEnv(): void {
  63. const envPath = join(REPO_ROOT, '.env')
  64. if (!existsSync(envPath)) return
  65. for (const line of readFileSync(envPath, 'utf8').split('\n')) {
  66. const m = /^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/.exec(line.trim())
  67. if (m !== null && process.env[m[1]!] === undefined) process.env[m[1]!] = m[2]
  68. }
  69. }
  70. /** A booted web scaffold: real composition, mode-selected model backend, temp world. */
  71. export interface WebScaffold {
  72. /** The active snapshot mode this scaffold booted under. */
  73. mode: WebSnapshotMode
  74. /** Browser-facing origin (http://127.0.0.1:<bound port>). */
  75. baseUrl: string
  76. /** Settled root context (the in-process barrier seam; headless event subscription is its sanctioned use). */
  77. ctx: Context
  78. /** Temp project directory sessions run in (bash/fs tool cwd). */
  79. workspaceCwd: string
  80. /** Temp persistence root (seeded sessions land here through the real API). */
  81. persistenceRoot: string
  82. /** Await a settled turn end: in-process turn/end, then the agent's idle flip (which follows the persistence flush). */
  83. whenTurnSettled(timeoutMs?: number): Promise<SessionId>
  84. /** Tear everything down; asserts the replay fixture was fully consumed first (replay/refresh). */
  85. close(): Promise<void>
  86. }
  87. /** Options for {@link launchWebScaffold}. */
  88. export interface LaunchOptions {
  89. /**
  90. * Replay fixture (session.jsonl) served by the inserted dsh-llm-replay row
  91. * in replay/refresh modes; ignored in record mode (the real adapter
  92. * answers). Omit for scenarios issuing no model calls — a stray stream then
  93. * fails loud with NO_ADAPTER (llm-deepseek is disabled and no replay row
  94. * mounts).
  95. */
  96. replayFixture?: string
  97. /** Per-chunk replay pacing (ms) so the browser observes genuinely incremental SSE; replay/refresh only. */
  98. paceMs?: number
  99. }
  100. /** Dispose the booted tree and remove both owned temp roots, reporting every independent cleanup failure. */
  101. async function cleanupScaffoldWorld(ctx: Context, workspaceCwd: string, persistenceRoot: string): Promise<unknown[]> {
  102. const failures: unknown[] = []
  103. await Promise.resolve(ctx.fiber.dispose()).catch((error: unknown) => failures.push(error))
  104. await rm(workspaceCwd, { recursive: true, force: true }).catch((error: unknown) => failures.push(error))
  105. await rm(persistenceRoot, { recursive: true, force: true }).catch((error: unknown) => failures.push(error))
  106. return failures
  107. }
  108. /**
  109. * Boot the real web composition under the current snapshot mode.
  110. * @param options - replay fixture selection and pacing.
  111. * @returns the running scaffold.
  112. */
  113. export async function launchWebScaffold(options: LaunchOptions = {}): Promise<WebScaffold> {
  114. requireDist()
  115. const mode = webSnapshotMode()
  116. if (mode === 'record') {
  117. loadRootEnv()
  118. if (process.env.DEEPSEEK_API_KEY === undefined || process.env.DEEPSEEK_API_KEY.length === 0) {
  119. throw new Error('web e2e record mode needs DEEPSEEK_API_KEY (env or repo-root .env)')
  120. }
  121. }
  122. const workspaceCwd = await mkdtemp(join(tmpdir(), 'dsh-web-e2e-ws-'))
  123. let persistenceRoot: string
  124. try {
  125. persistenceRoot = await mkdtemp(join(tmpdir(), 'dsh-web-e2e-sessions-'))
  126. } catch (error) {
  127. const failures: unknown[] = [error]
  128. await rm(workspaceCwd, { recursive: true, force: true }).catch((cleanupError: unknown) => failures.push(cleanupError))
  129. if (failures.length > 1) throw new AggregateError(failures, 'web scaffold temp-root setup failed')
  130. throw error
  131. }
  132. // The include patch set — the same mechanism AppCLIEntry and the ACP
  133. // snapshot overlay use, applied over the SAME shipped tree (a patch id that
  134. // stops matching a row fails the boot sweep loudly instead of drifting).
  135. const patches: PatchOptions[] = [
  136. { id: 'session-persistence-jsonl', config: { root: persistenceRoot } },
  137. // storage-json's './.storages' yml default is cwd-relative and resolves
  138. // per write; the scaffold restores the original cwd after boot, so the
  139. // row gets an absolute temp root (removed with the workspace at close).
  140. { id: 'storage-json', config: { root: join(workspaceCwd, '.dsh-storages') } },
  141. // fs/bash cwd default to process.cwd(); the gateway injects the same
  142. // value into session.cwd — chdir below anchors all three to the temp
  143. // workspace, keeping the composition untouched.
  144. { id: 'workspace-context', disabled: true },
  145. { id: 'session-title-llm', disabled: true },
  146. { id: 'webserver', config: { host: '127.0.0.1', port: 0, distIndex: DIST_INDEX } },
  147. ...mode === 'record' ? [] : [{ id: 'llm-deepseek', disabled: true }],
  148. ]
  149. // Sessions inherit the gateway's process.cwd() default; run the boot from
  150. // the temp workspace so tool cwd, session cwd, and fixtures agree.
  151. const originalCwd = process.cwd()
  152. const ctx = new Context()
  153. let port = 0
  154. let replayHandle: ReplayHandle | undefined
  155. try {
  156. process.chdir(workspaceCwd)
  157. ctx.baseUrl = pathToFileURL(join(resolve(CONFIG_PATH), '..')).href + '/'
  158. await ctx.plugin(Loader)
  159. ctx.loader.builtins.include = Include
  160. await ctx.loader.create({
  161. name: 'cordis:include',
  162. config: { path: pathToFileURL(resolve(CONFIG_PATH)).href, patches },
  163. })
  164. await ctx.loader.await()
  165. assertEntriesLoaded(ctx, 'web e2e scaffold')
  166. const boundPort = ctx.get('httpServer')?.port
  167. if (boundPort === undefined) {
  168. throw new Error('web e2e scaffold: httpServer service missing after settled boot')
  169. }
  170. port = boundPort
  171. // Fill the open llm seam on the settled root ctx (llm-deepseek is disabled
  172. // in keyless modes; a scenario with no fixture leaves the seam empty so a
  173. // stray stream fails loud with NO_ADAPTER). The direct install, unlike the
  174. // plugin row, returns the ReplayHandle for the teardown consumption check.
  175. if (mode !== 'record' && options.replayFixture !== undefined) {
  176. replayHandle = installLlmReplay(ctx, {
  177. file: options.replayFixture,
  178. providers: REPLAY_PROVIDERS,
  179. ...(options.paceMs === undefined ? {} : { paceMs: options.paceMs }),
  180. })
  181. }
  182. } catch (error) {
  183. if (process.cwd() !== originalCwd) process.chdir(originalCwd)
  184. const cleanupFailures = await cleanupScaffoldWorld(ctx, workspaceCwd, persistenceRoot)
  185. if (cleanupFailures.length > 0) {
  186. throw new AggregateError([error, ...cleanupFailures], 'web scaffold setup failed and cleanup was incomplete')
  187. }
  188. throw error
  189. } finally {
  190. if (process.cwd() !== originalCwd) process.chdir(originalCwd)
  191. }
  192. return {
  193. mode,
  194. baseUrl: `http://127.0.0.1:${port}`,
  195. ctx,
  196. workspaceCwd,
  197. persistenceRoot,
  198. // Barrier stack: the in-process turn/end identifies the session, then
  199. // agent.whenIdle() covers the persistence flush (the idle flip follows
  200. // the flush), and the caller's browser settled-poll comes last because
  201. // host completion strictly precedes render.
  202. whenTurnSettled(timeoutMs = mode === 'record' ? 180_000 : 30_000): Promise<SessionId> {
  203. return new Promise<SessionId>((resolveSettled, reject) => {
  204. const timer = setTimeout(() => {
  205. off()
  206. reject(new Error(`no turn/end within ${timeoutMs}ms`))
  207. }, timeoutMs)
  208. const off = ctx.on('session/event', (session: { id: SessionId }, event: SessionEvent) => {
  209. if (event.type !== 'turn/end') return
  210. clearTimeout(timer)
  211. off()
  212. const agent = ctx.agents.get(session.id)
  213. if (agent === undefined) {
  214. reject(new Error(`turn/end for ${session.id} but no live agent`))
  215. return
  216. }
  217. agent.whenIdle().then(() => { resolveSettled(session.id) }, reject)
  218. })
  219. })
  220. },
  221. async close(): Promise<void> {
  222. const failures: unknown[] = []
  223. // Fixture-consumption check first, while the run's binding state is
  224. // still authoritative — a scenario that drove fewer model calls than
  225. // recorded fails here instead of drifting green.
  226. try {
  227. replayHandle?.assertConsumed()
  228. } catch (error) {
  229. failures.push(error)
  230. }
  231. failures.push(...await cleanupScaffoldWorld(ctx, workspaceCwd, persistenceRoot))
  232. if (failures.length > 0) throw new AggregateError(failures, 'web scaffold teardown failed')
  233. },
  234. }
  235. }
  236. /**
  237. * Serialize a live session back to raw session-JSONL (header + events) — the
  238. * in-memory record-mode harvest, so the on-disk zstd default never matters.
  239. * Mirrors the TUI suite's rawSessionLog.
  240. */
  241. function rawSessionLog(session: Session): string {
  242. return [
  243. JSON.stringify({ type: 'session', ...session.header }),
  244. ...session.events.map(event => JSON.stringify(event)),
  245. '',
  246. ].join('\n')
  247. }
  248. /**
  249. * Record-mode fixture write-back: harvest the live session, scrub request
  250. * headers to {{system}}/{{tools}} (TODO(web-header-pin): the web lane pins no
  251. * header class — a deliberate deviation logged in the Agent Note's deferred
  252. * work), tokenize the run-local session id, cwd, and browser RPC id
  253. * ({{sessionId}}/{{cwd}}/{{rpcId}}, the committed fixture convention —
  254. * re-records then diff only on real content), and write the fixture.
  255. * @param scaffold - the record-mode scaffold.
  256. * @param sessionId - the driven session.
  257. * @param fixturePath - the committed session.jsonl / seed.jsonl target.
  258. */
  259. export async function recordFixture(scaffold: WebScaffold, sessionId: SessionId, fixturePath: string): Promise<void> {
  260. const agent = scaffold.ctx.agents.get(sessionId)
  261. if (agent === undefined) throw new Error(`record harvest: no live agent for ${sessionId}`)
  262. const tokenized = scrubRequestHeaders(rawSessionLog(agent.session))
  263. .split(sessionId).join('{{sessionId}}')
  264. .split(scaffold.workspaceCwd).join('{{cwd}}')
  265. .replace(/"rpcId":"[^"]+"/g, '"rpcId":"{{rpcId}}"')
  266. await writeFile(fixturePath, tokenized)
  267. }
  268. /**
  269. * The user prompts recorded in a fixture, in order — the single source tying
  270. * spec drive steps to recorded reality so script and fixture cannot drift.
  271. * @param fixtureText - raw session.jsonl contents.
  272. * @returns the recorded user prompt texts.
  273. */
  274. export function fixtureUserPrompts(fixtureText: string): string[] {
  275. return parseSessionLog(fixtureText).flatMap((event) => {
  276. if (event.type !== 'user/message' || event.data.source.kind !== 'user') return []
  277. const text = event.data.content.filter(block => block.type === 'text').map(block => block.text).join('')
  278. return text.length > 0 ? [text] : []
  279. })
  280. }
  281. /**
  282. * Seed a recorded session fixture into the scaffold's persistence root
  283. * through the REAL backend API (throwaway Context + SessionStore + JSONL
  284. * plugin — the semantic-checkpoint precedent), never raw file writes: no
  285. * knowledge of bucket hashing, filename encoding, or compression, and
  286. * malformed shapes fail loud at seed time. The fixture's tokenized identity
  287. * ({{sessionId}}/{{cwd}}) is realized for this world before parsing.
  288. * @param scaffold - the target scaffold.
  289. * @param fixtureText - raw recorded session.jsonl contents.
  290. * @param id - the seeded session id (stable for deterministic goldens).
  291. * @returns the seeded id.
  292. */
  293. export async function seedSession(scaffold: WebScaffold, fixtureText: string, id: string): Promise<SessionId> {
  294. const realized = fixtureText
  295. .split('{{sessionId}}').join(id)
  296. .split('{{cwd}}').join(scaffold.workspaceCwd)
  297. const fixtureCwd = (JSON.parse(realized.split('\n', 1)[0]!) as { cwd?: string }).cwd
  298. const rewritten = fixtureCwd === undefined
  299. ? realized
  300. : realized.split(fixtureCwd).join(scaffold.workspaceCwd)
  301. const events = parseSessionLog(rewritten)
  302. if (events.length === 0) throw new Error('seed fixture has no events')
  303. const last = events[events.length - 1]!
  304. // An open final turn would be mutated by resume's crash repair on first
  305. // open; a committed seed must be a closed recording.
  306. if (last.type !== 'turn/end') throw new Error(`seed fixture must end in turn/end, got ${last.type}`)
  307. const meta: SessionHeader = {
  308. version: SESSION_FORMAT_VERSION,
  309. id: SessionId(id),
  310. createdAt: Date.now() - 60_000,
  311. cwd: scaffold.workspaceCwd,
  312. delegationDepth: 0,
  313. }
  314. const seeder = new Context()
  315. try {
  316. await seeder.plugin(SessionStore)
  317. // Same root as the booted tree with the plugin's own default compression,
  318. // so the host's directory-scan list() sees one consistent encoding.
  319. await seeder.plugin(SessionPersistenceJsonl, { root: scaffold.persistenceRoot })
  320. await seeder.sessionPersistence.create(meta)
  321. await seeder.sessionPersistence.append(meta.id, events)
  322. // Deterministic sidebar order: cold summaries take updatedAt from mtime.
  323. const located = seeder.sessionPersistence.locate(meta)
  324. if (located !== undefined) {
  325. const backdated = new Date(meta.createdAt)
  326. await utimes(located.path, backdated, backdated)
  327. }
  328. } finally {
  329. await seeder.fiber.dispose()
  330. }
  331. return meta.id
  332. }
  333. /**
  334. * Normalize an aria snapshot: uuid, cwd, workspace-basename, and duration
  335. * volatility collapse to stable tokens.
  336. */
  337. function normalizeAria(snapshot: string, workspaceCwd: string): string {
  338. // The header breadcrumb renders the workspace's basename, not the full
  339. // path, so both spellings must collapse to the token.
  340. const base = workspaceCwd.split('/').pop()!
  341. return snapshot
  342. .split(workspaceCwd).join('{{cwd}}')
  343. .split(base).join('{{workspace}}')
  344. .replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi, '{{uuid}}')
  345. .replace(/\b\d+(?:\.\d+)?(?:ms|s|秒)\b/g, '{{duration}}')
  346. }
  347. /**
  348. * Capture the region's aria snapshot at a settled milestone: poll until two
  349. * consecutive normalized captures are equal — a single-shot capture races the
  350. * last React commits.
  351. * @param page - the page under test.
  352. * @param selector - the region locator selector.
  353. * @param workspaceCwd - normalization input.
  354. * @returns the stable normalized snapshot.
  355. */
  356. export async function captureStableAria(page: Page, selector: string, workspaceCwd: string): Promise<string> {
  357. const region = page.locator(selector).first()
  358. let previous = normalizeAria(await region.ariaSnapshot(), workspaceCwd)
  359. await expect.poll(async () => {
  360. const current = normalizeAria(await region.ariaSnapshot(), workspaceCwd)
  361. const stable = current === previous
  362. previous = current
  363. return stable
  364. }, { timeout: 5_000, message: 'aria snapshot did not stabilize' }).toBe(true)
  365. return previous
  366. }
  367. /**
  368. * Compare a normalized golden, or rewrite it under refresh. Refresh is the
  369. * ONLY writer: a missing golden in replay mode fails with the healing command
  370. * instead of silently self-bootstrapping.
  371. * @param goldenPath - the committed ui.expected.md path.
  372. * @param actual - the stable normalized snapshot.
  373. * @param mode - the active snapshot mode.
  374. */
  375. export async function compareOrRefreshGolden(goldenPath: string, actual: string, mode: WebSnapshotMode): Promise<void> {
  376. const payload = `${actual}\n`
  377. if (mode === 'refresh') {
  378. await writeFile(goldenPath, payload)
  379. return
  380. }
  381. if (!existsSync(goldenPath)) {
  382. throw new Error(`missing golden ${goldenPath} — run DSH_SNAPSHOT=refresh pnpm run test:web to generate it`)
  383. }
  384. expect(payload).toBe(await readFile(goldenPath, 'utf8'))
  385. }
  386. /**
  387. * Fixture-inventory guard (the TUI afterAll shape): the scenario directory
  388. * holds exactly the expected files and every committed JSONL is a scrub
  389. * fixed-point without a run-local browser RPC id.
  390. * @param dir - the scenario snapshot directory.
  391. * @param expected - the exact expected file inventory.
  392. */
  393. export async function assertFixtureInventory(dir: string, expected: string[]): Promise<void> {
  394. const entries = (await readdir(dir)).sort()
  395. expect(entries).toEqual([...expected].sort())
  396. for (const entry of entries.filter(name => name.endsWith('.jsonl'))) {
  397. const content = await readFile(join(dir, entry), 'utf8')
  398. expect(scrubRequestHeaders(content), `${dir}/${entry} carries request-header bulk`).toBe(content)
  399. expect(content, `${dir}/${entry} carries a run-local rpcId`)
  400. .not.toMatch(/"rpcId":"(?!\{\{rpcId\}\})[^"]+"/)
  401. }
  402. }
  403. /**
  404. * Console tripwires: reconnect/gap-repair self-healing or a pageerror must
  405. * fail the scenario, not mask a dead wire behind eventual consistency.
  406. * @param page - the page under test.
  407. * @returns live warning/pageerror collectors to assert empty at scenario end.
  408. */
  409. export function watchConsole(page: Page): { warnings: string[]; pageErrors: string[] } {
  410. const warnings: string[] = []
  411. const pageErrors: string[] = []
  412. page.on('console', (message) => {
  413. const text = message.text()
  414. if (/connection lost|gap repair|discontinuous/i.test(text)) warnings.push(text)
  415. })
  416. page.on('pageerror', (error) => { pageErrors.push(String(error)) })
  417. return { warnings, pageErrors }
  418. }