scaffold.ts 72 KB

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