scaffold.ts 71 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569
  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 { createHash } from 'node:crypto'
  27. import { mkdir, mkdtemp, readFile, readdir, realpath, rm, writeFile } from 'node:fs/promises'
  28. import { tmpdir } from 'node:os'
  29. import { basename, dirname, join, resolve } from 'node:path'
  30. import { pathToFileURL } from 'node:url'
  31. import type { Page } from 'playwright'
  32. import { expect } from 'vitest'
  33. import { Context } from '@deepseek-ai/cordis'
  34. import Loader from '@deepseek-ai/cordis-plugin-loader'
  35. import Include, { type PatchOptions } from '@deepseek-ai/cordis-plugin-include'
  36. import Group from '@deepseek-ai/cordis-plugin-group'
  37. import {
  38. captureExpectedWorkspaceSnapshot,
  39. captureWorkspaceSnapshot,
  40. assertSessionFixtureVersion,
  41. formatSystemPromptSnapshot,
  42. formatToolSchemasSnapshot,
  43. normalizedSystemPrompts,
  44. normalizedToolSchemas,
  45. parseSnapshotManifest,
  46. redactSessionSnapshotIds,
  47. normalizeSessionSnapshots,
  48. parseSessionFixtureName,
  49. scrubRequestHeaders,
  50. scrubSessionSnapshot,
  51. sessionFixtureFiles,
  52. sessionFixtureName,
  53. stabilizeFixtureMessageIds,
  54. stabilizeRefreshLog,
  55. writesCurrentSessionFixtures,
  56. type NormalizeContext,
  57. } from '@deepseek-ai/dsh-session-snapshot'
  58. import {
  59. assertEntriesLoaded,
  60. composeEntries,
  61. healProfilesModuleFallback,
  62. loadOverlayPatches,
  63. type Profile,
  64. } from '@deepseek-ai/dsh-app-boot'
  65. import { dshHomePath } from '@deepseek-ai/dsh-home-paths'
  66. import { LlmAdapter } from '@deepseek-ai/dsh-llm'
  67. import type {
  68. LlmModelInfo, LlmProviderInfo, LlmResolvedModelInfo, RetryPolicyConfig, StreamChunk,
  69. } from '@deepseek-ai/dsh-llm'
  70. import type { ReplayHandle, ReplayProviderConfig } from '@deepseek-ai/dsh-llm-replay'
  71. import {
  72. installLlmReplay,
  73. parseSessionLog,
  74. prepareSessionSnapshotFixtureForComparison,
  75. } from '@deepseek-ai/dsh-llm-replay'
  76. import type { SessionFormatEvent } from '@deepseek-ai/dsh-session-format'
  77. import { sessionFormatCatalog } from '@deepseek-ai/dsh-session-format-catalog'
  78. import {
  79. SESSION_FORMAT_VERSION,
  80. SessionId,
  81. type Session,
  82. type SessionEvent,
  83. type SessionHeader,
  84. } from '@deepseek-ai/dsh-session'
  85. import JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl'
  86. // Empty type imports carry the webServer/agents/sessionPersistence Context merges.
  87. import type {} from '@deepseek-ai/dsh-host-webserver'
  88. import type {} from '@deepseek-ai/dsh-agent'
  89. import { provideCmdline } from '@deepseek-ai/dsh-cmdline'
  90. import { REPO_ROOT, requireDist } from './support.ts'
  91. // Host-side web e2e cannot import a browser package: doing so would pull that
  92. // package's complete TS project into this graph. Mirrored from
  93. // packages/client/ui-settings-models/src/onboarding-copy.ts; drift makes the
  94. // default pre-acknowledgement stop suppressing the notice and fails loudly.
  95. // import {
  96. // WELCOME_NOTICE_ACK_FIELD, WELCOME_NOTICE_SETTINGS_NAMESPACE,
  97. // WELCOME_NOTICE_VERSION, WELCOME_NOTICE_COPY,
  98. // } from '@deepseek-ai/dsh-client-ui-settings-models'
  99. export const WELCOME_NOTICE_SETTINGS_NAMESPACE = 'ui-onboarding'
  100. export const WELCOME_NOTICE_ACK_FIELD = 'welcomeNoticeVersion'
  101. export const WELCOME_NOTICE_VERSION = '2026-08-13.1'
  102. export const WELCOME_NOTICE_COPY = {
  103. zh: {
  104. title: '内测声明',
  105. body: 'DeepSeek Harness 目前的 0.1 版本仍处在面向 Harness 开发者进行测试的阶段,还有许多地方需要持续改进和打磨,希望听取广大开发者的反馈建议。预计 DeepSeek Harness 的核心插件以及基础 API 都会在接下来的一段时间内快速迭代、持续演化。\n\n我们期待与全球开发者一起,在开源、开放、可复用、可组合的基础设施之上,共同探索智能上限。欢迎全球 Harness 开发者加入 DSH 插件生态。',
  106. continueLabel: '继续',
  107. },
  108. } as const
  109. /** Snapshot mode for the lane, from $DSH_SNAPSHOT (same vocabulary as the other snapshot suites). */
  110. export type WebSnapshotMode = 'replay' | 'record' | 'refresh'
  111. /**
  112. * Resolve and validate the lane's snapshot mode.
  113. * @returns the active mode; unset/empty selects replay.
  114. */
  115. export function webSnapshotMode(): WebSnapshotMode {
  116. const value = process.env.DSH_SNAPSHOT
  117. if (value === undefined || value === '' || value === 'replay') return 'replay'
  118. if (value === 'record' || value === 'refresh') return value
  119. throw new Error(`DSH_SNAPSHOT must be replay, record, or refresh; got ${JSON.stringify(value)}`)
  120. }
  121. /**
  122. * Compare a session-driven Web scenario's complete workspace with its committed independent expected state.
  123. * @param scenarioDir - Absolute recorded-session scenario directory.
  124. * @param workspaceRoot - Absolute cwd used by the controlled session.
  125. */
  126. export async function assertFinalWorkspaceSnapshot(scenarioDir: string, workspaceRoot: string): Promise<void> {
  127. const manifestPath = join(scenarioDir, 'snapshot.yml')
  128. const manifest = parseSnapshotManifest(await readFile(manifestPath, 'utf8'), manifestPath)
  129. expect(manifest.workspace?.final, `${manifest.scenario ?? scenarioDir}: mutating Web scenario declares workspace.final`)
  130. .toBe(true)
  131. const actual = await captureWorkspaceSnapshot(workspaceRoot)
  132. const expected = await captureExpectedWorkspaceSnapshot(join(scenarioDir, 'workspace.expected'))
  133. expect(actual, `${manifest.scenario ?? scenarioDir}: complete final workspace`).toEqual(expected)
  134. }
  135. async function ownsReplayFixture(replayFixture: string | undefined): Promise<boolean> {
  136. if (replayFixture === undefined) return false
  137. const fixture = parseSessionFixtureName(basename(replayFixture))
  138. if (fixture === undefined || fixture.index !== 0) return false
  139. const manifestPath = join(dirname(replayFixture), 'snapshot.yml')
  140. if (!existsSync(manifestPath)) return false
  141. const manifest = parseSnapshotManifest(await readFile(manifestPath, 'utf8'), manifestPath)
  142. return manifest.session === undefined
  143. }
  144. /**
  145. * Resolve one requested fixture role to its highest committed generation.
  146. * @param path - any generation path for the requested parent or child role.
  147. * @param allowAbsent - Keep an absent canonical path only for an override-only replay script.
  148. * @returns the highest canonical sibling generation, or the input for non-Session files.
  149. */
  150. export async function selectedSessionFixture(path: string, allowAbsent = false): Promise<string> {
  151. const requested = parseSessionFixtureName(basename(path))
  152. if (requested === undefined) return path
  153. const entries = await readdir(dirname(path))
  154. if (allowAbsent && !entries.some(name => parseSessionFixtureName(name) !== undefined)) return path
  155. const selected = sessionFixtureFiles(entries)
  156. .find(candidate => candidate.index === requested.index)
  157. if (selected === undefined) throw new Error(`${path}: missing Session fixture role ${requested.index}`)
  158. const resolved = join(dirname(path), selected.name)
  159. assertSessionFixtureVersion(selected.name, await readFile(resolved, 'utf8'))
  160. return resolved
  161. }
  162. /**
  163. * Return the current-writer target without replacing the requested older fixture.
  164. * @param path - any canonical fixture generation for one role.
  165. * @param version - generation emitted by the current writer.
  166. * @returns the canonical sibling path for that role and generation.
  167. */
  168. export function recordedSessionFixturePath(path: string, version: number): string {
  169. const fixture = parseSessionFixtureName(basename(path))
  170. if (fixture === undefined) throw new Error(`record harvest: invalid Session fixture path ${path}`)
  171. return join(dirname(path), sessionFixtureName(fixture.index, version))
  172. }
  173. /** The shipped composition under test: the dsh-base and dsh-web-app bundle patches over the empty profile root. */
  174. const BASE_PATCH_PATH = join(REPO_ROOT, 'packages/bundle/base/cordis.patch.yml')
  175. const WEB_PATCH_PATH = join(REPO_ROOT, 'packages/bundle/web-app/cordis.patch.yml')
  176. /** The installation anchor whose dependency surface the profile module fallback mirrors. */
  177. const INSTALL_ANCHOR = join(REPO_ROOT, 'apps/cli/package.json')
  178. // Replay publishes the provider catalog the gateway routes to (providers
  179. // mode, never catch-all: with llm-deepseek disabled no adapter exists, so a
  180. // catch-all would leave resolveModelInfo unroutable and compaction-basic's
  181. // post-step pressure check would warn every step). The published
  182. // contextWindow keeps that pressure path provably inert for small fixtures.
  183. const REPLAY_PROVIDERS = [{
  184. id: 'deepseek-official',
  185. name: 'DeepSeek',
  186. models: [
  187. { id: 'deepseek-v4-flash', name: 'DeepSeek-V4-Flash', contextWindow: 128_000 },
  188. {
  189. id: 'deepseek-v4-flash-vision-exp',
  190. name: 'DeepSeek-V4-Flash-Vision-Exp',
  191. contextWindow: 1_000_000,
  192. inputModalities: ['text', 'image'] as const,
  193. defaultMaxTokens: 256_000,
  194. reasoningEfforts: ['off', 'low', 'high', 'max'],
  195. defaultReasoningEffort: 'high',
  196. },
  197. ],
  198. }]
  199. /**
  200. * The routes a shipped composition always has, with no ability to stream.
  201. * A fixture-less keyless scenario issues no model calls, but its tree must
  202. * still answer `listProviders()` — surfaces legitimately gate on whether any
  203. * adapter serves a session's route, and an empty registry is a test artifact,
  204. * not a product state.
  205. */
  206. class RouteOnlyAdapter extends LlmAdapter {
  207. constructor(private readonly providers: typeof REPLAY_PROVIDERS) {
  208. super()
  209. }
  210. override providerInfo(provider: string): LlmProviderInfo {
  211. return { id: provider, name: this.providers.find(entry => entry.id === provider)?.name ?? provider }
  212. }
  213. override listModels(provider: string): Promise<readonly LlmModelInfo[]> {
  214. return Promise.resolve((this.providers.find(entry => entry.id === provider)?.models ?? [])
  215. .map(model => ({ provider, id: model.id, name: model.name })))
  216. }
  217. override resolveModel(provider: string, model: string): Promise<LlmResolvedModelInfo> {
  218. const listed = this.providers.find(entry => entry.id === provider)?.models
  219. .find(entry => entry.id === model)
  220. return Promise.resolve({
  221. provider,
  222. id: model,
  223. name: listed?.name ?? model,
  224. ...listed?.contextWindow === undefined ? {} : { contextWindow: listed.contextWindow },
  225. })
  226. }
  227. override async *stream(): AsyncIterable<StreamChunk> {
  228. throw new Error(
  229. 'web e2e scaffold: a model call was issued by a scenario that declared no replay fixture'
  230. + ' — pass replayFixture, or keep the scenario free of model calls',
  231. )
  232. }
  233. }
  234. function replayProviders(contextWindow: number | undefined): typeof REPLAY_PROVIDERS {
  235. if (contextWindow === undefined) return REPLAY_PROVIDERS
  236. return REPLAY_PROVIDERS.map(provider => ({
  237. ...provider,
  238. models: provider.models.map(model => ({ ...model, contextWindow })),
  239. }))
  240. }
  241. /** A booted web scaffold: real composition, mode-selected model backend, temp world. */
  242. export interface WebScaffold {
  243. /** The active snapshot mode this scaffold booted under. */
  244. mode: WebSnapshotMode
  245. /** Browser-facing origin for the bound test server. */
  246. baseUrl: string
  247. /** Process-token URL that establishes this scaffold's browser session. */
  248. authenticatedUrl: string
  249. /** Settled root context (the in-process readiness barrier; headless event subscription is its sanctioned use). */
  250. ctx: Context
  251. /** Temp project directory sessions run in (shell/fs tool cwd). */
  252. workspaceCwd: string
  253. /** Temp persistence root (seeded sessions land here through the real API). */
  254. persistenceRoot: string
  255. /** Isolated harness home the settings/credentials rows write ($DSH_HOME double). */
  256. harnessHome: string
  257. /** Send a browser-equivalent Host request with this scaffold's authenticated cookie. */
  258. hostFetch(path: string, init?: RequestInit): Promise<Response>
  259. /** Await a settled turn end: in-process turn/end, then the agent's idle flip (which follows the persistence flush). */
  260. whenTurnSettled(timeoutMs?: number): Promise<SessionId>
  261. /**
  262. * Tear everything down; asserts the replay fixture was fully consumed first
  263. * (replay/refresh), unless booted with replayProvidersOnly (whose fixture
  264. * is validated call-free at boot).
  265. */
  266. close(): Promise<void>
  267. }
  268. /** Options for {@link launchWebScaffold}. */
  269. export interface LaunchOptions {
  270. /** Compare the replayed root session with `replayFixture`; defaults on for a manifest-owned canonical recording. */
  271. compareReplaySession?: boolean
  272. /**
  273. * Optional product overlay applied after the shipped Web surface and before
  274. * the scaffold's hermetic test patches, matching the launcher's `--patch`
  275. * ordering.
  276. */
  277. extraOverlayPath?: string
  278. /**
  279. * Additional source-checkout package manifests whose dependency closures
  280. * supply private profile layers named by {@link extraOverlayPath}.
  281. */
  282. extraInstallAnchors?: string[]
  283. /**
  284. * Replay fixture (session.jsonl) served by the inserted dsh-llm-replay row
  285. * in replay/refresh modes; ignored in record mode (the real adapter
  286. * answers). Omit for scenarios issuing no model calls — a stray stream then
  287. * fails loud with NO_ADAPTER (llm-deepseek is disabled and no replay row
  288. * mounts). With {@link replayProvidersOnly}, the fixture must record no
  289. * model calls (its header alone mounts the catalog).
  290. */
  291. replayFixture?: string
  292. /** Explicit replay routes for scenarios exercising provider-dependent behavior; replay/refresh only. */
  293. replayProviders?: ReplayProviderConfig[]
  294. /**
  295. * Mount the replay provider catalog (the model directory the UI shows)
  296. * without consuming any recorded script: for scenarios that never call a
  297. * model but need the real provider/model labels rendered. Requires
  298. * {@link replayFixture} whose log records no model calls, and rejects
  299. * {@link replayOverride} and {@link replayChildFixtures}; the teardown
  300. * consumption check is skipped for this mode. `replayFixture` without this
  301. * flag keeps the consumption check.
  302. */
  303. replayProvidersOnly?: boolean
  304. /**
  305. * Recorded child logs assigned in child creation order. Each child owns its
  306. * own positional replay cursor across initial and continuation turns.
  307. */
  308. replayChildFixtures?: string[]
  309. /**
  310. * Optional replay.override.json sidecar (whole-script replacement or
  311. * `{ patches }` augmentation) for throw/hang scenarios not expressible as
  312. * recorded chunks; replay/refresh only.
  313. */
  314. replayOverride?: string
  315. /**
  316. * Retry policy registered on every replay provider route, for failure-
  317. * injection scenarios that must exhaust recovery quickly instead of walking
  318. * the shared normal default's five backed-off retries; replay/refresh only.
  319. */
  320. replayRetryPolicy?: RetryPolicyConfig
  321. /** Per-chunk replay pacing (ms) so the browser observes genuinely incremental SSE; replay/refresh only. */
  322. paceMs?: number
  323. /** Synthetic model capacity for UI scenarios whose seeded history must remain uncompacted. */
  324. replayContextWindow?: number
  325. /**
  326. * Tool presentation mode patched onto the shipped `tools` row (`code`
  327. * collapses the wire to run_code + the SDK prompt section). Omit for the
  328. * yml default. The code runtime row is always in the tree, so no extra
  329. * insertion is needed.
  330. */
  331. toolsMode?: 'native' | 'ptc' | 'both'
  332. /**
  333. * Insert the opt-in model-facing Cordis tool provider into the shipped tree.
  334. * Record and replay use the same tool surface, so captured request headers
  335. * remain reconstructable without making the tools a product default.
  336. */
  337. cordisTools?: boolean
  338. /**
  339. * Keep the shipped DeepSeek adapter mounted while masking the process
  340. * environment's DEEPSEEK_API_KEY for this scaffold lifetime. This is the
  341. * keyless first-run configuration lane; the default disables the adapter.
  342. */
  343. deepSeekMissingCredential?: boolean
  344. /** Leave the current welcome notice pending; ordinary scenarios pre-acknowledge it before browser boot. */
  345. welcomeNoticePending?: boolean
  346. /**
  347. * Patch the shipped DeepSeek search row to a deterministic endpoint and
  348. * credential reference. Browser search scenarios keep the real provider and
  349. * credentials seam while avoiding external search traffic and ambient keys.
  350. */
  351. deepSeekSearch?: {
  352. /** Anthropic-compatible base URL; the provider appends `/messages`. */
  353. baseURL: string
  354. /** Credential reference resolved by the shipped search provider. */
  355. apiKeyEnv: string
  356. }
  357. /**
  358. * Replace the roster row the scaffold pins by default (no configured roots,
  359. * default `standard` — the plugin's own shipped presets). Supply this only
  360. * to change WHICH presets a scenario sees beyond the shipped set — a
  361. * writable user root, a different default. The patch lands after the
  362. * default, so it wins.
  363. */
  364. agentPresets?: {
  365. /** Roots to discover after the plugin's shipped root, in precedence order. */
  366. roots: { path: string; trust: 'system' | 'user' }[]
  367. /** The preset a session that names none is composed from. */
  368. default: string
  369. }
  370. /**
  371. * Patch the telemetry exporter URL while preserving the shipped enabled
  372. * setting. A scenario-owned loopback collector contains all fixture uploads.
  373. */
  374. telemetryUrl?: string
  375. /** Mode when telemetryUrl is supplied; defaults to FEEDBACK_ONLY without enabling a disabled row. */
  376. telemetryMode?: 'FEEDBACK_ONLY'
  377. /** SDK batch cadence for a scenario-owned collector; omitted to retain the SDK default. */
  378. telemetryScheduledDelayMillis?: number
  379. /**
  380. * Browse through a trusted non-loopback hostname that the browser resolves
  381. * to loopback (for example `*.localhost`). The test server stays bound to
  382. * 127.0.0.1; a non-resolving authority fails before Host trust is exercised.
  383. */
  384. remoteAuthority?: string
  385. /** Reuse an existing harness home so a second Host can verify user settings across origins. */
  386. harnessHome?: string
  387. }
  388. /** Dispose the booted tree and remove both owned temp roots, reporting every independent cleanup failure. */
  389. async function cleanupScaffoldWorld(ctx: Context, workspaceCwd: string, persistenceRoot: string): Promise<unknown[]> {
  390. const failures: unknown[] = []
  391. await Promise.resolve(ctx.fiber.dispose()).catch((error: unknown) => failures.push(error))
  392. await rm(workspaceCwd, { recursive: true, force: true }).catch((error: unknown) => failures.push(error))
  393. await rm(persistenceRoot, { recursive: true, force: true }).catch((error: unknown) => failures.push(error))
  394. return failures
  395. }
  396. /**
  397. * Boot the real web composition under the current snapshot mode.
  398. * @param options - replay fixture selection and pacing.
  399. * @returns the running scaffold.
  400. */
  401. export async function launchWebScaffold(options: LaunchOptions = {}): Promise<WebScaffold> {
  402. requireDist()
  403. const mode = webSnapshotMode()
  404. const replayFixture = options.replayFixture === undefined
  405. ? undefined
  406. : await selectedSessionFixture(options.replayFixture, options.replayOverride !== undefined)
  407. const replayChildFixtures = options.replayChildFixtures === undefined
  408. ? undefined
  409. : await Promise.all(options.replayChildFixtures.map(path => selectedSessionFixture(path)))
  410. const compareReplaySession = options.compareReplaySession ?? await ownsReplayFixture(replayFixture)
  411. const browserHost = options.remoteAuthority ?? '127.0.0.1'
  412. if (mode === 'record') {
  413. // Both owning vitest configs (web unconditionally, snapshot in record
  414. // mode) load the repo-root .env before this file runs.
  415. if (process.env.DEEPSEEK_API_KEY === undefined || process.env.DEEPSEEK_API_KEY.length === 0) {
  416. throw new Error('web e2e record mode needs DEEPSEEK_API_KEY (env or repo-root .env)')
  417. }
  418. }
  419. if (mode === 'record' && options.deepSeekMissingCredential === true) {
  420. throw new Error('deepSeekMissingCredential is a keyless replay/refresh option')
  421. }
  422. const maskDeepSeekCredential = mode !== 'record' && options.deepSeekMissingCredential === true
  423. const originalDeepSeekCredential = process.env.DEEPSEEK_API_KEY
  424. let credentialEnvironmentRestored = false
  425. const restoreCredentialEnvironment = (): void => {
  426. if (credentialEnvironmentRestored || !maskDeepSeekCredential) return
  427. credentialEnvironmentRestored = true
  428. if (originalDeepSeekCredential === undefined) {
  429. Reflect.deleteProperty(process.env, 'DEEPSEEK_API_KEY')
  430. } else {
  431. process.env.DEEPSEEK_API_KEY = originalDeepSeekCredential
  432. }
  433. }
  434. const workspaceCwd = await realpath(await mkdtemp(join(tmpdir(), 'dsh-web-e2e-ws-')))
  435. // Isolated harness home: the settings/credentials rows resolve $DSH_HOME
  436. // paths at load, and an in-process boot must NEVER touch the developer's
  437. // real ~/.dsh document or credential file.
  438. const harnessHome = options.harnessHome ?? join(workspaceCwd, '.dsh-home')
  439. // Skill discovery is model-visible input, and its roots now resolve inside a
  440. // PRESET — a subtree this lane's include patches cannot reach, because the
  441. // roster mounts it directly per session rather than as a row of the booted
  442. // tree. The row's documented fallback is the environment, so pin that: the
  443. // whole scaffold lifetime, not just the boot, since presets mount when a
  444. // session is created. Without this a developer's real ~/.dsh/skills silently
  445. // enters replay requests and goldens while CI sees none. `DSH_HOME` follows
  446. // the resolved harness home so a scaffold sharing another's home — the
  447. // cross-port persistence scenario — pins the same roots the settings and
  448. // credentials rows were configured with.
  449. const skillRootEnvironment = {
  450. DSH_HOME: harnessHome,
  451. DSH_AGENTS_HOME: join(workspaceCwd, '.agents-home'),
  452. DSH_BUNDLED_SKILL_DIR: join(workspaceCwd, '.bundled-skills'),
  453. }
  454. const originalSkillRootEnvironment = Object.fromEntries(
  455. Object.keys(skillRootEnvironment).map(key => [key, process.env[key]]),
  456. )
  457. let skillRootEnvironmentRestored = false
  458. const restoreSkillRootEnvironment = (): void => {
  459. if (skillRootEnvironmentRestored) return
  460. skillRootEnvironmentRestored = true
  461. for (const [key, value] of Object.entries(originalSkillRootEnvironment)) {
  462. if (value === undefined) Reflect.deleteProperty(process.env, key)
  463. else process.env[key] = value
  464. }
  465. }
  466. Object.assign(process.env, skillRootEnvironment)
  467. let persistenceRoot: string
  468. try {
  469. persistenceRoot = await mkdtemp(join(tmpdir(), 'dsh-web-e2e-sessions-'))
  470. } catch (error) {
  471. const failures: unknown[] = [error]
  472. await rm(workspaceCwd, { recursive: true, force: true }).catch((cleanupError: unknown) => failures.push(cleanupError))
  473. restoreSkillRootEnvironment()
  474. if (failures.length > 1) throw new AggregateError(failures, 'web scaffold temp-root setup failed')
  475. throw error
  476. }
  477. if (maskDeepSeekCredential) Reflect.deleteProperty(process.env, 'DEEPSEEK_API_KEY')
  478. // The include patch set — the same layer stack the profile boot composes
  479. // (bundle patches in dsh.profile.bundles order), applied over the SAME empty root (a
  480. // patch id that stops matching a row fails the boot sweep loudly instead of
  481. // drifting).
  482. const basePatches = loadOverlayPatches('web e2e scaffold', BASE_PATCH_PATH)
  483. const surfacePatches = loadOverlayPatches('web e2e scaffold', WEB_PATCH_PATH)
  484. const extraOverlayPatches = options.extraOverlayPath === undefined
  485. ? []
  486. : loadOverlayPatches('web e2e scaffold', options.extraOverlayPath)
  487. const composedRows = composeEntries([basePatches, surfacePatches, extraOverlayPatches])
  488. const webRuntimeConfig = composedRows.find(row => row.id === 'web-runtime')?.config as {
  489. surfaceContext?: boolean
  490. } | undefined
  491. const surfaceContext = webRuntimeConfig?.surfaceContext !== false
  492. const patches: PatchOptions[] = [
  493. ...basePatches,
  494. ...surfacePatches,
  495. ...extraOverlayPatches,
  496. // The roster's shipped presets are the plugin's own, bundled inside
  497. // `dsh-agent-presets` and prepended by it. Pin only the machine-local
  498. // root away: a developer's own `~/.dsh/.agent-presets` must not be able
  499. // to change a golden.
  500. {
  501. id: 'agent-presets',
  502. config: {
  503. default: 'standard',
  504. includeUserRoot: false,
  505. },
  506. },
  507. { id: 'session-persistence-jsonl', config: { root: persistenceRoot } },
  508. // Content search is enabled here although the shipped bundles default it
  509. // off (`openAt: never`, pinned by apps/cli/tests/lazy-search-startup):
  510. // the seeded-session scenarios navigate by content search, and these e2e
  511. // runs are the assembled coverage for the opt-in search path.
  512. { id: 'session-query-sqlite', config: { path: ':memory:', openAt: 'first-search' } },
  513. // storage-json's yml root is anchored to the real $DSH_HOME; pin the row
  514. // to an absolute temp root (removed with the workspace at close) so tests
  515. // never write the user's harness home.
  516. { id: 'storage-json', config: { root: join(workspaceCwd, '.dsh-storages') } },
  517. // Skill discovery is model-visible input. Pin every host-level root inside
  518. // the owned temp world so ~/.dsh, ~/.agents, and a bundled-root env setting
  519. // cannot change replay requests or conversation goldens. Project roots stay
  520. // enabled against the same empty temp workspace, preserving the real seam.
  521. {
  522. id: 'skill-filesystem',
  523. config: {
  524. dshHome: join(workspaceCwd, '.dsh-home'),
  525. agentsHome: join(workspaceCwd, '.agents-home'),
  526. bundledSkillDir: join(workspaceCwd, '.bundled-skills'),
  527. watch: false,
  528. },
  529. },
  530. // fs/bash cwd default to process.cwd(); the gateway injects the same
  531. // value into session.cwd — chdir below anchors all three to the temp
  532. // workspace, keeping the composition untouched.
  533. { id: 'agent-instructions', disabled: true },
  534. { id: 'session-title-llm', disabled: true },
  535. // Fixture sessions must never leave the process: the shipped row defaults
  536. // to the production OTLP endpoint (or whatever DSH_TELEMETRY_OTLP_URL
  537. // names in the ambient environment). A scenario with a local collector
  538. // preserves the shipped disabled setting instead of overriding it.
  539. options.telemetryUrl === undefined
  540. ? { id: 'session-telemetry-otel', disabled: true }
  541. : {
  542. id: 'session-telemetry-otel',
  543. config: {
  544. mode: options.telemetryMode ?? 'FEEDBACK_ONLY',
  545. exporter: { url: options.telemetryUrl },
  546. ...(options.telemetryScheduledDelayMillis === undefined ? {} : {
  547. processor: { scheduledDelayMillis: options.telemetryScheduledDelayMillis },
  548. }),
  549. shutdownTimeoutMillis: 1_000,
  550. },
  551. },
  552. // Use an ephemeral port while preserving the shipped compression policy;
  553. // a patch replaces the row's complete config.
  554. {
  555. id: 'webserver',
  556. config: {
  557. host: '127.0.0.1', port: 0, compression: 'gzip',
  558. compressionLevel: 1, compressionThresholdBytes: 1024,
  559. },
  560. },
  561. // The bundle's web-runtime row resolves the same built dist under test
  562. // (apps/web IS @deepseek-ai/dsh-web-frontend); native browser opening and the
  563. // URL line are disabled because this scaffold owns its Playwright browser.
  564. // Preserve the composed surface-context choice because a patch replaces
  565. // the row's complete config.
  566. { id: 'web-runtime', config: { openBrowser: false, printUrl: false, surfaceContext } },
  567. ...options.remoteAuthority === undefined
  568. ? []
  569. : [{ id: 'connection', config: { trustedHosts: [options.remoteAuthority] } }],
  570. { id: 'settings', config: { dshHome: harnessHome } },
  571. { id: 'credentials', config: { dshHome: harnessHome } },
  572. // The shipped directory-picker row is the -auto chooser, which resolves
  573. // the interaction from the RUNNING host (display, SSH launch, bind). The
  574. // lane's goldens are interaction-specific (workspace-management drives
  575. // the in-app browse dialog), so pin -browse deterministically on every
  576. // host: patch `name` is an assertion, not an override, hence the
  577. // disable+insert pair.
  578. { id: 'directory-picker', disabled: true },
  579. { insert: [
  580. { id: 'directory-picker-browse', name: '@deepseek-ai/dsh-host-directory-picker-browse' },
  581. { id: 'ui-directory-picker-browse', name: '@deepseek-ai/dsh-client-ui-directory-picker-browse' },
  582. ] },
  583. // The open-in-app header button reflects the host application probe —
  584. // whatever editors and terminals the RUNNING machine has installed — so
  585. // its presence and label would vary per host and platform. Pin both rows
  586. // off (routes and surface); the packages' own composition and jsdom tests
  587. // cover the button.
  588. { id: 'open-in-app', disabled: true },
  589. { id: 'ui-open-in-app', disabled: true },
  590. ...options.agentPresets === undefined
  591. ? []
  592. // Never the derived harness-home root: a developer's own presets must not
  593. // be able to change a golden, whatever roots a scenario asks for.
  594. : [{ id: 'agent-presets', config: { ...options.agentPresets, includeUserRoot: false } }],
  595. ...options.toolsMode === undefined ? [] : [{ id: 'tools', config: { mode: options.toolsMode } }],
  596. // The shipped Web bundle already owns both runners and the Cordis UI. This
  597. // scenario adds only the model-facing tools that exercise those services.
  598. ...options.cordisTools === true
  599. ? [{ insert: [
  600. { id: 'tool-cordis', name: '@deepseek-ai/dsh-tool-cordis' },
  601. ] }]
  602. : [],
  603. ...options.deepSeekSearch === undefined
  604. ? []
  605. : [{
  606. id: 'web-search-deepseek',
  607. config: {
  608. apiKeyEnv: options.deepSeekSearch.apiKeyEnv,
  609. baseURL: options.deepSeekSearch.baseURL,
  610. },
  611. }],
  612. ...mode === 'record' || options.deepSeekMissingCredential === true
  613. ? []
  614. : [{ id: 'llm-deepseek', disabled: true }],
  615. ]
  616. // Sessions inherit the gateway's process.cwd() default; run the boot from
  617. // the temp workspace so tool cwd, session cwd, and fixtures agree.
  618. const originalCwd = process.cwd()
  619. const ctx = new Context()
  620. const observedSessions = new Map<SessionId, Session>()
  621. const stopObservingSessions = ctx.on('session/created', (session) => {
  622. observedSessions.set(session.id, session)
  623. })
  624. let port = 0
  625. let baseUrl = ''
  626. let authenticatedUrl = ''
  627. let cookieHeader = ''
  628. let replayHandle: ReplayHandle | undefined
  629. try {
  630. process.chdir(workspaceCwd)
  631. const profileDir = join(harnessHome, 'profiles', 'scaffold')
  632. const extraLayers: Profile['layers'] = await Promise.all((options.extraInstallAnchors ?? []).map(async (anchor) => {
  633. const manifest = JSON.parse(await readFile(anchor, 'utf8')) as { name?: unknown }
  634. if (typeof manifest.name !== 'string' || manifest.name === '') {
  635. throw new Error(`web scaffold extra install anchor has no package name: ${anchor}`)
  636. }
  637. const packageDir = dirname(anchor)
  638. return {
  639. packageName: manifest.name,
  640. packageDir,
  641. patchPath: join(packageDir, 'cordis.patch.yml'),
  642. patches: [],
  643. }
  644. }))
  645. // Mirror the production launcher: the shared installation closure keeps
  646. // its carrier-specific fallback, while private bundle dependencies stay
  647. // isolated to this synthetic scaffold profile.
  648. await healProfilesModuleFallback({
  649. installAnchor: INSTALL_ANCHOR,
  650. home: harnessHome,
  651. profile: {
  652. name: 'scaffold',
  653. dir: profileDir,
  654. layers: extraLayers,
  655. patchPath: join(profileDir, 'cordis.patch.yml'),
  656. patches: [],
  657. patchReload: 'startup',
  658. },
  659. })
  660. await mkdir(profileDir, { recursive: true })
  661. const rootConfig = join(profileDir, 'cordis.yml')
  662. await writeFile(rootConfig, '[]\n')
  663. ctx.baseUrl = pathToFileURL(profileDir).href + '/'
  664. // This direct Loader harness supplies the same root-path capability as app-boot.
  665. ctx.provide('dshHomePath', dshHomePath)
  666. // A host with no command line still provides one: the web bundle's startup
  667. // row releases the rows waiting on it, and with no arguments each starts on
  668. // the values this scaffold composed above. An exit request can only come
  669. // from a rejected argument, which a fixed empty list has none of.
  670. provideCmdline(ctx, {
  671. args: [],
  672. exit: (code) => {
  673. throw new Error(`web e2e scaffold: the web app requested exit ${String(code)} with no arguments to reject`)
  674. },
  675. })
  676. await ctx.plugin(Loader)
  677. ctx.loader.builtins.include = Include
  678. // `cordis:group` beside it, exactly as `boot()` registers it: a group row is
  679. // how a preset gives one `isolate` realm to a provider and its consumers,
  680. // and a preset resolving package names from its own directory cannot reach
  681. // `@deepseek-ai/cordis-plugin-group` by name.
  682. ctx.loader.builtins.group = Group
  683. await ctx.loader.create({
  684. name: 'cordis:include',
  685. config: { path: pathToFileURL(rootConfig).href, patches },
  686. })
  687. await ctx.loader.await()
  688. assertEntriesLoaded(ctx, 'web e2e scaffold')
  689. if (options.welcomeNoticePending !== true) {
  690. await ctx.settings.mutate(WELCOME_NOTICE_SETTINGS_NAMESPACE, [{
  691. op: 'set', path: [WELCOME_NOTICE_ACK_FIELD], value: WELCOME_NOTICE_VERSION,
  692. }])
  693. }
  694. const boundPort = ctx.get('webServer')?.port
  695. if (boundPort === undefined) {
  696. throw new Error('web e2e scaffold: webServer service missing after settled boot')
  697. }
  698. port = boundPort
  699. // Fill the open llm seam on the settled root ctx. Ordinary keyless modes
  700. // disable llm-deepseek; the first-run lane keeps it mounted but has no
  701. // replay fixture and never streams. The direct install, unlike the plugin
  702. // row, returns the ReplayHandle for the teardown consumption check.
  703. if (options.replayProvidersOnly) {
  704. if (replayFixture === undefined) {
  705. throw new Error('replayProvidersOnly requires replayFixture (its file supplies the header)')
  706. }
  707. const fixtureText = readFileSync(replayFixture, 'utf8')
  708. // The consumption check is skipped for this mode, so no script source
  709. // may carry callable entries: reject override/child sources outright
  710. // and any call-bearing fixture.
  711. if (options.replayOverride !== undefined || replayChildFixtures !== undefined) {
  712. throw new Error('replayProvidersOnly cannot combine with replayOverride or replayChildFixtures')
  713. }
  714. // A fixture without a session header row must not mount the catalog
  715. // silently: the consumption-skip assumes the header-only shape.
  716. let headerType: unknown
  717. try {
  718. headerType = (JSON.parse(fixtureText.trimStart().split('\n', 1)[0] ?? '') as { type?: unknown }).type
  719. } catch {
  720. headerType = undefined
  721. }
  722. if (headerType !== 'session') {
  723. throw new Error('replayProvidersOnly fixture must open with a session header row')
  724. }
  725. const recorded = parseSessionLog(fixtureText)
  726. const hasModelCall = recorded.some(event => (
  727. event.type === 'assistant/message' || event.type === 'assistant/attempt'
  728. || event.type === 'request/header' || event.type === 'tool/call'
  729. ))
  730. if (hasModelCall) {
  731. throw new Error('replayProvidersOnly fixture must record no model calls')
  732. }
  733. }
  734. if (mode !== 'record' && replayFixture !== undefined) {
  735. replayHandle = installLlmReplay(ctx, {
  736. file: replayFixture,
  737. providers: (options.replayProviders ?? replayProviders(options.replayContextWindow)).map(provider => ({
  738. ...provider,
  739. ...(options.replayRetryPolicy === undefined ? {} : { retryPolicy: options.replayRetryPolicy }),
  740. })),
  741. ...(options.replayOverride === undefined ? {} : { overrideFile: options.replayOverride }),
  742. ...(replayChildFixtures === undefined ? {} : { childFiles: replayChildFixtures }),
  743. ...(options.paceMs === undefined ? {} : { paceMs: options.paceMs }),
  744. })
  745. } else if (mode !== 'record' && options.deepSeekMissingCredential !== true) {
  746. // No fixture and no shipped adapter would leave the tree with ZERO
  747. // provider routes — a state no product composition has, and one the
  748. // composer refuses to type into. Register the same routes
  749. // a fixture would, with streaming that still fails loud: the scenario
  750. // issues no model calls, and one that slipped in must not pass quietly.
  751. ctx.effect(() => ctx.llm.registerAdapter(
  752. replayProviders(options.replayContextWindow).map(provider => provider.id),
  753. new RouteOnlyAdapter(replayProviders(options.replayContextWindow)),
  754. ), 'web e2e scaffold: route-only adapter')
  755. }
  756. baseUrl = `http://${browserHost}:${String(port)}`
  757. authenticatedUrl = ctx.connection.authenticatedUrl(baseUrl)
  758. const login = await fetch(authenticatedUrl, { redirect: 'manual' })
  759. const setCookie = login.headers.get('set-cookie')
  760. if (login.status !== 303 || login.headers.get('location') !== '/' || setCookie === null) {
  761. throw new Error('web e2e scaffold: browser token exchange did not return its session cookie')
  762. }
  763. cookieHeader = setCookie.split(';', 1)[0] ?? ''
  764. if (cookieHeader.length === 0) {
  765. throw new Error('web e2e scaffold: browser token exchange returned an empty session cookie')
  766. }
  767. } catch (error) {
  768. if (process.cwd() !== originalCwd) process.chdir(originalCwd)
  769. const cleanupFailures = await cleanupScaffoldWorld(ctx, workspaceCwd, persistenceRoot)
  770. restoreCredentialEnvironment()
  771. restoreSkillRootEnvironment()
  772. if (cleanupFailures.length > 0) {
  773. throw new AggregateError([error, ...cleanupFailures], 'web scaffold setup failed and cleanup was incomplete')
  774. }
  775. throw error
  776. } finally {
  777. if (process.cwd() !== originalCwd) process.chdir(originalCwd)
  778. }
  779. return {
  780. harnessHome,
  781. mode,
  782. baseUrl,
  783. authenticatedUrl,
  784. ctx,
  785. workspaceCwd,
  786. persistenceRoot,
  787. hostFetch(path: string, init: RequestInit = {}): Promise<Response> {
  788. const headers = new Headers(init.headers)
  789. headers.set('cookie', cookieHeader)
  790. return fetch(new URL(path, baseUrl), { ...init, headers })
  791. },
  792. // Barrier stack: the in-process turn/end identifies the session, its
  793. // explicit flush makes the transcript durable, and the caller's browser
  794. // settled-poll comes last because host completion strictly precedes render.
  795. whenTurnSettled(timeoutMs = mode === 'record' ? 180_000 : 30_000): Promise<SessionId> {
  796. return new Promise<SessionId>((resolveSettled, reject) => {
  797. const timer = setTimeout(() => {
  798. off()
  799. reject(new Error(`no turn/end within ${timeoutMs}ms`))
  800. }, timeoutMs)
  801. const off = ctx.on('session/event', (session: Session, event: SessionEvent) => {
  802. if (event.type !== 'turn/end') return
  803. clearTimeout(timer)
  804. off()
  805. ctx.sessions.flush(session)
  806. .then(() => { resolveSettled(session.id) }, reject)
  807. })
  808. })
  809. },
  810. async close(): Promise<void> {
  811. const failures: unknown[] = []
  812. if (mode !== 'record'
  813. && replayFixture !== undefined
  814. && options.replayProvidersOnly !== true
  815. && compareReplaySession) {
  816. try {
  817. await assertReplaySession(
  818. [...observedSessions.values()],
  819. replayFixture,
  820. mode,
  821. `http://${browserHost}:${port}`,
  822. harnessHome,
  823. )
  824. } catch (error) {
  825. failures.push(error)
  826. }
  827. }
  828. // Fixture-consumption check first, while the run's binding state is
  829. // still authoritative — a scenario that drove fewer model calls than
  830. // recorded fails here instead of drifting green. Skipped for
  831. // replayProvidersOnly, whose fixture is validated call-free at boot.
  832. if (!options.replayProvidersOnly) {
  833. try {
  834. replayHandle?.assertConsumed()
  835. } catch (error) {
  836. failures.push(error)
  837. }
  838. }
  839. try {
  840. stopObservingSessions()
  841. failures.push(...await cleanupScaffoldWorld(ctx, workspaceCwd, persistenceRoot))
  842. } finally {
  843. restoreCredentialEnvironment()
  844. restoreSkillRootEnvironment()
  845. }
  846. if (failures.length > 0) throw new AggregateError(failures, 'web scaffold teardown failed')
  847. },
  848. }
  849. }
  850. /**
  851. * Serialize a live session to the canonical raw session-JSONL layout — the
  852. * in-memory record-mode harvest, so the on-disk zstd default never matters.
  853. */
  854. function rawSessionLog(session: Session): string {
  855. const encodedEvents = (session.snapshotEvents() as unknown as readonly SessionFormatEvent[])
  856. .map(event => sessionFormatCatalog.encodeCurrentEvent(event))
  857. const header = sessionFormatCatalog.encodeCurrentHeader({
  858. ...session.header,
  859. delegationDepth: session.header.delegationDepth ?? 0,
  860. }, session.inheritedEventCount)
  861. return [
  862. JSON.stringify(header),
  863. ...encodedEvents.map(record => JSON.stringify(record)),
  864. '',
  865. ].join('\n')
  866. }
  867. function mapJsonStringValues(value: unknown, map: (value: string) => string): unknown {
  868. if (typeof value === 'string') return map(value)
  869. if (Array.isArray(value)) return value.map(item => mapJsonStringValues(item, map))
  870. if (value !== null && typeof value === 'object') {
  871. return Object.fromEntries(Object.entries(value).map(([key, item]) => [
  872. key,
  873. mapJsonStringValues(item, map),
  874. ]))
  875. }
  876. return value
  877. }
  878. const WEB_PATH_TEXT_BOUNDARY_RE = /[\s<>'"`()\[\]{},;:!?=]/
  879. const WEB_FILE_URI_PATH_PREFIX_RE = /(?:^|[^a-z0-9+.-])file:\/\/\/?$/i
  880. function isWebCwdMatch(value: string, start: number, length: number): boolean {
  881. const before = value[start - 1]
  882. const after = value[start + length]
  883. const afterPunctuation = value[start + length + 1]
  884. const startsAtBoundary = before === undefined
  885. || WEB_PATH_TEXT_BOUNDARY_RE.test(before)
  886. || WEB_FILE_URI_PATH_PREFIX_RE.test(value.slice(0, start))
  887. const endsAtBoundary = after === undefined
  888. || after === '/'
  889. || after === '\\'
  890. || WEB_PATH_TEXT_BOUNDARY_RE.test(after)
  891. || after === '.' && (afterPunctuation === undefined || WEB_PATH_TEXT_BOUNDARY_RE.test(afterPunctuation))
  892. return startsAtBoundary && endsAtBoundary
  893. }
  894. function replaceWebCwd(value: string, cwd: string): string {
  895. let cursor = 0
  896. let normalized = ''
  897. while (cursor < value.length) {
  898. const match = value.indexOf(cwd, cursor)
  899. if (match < 0) return normalized + value.slice(cursor)
  900. const end = match + cwd.length
  901. if (isWebCwdMatch(value, match, cwd.length)) {
  902. normalized += value.slice(cursor, match) + '{{cwd}}'
  903. cursor = end
  904. } else {
  905. normalized += value.slice(cursor, end)
  906. cursor = end
  907. }
  908. }
  909. return normalized
  910. }
  911. /**
  912. * Normalize Web-only volatile strings while preserving JSON structure and row framing.
  913. * @param log - raw Session JSONL.
  914. * @param workspaceCwd - optional scaffold parent used before a live Session selects its cwd.
  915. * @returns compact JSONL with run-local strings tokenized.
  916. */
  917. export function normalizeWebSessionVolatiles(log: string, workspaceCwd?: string): string {
  918. const headerLine = log.split(/\r?\n/).find(line => line.trim().length > 0)
  919. const header = headerLine === undefined ? undefined : JSON.parse(headerLine) as { cwd?: unknown }
  920. const sessionCwd = typeof header?.cwd === 'string' && header.cwd.length > 0 ? header.cwd : undefined
  921. const cwdSpellings = [...new Set([sessionCwd ?? workspaceCwd]
  922. .filter((value): value is string => typeof value === 'string' && value.length > 0)
  923. .flatMap((value) => {
  924. const forward = value.replaceAll('\\', '/')
  925. const native = /^[A-Za-z]:[\\/]/.test(value) ? forward.replaceAll('/', '\\') : value
  926. return [value, value.replaceAll('\\', '\\\\'), forward, native]
  927. }))].sort((left, right) => right.length - left.length)
  928. return log.split(/\r?\n/).map((line) => {
  929. if (line.trim() === '') return line
  930. const record = mapJsonStringValues(JSON.parse(line), (value) => {
  931. let normalized = value
  932. .replace(/Anonymous user: [0-9a-f-]{36}(?=\.$)/gi, 'Anonymous user: {{anonymousUserId}}')
  933. for (const cwd of cwdSpellings) normalized = replaceWebCwd(normalized, cwd)
  934. return normalized
  935. }) as { type?: unknown; data?: { endpoint?: unknown } }
  936. if (record.type === 'web/deepseek-search-llm-request' && typeof record.data?.endpoint === 'string') {
  937. record.data.endpoint = '{{webSearchEndpoint}}'
  938. }
  939. return JSON.stringify(record)
  940. }).join('\n')
  941. }
  942. function stableSessionFixture(
  943. session: Session,
  944. existing: string,
  945. workspaceCwd: string,
  946. harnessHome: string,
  947. ): string {
  948. const prepared = prepareSessionSnapshotFixtureForComparison(
  949. normalizeWebSessionVolatiles(rawSessionLog(session), workspaceCwd),
  950. )
  951. const stabilized = existing === ''
  952. ? prepared
  953. : stabilizeRefreshLog(prepared, existing, [], {
  954. sessionIds: [String(session.id)],
  955. cwd: workspaceCwd,
  956. })
  957. const fresh = scrubSessionSnapshot(stabilized)
  958. .split(session.id).join('{{session:1}}')
  959. .split(harnessHome).join('{{harnessHome}}')
  960. const stable = redactSessionSnapshotIds(stabilizeFixtureMessageIds([fresh], [existing]))[0]
  961. if (stable === undefined) throw new Error('session harvest produced no stabilized fixture')
  962. return stable
  963. }
  964. async function assertReplaySession(
  965. sessions: readonly Session[],
  966. fixturePath: string,
  967. mode: WebSnapshotMode,
  968. webUrl: string,
  969. harnessHome: string,
  970. ): Promise<void> {
  971. let expected = await readFile(fixturePath, 'utf8')
  972. const fixtureDir = dirname(fixturePath)
  973. const manifestPath = join(fixtureDir, 'snapshot.yml')
  974. const manifest = parseSnapshotManifest(await readFile(manifestPath, 'utf8'), manifestPath)
  975. let expectedPath = fixturePath
  976. const userPrompts = fixtureUserPrompts(expected)
  977. const candidates = sessions.filter((session) => {
  978. if (session.header.parentSession !== undefined) return false
  979. const actual = session.snapshotEvents().flatMap((event) => {
  980. if (event.type !== 'user/message' || event.data.source.kind !== 'user') return []
  981. const text = event.data.content.filter(block => block.type === 'text').map(block => block.text).join('')
  982. return text.length === 0 ? [] : [text]
  983. })
  984. return JSON.stringify(actual) === JSON.stringify(userPrompts)
  985. })
  986. expect(candidates, `Web replay fixture ${fixturePath} must match one live root session`).toHaveLength(1)
  987. const session = candidates[0] as Session
  988. const sessionCwd = session.header.cwd
  989. if (sessionCwd === undefined) throw new Error(`${fixturePath}: replayed session has no cwd`)
  990. const actual = rawSessionLog(session)
  991. if (mode === 'refresh' && writesCurrentSessionFixtures(manifest, mode)) {
  992. expected = stableSessionFixture(session, expected, sessionCwd, harnessHome)
  993. expectedPath = recordedSessionFixturePath(fixturePath, session.header.version)
  994. await writeFile(expectedPath, expected)
  995. }
  996. const expectedHeader = JSON.parse(expected.split('\n').find(line => line.trim() !== '') ?? '{}') as {
  997. id?: unknown
  998. cwd?: unknown
  999. }
  1000. const actualContext: NormalizeContext = { sessionIds: [String(session.id)], cwd: sessionCwd }
  1001. const expectedContext: NormalizeContext = {
  1002. sessionIds: typeof expectedHeader.id === 'string' ? [expectedHeader.id] : [],
  1003. cwd: typeof expectedHeader.cwd === 'string' ? expectedHeader.cwd : '\0no-cwd\0',
  1004. }
  1005. const actualSnapshot = normalizeSessionSnapshots([normalizeWebSessionVolatiles(actual)], actualContext)[0]
  1006. ?.split(harnessHome).join('{{harnessHome}}')
  1007. const expectedSnapshot = normalizeSessionSnapshots([normalizeWebSessionVolatiles(expected)], expectedContext)[0]
  1008. ?.split(harnessHome).join('{{harnessHome}}')
  1009. expect(actualSnapshot, `${fixturePath}: persisted replay`).toBe(expectedSnapshot)
  1010. if (manifest.header?.pin !== true) return
  1011. const normalizePrompt = (value: string): string => value
  1012. .split(REPO_ROOT).join('{{sourceRoot}}')
  1013. .split(webUrl).join('{{webUrl}}')
  1014. const prompts = normalizedSystemPrompts(actual, actualContext).map(normalizePrompt)
  1015. const schemas = normalizedToolSchemas(actual, actualContext)
  1016. const promptPath = join(fixtureDir, 'system-prompt.expected.md')
  1017. const schemaPath = join(fixtureDir, 'tool-schemas.expected.json')
  1018. const promptSnapshot = formatSystemPromptSnapshot(prompts[0] as string, prompts.slice(1))
  1019. const schemaSnapshot = formatToolSchemasSnapshot(schemas[0] as unknown[], schemas.slice(1))
  1020. if (mode === 'refresh') {
  1021. await Promise.all([writeFile(promptPath, promptSnapshot), writeFile(schemaPath, schemaSnapshot)])
  1022. }
  1023. expect(promptSnapshot, `${fixturePath}: system-prompt pin`).toBe(await readFile(promptPath, 'utf8'))
  1024. expect(schemaSnapshot, `${fixturePath}: tool-schema pin`).toBe(await readFile(schemaPath, 'utf8'))
  1025. }
  1026. /**
  1027. * Record-mode fixture write-back: harvest the live session, scrub request
  1028. * headers to {{system}}/{{tools}}, tokenize the run-local cwd and Harness Home, redact opaque
  1029. * identities with typed relationship-preserving tokens, and write the fixture.
  1030. * A manifest-retained historical generation makes the write-back a no-op.
  1031. * @param scaffold - the record-mode scaffold.
  1032. * @param sessionId - the driven session.
  1033. * @param fixturePath - the committed session.jsonl target.
  1034. */
  1035. export async function recordFixture(scaffold: WebScaffold, sessionId: SessionId, fixturePath: string): Promise<void> {
  1036. const agent = scaffold.ctx.agents.get(sessionId)
  1037. if (agent === undefined) throw new Error(`record harvest: no live agent for ${sessionId}`)
  1038. const manifestPath = join(dirname(fixturePath), 'snapshot.yml')
  1039. const manifest = parseSnapshotManifest(await readFile(manifestPath, 'utf8'), manifestPath)
  1040. if (!writesCurrentSessionFixtures(manifest, 'record')) return
  1041. const target = recordedSessionFixturePath(fixturePath, agent.session.header.version)
  1042. const existingPath = existsSync(target) ? target : fixturePath
  1043. const existing = existsSync(existingPath) ? await readFile(existingPath, 'utf8') : ''
  1044. await writeFile(target, stableSessionFixture(
  1045. agent.session,
  1046. existing,
  1047. scaffold.workspaceCwd,
  1048. scaffold.harnessHome,
  1049. ))
  1050. }
  1051. /**
  1052. * The user prompts recorded in a fixture, in order — the single source tying
  1053. * spec drive steps to recorded reality so script and fixture cannot drift.
  1054. * @param fixtureText - raw session.jsonl contents.
  1055. * @returns the recorded user prompt texts.
  1056. */
  1057. export function fixtureUserPrompts(fixtureText: string): string[] {
  1058. return parseSessionLog(fixtureText).flatMap((event) => {
  1059. if (event.type !== 'user/message' || event.data.source.kind !== 'user') return []
  1060. const text = event.data.content.filter(block => block.type === 'text').map(block => block.text).join('')
  1061. return text.length > 0 ? [text] : []
  1062. })
  1063. }
  1064. /** Deterministic UUID used when a seed fixture's typed identity token is materialized. */
  1065. export function fixtureIdentity(
  1066. kind: 'message' | 'approval' | 'workflow' | 'command' | 'rpc' | 'retry' | 'id',
  1067. ordinal: number,
  1068. ): string {
  1069. const hex = createHash('sha256').update(`${kind}:${ordinal}`).digest('hex').slice(0, 32).split('')
  1070. hex[12] = '4'
  1071. hex[16] = ['8', '9', 'a', 'b'][Number.parseInt(hex[16] as string, 16) % 4] as string
  1072. return `${hex.slice(0, 8).join('')}-${hex.slice(8, 12).join('')}-${hex.slice(12, 16).join('')}-${hex.slice(16, 20).join('')}-${hex.slice(20).join('')}`
  1073. }
  1074. /**
  1075. * Realize a recorded seed fixture against one scaffold: substitute the
  1076. * `{{sessionId}}`/`{{cwd}}`/`{{harnessHome}}` placeholders and rewrite the
  1077. * recorded cwd to the scaffold's workspace. Idempotent, so a caller may realize early (e.g. to
  1078. * price content exactly as the host will fold it) and still pass the result
  1079. * through {@link seedSession}.
  1080. * @param scaffold - the booted scaffold whose workspace the seed targets.
  1081. * @param fixtureText - the committed seed fixture text.
  1082. * @param id - the session id the seed is realized for.
  1083. * @returns the realized fixture text.
  1084. */
  1085. export function realizeSeedFixture(scaffold: WebScaffold, fixtureText: string, id: string): string {
  1086. const firstLine = fixtureText.split(/\r?\n/).find(line => line.trim().length > 0)
  1087. const fixtureCwd = firstLine === undefined
  1088. ? undefined
  1089. : (JSON.parse(firstLine) as { cwd?: unknown }).cwd
  1090. return fixtureText.split(/\r?\n/).map((line) => {
  1091. if (line.trim() === '') return line
  1092. const realized = mapJsonStringValues(JSON.parse(line), (value) => {
  1093. let result = typeof fixtureCwd === 'string'
  1094. ? value.split(fixtureCwd).join(scaffold.workspaceCwd)
  1095. : value
  1096. result = result
  1097. .split('{{sessionId}}').join(id)
  1098. .split('{{session:1}}').join(id)
  1099. .replace(/\{\{session:([2-9]\d*)\}\}/g, (_token, ordinal: string) => `${id}-child-${ordinal}`)
  1100. .replace(/\{\{(message|approval|workflow|command|rpc|retry|id):([1-9]\d*)\}\}/g, (_token, kind: string, ordinal: string) =>
  1101. fixtureIdentity(kind as 'message' | 'approval' | 'workflow' | 'command' | 'rpc' | 'retry' | 'id', Number(ordinal)))
  1102. .split('{{harnessHome}}').join(scaffold.harnessHome)
  1103. .split('{{cwd}}').join(scaffold.workspaceCwd)
  1104. return result
  1105. })
  1106. return JSON.stringify(realized)
  1107. }).join('\n')
  1108. }
  1109. /**
  1110. * Parse a committed web seed fixture through the replay reader.
  1111. * @param fixtureText - session JSONL fixture contents.
  1112. * @returns the current header line, parsed header, and logical events.
  1113. */
  1114. /** Give a migrated fixture stream positive relative timing before its final wall-clock rebase. */
  1115. function spreadMigratedSeedStream(
  1116. stream: SessionEvent<'assistant/message'>['data']['stream'],
  1117. ): SessionEvent<'assistant/message'>['data']['stream'] {
  1118. let nextTime = 0
  1119. return stream.map((record) => {
  1120. if ('time' in record) {
  1121. const timed = { ...record, time: nextTime }
  1122. nextTime += 1
  1123. return timed
  1124. }
  1125. const timed = { ...record, time0: nextTime }
  1126. nextTime += record.dt.reduce((total, delta) => total + delta, 0) + 1
  1127. return timed
  1128. })
  1129. }
  1130. export function parseSeedFixture(fixtureText: string): {
  1131. headerLine: string
  1132. header: Record<string, unknown>
  1133. events: SessionEvent[]
  1134. } {
  1135. const sourceHeaderLine = fixtureText.split(/\r?\n/).find(line => line.trim().length > 0)
  1136. if (sourceHeaderLine === undefined) throw new Error('seed fixture has no session header')
  1137. const sourceHeader = JSON.parse(sourceHeaderLine) as { version?: unknown }
  1138. const current = prepareSessionSnapshotFixtureForComparison(fixtureText)
  1139. const headerLine = current.split(/\r?\n/).find(line => line.trim().length > 0)
  1140. if (headerLine === undefined) throw new Error('seed fixture has no session header')
  1141. const header = JSON.parse(headerLine) as Record<string, unknown>
  1142. if (header.type !== 'session') throw new Error('seed fixture must start with a session header')
  1143. const events = parseSessionLog(current).map((event) => {
  1144. if (sourceHeader.version === SESSION_FORMAT_VERSION) return event
  1145. if (event.type === 'assistant/message') {
  1146. return { ...event, data: { ...event.data, stream: spreadMigratedSeedStream(event.data.stream) } }
  1147. }
  1148. if (event.type === 'assistant/attempt') {
  1149. return { ...event, data: { ...event.data, stream: spreadMigratedSeedStream(event.data.stream) } }
  1150. }
  1151. return event
  1152. })
  1153. return { headerLine, header, events }
  1154. }
  1155. /**
  1156. * Render logical events as an envelope-free web seed fixture.
  1157. * @param headerLine - original session header line.
  1158. * @param events - logical session events in order.
  1159. * @returns projected session JSONL.
  1160. */
  1161. export function renderSeedFixture(
  1162. headerLine: string,
  1163. events: readonly ({ readonly seq: number; readonly time: number } & object)[],
  1164. ): string {
  1165. return [
  1166. headerLine,
  1167. ...events.map(({ seq: _seq, time: _time, ...event }) => JSON.stringify(event)),
  1168. '',
  1169. ].join('\n')
  1170. }
  1171. /** Re-anchor one projected embedded stream while preserving every intra-stream gap. */
  1172. function rebaseSeedStream(
  1173. stream: SessionEvent<'assistant/message'>['data']['stream'],
  1174. startAt: number,
  1175. ): SessionEvent<'assistant/message'>['data']['stream'] {
  1176. const first = stream[0]
  1177. if (first === undefined) return stream
  1178. const sourceStart = 'time' in first ? first.time : first.time0
  1179. const delta = startAt - sourceStart
  1180. return stream.map(record => 'time' in record
  1181. ? { ...record, time: record.time + delta }
  1182. : { ...record, time0: record.time0 + delta })
  1183. }
  1184. /** Last logical timestamp carried by an embedded Assistant stream. */
  1185. function seedStreamEnd(
  1186. stream: SessionEvent<'assistant/message'>['data']['stream'],
  1187. ): number | undefined {
  1188. let end: number | undefined
  1189. for (const record of stream) {
  1190. const recordEnd = 'time' in record
  1191. ? record.time
  1192. : record.time0 + record.dt.reduce((total, delta) => total + delta, 0)
  1193. end = end === undefined ? recordEnd : Math.max(end, recordEnd)
  1194. }
  1195. return end
  1196. }
  1197. /**
  1198. * Seed a recorded session fixture into the scaffold's persistence root
  1199. * through the real Session and JSONL APIs.
  1200. * @param scaffold - the target scaffold.
  1201. * @param fixtureText - raw recorded session.jsonl contents.
  1202. * @param id - the seeded session id.
  1203. * @param agentPreset - preset recorded by scenarios that assert resumed composition.
  1204. * @param options - deterministic metadata overrides for ordering-sensitive scenarios.
  1205. * @returns the seeded id.
  1206. */
  1207. export async function seedSession(
  1208. scaffold: WebScaffold,
  1209. fixtureText: string,
  1210. id: string,
  1211. agentPreset?: string,
  1212. options: { readonly createdAt?: number } = {},
  1213. ): Promise<SessionId> {
  1214. const decoded = parseSeedFixture(realizeSeedFixture(scaffold, fixtureText, id))
  1215. const events = decoded.events
  1216. if (events.length === 0) throw new Error('seed fixture has no events')
  1217. const last = events[events.length - 1]!
  1218. // An open final turn would be mutated by resume's crash repair on first
  1219. // open; a committed seed must be a closed recording.
  1220. if (last.type !== 'turn/end') throw new Error(`seed fixture must end in turn/end, got ${last.type}`)
  1221. const createdAt = options.createdAt ?? Date.now() - 60_000
  1222. const meta: SessionHeader = {
  1223. version: SESSION_FORMAT_VERSION,
  1224. id: SessionId(id),
  1225. createdAt,
  1226. isSeeded: false,
  1227. cwd: scaffold.workspaceCwd,
  1228. delegationDepth: 0,
  1229. ...agentPreset === undefined ? {} : { agentPreset },
  1230. }
  1231. const fixtureCreatedAt = decoded.header.createdAt
  1232. if (typeof fixtureCreatedAt !== 'number') {
  1233. throw new Error('seed fixture requires a numeric createdAt header')
  1234. }
  1235. const timeAnchor = fixtureCreatedAt === 0 ? createdAt : fixtureCreatedAt
  1236. let nextTime = timeAnchor
  1237. const materializedEvents: SessionEvent[] = events.map((event) => {
  1238. const time = nextTime
  1239. if (event.type === 'assistant/message') {
  1240. const stream = rebaseSeedStream(event.data.stream, time)
  1241. const completedAt = Math.max(time, seedStreamEnd(stream) ?? time)
  1242. nextTime = completedAt + 1
  1243. return {
  1244. ...event,
  1245. time: completedAt,
  1246. data: { ...event.data, stream },
  1247. }
  1248. }
  1249. if (event.type === 'assistant/attempt') {
  1250. const stream = rebaseSeedStream(event.data.stream, time)
  1251. const completedAt = Math.max(time, seedStreamEnd(stream) ?? time)
  1252. nextTime = completedAt + 1
  1253. return {
  1254. ...event,
  1255. time: completedAt,
  1256. data: { ...event.data, stream },
  1257. }
  1258. }
  1259. nextTime = time + 1
  1260. return { ...event, time }
  1261. })
  1262. await persistSeedSession(scaffold, meta, materializedEvents)
  1263. return meta.id
  1264. }
  1265. /** Materialize one detached Session fixture through the shipped JSONL provider. */
  1266. async function persistSeedSession(
  1267. scaffold: WebScaffold,
  1268. meta: SessionHeader,
  1269. events: readonly SessionEvent[],
  1270. ): Promise<void> {
  1271. const seeder = new Context()
  1272. try {
  1273. // Same root as the booted tree with the plugin's own default compression,
  1274. // so the host's directory-scan list() sees one consistent encoding.
  1275. await seeder.plugin(JsonlSessionPersistence, { root: scaffold.persistenceRoot })
  1276. const handle = await seeder.sessionPersistence.create(meta)
  1277. await handle.append(events)
  1278. await handle.close()
  1279. } finally {
  1280. await seeder.fiber.dispose()
  1281. }
  1282. }
  1283. /**
  1284. * Read one stored session's physical event log through a throwaway read
  1285. * handle. The physical log carries no synthetic closers: a resumed session
  1286. * shows the closers the loop appended durably, and a never-resumed
  1287. * interrupted log stays interrupted.
  1288. * @param scaffold - the booted scaffold whose persistence holds the session.
  1289. * @param id - the stored session to read.
  1290. * @returns the stored events.
  1291. */
  1292. export async function readPersistedEvents(scaffold: WebScaffold, id: SessionId): Promise<readonly SessionEvent[]> {
  1293. const handle = await scaffold.ctx.sessionPersistence.open(id, 'read')
  1294. try {
  1295. return (await handle.read()).events
  1296. } finally {
  1297. await handle.close()
  1298. }
  1299. }
  1300. /**
  1301. * Normalize an aria snapshot: uuid, cwd, workspace-basename, duration,
  1302. * decode-throughput, and path-sensitive compaction estimates collapse to
  1303. * stable tokens.
  1304. *
  1305. * Throughput needs a token for the same reason durations do, and no fixture
  1306. * can supply one: the figure divides a replayed step's output tokens by the
  1307. * wall time the local run took to stream them, so it moves between two runs
  1308. * on one machine (measured 69 → 70 tok/s) and swings wildly on a fast replay
  1309. * (26333 tok/s for a 3 ms stream).
  1310. */
  1311. /**
  1312. * Relative-time buckets rendered by a dated row, in both dictionaries.
  1313. *
  1314. * Opt-in per capture: a session-tree golden asserts its own literal age (a
  1315. * fresh row reads `now`, an older one does not), so collapsing the vocabulary
  1316. * everywhere would delete that assertion. A region whose rows are dated from
  1317. * live wall-clock state asks for it instead. Anchored on an aria label's
  1318. * closing quote, where the bucket is always last.
  1319. */
  1320. const ARIA_AGE =
  1321. /(?:now|\d+min|\d+h|\d+d|\d+mo|\d+y|刚刚|\d+分钟|\d+小时|\d+天|\d+个月|\d+年)(?=")/g
  1322. function normalizeAria(snapshot: string, workspaceCwd: string, age: boolean): string {
  1323. // The session heading renders the workspace's basename, not the full
  1324. // path, so both spellings must collapse to the token.
  1325. const base = workspaceCwd.split('/').pop()!
  1326. return (age ? snapshot.replace(ARIA_AGE, '{{age}}') : snapshot)
  1327. .split(workspaceCwd).join('{{cwd}}')
  1328. .split(base).join('{{workspace}}')
  1329. .replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi, '{{uuid}}')
  1330. // The optional space in `\d+m ?\d+s` covers both minute spellings: the
  1331. // stats line's compact `2m42s` and the message-chrome template's `2m 42s`.
  1332. .replace(
  1333. /~\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,
  1334. duration => duration.startsWith('~') ? duration : '{{duration}}',
  1335. )
  1336. .replace(/\b\d[\d,]*(?:\.\d+)? ms\b/g, '{{duration}}')
  1337. .replace(
  1338. /约\d+(?:年(?:\d+个月)?|个月(?:\d+天)?)|\d+(?:天(?:\d+小时(?:\d+分\d+秒)?)?|小时\d+分\d+秒|分\d+秒|(?:\.\d+)?秒)/g,
  1339. duration => duration.startsWith('约') ? duration : '{{duration}}',
  1340. )
  1341. .replace(/\d+(?:\.\d+)?(?= tok\/s(?!\w))/g, '{{throughput}}')
  1342. // Seeded compaction prices realized file paths, whose length differs
  1343. // between local worktrees and CI scratch directories.
  1344. .replace(/(Compacted \d+ history items \(~)\d+( tokens\))/g, '$1{{tokens}}$2')
  1345. // Session summaries and Message IconActions clocks cross calendar
  1346. // boundaries; collapse every shape so goldens stay stable across them.
  1347. .replace(/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z/g, '{{timestamp}}')
  1348. .replace(/\d{4}年\d{1,2}月\d{1,2}日 \d{2}:\d{2}/g, '{{clock}}')
  1349. .replace(/\d{1,2}月\d{1,2}日 \d{2}:\d{2}/g, '{{clock}}')
  1350. .replace(/(?<!\d)\d{1,2}:\d{2}:\d{2}(?:\.\d+)?(?:\s*[AP]M)?(?!\d)/gi, '{{clock}}')
  1351. .replace(/(?<!\d)\d{2}:\d{2}(?!\d)/g, '{{clock}}')
  1352. }
  1353. /**
  1354. * Capture the region's aria snapshot at a settled milestone: poll until two
  1355. * consecutive normalized captures are equal — a single-shot capture races the
  1356. * last React commits.
  1357. * @param page - the page under test.
  1358. * @param selector - the region locator selector.
  1359. * @param workspaceCwd - normalization input.
  1360. * @param options - `normalizeAge` collapses relative-time buckets to `{{age}}`
  1361. * for a region whose rows are dated from live wall-clock state;
  1362. * `replacements` tokenizes scenario-owned values before generic normalization.
  1363. * @returns the stable normalized snapshot.
  1364. */
  1365. export async function captureStableAria(
  1366. page: Page,
  1367. selector: string,
  1368. workspaceCwd: string,
  1369. options: {
  1370. normalizeAge?: boolean
  1371. replacements?: readonly (readonly [value: string, token: string])[]
  1372. } = {},
  1373. ): Promise<string> {
  1374. const region = page.locator(selector).first()
  1375. const age = options.normalizeAge === true
  1376. const normalize = (snapshot: string): string => {
  1377. for (const [value, token] of options.replacements ?? []) {
  1378. snapshot = snapshot.split(value).join(token)
  1379. }
  1380. return normalizeAria(snapshot, workspaceCwd, age)
  1381. }
  1382. let previous = normalize(await region.ariaSnapshot())
  1383. await expect.poll(async () => {
  1384. const current = normalize(await region.ariaSnapshot())
  1385. const stable = current === previous
  1386. previous = current
  1387. return stable
  1388. }, { timeout: 5_000, message: 'aria snapshot did not stabilize' }).toBe(true)
  1389. return previous
  1390. }
  1391. /**
  1392. * Capture a stable aria snapshot with every eligible Turn process expanded,
  1393. * then restore the controls that were closed before the capture.
  1394. * @param page - the page under test.
  1395. * @param selector - the region locator selector.
  1396. * @param workspaceCwd - normalization input.
  1397. * @param options - optional user-visible state to establish before capture.
  1398. * @returns the stable normalized expanded snapshot.
  1399. */
  1400. export async function captureExpandedTurnProcessAria(
  1401. page: Page,
  1402. selector: string,
  1403. workspaceCwd: string,
  1404. options: { scrollToBottom?: boolean } = {},
  1405. ): Promise<string> {
  1406. const controls = page.locator('[data-turn-process]')
  1407. const count = await controls.count()
  1408. expect(count).toBeGreaterThan(0)
  1409. const opened: number[] = []
  1410. for (let index = 0; index < count; index++) {
  1411. const control = controls.nth(index)
  1412. if (!await control.isVisible() || await control.getAttribute('aria-expanded') === 'true') continue
  1413. await control.click()
  1414. opened.push(index)
  1415. }
  1416. try {
  1417. if (options.scrollToBottom === true) {
  1418. const backToBottom = page.getByRole('button', { name: 'Back to bottom', exact: true })
  1419. const scroll = page.locator('[data-conversation-scroll]')
  1420. await expect.poll(async () => {
  1421. const distanceFromBottom = await scroll.evaluate((host) => {
  1422. host.scrollTop = host.scrollHeight
  1423. return host.scrollHeight - host.clientHeight - host.scrollTop
  1424. })
  1425. return Math.abs(distanceFromBottom) <= 1 && await backToBottom.count() === 0
  1426. }, { timeout: 10_000 }).toBe(true)
  1427. }
  1428. return await captureStableAria(page, selector, workspaceCwd)
  1429. } finally {
  1430. for (const index of opened.reverse()) {
  1431. const control = controls.nth(index)
  1432. if (await control.getAttribute('aria-expanded') === 'true') await control.click()
  1433. }
  1434. }
  1435. }
  1436. /**
  1437. * Compare a normalized golden, or rewrite it under refresh. Refresh is the
  1438. * ONLY writer: a missing golden in replay mode fails with the healing command
  1439. * instead of silently self-bootstrapping.
  1440. * @param goldenPath - the committed ui.expected.md path.
  1441. * @param actual - the stable normalized snapshot.
  1442. * @param mode - the active snapshot mode.
  1443. */
  1444. export async function compareOrRefreshGolden(goldenPath: string, actual: string, mode: WebSnapshotMode): Promise<void> {
  1445. const payload = `${actual}\n`
  1446. if (mode === 'refresh') {
  1447. await writeFile(goldenPath, payload)
  1448. return
  1449. }
  1450. if (!existsSync(goldenPath)) {
  1451. throw new Error(`missing golden ${goldenPath} — run DSH_SNAPSHOT=refresh pnpm run test:web to generate it`)
  1452. }
  1453. expect(payload).toBe(await readFile(goldenPath, 'utf8'))
  1454. }
  1455. /**
  1456. * Fixture-inventory guard: the scenario directory holds exactly the expected
  1457. * files and every committed JSONL is a header-scrubbed, typed-redaction fixed point.
  1458. * @param dir - the scenario snapshot directory.
  1459. * @param expected - the exact expected file inventory.
  1460. */
  1461. export async function assertFixtureInventory(dir: string, expected: string[]): Promise<void> {
  1462. const entries = (await readdir(dir)).sort()
  1463. const ownsManifest = entries.includes('snapshot.yml')
  1464. const artifacts = entries.filter(name => name !== 'snapshot.yml')
  1465. const roleInventory = (names: readonly string[]): string[] => [...new Set(names.map((name) => {
  1466. const fixture = parseSessionFixtureName(name)
  1467. return fixture === undefined ? name : sessionFixtureName(fixture.index, 0)
  1468. }))].sort()
  1469. expect(roleInventory(artifacts)).toEqual(roleInventory(expected))
  1470. if (ownsManifest) {
  1471. const manifestPath = join(dir, 'snapshot.yml')
  1472. const manifest = parseSnapshotManifest(await readFile(manifestPath, 'utf8'), manifestPath)
  1473. expect(manifest.profile).toBe('web')
  1474. if (manifest.session === undefined) {
  1475. expect(
  1476. artifacts.some(name => parseSessionFixtureName(name)?.index === 0),
  1477. `${dir}: session owner must carry a canonical parent Session fixture`,
  1478. ).toBe(true)
  1479. } else {
  1480. expect(existsSync(resolve(dir, manifest.session.source)), `${dir}: session source`).toBe(true)
  1481. }
  1482. }
  1483. for (const entry of artifacts.filter(name => name.endsWith('.jsonl'))) {
  1484. const content = await readFile(join(dir, entry), 'utf8')
  1485. expect(scrubRequestHeaders(content), `${dir}/${entry} carries request-header bulk`).toBe(content)
  1486. expect(redactSessionSnapshotIds([content]), `${dir}/${entry} carries unredacted identities`).toEqual([content])
  1487. }
  1488. }
  1489. /**
  1490. * Console tripwires: reconnect/gap-repair self-healing or a pageerror must
  1491. * fail the scenario, not mask a dead wire behind eventual consistency.
  1492. * @param page - the page under test.
  1493. * @returns live warning/pageerror collectors to assert empty at scenario end.
  1494. */
  1495. export function watchConsole(page: Page): { warnings: string[]; pageErrors: string[] } {
  1496. const warnings: string[] = []
  1497. const pageErrors: string[] = []
  1498. page.on('console', (message) => {
  1499. const text = message.text()
  1500. if (/connection lost|gap repair|discontinuous/i.test(text)) warnings.push(text)
  1501. })
  1502. page.on('pageerror', (error) => { pageErrors.push(String(error)) })
  1503. return { warnings, pageErrors }
  1504. }
  1505. /**
  1506. * Remove only connection-loss warnings emitted after an intentional reload.
  1507. * Earlier warnings and all gap-repair/discontinuity warnings remain fatal.
  1508. * @param tripwire - the live console-warning collector.
  1509. * @param warningStart - warning count captured immediately before reloading.
  1510. */
  1511. export function acknowledgeReloadConnectionLoss(
  1512. tripwire: ReturnType<typeof watchConsole>,
  1513. warningStart: number,
  1514. ): void {
  1515. const reloadWarnings = tripwire.warnings.splice(warningStart)
  1516. tripwire.warnings.push(...reloadWarnings.filter(text => !/connection lost/i.test(text)))
  1517. }