scaffold.ts 73 KB

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