scaffold.ts 46 KB

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