scaffold.ts 72 KB

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