scaffold.ts 74 KB

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