scaffold.ts 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015
  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; agent-instructions
  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, readFileSync } from 'node:fs'
  26. import { mkdir, mkdtemp, readFile, readdir, realpath, rm, 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 '@deepseek-ai/cordis'
  33. import Loader from '@deepseek-ai/cordis-plugin-loader'
  34. import Include, { type PatchOptions } from '@deepseek-ai/cordis-plugin-include'
  35. import Group from '@deepseek-ai/cordis-plugin-group'
  36. import {
  37. scrubRequestHeaders,
  38. scrubSessionSnapshot,
  39. stabilizeFixtureMessageIds,
  40. } from '@deepseek-ai/dsh-acp-snapshot'
  41. import {
  42. assertEntriesLoaded,
  43. composeEntries,
  44. healProfilesModuleFallback,
  45. loadOverlayPatches,
  46. } from '@deepseek-ai/dsh-app-boot'
  47. import { dshHomePath } from '@deepseek-ai/dsh-home-paths'
  48. import { settingsNamespace } from '@deepseek-ai/dsh-settings'
  49. import { LlmAdapter } from '@deepseek-ai/dsh-llm'
  50. import type {
  51. LlmModelInfo, LlmProviderInfo, LlmResolvedModelInfo, RetryPolicyConfig, StreamChunk,
  52. } from '@deepseek-ai/dsh-llm'
  53. import type { ReplayHandle } from '@deepseek-ai/dsh-llm-replay'
  54. import { installLlmReplay, parseSessionLog } from '@deepseek-ai/dsh-llm-replay'
  55. import SessionStore, {
  56. packChunkRuns,
  57. SESSION_FORMAT_VERSION,
  58. SessionId,
  59. type Session,
  60. type SessionEvent,
  61. type SessionHeader,
  62. } from '@deepseek-ai/dsh-session'
  63. import JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl'
  64. // Empty type imports carry the webServer/agents/sessionPersistence Context merges.
  65. import type {} from '@deepseek-ai/dsh-host-webserver'
  66. import type {} from '@deepseek-ai/dsh-agent'
  67. import { provideCmdline } from '@deepseek-ai/dsh-cmdline'
  68. import { REPO_ROOT, requireDist } from './support.ts'
  69. // Host-side web e2e cannot import a browser package: doing so would pull that
  70. // package's complete TS project into this graph. Mirrored from
  71. // packages/client/ui-settings-models/src/onboarding-copy.ts; drift makes the
  72. // default pre-acknowledgement stop suppressing the notice and fails loudly.
  73. // import {
  74. // WELCOME_NOTICE_ACK_FIELD, WELCOME_NOTICE_SETTINGS_NAMESPACE,
  75. // WELCOME_NOTICE_VERSION, WELCOME_NOTICE_COPY,
  76. // } from '@deepseek-ai/dsh-client-ui-settings-models'
  77. export const WELCOME_NOTICE_SETTINGS_NAMESPACE = 'ui-onboarding'
  78. export const WELCOME_NOTICE_ACK_FIELD = 'welcomeNoticeVersion'
  79. export const WELCOME_NOTICE_VERSION = '2026-08-13.1'
  80. export const WELCOME_NOTICE_COPY = {
  81. zh: {
  82. title: '内测声明',
  83. body: 'DeepSeek Harness 目前的 0.1 版本仍处在面向 Harness 开发者进行测试的阶段,还有许多地方需要持续改进和打磨,希望听取广大开发者的反馈建议。预计 DeepSeek Harness 的核心插件以及基础 API 都会在接下来的一段时间内快速迭代、持续演化。\n\n我们期待与全球开发者一起,在开源、开放、可复用、可组合的基础设施之上,共同探索智能上限。欢迎全球 Harness 开发者加入 DSH 插件生态。',
  84. continueLabel: '继续',
  85. },
  86. } as const
  87. /** Snapshot mode for the lane, from $DSH_SNAPSHOT (same vocabulary as the other snapshot suites). */
  88. export type WebSnapshotMode = 'replay' | 'record' | 'refresh'
  89. /**
  90. * Resolve and validate the lane's snapshot mode.
  91. * @returns the active mode; unset/empty selects replay.
  92. */
  93. export function webSnapshotMode(): WebSnapshotMode {
  94. const value = process.env.DSH_SNAPSHOT
  95. if (value === undefined || value === '' || value === 'replay') return 'replay'
  96. if (value === 'record' || value === 'refresh') return value
  97. throw new Error(`DSH_SNAPSHOT must be replay, record, or refresh; got ${JSON.stringify(value)}`)
  98. }
  99. /** The shipped composition under test: the dsh-base and dsh-web-app bundle patches over the empty profile root. */
  100. const BASE_PATCH_PATH = join(REPO_ROOT, 'packages/bundle/base/cordis.patch.yml')
  101. const WEB_PATCH_PATH = join(REPO_ROOT, 'packages/bundle/web-app/cordis.patch.yml')
  102. /** The installation anchor whose dependency surface the profile module fallback mirrors. */
  103. const INSTALL_ANCHOR = join(REPO_ROOT, 'apps/cli/package.json')
  104. /** The deployment's own agent-preset root, shipped beside the app's config. */
  105. const SHIPPED_PRESET_DIR = join(REPO_ROOT, 'apps/cli/config/agent-presets')
  106. // Replay publishes the provider catalog the gateway routes to (providers
  107. // mode, never catch-all: with llm-deepseek disabled no adapter exists, so a
  108. // catch-all would leave resolveModelInfo unroutable and compaction-basic's
  109. // post-step pressure check would warn every step). The published
  110. // contextWindow keeps that pressure path provably inert for small fixtures.
  111. const REPLAY_PROVIDERS = [{
  112. id: 'deepseek-official',
  113. name: 'DeepSeek',
  114. models: [{ id: 'deepseek-v4-flash', name: 'DeepSeek-V4-Flash', contextWindow: 128_000 }],
  115. }]
  116. /**
  117. * The routes a shipped composition always has, with no ability to stream.
  118. * A fixture-less keyless scenario issues no model calls, but its tree must
  119. * still answer `listProviders()` — surfaces legitimately gate on whether any
  120. * adapter serves a session's route, and an empty registry is a test artifact,
  121. * not a product state.
  122. */
  123. class RouteOnlyAdapter extends LlmAdapter {
  124. constructor(private readonly providers: typeof REPLAY_PROVIDERS) {
  125. super()
  126. }
  127. override providerInfo(provider: string): LlmProviderInfo {
  128. return { id: provider, name: this.providers.find(entry => entry.id === provider)?.name ?? provider }
  129. }
  130. override listModels(provider: string): Promise<readonly LlmModelInfo[]> {
  131. return Promise.resolve((this.providers.find(entry => entry.id === provider)?.models ?? [])
  132. .map(model => ({ provider, id: model.id, name: model.name })))
  133. }
  134. override resolveModel(provider: string, model: string): Promise<LlmResolvedModelInfo> {
  135. const listed = this.providers.find(entry => entry.id === provider)?.models
  136. .find(entry => entry.id === model)
  137. return Promise.resolve({
  138. provider,
  139. id: model,
  140. name: listed?.name ?? model,
  141. ...listed?.contextWindow === undefined ? {} : { contextWindow: listed.contextWindow },
  142. })
  143. }
  144. override async *stream(): AsyncIterable<StreamChunk> {
  145. throw new Error(
  146. 'web e2e scaffold: a model call was issued by a scenario that declared no replay fixture'
  147. + ' — pass replayFixture, or keep the scenario free of model calls',
  148. )
  149. }
  150. }
  151. function replayProviders(contextWindow: number | undefined): typeof REPLAY_PROVIDERS {
  152. if (contextWindow === undefined) return REPLAY_PROVIDERS
  153. return REPLAY_PROVIDERS.map(provider => ({
  154. ...provider,
  155. models: provider.models.map(model => ({ ...model, contextWindow })),
  156. }))
  157. }
  158. /** A booted web scaffold: real composition, mode-selected model backend, temp world. */
  159. export interface WebScaffold {
  160. /** The active snapshot mode this scaffold booted under. */
  161. mode: WebSnapshotMode
  162. /** Browser-facing origin for the bound test server. */
  163. baseUrl: string
  164. /** Settled root context (the in-process readiness barrier; headless event subscription is its sanctioned use). */
  165. ctx: Context
  166. /** Temp project directory sessions run in (shell/fs tool cwd). */
  167. workspaceCwd: string
  168. /** Temp persistence root (seeded sessions land here through the real API). */
  169. persistenceRoot: string
  170. /** Isolated harness home the settings/credentials rows write ($DSH_HOME double). */
  171. harnessHome: string
  172. /** Await a settled turn end: in-process turn/end, then the agent's idle flip (which follows the persistence flush). */
  173. whenTurnSettled(timeoutMs?: number): Promise<SessionId>
  174. /**
  175. * Tear everything down; asserts the replay fixture was fully consumed first
  176. * (replay/refresh), unless booted with replayProvidersOnly (whose fixture
  177. * is validated call-free at boot).
  178. */
  179. close(): Promise<void>
  180. }
  181. /** Options for {@link launchWebScaffold}. */
  182. export interface LaunchOptions {
  183. /**
  184. * Optional product overlay applied after the shipped Web surface and before
  185. * the scaffold's hermetic test patches, matching the launcher's `--patch`
  186. * ordering.
  187. */
  188. extraOverlayPath?: string
  189. /**
  190. * Replay fixture (session.jsonl) served by the inserted dsh-llm-replay row
  191. * in replay/refresh modes; ignored in record mode (the real adapter
  192. * answers). Omit for scenarios issuing no model calls — a stray stream then
  193. * fails loud with NO_ADAPTER (llm-deepseek is disabled and no replay row
  194. * mounts). With {@link replayProvidersOnly}, the fixture must record no
  195. * model calls (its header alone mounts the catalog).
  196. */
  197. replayFixture?: string
  198. /**
  199. * Mount the replay provider catalog (the model directory the UI shows)
  200. * without consuming any recorded script: for scenarios that never call a
  201. * model but need the real provider/model labels rendered. Requires
  202. * {@link replayFixture} whose log records no model calls, and rejects
  203. * {@link replayOverride} and {@link replayChildFixtures}; the teardown
  204. * consumption check is skipped for this mode. `replayFixture` without this
  205. * flag keeps the consumption check.
  206. */
  207. replayProvidersOnly?: boolean
  208. /**
  209. * Recorded child logs assigned in child creation order. Each child owns its
  210. * own positional replay cursor across initial and continuation turns.
  211. */
  212. replayChildFixtures?: string[]
  213. /**
  214. * Optional replay.override.json sidecar (whole-script replacement or
  215. * `{ patches }` augmentation) for throw/hang scenarios not expressible as
  216. * recorded chunks; replay/refresh only.
  217. */
  218. replayOverride?: string
  219. /**
  220. * Retry policy registered on every replay provider route, for failure-
  221. * injection scenarios that must exhaust recovery quickly instead of walking
  222. * the shared normal default's five backed-off retries; replay/refresh only.
  223. */
  224. replayRetryPolicy?: RetryPolicyConfig
  225. /** Per-chunk replay pacing (ms) so the browser observes genuinely incremental SSE; replay/refresh only. */
  226. paceMs?: number
  227. /** Synthetic model capacity for UI scenarios whose seeded history must remain uncompacted. */
  228. replayContextWindow?: number
  229. /**
  230. * Tool presentation mode patched onto the shipped `tools` row (`code`
  231. * collapses the wire to run_code + the SDK prompt section). Omit for the
  232. * yml default. The code runtime row is always in the tree, so no extra
  233. * insertion is needed.
  234. */
  235. toolsMode?: 'native' | 'code' | 'both'
  236. /**
  237. * Insert the opt-in model-facing Cordis tool provider into the shipped tree.
  238. * Record and replay use the same tool surface, so captured request headers
  239. * remain reconstructable without making the tools a product default.
  240. */
  241. cordisTools?: boolean
  242. /**
  243. * Keep the shipped DeepSeek adapter mounted while masking the process
  244. * environment's DEEPSEEK_API_KEY for this scaffold lifetime. This is the
  245. * keyless first-run configuration lane; the default disables the adapter.
  246. */
  247. deepSeekMissingCredential?: boolean
  248. /** Leave the current welcome notice pending; ordinary scenarios pre-acknowledge it before browser boot. */
  249. welcomeNoticePending?: boolean
  250. /**
  251. * Patch the shipped DeepSeek search row to a deterministic endpoint and
  252. * credential reference. Browser search scenarios keep the real provider and
  253. * credentials seam while avoiding external search traffic and ambient keys.
  254. */
  255. deepSeekSearch?: {
  256. /** Anthropic-compatible base URL; the provider appends `/messages`. */
  257. baseURL: string
  258. /** Credential reference resolved by the shipped search provider. */
  259. apiKeyEnv: string
  260. }
  261. /**
  262. * Replace the roster the scaffold mounts by default (the shipped directory
  263. * at `system` trust, default `standard`). Supply this only to change WHICH
  264. * presets a scenario sees — a writable user root, a different default —
  265. * never to turn the roster on: without one every session composes an agent
  266. * with no tools, no persona, and no token meter, which is not a shape the
  267. * product ever boots in. The patch lands after the default, so it wins.
  268. */
  269. agentPresets?: {
  270. /** Roots to discover, in precedence order; the shipped directory is `system`. */
  271. roots: { path: string; trust: 'system' | 'user' }[]
  272. /** The preset a session that names none is composed from. */
  273. default: string
  274. }
  275. /**
  276. * Mount the shipped telemetry row in FULL mode against this exporter URL
  277. * instead of disabling it. Used to pin a real backend disclosure in
  278. * assembled coverage; point the URL at a local dead endpoint so no record
  279. * leaves the process.
  280. */
  281. telemetryUrl?: string
  282. /**
  283. * Browse through a trusted non-loopback hostname that the browser resolves
  284. * to loopback (for example `*.localhost`). The test server stays bound to
  285. * 127.0.0.1; a non-resolving authority fails before Host trust is exercised.
  286. */
  287. remoteAuthority?: string
  288. /** Reuse an existing harness home so a second Host can verify user settings across origins. */
  289. harnessHome?: string
  290. }
  291. /** Dispose the booted tree and remove both owned temp roots, reporting every independent cleanup failure. */
  292. async function cleanupScaffoldWorld(ctx: Context, workspaceCwd: string, persistenceRoot: string): Promise<unknown[]> {
  293. const failures: unknown[] = []
  294. await Promise.resolve(ctx.fiber.dispose()).catch((error: unknown) => failures.push(error))
  295. await rm(workspaceCwd, { recursive: true, force: true }).catch((error: unknown) => failures.push(error))
  296. await rm(persistenceRoot, { recursive: true, force: true }).catch((error: unknown) => failures.push(error))
  297. return failures
  298. }
  299. /**
  300. * Boot the real web composition under the current snapshot mode.
  301. * @param options - replay fixture selection and pacing.
  302. * @returns the running scaffold.
  303. */
  304. export async function launchWebScaffold(options: LaunchOptions = {}): Promise<WebScaffold> {
  305. requireDist()
  306. const mode = webSnapshotMode()
  307. const browserHost = options.remoteAuthority ?? '127.0.0.1'
  308. if (mode === 'record') {
  309. // Both owning vitest configs (web unconditionally, snapshot in record
  310. // mode) load the repo-root .env before this file runs.
  311. if (process.env.DEEPSEEK_API_KEY === undefined || process.env.DEEPSEEK_API_KEY.length === 0) {
  312. throw new Error('web e2e record mode needs DEEPSEEK_API_KEY (env or repo-root .env)')
  313. }
  314. }
  315. if (mode === 'record' && options.deepSeekMissingCredential === true) {
  316. throw new Error('deepSeekMissingCredential is a keyless replay/refresh option')
  317. }
  318. const maskDeepSeekCredential = mode !== 'record' && options.deepSeekMissingCredential === true
  319. const originalDeepSeekCredential = process.env.DEEPSEEK_API_KEY
  320. let credentialEnvironmentRestored = false
  321. const restoreCredentialEnvironment = (): void => {
  322. if (credentialEnvironmentRestored || !maskDeepSeekCredential) return
  323. credentialEnvironmentRestored = true
  324. if (originalDeepSeekCredential === undefined) {
  325. Reflect.deleteProperty(process.env, 'DEEPSEEK_API_KEY')
  326. } else {
  327. process.env.DEEPSEEK_API_KEY = originalDeepSeekCredential
  328. }
  329. }
  330. const workspaceCwd = await realpath(await mkdtemp(join(tmpdir(), 'dsh-web-e2e-ws-')))
  331. // Isolated harness home: the settings/credentials rows resolve $DSH_HOME
  332. // paths at load, and an in-process boot must NEVER touch the developer's
  333. // real ~/.dsh document or credential file.
  334. const harnessHome = options.harnessHome ?? join(workspaceCwd, '.dsh-home')
  335. // Skill discovery is model-visible input, and its roots now resolve inside a
  336. // PRESET — a subtree this lane's include patches cannot reach, because the
  337. // roster mounts it directly per session rather than as a row of the booted
  338. // tree. The row's documented fallback is the environment, so pin that: the
  339. // whole scaffold lifetime, not just the boot, since presets mount when a
  340. // session is created. Without this a developer's real ~/.dsh/skills silently
  341. // enters replay requests and goldens while CI sees none. `DSH_HOME` follows
  342. // the resolved harness home so a scaffold sharing another's home — the
  343. // cross-port persistence scenario — pins the same roots the settings and
  344. // credentials rows were configured with.
  345. const skillRootEnvironment = {
  346. DSH_HOME: harnessHome,
  347. DSH_AGENTS_HOME: join(workspaceCwd, '.agents-home'),
  348. DSH_BUNDLED_SKILL_DIR: join(workspaceCwd, '.bundled-skills'),
  349. }
  350. const originalSkillRootEnvironment = Object.fromEntries(
  351. Object.keys(skillRootEnvironment).map(key => [key, process.env[key]]),
  352. )
  353. let skillRootEnvironmentRestored = false
  354. const restoreSkillRootEnvironment = (): void => {
  355. if (skillRootEnvironmentRestored) return
  356. skillRootEnvironmentRestored = true
  357. for (const [key, value] of Object.entries(originalSkillRootEnvironment)) {
  358. if (value === undefined) Reflect.deleteProperty(process.env, key)
  359. else process.env[key] = value
  360. }
  361. }
  362. Object.assign(process.env, skillRootEnvironment)
  363. let persistenceRoot: string
  364. try {
  365. persistenceRoot = await mkdtemp(join(tmpdir(), 'dsh-web-e2e-sessions-'))
  366. } catch (error) {
  367. const failures: unknown[] = [error]
  368. await rm(workspaceCwd, { recursive: true, force: true }).catch((cleanupError: unknown) => failures.push(cleanupError))
  369. restoreSkillRootEnvironment()
  370. if (failures.length > 1) throw new AggregateError(failures, 'web scaffold temp-root setup failed')
  371. throw error
  372. }
  373. if (maskDeepSeekCredential) Reflect.deleteProperty(process.env, 'DEEPSEEK_API_KEY')
  374. // The include patch set — the same layer stack the profile boot composes
  375. // (bundle patches in dsh.profile.bundles order), applied over the SAME empty root (a
  376. // patch id that stops matching a row fails the boot sweep loudly instead of
  377. // drifting).
  378. const basePatches = loadOverlayPatches('web e2e scaffold', BASE_PATCH_PATH)
  379. const surfacePatches = loadOverlayPatches('web e2e scaffold', WEB_PATCH_PATH)
  380. const extraOverlayPatches = options.extraOverlayPath === undefined
  381. ? []
  382. : loadOverlayPatches('web e2e scaffold', options.extraOverlayPath)
  383. const composedRows = composeEntries([basePatches, surfacePatches, extraOverlayPatches])
  384. const webRuntimeConfig = composedRows.find(row => row.id === 'web-runtime')?.config as {
  385. surfaceContext?: boolean
  386. } | undefined
  387. const surfaceContext = webRuntimeConfig?.surfaceContext !== false
  388. const patches: PatchOptions[] = [
  389. ...basePatches,
  390. ...surfacePatches,
  391. ...extraOverlayPatches,
  392. // The roster's `roots` is an assembly fact AppCLIEntry resolves and patches
  393. // in, exactly like `distIndex` on the webserver row — the shipped preset
  394. // directory sits beside the composition that names it, and no config author
  395. // chooses it. This lane boots the shipped tree WITHOUT AppCLIEntry, so it
  396. // has to supply the same fact or the roster resolves nothing and every
  397. // session composes an agent with no tools, no persona, and no token meter.
  398. // Only the shipped root: a developer's own `~/.dsh/.agent-presets` must not be
  399. // able to change a golden.
  400. {
  401. id: 'agent-presets',
  402. config: {
  403. default: 'standard',
  404. roots: [{ path: SHIPPED_PRESET_DIR, trust: 'system' }],
  405. includeUserRoot: false,
  406. },
  407. },
  408. { id: 'session-persistence-jsonl', config: { root: persistenceRoot } },
  409. // Content search is enabled here although the shipped bundles default it
  410. // off (`openAt: never`, pinned by apps/cli/tests/lazy-search-startup):
  411. // the seeded-session scenarios navigate by content search, and these e2e
  412. // runs are the assembled coverage for the opt-in search path.
  413. { id: 'session-query-sqlite', config: { path: ':memory:', openAt: 'first-search' } },
  414. // storage-json's yml root is anchored to the real $DSH_HOME; pin the row
  415. // to an absolute temp root (removed with the workspace at close) so tests
  416. // never write the user's harness home.
  417. { id: 'storage-json', config: { root: join(workspaceCwd, '.dsh-storages') } },
  418. // Skill discovery is model-visible input. Pin every host-level root inside
  419. // the owned temp world so ~/.dsh, ~/.agents, and a bundled-root env setting
  420. // cannot change replay requests or conversation goldens. Project roots stay
  421. // enabled against the same empty temp workspace, preserving the real seam.
  422. {
  423. id: 'skill-filesystem',
  424. config: {
  425. dshHome: join(workspaceCwd, '.dsh-home'),
  426. agentsHome: join(workspaceCwd, '.agents-home'),
  427. bundledSkillDir: join(workspaceCwd, '.bundled-skills'),
  428. watch: false,
  429. },
  430. },
  431. // fs/bash cwd default to process.cwd(); the gateway injects the same
  432. // value into session.cwd — chdir below anchors all three to the temp
  433. // workspace, keeping the composition untouched.
  434. { id: 'agent-instructions', disabled: true },
  435. { id: 'session-title-llm', disabled: true },
  436. // Fixture sessions must never leave the process: the shipped row defaults
  437. // to the production OTLP endpoint (or whatever DSH_TELEMETRY_OTLP_URL
  438. // names in the ambient environment). A scenario that pins a real backend
  439. // disclosure passes a local dead endpoint instead of disabling the row.
  440. options.telemetryUrl === undefined
  441. ? { id: 'session-telemetry-otel', disabled: true }
  442. : {
  443. id: 'session-telemetry-otel',
  444. config: {
  445. mode: 'FULL',
  446. exporter: { url: options.telemetryUrl },
  447. shutdownTimeoutMillis: 1_000,
  448. },
  449. },
  450. {
  451. id: 'webserver',
  452. config: { host: '127.0.0.1', port: 0 },
  453. },
  454. // The bundle's web-runtime row resolves the same built dist under test
  455. // (apps/web IS @deepseek-ai/dsh-web-frontend); native browser opening and the
  456. // URL line are disabled because this scaffold owns its Playwright browser.
  457. // Preserve the composed surface-context choice because a patch replaces
  458. // the row's complete config.
  459. { id: 'web-runtime', config: { openBrowser: false, printUrl: false, surfaceContext } },
  460. ...options.remoteAuthority === undefined
  461. ? []
  462. : [{ id: 'connection', config: { trustedHosts: [options.remoteAuthority] } }],
  463. { id: 'settings', config: { dshHome: harnessHome } },
  464. { id: 'credentials', config: { dshHome: harnessHome } },
  465. // The shipped directory-picker row is the -auto chooser, which resolves
  466. // the interaction from the RUNNING host (display, SSH launch, bind). The
  467. // lane's goldens are interaction-specific (workspace-management drives
  468. // the in-app browse dialog), so pin -browse deterministically on every
  469. // host: patch `name` is an assertion, not an override, hence the
  470. // disable+insert pair.
  471. { id: 'directory-picker', disabled: true },
  472. { insert: [
  473. { id: 'directory-picker-browse', name: '@deepseek-ai/dsh-host-directory-picker-browse' },
  474. { id: 'ui-directory-picker-browse', name: '@deepseek-ai/dsh-client-ui-directory-picker-browse' },
  475. ] },
  476. ...options.agentPresets === undefined
  477. ? []
  478. // Never the derived harness-home root: a developer's own presets must not
  479. // be able to change a golden, whatever roots a scenario asks for.
  480. : [{ id: 'agent-presets', config: { ...options.agentPresets, includeUserRoot: false } }],
  481. ...options.toolsMode === undefined ? [] : [{ id: 'tools', config: { mode: options.toolsMode } }],
  482. // The shipped Web bundle already owns both runners and the Cordis UI. This
  483. // scenario adds only the model-facing tools that exercise those services.
  484. ...options.cordisTools === true
  485. ? [{ insert: [
  486. { id: 'tool-cordis', name: '@deepseek-ai/dsh-tool-cordis' },
  487. ] }]
  488. : [],
  489. ...options.deepSeekSearch === undefined
  490. ? []
  491. : [{
  492. id: 'web-search-deepseek',
  493. config: {
  494. apiKeyEnv: options.deepSeekSearch.apiKeyEnv,
  495. baseURL: options.deepSeekSearch.baseURL,
  496. },
  497. }],
  498. ...mode === 'record' || options.deepSeekMissingCredential === true
  499. ? []
  500. : [{ id: 'llm-deepseek', disabled: true }],
  501. ]
  502. // Sessions inherit the gateway's process.cwd() default; run the boot from
  503. // the temp workspace so tool cwd, session cwd, and fixtures agree.
  504. const originalCwd = process.cwd()
  505. const ctx = new Context()
  506. let port = 0
  507. let replayHandle: ReplayHandle | undefined
  508. try {
  509. process.chdir(workspaceCwd)
  510. // The production module-resolution setup: an empty profile root inside the temp
  511. // harness home, with bare plugin names resolving through the flat module
  512. // fallback the launcher heals under <home>/profiles.
  513. healProfilesModuleFallback(INSTALL_ANCHOR, harnessHome)
  514. const profileDir = join(harnessHome, 'profiles', 'scaffold')
  515. await mkdir(profileDir, { recursive: true })
  516. const rootConfig = join(profileDir, 'cordis.yml')
  517. await writeFile(rootConfig, '[]\n')
  518. ctx.baseUrl = pathToFileURL(profileDir).href + '/'
  519. // This direct Loader harness supplies the same root-path capability as app-boot.
  520. ctx.provide('dshHomePath', dshHomePath)
  521. // A host with no command line still provides one: the web bundle's startup
  522. // row releases the rows waiting on it, and with no arguments each starts on
  523. // the values this scaffold composed above. An exit request can only come
  524. // from a rejected argument, which a fixed empty list has none of.
  525. provideCmdline(ctx, {
  526. args: [],
  527. exit: (code) => {
  528. throw new Error(`web e2e scaffold: the web app requested exit ${String(code)} with no arguments to reject`)
  529. },
  530. })
  531. await ctx.plugin(Loader)
  532. ctx.loader.builtins.include = Include
  533. // `cordis:group` beside it, exactly as `boot()` registers it: a group row is
  534. // how a preset gives one `isolate` realm to a provider and its consumers,
  535. // and a preset resolving package names from its own directory cannot reach
  536. // `@deepseek-ai/cordis-plugin-group` by name.
  537. ctx.loader.builtins.group = Group
  538. await ctx.loader.create({
  539. name: 'cordis:include',
  540. config: { path: pathToFileURL(rootConfig).href, patches },
  541. })
  542. await ctx.loader.await()
  543. assertEntriesLoaded(ctx, 'web e2e scaffold')
  544. if (options.welcomeNoticePending !== true) {
  545. await ctx.settings.mutate(settingsNamespace(WELCOME_NOTICE_SETTINGS_NAMESPACE), [{
  546. op: 'set', path: [WELCOME_NOTICE_ACK_FIELD], value: WELCOME_NOTICE_VERSION,
  547. }])
  548. }
  549. const boundPort = ctx.get('webServer')?.port
  550. if (boundPort === undefined) {
  551. throw new Error('web e2e scaffold: webServer service missing after settled boot')
  552. }
  553. port = boundPort
  554. // Fill the open llm seam on the settled root ctx. Ordinary keyless modes
  555. // disable llm-deepseek; the first-run lane keeps it mounted but has no
  556. // replay fixture and never streams. The direct install, unlike the plugin
  557. // row, returns the ReplayHandle for the teardown consumption check.
  558. if (options.replayProvidersOnly) {
  559. if (options.replayFixture === undefined) {
  560. throw new Error('replayProvidersOnly requires replayFixture (its file supplies the header)')
  561. }
  562. const fixtureText = readFileSync(options.replayFixture, 'utf8')
  563. // The consumption check is skipped for this mode, so no script source
  564. // may carry callable entries: reject override/child sources outright
  565. // and any call-bearing fixture.
  566. if (options.replayOverride !== undefined || options.replayChildFixtures !== undefined) {
  567. throw new Error('replayProvidersOnly cannot combine with replayOverride or replayChildFixtures')
  568. }
  569. // A fixture without a session header row must not mount the catalog
  570. // silently: the consumption-skip assumes the header-only shape.
  571. let headerType: unknown
  572. try {
  573. headerType = (JSON.parse(fixtureText.trimStart().split('\n', 1)[0] ?? '') as { type?: unknown }).type
  574. } catch {
  575. headerType = undefined
  576. }
  577. if (headerType !== 'session') {
  578. throw new Error('replayProvidersOnly fixture must open with a session header row')
  579. }
  580. const recorded = parseSessionLog(fixtureText)
  581. const hasModelCall = recorded.some(event => (
  582. event.type === 'assistant/chunk' || event.type === 'request/header' || event.type === 'tool/call'
  583. ))
  584. if (hasModelCall) {
  585. throw new Error('replayProvidersOnly fixture must record no model calls')
  586. }
  587. }
  588. if (mode !== 'record' && options.replayFixture !== undefined) {
  589. replayHandle = installLlmReplay(ctx, {
  590. file: options.replayFixture,
  591. providers: replayProviders(options.replayContextWindow).map(provider => ({
  592. ...provider,
  593. ...(options.replayRetryPolicy === undefined ? {} : { retryPolicy: options.replayRetryPolicy }),
  594. })),
  595. ...(options.replayOverride === undefined ? {} : { overrideFile: options.replayOverride }),
  596. ...(options.replayChildFixtures === undefined ? {} : { childFiles: options.replayChildFixtures }),
  597. ...(options.paceMs === undefined ? {} : { paceMs: options.paceMs }),
  598. })
  599. } else if (mode !== 'record' && options.deepSeekMissingCredential !== true) {
  600. // No fixture and no shipped adapter would leave the tree with ZERO
  601. // provider routes — a state no product composition has, and one the
  602. // composer refuses to type into. Register the same routes
  603. // a fixture would, with streaming that still fails loud: the scenario
  604. // issues no model calls, and one that slipped in must not pass quietly.
  605. ctx.effect(() => ctx.llm.registerAdapter(
  606. replayProviders(options.replayContextWindow).map(provider => provider.id),
  607. new RouteOnlyAdapter(replayProviders(options.replayContextWindow)),
  608. ), 'web e2e scaffold: route-only adapter')
  609. }
  610. } catch (error) {
  611. if (process.cwd() !== originalCwd) process.chdir(originalCwd)
  612. const cleanupFailures = await cleanupScaffoldWorld(ctx, workspaceCwd, persistenceRoot)
  613. restoreCredentialEnvironment()
  614. restoreSkillRootEnvironment()
  615. if (cleanupFailures.length > 0) {
  616. throw new AggregateError([error, ...cleanupFailures], 'web scaffold setup failed and cleanup was incomplete')
  617. }
  618. throw error
  619. } finally {
  620. if (process.cwd() !== originalCwd) process.chdir(originalCwd)
  621. }
  622. return {
  623. harnessHome,
  624. mode,
  625. baseUrl: `http://${browserHost}:${port}`,
  626. ctx,
  627. workspaceCwd,
  628. persistenceRoot,
  629. // Barrier stack: the in-process turn/end identifies the session, its
  630. // explicit flush makes the transcript durable, and the caller's browser
  631. // settled-poll comes last because host completion strictly precedes render.
  632. whenTurnSettled(timeoutMs = mode === 'record' ? 180_000 : 30_000): Promise<SessionId> {
  633. return new Promise<SessionId>((resolveSettled, reject) => {
  634. const timer = setTimeout(() => {
  635. off()
  636. reject(new Error(`no turn/end within ${timeoutMs}ms`))
  637. }, timeoutMs)
  638. const off = ctx.on('session/event', (session: Session, event: SessionEvent) => {
  639. if (event.type !== 'turn/end') return
  640. clearTimeout(timer)
  641. off()
  642. ctx.sessions.flush(session)
  643. .then(() => { resolveSettled(session.id) }, reject)
  644. })
  645. })
  646. },
  647. async close(): Promise<void> {
  648. const failures: unknown[] = []
  649. // Fixture-consumption check first, while the run's binding state is
  650. // still authoritative — a scenario that drove fewer model calls than
  651. // recorded fails here instead of drifting green. Skipped for
  652. // replayProvidersOnly, whose fixture is validated call-free at boot.
  653. if (!options.replayProvidersOnly) {
  654. try {
  655. replayHandle?.assertConsumed()
  656. } catch (error) {
  657. failures.push(error)
  658. }
  659. }
  660. try {
  661. failures.push(...await cleanupScaffoldWorld(ctx, workspaceCwd, persistenceRoot))
  662. } finally {
  663. restoreCredentialEnvironment()
  664. restoreSkillRootEnvironment()
  665. }
  666. if (failures.length > 0) throw new AggregateError(failures, 'web scaffold teardown failed')
  667. },
  668. }
  669. }
  670. /**
  671. * Serialize a live session to the canonical raw session-JSONL layout — the
  672. * in-memory record-mode harvest, so the on-disk zstd default never matters.
  673. */
  674. function rawSessionLog(session: Session): string {
  675. return [
  676. JSON.stringify({ type: 'session', ...session.header }),
  677. ...packChunkRuns(session.events).map(record => JSON.stringify(record)),
  678. '',
  679. ].join('\n')
  680. }
  681. /**
  682. * Record-mode fixture write-back: harvest the live session, scrub request
  683. * headers to {{system}}/{{tools}} (TODO(web-header-pin): the web lane pins no
  684. * header class — a deliberate deviation logged in the Agent Note's deferred
  685. * work), tokenize the run-local session id, cwd, and browser RPC id
  686. * ({{sessionId}}/{{cwd}}/{{rpcId}}, the committed fixture convention —
  687. * re-records then diff only on real content), and write the fixture.
  688. * @param scaffold - the record-mode scaffold.
  689. * @param sessionId - the driven session.
  690. * @param fixturePath - the committed session.jsonl / seed.jsonl target.
  691. */
  692. export async function recordFixture(scaffold: WebScaffold, sessionId: SessionId, fixturePath: string): Promise<void> {
  693. const agent = scaffold.ctx.agents.get(sessionId)
  694. if (agent === undefined) throw new Error(`record harvest: no live agent for ${sessionId}`)
  695. const fresh = scrubSessionSnapshot(rawSessionLog(agent.session))
  696. .split(sessionId).join('{{sessionId}}')
  697. .split(scaffold.workspaceCwd).join('{{cwd}}')
  698. .replace(/"rpcId":"[^"]+"/g, '"rpcId":"{{rpcId}}"')
  699. const existing = existsSync(fixturePath) ? await readFile(fixturePath, 'utf8') : ''
  700. const stable = stabilizeFixtureMessageIds([fresh], [existing])[0]
  701. if (stable === undefined) throw new Error('record harvest: no stabilized fixture')
  702. await writeFile(fixturePath, stable)
  703. }
  704. /**
  705. * The user prompts recorded in a fixture, in order — the single source tying
  706. * spec drive steps to recorded reality so script and fixture cannot drift.
  707. * @param fixtureText - raw session.jsonl contents.
  708. * @returns the recorded user prompt texts.
  709. */
  710. export function fixtureUserPrompts(fixtureText: string): string[] {
  711. return parseSessionLog(fixtureText).flatMap((event) => {
  712. if (event.type !== 'user/message' || event.data.source.kind !== 'user') return []
  713. const text = event.data.content.filter(block => block.type === 'text').map(block => block.text).join('')
  714. return text.length > 0 ? [text] : []
  715. })
  716. }
  717. /**
  718. * Seed a recorded session fixture into the scaffold's persistence root
  719. * through the REAL backend API (throwaway Context + SessionStore + JSONL
  720. * plugin — the semantic-checkpoint precedent), never raw file writes: no
  721. * knowledge of bucket hashing, filename encoding, or compression, and
  722. * malformed session events fail loud at seed time. The fixture's tokenized identity
  723. * ({{sessionId}}/{{cwd}}) is realized for this world before parsing. Event
  724. * times are materialized from event order against the fixture header's
  725. * creation time, or the seeded creation time when normalization replaced the
  726. * header value with zero.
  727. * @param scaffold - the target scaffold.
  728. * @param fixtureText - raw recorded session.jsonl contents.
  729. * @param id - the seeded session id (stable for deterministic goldens).
  730. * @param agentPreset - the preset the recorded session was composed from,
  731. * for scenarios asserting what a resumed session reports running.
  732. * @returns the seeded id.
  733. */
  734. /**
  735. * Realize a recorded seed fixture against one scaffold: substitute the
  736. * `{{sessionId}}`/`{{cwd}}` placeholders and rewrite the recorded cwd to the
  737. * scaffold's workspace. Idempotent, so a caller may realize early (e.g. to
  738. * price content exactly as the host will fold it) and still pass the result
  739. * through {@link seedSession}.
  740. * @param scaffold - the booted scaffold whose workspace the seed targets.
  741. * @param fixtureText - the committed seed fixture text.
  742. * @param id - the session id the seed is realized for.
  743. * @returns the realized fixture text.
  744. */
  745. export function realizeSeedFixture(scaffold: WebScaffold, fixtureText: string, id: string): string {
  746. const realized = fixtureText
  747. .split('{{sessionId}}').join(id)
  748. .split('{{cwd}}').join(scaffold.workspaceCwd)
  749. const fixtureCwd = (JSON.parse(realized.split('\n', 1)[0]!) as { cwd?: string }).cwd
  750. return fixtureCwd === undefined
  751. ? realized
  752. : realized.split(fixtureCwd).join(scaffold.workspaceCwd)
  753. }
  754. /**
  755. * Parse a committed web seed fixture through the replay reader.
  756. * @param fixtureText - session JSONL fixture contents.
  757. * @returns the original header line, parsed header, and logical events.
  758. */
  759. export function parseSeedFixture(fixtureText: string): {
  760. headerLine: string
  761. header: Record<string, unknown>
  762. events: SessionEvent[]
  763. } {
  764. const headerLine = fixtureText.split(/\r?\n/).find(line => line.trim().length > 0)
  765. if (headerLine === undefined) throw new Error('seed fixture has no session header')
  766. const header = JSON.parse(headerLine) as Record<string, unknown>
  767. if (header.type !== 'session') throw new Error('seed fixture must start with a session header')
  768. return { headerLine, header, events: parseSessionLog(fixtureText) }
  769. }
  770. /**
  771. * Render logical events as an envelope-free web seed fixture.
  772. * @param headerLine - original session header line.
  773. * @param events - logical session events in order.
  774. * @returns projected session JSONL.
  775. */
  776. export function renderSeedFixture(
  777. headerLine: string,
  778. events: readonly ({ readonly seq: number; readonly time: number } & object)[],
  779. ): string {
  780. return [
  781. headerLine,
  782. ...events.map(({ seq: _seq, time: _time, ...event }) => JSON.stringify(event)),
  783. '',
  784. ].join('\n')
  785. }
  786. export async function seedSession(
  787. scaffold: WebScaffold,
  788. fixtureText: string,
  789. id: string,
  790. agentPreset?: string,
  791. ): Promise<SessionId> {
  792. const decoded = parseSeedFixture(realizeSeedFixture(scaffold, fixtureText, id))
  793. const events = decoded.events
  794. if (events.length === 0) throw new Error('seed fixture has no events')
  795. const last = events[events.length - 1]!
  796. // An open final turn would be mutated by resume's crash repair on first
  797. // open; a committed seed must be a closed recording.
  798. if (last.type !== 'turn/end') throw new Error(`seed fixture must end in turn/end, got ${last.type}`)
  799. const meta: SessionHeader = {
  800. version: SESSION_FORMAT_VERSION,
  801. id: SessionId(id),
  802. createdAt: Date.now() - 60_000,
  803. cwd: scaffold.workspaceCwd,
  804. delegationDepth: 0,
  805. ...agentPreset === undefined ? {} : { agentPreset },
  806. }
  807. const fixtureCreatedAt = decoded.header.createdAt
  808. if (typeof fixtureCreatedAt !== 'number') {
  809. throw new Error('seed fixture requires a numeric createdAt header')
  810. }
  811. const timeAnchor = fixtureCreatedAt === 0 ? meta.createdAt : fixtureCreatedAt
  812. const materializedEvents = events.map((event, index) => ({ ...event, time: timeAnchor + index }))
  813. await persistSeedSession(scaffold, meta, materializedEvents)
  814. return meta.id
  815. }
  816. /** Seed one materialized cold Session whose log has no turn/start event. */
  817. export async function seedBlankSession(
  818. scaffold: WebScaffold,
  819. id: string,
  820. cwd: string,
  821. ): Promise<SessionId> {
  822. const meta: SessionHeader = {
  823. version: SESSION_FORMAT_VERSION,
  824. id: SessionId(id),
  825. createdAt: Date.now() - 60_000,
  826. cwd,
  827. delegationDepth: 0,
  828. }
  829. await persistSeedSession(scaffold, meta, [{
  830. type: 'session/end-seed',
  831. seq: 0,
  832. time: meta.createdAt,
  833. data: {},
  834. }])
  835. return meta.id
  836. }
  837. /** Materialize one detached Session fixture through the shipped JSONL provider. */
  838. async function persistSeedSession(
  839. scaffold: WebScaffold,
  840. meta: SessionHeader,
  841. events: readonly SessionEvent[],
  842. ): Promise<void> {
  843. const seeder = new Context()
  844. try {
  845. await seeder.plugin(SessionStore)
  846. // Same root as the booted tree with the plugin's own default compression,
  847. // so the host's directory-scan list() sees one consistent encoding.
  848. await seeder.plugin(JsonlSessionPersistence, { root: scaffold.persistenceRoot })
  849. await seeder.sessionPersistence.create(meta)
  850. await seeder.sessionPersistence.append(meta.id, events)
  851. } finally {
  852. await seeder.fiber.dispose()
  853. }
  854. }
  855. /**
  856. * Normalize an aria snapshot: uuid, cwd, workspace-basename, duration,
  857. * decode-throughput, and path-sensitive compaction estimates collapse to
  858. * stable tokens.
  859. *
  860. * Throughput needs a token for the same reason durations do, and no fixture
  861. * can supply one: the figure divides a replayed step's output tokens by the
  862. * wall time the local run took to stream them, so it moves between two runs
  863. * on one machine (measured 69 → 70 tok/s) and swings wildly on a fast replay
  864. * (26333 tok/s for a 3 ms stream).
  865. */
  866. function normalizeAria(snapshot: string, workspaceCwd: string): string {
  867. // The session heading renders the workspace's basename, not the full
  868. // path, so both spellings must collapse to the token.
  869. const base = workspaceCwd.split('/').pop()!
  870. return snapshot
  871. .split(workspaceCwd).join('{{cwd}}')
  872. .split(base).join('{{workspace}}')
  873. .replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi, '{{uuid}}')
  874. // The optional space in `\d+m ?\d+s` covers both minute spellings: the
  875. // stats line's compact `2m42s` and the message-chrome template's `2m 42s`.
  876. .replace(
  877. /~\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,
  878. duration => duration.startsWith('~') ? duration : '{{duration}}',
  879. )
  880. .replace(/\b\d[\d,]*(?:\.\d+)? ms\b/g, '{{duration}}')
  881. .replace(
  882. /约\d+(?:年(?:\d+个月)?|个月(?:\d+天)?)|\d+(?:天(?:\d+小时(?:\d+分\d+秒)?)?|小时\d+分\d+秒|分\d+秒|(?:\.\d+)?秒)/g,
  883. duration => duration.startsWith('约') ? duration : '{{duration}}',
  884. )
  885. .replace(/\d+(?:\.\d+)?(?= tok\/s(?!\w))/g, '{{throughput}}')
  886. // Seeded compaction prices realized file paths, whose length differs
  887. // between local worktrees and CI scratch directories.
  888. .replace(/(Compacted \d+ history items \(~)\d+( tokens\))/g, '$1{{tokens}}$2')
  889. // Session summaries and Message IconActions clocks cross calendar
  890. // boundaries; collapse every shape so goldens stay stable across them.
  891. .replace(/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z/g, '{{timestamp}}')
  892. .replace(/\d{4}年\d{1,2}月\d{1,2}日 \d{2}:\d{2}/g, '{{clock}}')
  893. .replace(/\d{1,2}月\d{1,2}日 \d{2}:\d{2}/g, '{{clock}}')
  894. .replace(/(?<!\d)\d{1,2}:\d{2}:\d{2}(?:\.\d+)?(?:\s*[AP]M)?(?!\d)/gi, '{{clock}}')
  895. .replace(/(?<!\d)\d{2}:\d{2}(?!\d)/g, '{{clock}}')
  896. }
  897. /**
  898. * Capture the region's aria snapshot at a settled milestone: poll until two
  899. * consecutive normalized captures are equal — a single-shot capture races the
  900. * last React commits.
  901. * @param page - the page under test.
  902. * @param selector - the region locator selector.
  903. * @param workspaceCwd - normalization input.
  904. * @returns the stable normalized snapshot.
  905. */
  906. export async function captureStableAria(page: Page, selector: string, workspaceCwd: string): Promise<string> {
  907. const region = page.locator(selector).first()
  908. let previous = normalizeAria(await region.ariaSnapshot(), workspaceCwd)
  909. await expect.poll(async () => {
  910. const current = normalizeAria(await region.ariaSnapshot(), workspaceCwd)
  911. const stable = current === previous
  912. previous = current
  913. return stable
  914. }, { timeout: 5_000, message: 'aria snapshot did not stabilize' }).toBe(true)
  915. return previous
  916. }
  917. /**
  918. * Compare a normalized golden, or rewrite it under refresh. Refresh is the
  919. * ONLY writer: a missing golden in replay mode fails with the healing command
  920. * instead of silently self-bootstrapping.
  921. * @param goldenPath - the committed ui.expected.md path.
  922. * @param actual - the stable normalized snapshot.
  923. * @param mode - the active snapshot mode.
  924. */
  925. export async function compareOrRefreshGolden(goldenPath: string, actual: string, mode: WebSnapshotMode): Promise<void> {
  926. const payload = `${actual}\n`
  927. if (mode === 'refresh') {
  928. await writeFile(goldenPath, payload)
  929. return
  930. }
  931. if (!existsSync(goldenPath)) {
  932. throw new Error(`missing golden ${goldenPath} — run DSH_SNAPSHOT=refresh pnpm run test:web to generate it`)
  933. }
  934. expect(payload).toBe(await readFile(goldenPath, 'utf8'))
  935. }
  936. /**
  937. * Fixture-inventory guard: the scenario directory holds exactly the expected
  938. * files and every committed JSONL is a scrub fixed-point without a run-local
  939. * browser RPC id.
  940. * @param dir - the scenario snapshot directory.
  941. * @param expected - the exact expected file inventory.
  942. */
  943. export async function assertFixtureInventory(dir: string, expected: string[]): Promise<void> {
  944. const entries = (await readdir(dir)).sort()
  945. expect(entries).toEqual([...expected].sort())
  946. for (const entry of entries.filter(name => name.endsWith('.jsonl'))) {
  947. const content = await readFile(join(dir, entry), 'utf8')
  948. expect(scrubRequestHeaders(content), `${dir}/${entry} carries request-header bulk`).toBe(content)
  949. expect(content, `${dir}/${entry} carries a run-local rpcId`)
  950. .not.toMatch(/"rpcId":"(?!\{\{rpcId\}\})[^"]+"/)
  951. }
  952. }
  953. /**
  954. * Console tripwires: reconnect/gap-repair self-healing or a pageerror must
  955. * fail the scenario, not mask a dead wire behind eventual consistency.
  956. * @param page - the page under test.
  957. * @returns live warning/pageerror collectors to assert empty at scenario end.
  958. */
  959. export function watchConsole(page: Page): { warnings: string[]; pageErrors: string[] } {
  960. const warnings: string[] = []
  961. const pageErrors: string[] = []
  962. page.on('console', (message) => {
  963. const text = message.text()
  964. if (/connection lost|gap repair|discontinuous/i.test(text)) warnings.push(text)
  965. })
  966. page.on('pageerror', (error) => { pageErrors.push(String(error)) })
  967. return { warnings, pageErrors }
  968. }
  969. /**
  970. * Remove only connection-loss warnings emitted after an intentional reload.
  971. * Earlier warnings and all gap-repair/discontinuity warnings remain fatal.
  972. * @param tripwire - the live console-warning collector.
  973. * @param warningStart - warning count captured immediately before reloading.
  974. */
  975. export function acknowledgeReloadConnectionLoss(
  976. tripwire: ReturnType<typeof watchConsole>,
  977. warningStart: number,
  978. ): void {
  979. const reloadWarnings = tripwire.warnings.splice(warningStart)
  980. tripwire.warnings.push(...reloadWarnings.filter(text => !/connection lost/i.test(text)))
  981. }