scaffold.ts 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600
  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. auditStartupEntries,
  61. composeEntries,
  62. healProfilesModuleFallback,
  63. loadOverlayPatches,
  64. type Profile,
  65. } from '@deepseek-ai/dsh-app-boot'
  66. import { dshHomePath } from '@deepseek-ai/dsh-home-paths'
  67. import { 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 package manifests whose dependency closures supply experimental
  283. * 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. // Keyless scenarios retain the recorded default; explicit scenario overlays win.
  499. ...mode === 'record' || options.deepSeekMissingCredential === true
  500. ? []
  501. : [{ id: 'agent-default-model', config: { provider: 'deepseek-official', model: 'deepseek-v4-flash' } }],
  502. ...extraOverlayPatches,
  503. // The roster's shipped presets are the plugin's own, bundled inside
  504. // `dsh-agent-presets` and prepended by it. Pin only the machine-local
  505. // root away: a developer's own `~/.dsh/.agent-presets` must not be able
  506. // to change a golden.
  507. {
  508. id: 'agent-presets',
  509. config: {
  510. default: 'standard',
  511. includeUserRoot: false,
  512. },
  513. },
  514. { id: 'session-persistence-jsonl', config: { root: persistenceRoot } },
  515. // Content search is enabled here although the shipped bundles default it
  516. // off (`openAt: never`, pinned by apps/cli/tests/lazy-search-startup):
  517. // the seeded-session scenarios navigate by content search, and these e2e
  518. // runs are the assembled coverage for the opt-in search path.
  519. { id: 'session-query-sqlite', config: { path: ':memory:', openAt: 'first-search' } },
  520. // storage-json's yml root is anchored to the real $DSH_HOME; pin the row
  521. // to an absolute temp root (removed with the workspace at close) so tests
  522. // never write the user's harness home.
  523. { id: 'storage-json', config: { root: join(workspaceCwd, '.dsh-storages') } },
  524. // Skill discovery is model-visible input. Pin every host-level root inside
  525. // the owned temp world so ~/.dsh, ~/.agents, and a bundled-root env setting
  526. // cannot change replay requests or conversation goldens. Project roots stay
  527. // enabled against the same empty temp workspace, preserving the real seam.
  528. {
  529. id: 'skill-filesystem',
  530. config: {
  531. dshHome: join(workspaceCwd, '.dsh-home'),
  532. agentsHome: join(workspaceCwd, '.agents-home'),
  533. bundledSkillDir: join(workspaceCwd, '.bundled-skills'),
  534. watch: false,
  535. },
  536. },
  537. // fs/bash cwd default to process.cwd(); the gateway injects the same
  538. // value into session.cwd — chdir below anchors all three to the temp
  539. // workspace, keeping the composition untouched.
  540. { id: 'agent-instructions', disabled: true },
  541. { id: 'session-title-llm', disabled: true },
  542. // Fixture sessions must never leave the process: the shipped row defaults
  543. // to the production OTLP endpoint (or whatever DSH_TELEMETRY_OTLP_URL
  544. // names in the ambient environment). A scenario with a local collector
  545. // preserves the shipped disabled setting instead of overriding it.
  546. options.telemetryUrl === undefined
  547. ? { id: 'session-telemetry-otel', disabled: true }
  548. : {
  549. id: 'session-telemetry-otel',
  550. config: {
  551. mode: options.telemetryMode ?? 'FEEDBACK_ONLY',
  552. exporter: { url: options.telemetryUrl },
  553. ...(options.telemetryScheduledDelayMillis === undefined ? {} : {
  554. processor: { scheduledDelayMillis: options.telemetryScheduledDelayMillis },
  555. }),
  556. shutdownTimeoutMillis: 1_000,
  557. },
  558. },
  559. // Use an ephemeral port while preserving the shipped compression policy;
  560. // a patch replaces the row's complete config.
  561. {
  562. id: 'webserver',
  563. config: {
  564. host: '127.0.0.1', port: 0, compression: 'gzip',
  565. compressionLevel: 1, compressionThresholdBytes: 1024,
  566. },
  567. },
  568. // The bundle's web-runtime row resolves the same built dist under test
  569. // (apps/web IS @deepseek-ai/dsh-web-frontend); native browser opening and the
  570. // URL line are disabled because this scaffold owns its Playwright browser.
  571. // Preserve the composed surface-context choice because a patch replaces
  572. // the row's complete config.
  573. { id: 'web-runtime', config: { openBrowser: false, printUrl: false, surfaceContext } },
  574. ...options.remoteAuthority === undefined
  575. ? []
  576. : [{ id: 'connection', config: { trustedHosts: [options.remoteAuthority] } }],
  577. { id: 'settings', config: { dshHome: harnessHome } },
  578. { id: 'credentials', config: { dshHome: harnessHome } },
  579. // The shipped directory-picker row is the -auto chooser, which resolves
  580. // the interaction from the RUNNING host (display, SSH launch, bind). The
  581. // lane's goldens are interaction-specific (workspace-management drives
  582. // the in-app browse dialog), so pin -browse deterministically on every
  583. // host: patch `name` is an assertion, not an override, hence the
  584. // disable+insert pair.
  585. { id: 'directory-picker', disabled: true },
  586. { insert: [
  587. { id: 'directory-picker-browse', name: '@deepseek-ai/dsh-host-directory-picker-browse' },
  588. { id: 'ui-directory-picker-browse', name: '@deepseek-ai/dsh-client-ui-directory-picker-browse' },
  589. ] },
  590. // Ordinary scenarios exclude host-dependent application discovery. The
  591. // Open In scenario supplies launch facts that suppress every native probe.
  592. { id: 'open-in-app', disabled: options.openInAppEnvironment === undefined },
  593. { id: 'ui-open-in-app', disabled: options.openInAppEnvironment === undefined },
  594. ...options.agentPresets === undefined
  595. ? []
  596. // Never the derived harness-home root: a developer's own presets must not
  597. // be able to change a golden, whatever roots a scenario asks for.
  598. : [{ id: 'agent-presets', config: { ...options.agentPresets, includeUserRoot: false } }],
  599. ...options.toolsMode === undefined ? [] : [{ id: 'tools', config: { mode: options.toolsMode } }],
  600. // The shipped Web bundle already owns both runners and the Cordis UI. This
  601. // scenario adds only the model-facing tools that exercise those services.
  602. ...options.cordisTools === true
  603. ? [{ insert: [
  604. { id: 'tool-cordis', name: '@deepseek-ai/dsh-tool-cordis' },
  605. ] }]
  606. : [],
  607. ...options.deepSeekSearch === undefined
  608. ? []
  609. : [{
  610. id: 'web-search-deepseek',
  611. config: {
  612. apiKeyEnv: options.deepSeekSearch.apiKeyEnv,
  613. baseURL: options.deepSeekSearch.baseURL,
  614. },
  615. }],
  616. ...mode === 'record' || options.deepSeekMissingCredential === true
  617. ? []
  618. : [{ id: 'llm-deepseek', disabled: true }],
  619. ]
  620. // Sessions inherit the gateway's process.cwd() default; run the boot from
  621. // the temp workspace so tool cwd, session cwd, and fixtures agree.
  622. const originalCwd = process.cwd()
  623. const ctx = new Context()
  624. if (options.openInAppEnvironment !== undefined) ctx.provide(DSH_LAUNCH_ENVIRONMENT_KEY, options.openInAppEnvironment)
  625. const observedSessions = new Map<SessionId, Session>()
  626. const stopObservingSessions = ctx.on('session/created', (session) => {
  627. observedSessions.set(session.id, session)
  628. })
  629. let port = 0
  630. let baseUrl = ''
  631. let authenticatedUrl = ''
  632. let cookieHeader = ''
  633. let replayHandle: ReplayHandle | undefined
  634. try {
  635. process.chdir(workspaceCwd)
  636. const profileDir = join(harnessHome, 'profiles', 'scaffold')
  637. const extraLayers: Profile['layers'] = await Promise.all((options.extraInstallAnchors ?? []).map(async (anchor) => {
  638. const manifest = JSON.parse(await readFile(anchor, 'utf8')) as { name?: unknown }
  639. if (typeof manifest.name !== 'string' || manifest.name === '') {
  640. throw new Error(`web scaffold extra install anchor has no package name: ${anchor}`)
  641. }
  642. const packageDir = dirname(anchor)
  643. return {
  644. packageName: manifest.name,
  645. version: undefined,
  646. packageDir,
  647. patchPath: join(packageDir, 'cordis.patch.yml'),
  648. trust: 'builtin' as const,
  649. stage: 'runtime' as const,
  650. patches: [],
  651. }
  652. }))
  653. // Mirror the production launcher: the shared installation closure keeps
  654. // its carrier-specific fallback, while private bundle dependencies stay
  655. // isolated to this synthetic scaffold profile.
  656. await healProfilesModuleFallback({
  657. installAnchor: INSTALL_ANCHOR,
  658. home: harnessHome,
  659. profile: {
  660. name: 'scaffold',
  661. dir: profileDir,
  662. layers: extraLayers,
  663. patchPath: join(profileDir, 'cordis.patch.yml'),
  664. patches: [],
  665. patchReload: 'startup',
  666. },
  667. })
  668. await mkdir(profileDir, { recursive: true })
  669. const rootConfig = join(profileDir, 'cordis.yml')
  670. await writeFile(rootConfig, '[]\n')
  671. ctx.baseUrl = pathToFileURL(profileDir).href + '/'
  672. // This direct Loader harness supplies the same root-path capability as app-boot.
  673. ctx.provide('dshHomePath', dshHomePath)
  674. // A host with no command line still provides one: the web bundle's startup
  675. // row releases the rows waiting on it, and with no arguments each starts on
  676. // the values this scaffold composed above. An exit request can only come
  677. // from a rejected argument, which a fixed empty list has none of.
  678. provideCmdline(ctx, {
  679. args: [],
  680. exit: (code) => {
  681. throw new Error(`web e2e scaffold: the web app requested exit ${String(code)} with no arguments to reject`)
  682. },
  683. })
  684. await ctx.plugin(Loader)
  685. ctx.loader.builtins.include = Include
  686. // `cordis:group` beside it, exactly as `boot()` registers it: a group row is
  687. // how a preset gives one `isolate` realm to a provider and its consumers,
  688. // and a preset resolving package names from its own directory cannot reach
  689. // `@deepseek-ai/cordis-plugin-group` by name.
  690. ctx.loader.builtins.group = Group
  691. await ctx.loader.create({
  692. name: 'cordis:include',
  693. config: { path: pathToFileURL(rootConfig).href, patches },
  694. })
  695. await ctx.loader.await()
  696. await auditStartupEntries(ctx, 'web e2e scaffold')
  697. if (options.welcomeNoticePending !== true) {
  698. await ctx.settings.mutate(WELCOME_NOTICE_SETTINGS_NAMESPACE, [{
  699. op: 'set', path: [WELCOME_NOTICE_ACK_FIELD], value: WELCOME_NOTICE_VERSION,
  700. }])
  701. }
  702. const boundPort = ctx.get('webServer')?.port
  703. if (boundPort === undefined) {
  704. throw new Error('web e2e scaffold: webServer service missing after settled boot')
  705. }
  706. port = boundPort
  707. // Fill the open llm seam on the settled root ctx. Ordinary keyless modes
  708. // disable llm-deepseek; the first-run lane keeps it mounted but has no
  709. // replay fixture and never streams. The direct install, unlike the plugin
  710. // row, returns the ReplayHandle for the teardown consumption check.
  711. if (options.replayProvidersOnly) {
  712. if (replayFixture === undefined) {
  713. throw new Error('replayProvidersOnly requires replayFixture (its file supplies the header)')
  714. }
  715. const fixtureText = readFileSync(replayFixture, 'utf8')
  716. // The consumption check is skipped for this mode, so no script source
  717. // may carry callable entries: reject override/child sources outright
  718. // and any call-bearing fixture.
  719. if (options.replayOverride !== undefined || replayChildFixtures !== undefined) {
  720. throw new Error('replayProvidersOnly cannot combine with replayOverride or replayChildFixtures')
  721. }
  722. // A fixture without a session header row must not mount the catalog
  723. // silently: the consumption-skip assumes the header-only shape.
  724. let headerType: unknown
  725. try {
  726. headerType = (JSON.parse(fixtureText.trimStart().split('\n', 1)[0] ?? '') as { type?: unknown }).type
  727. } catch {
  728. headerType = undefined
  729. }
  730. if (headerType !== 'session') {
  731. throw new Error('replayProvidersOnly fixture must open with a session header row')
  732. }
  733. const recorded = parseSessionLog(fixtureText)
  734. const hasModelCall = recorded.some(event => (
  735. event.type === 'assistant/message' || event.type === 'assistant/attempt'
  736. || event.type === 'request/header' || event.type === 'tool/call'
  737. ))
  738. if (hasModelCall) {
  739. throw new Error('replayProvidersOnly fixture must record no model calls')
  740. }
  741. }
  742. if (mode !== 'record' && replayFixture !== undefined) {
  743. replayHandle = installLlmReplay(ctx, {
  744. file: replayFixture,
  745. providers: (options.replayProviders ?? replayProviders(options.replayContextWindow)).map(provider => ({
  746. ...provider,
  747. ...(options.replayRetryPolicy === undefined ? {} : { retryPolicy: options.replayRetryPolicy }),
  748. })),
  749. ...(options.replayOverride === undefined ? {} : { overrideFile: options.replayOverride }),
  750. ...(replayChildFixtures === undefined ? {} : { childFiles: replayChildFixtures }),
  751. ...(options.paceMs === undefined ? {} : { paceMs: options.paceMs }),
  752. })
  753. } else if (mode !== 'record' && options.deepSeekMissingCredential !== true) {
  754. // No fixture and no shipped adapter would leave the tree with ZERO
  755. // provider routes — a state no product composition has, and one the
  756. // composer refuses to type into. Register the same routes
  757. // a fixture would, with streaming that still fails loud: the scenario
  758. // issues no model calls, and one that slipped in must not pass quietly.
  759. ctx.effect(() => ctx.llm.registerAdapter(
  760. replayProviders(options.replayContextWindow).map(provider => provider.id),
  761. new RouteOnlyAdapter(replayProviders(options.replayContextWindow)),
  762. ), 'web e2e scaffold: route-only adapter')
  763. }
  764. baseUrl = `http://${browserHost}:${String(port)}`
  765. authenticatedUrl = ctx.connection.authenticatedUrl(baseUrl)
  766. const login = await fetch(authenticatedUrl, { redirect: 'manual' })
  767. const setCookie = login.headers.get('set-cookie')
  768. if (login.status !== 303 || login.headers.get('location') !== '/' || setCookie === null) {
  769. throw new Error('web e2e scaffold: browser token exchange did not return its session cookie')
  770. }
  771. cookieHeader = setCookie.split(';', 1)[0] ?? ''
  772. if (cookieHeader.length === 0) {
  773. throw new Error('web e2e scaffold: browser token exchange returned an empty session cookie')
  774. }
  775. } catch (error) {
  776. if (process.cwd() !== originalCwd) process.chdir(originalCwd)
  777. const cleanupFailures = await cleanupScaffoldWorld(ctx, workspaceCwd, persistenceRoot)
  778. restoreCredentialEnvironment()
  779. restoreSkillRootEnvironment()
  780. if (cleanupFailures.length > 0) {
  781. throw new AggregateError([error, ...cleanupFailures], 'web scaffold setup failed and cleanup was incomplete')
  782. }
  783. throw error
  784. } finally {
  785. if (process.cwd() !== originalCwd) process.chdir(originalCwd)
  786. }
  787. return {
  788. harnessHome,
  789. mode,
  790. baseUrl,
  791. authenticatedUrl,
  792. ctx,
  793. workspaceCwd,
  794. persistenceRoot,
  795. hostFetch(path: string, init: RequestInit = {}): Promise<Response> {
  796. const headers = new Headers(init.headers)
  797. headers.set('cookie', cookieHeader)
  798. return fetch(new URL(path, baseUrl), { ...init, headers })
  799. },
  800. // Barrier stack: the in-process turn/end identifies the session, its
  801. // explicit flush makes the transcript durable, and the caller's browser
  802. // settled-poll comes last because host completion strictly precedes render.
  803. whenTurnSettled(timeoutMs = mode === 'record' ? 180_000 : 30_000): Promise<SessionId> {
  804. return new Promise<SessionId>((resolveSettled, reject) => {
  805. const timer = setTimeout(() => {
  806. off()
  807. reject(new Error(`no turn/end within ${timeoutMs}ms`))
  808. }, timeoutMs)
  809. const off = ctx.on('session/event', (session: Session, event: SessionEvent) => {
  810. if (event.type !== 'turn/end') return
  811. clearTimeout(timer)
  812. off()
  813. ctx.sessions.flush(session)
  814. .then(() => { resolveSettled(session.id) }, reject)
  815. })
  816. })
  817. },
  818. async close(): Promise<void> {
  819. const failures: unknown[] = []
  820. if (mode !== 'record'
  821. && replayFixture !== undefined
  822. && options.replayProvidersOnly !== true
  823. && compareReplaySession) {
  824. try {
  825. await assertReplaySession(
  826. [...observedSessions.values()],
  827. replayFixture,
  828. mode,
  829. `http://${browserHost}:${port}`,
  830. harnessHome,
  831. )
  832. } catch (error) {
  833. failures.push(error)
  834. }
  835. }
  836. // Fixture-consumption check first, while the run's binding state is
  837. // still authoritative — a scenario that drove fewer model calls than
  838. // recorded fails here instead of drifting green. Skipped for
  839. // replayProvidersOnly, whose fixture is validated call-free at boot.
  840. if (!options.replayProvidersOnly) {
  841. try {
  842. replayHandle?.assertConsumed()
  843. } catch (error) {
  844. failures.push(error)
  845. }
  846. }
  847. try {
  848. stopObservingSessions()
  849. failures.push(...await cleanupScaffoldWorld(ctx, workspaceCwd, persistenceRoot))
  850. } finally {
  851. restoreCredentialEnvironment()
  852. restoreSkillRootEnvironment()
  853. }
  854. if (failures.length > 0) throw new AggregateError(failures, 'web scaffold teardown failed')
  855. },
  856. }
  857. }
  858. /**
  859. * Serialize a live session to the canonical raw session-JSONL layout — the
  860. * in-memory record-mode harvest, so the on-disk zstd default never matters.
  861. */
  862. function rawSessionLog(session: Session): string {
  863. const encodedEvents = (session.snapshotEvents() as unknown as readonly SessionFormatEvent[])
  864. .map(event => sessionFormatCatalog.encodeCurrentEvent(event))
  865. const header = sessionFormatCatalog.encodeCurrentHeader({
  866. ...session.header,
  867. delegationDepth: session.header.delegationDepth ?? 0,
  868. }, session.inheritedEventCount)
  869. return [
  870. JSON.stringify(header),
  871. ...encodedEvents.map(record => JSON.stringify(record)),
  872. '',
  873. ].join('\n')
  874. }
  875. function mapJsonStringValues(value: unknown, map: (value: string) => string): unknown {
  876. if (typeof value === 'string') return map(value)
  877. if (Array.isArray(value)) return value.map(item => mapJsonStringValues(item, map))
  878. if (value !== null && typeof value === 'object') {
  879. return Object.fromEntries(Object.entries(value).map(([key, item]) => [
  880. key,
  881. mapJsonStringValues(item, map),
  882. ]))
  883. }
  884. return value
  885. }
  886. /** Tokenize the browser timezone carried by user message sources. */
  887. function normalizeClientTimeZones(value: unknown): unknown {
  888. if (Array.isArray(value)) return value.map(item => normalizeClientTimeZones(item))
  889. if (value !== null && typeof value === 'object') {
  890. const next = Object.fromEntries(Object.entries(value).map(([key, item]) => [
  891. key,
  892. normalizeClientTimeZones(item),
  893. ]))
  894. const source = (next as { source?: unknown }).source
  895. if (source !== null && typeof source === 'object'
  896. && (source as { kind?: unknown }).kind === 'user'
  897. && typeof (source as { clientTimeZone?: unknown }).clientTimeZone === 'string') {
  898. return {
  899. ...next,
  900. source: { ...source, clientTimeZone: '{{clientTimeZone}}' },
  901. }
  902. }
  903. return next
  904. }
  905. return value
  906. }
  907. const WEB_PATH_TEXT_BOUNDARY_RE = /[\s<>'"`()\[\]{},;:!?=]/
  908. const WEB_FILE_URI_PATH_PREFIX_RE = /(?:^|[^a-z0-9+.-])file:\/\/\/?$/i
  909. function isWebCwdMatch(value: string, start: number, length: number): boolean {
  910. const before = value[start - 1]
  911. const after = value[start + length]
  912. const afterPunctuation = value[start + length + 1]
  913. const startsAtBoundary = before === undefined
  914. || WEB_PATH_TEXT_BOUNDARY_RE.test(before)
  915. || WEB_FILE_URI_PATH_PREFIX_RE.test(value.slice(0, start))
  916. const endsAtBoundary = after === undefined
  917. || after === '/'
  918. || after === '\\'
  919. || WEB_PATH_TEXT_BOUNDARY_RE.test(after)
  920. || after === '.' && (afterPunctuation === undefined || WEB_PATH_TEXT_BOUNDARY_RE.test(afterPunctuation))
  921. return startsAtBoundary && endsAtBoundary
  922. }
  923. function replaceWebCwd(value: string, cwd: string): string {
  924. let cursor = 0
  925. let normalized = ''
  926. while (cursor < value.length) {
  927. const match = value.indexOf(cwd, cursor)
  928. if (match < 0) return normalized + value.slice(cursor)
  929. const end = match + cwd.length
  930. if (isWebCwdMatch(value, match, cwd.length)) {
  931. normalized += value.slice(cursor, match) + '{{cwd}}'
  932. cursor = end
  933. } else {
  934. normalized += value.slice(cursor, end)
  935. cursor = end
  936. }
  937. }
  938. return normalized
  939. }
  940. /**
  941. * Normalize Web-only volatile strings while preserving JSON structure and row framing.
  942. * @param log - raw Session JSONL.
  943. * @param workspaceCwd - optional scaffold parent used before a live Session selects its cwd.
  944. * @returns compact JSONL with run-local strings tokenized.
  945. */
  946. export function normalizeWebSessionVolatiles(log: string, workspaceCwd?: string): string {
  947. const headerLine = log.split(/\r?\n/).find(line => line.trim().length > 0)
  948. const header = headerLine === undefined ? undefined : JSON.parse(headerLine) as { cwd?: unknown }
  949. const sessionCwd = typeof header?.cwd === 'string' && header.cwd.length > 0 ? header.cwd : undefined
  950. const cwdSpellings = [...new Set([sessionCwd ?? workspaceCwd]
  951. .filter((value): value is string => typeof value === 'string' && value.length > 0)
  952. .flatMap((value) => {
  953. const forward = value.replaceAll('\\', '/')
  954. const native = /^[A-Za-z]:[\\/]/.test(value) ? forward.replaceAll('/', '\\') : value
  955. return [value, value.replaceAll('\\', '\\\\'), forward, native]
  956. }))].sort((left, right) => right.length - left.length)
  957. return log.split(/\r?\n/).map((line) => {
  958. if (line.trim() === '') return line
  959. const record = normalizeClientTimeZones(mapJsonStringValues(JSON.parse(line), (value) => {
  960. let normalized = value
  961. .replace(/Anonymous user: [0-9a-f-]{36}(?=\.$)/gi, 'Anonymous user: {{anonymousUserId}}')
  962. for (const cwd of cwdSpellings) normalized = replaceWebCwd(normalized, cwd)
  963. return normalized
  964. })) as { type?: unknown; data?: { endpoint?: unknown } }
  965. if (record.type === 'web/deepseek-search-llm-request' && typeof record.data?.endpoint === 'string') {
  966. record.data.endpoint = '{{webSearchEndpoint}}'
  967. }
  968. return JSON.stringify(record)
  969. }).join('\n')
  970. }
  971. function stableSessionFixture(
  972. session: Session,
  973. existing: string,
  974. workspaceCwd: string,
  975. harnessHome: string,
  976. ): string {
  977. const prepared = prepareSessionSnapshotFixtureForComparison(
  978. normalizeWebSessionVolatiles(rawSessionLog(session), workspaceCwd),
  979. )
  980. const stabilized = existing === ''
  981. ? prepared
  982. : stabilizeRefreshLog(prepared, existing, [], {
  983. sessionIds: [String(session.id)],
  984. cwd: workspaceCwd,
  985. })
  986. const fresh = scrubSessionSnapshot(stabilized)
  987. .split(session.id).join('{{session:1}}')
  988. .split(harnessHome).join('{{harnessHome}}')
  989. const stable = redactSessionSnapshotIds(stabilizeFixtureMessageIds([fresh], [existing]))[0]
  990. if (stable === undefined) throw new Error('session harvest produced no stabilized fixture')
  991. return stable
  992. }
  993. async function assertReplaySession(
  994. sessions: readonly Session[],
  995. fixturePath: string,
  996. mode: WebSnapshotMode,
  997. webUrl: string,
  998. harnessHome: string,
  999. ): Promise<void> {
  1000. let expected = await readFile(fixturePath, 'utf8')
  1001. const fixtureDir = dirname(fixturePath)
  1002. const manifestPath = join(fixtureDir, 'snapshot.yml')
  1003. const manifest = parseSnapshotManifest(await readFile(manifestPath, 'utf8'), manifestPath)
  1004. let expectedPath = fixturePath
  1005. const userPrompts = fixtureUserPrompts(expected)
  1006. const candidates = sessions.filter((session) => {
  1007. if (session.header.parentSession !== undefined) return false
  1008. const actual = session.snapshotEvents().flatMap((event) => {
  1009. if (event.type !== 'user/message' || event.data.source.kind !== 'user') return []
  1010. const text = event.data.content.filter(block => block.type === 'text').map(block => block.text).join('')
  1011. return text.length === 0 ? [] : [text]
  1012. })
  1013. return JSON.stringify(actual) === JSON.stringify(userPrompts)
  1014. })
  1015. expect(candidates, `Web replay fixture ${fixturePath} must match one live root session`).toHaveLength(1)
  1016. const session = candidates[0] as Session
  1017. const sessionCwd = session.header.cwd
  1018. if (sessionCwd === undefined) throw new Error(`${fixturePath}: replayed session has no cwd`)
  1019. const actual = rawSessionLog(session)
  1020. if (mode === 'refresh' && writesCurrentSessionFixtures(manifest, mode)) {
  1021. expected = stableSessionFixture(session, expected, sessionCwd, harnessHome)
  1022. expectedPath = recordedSessionFixturePath(fixturePath, session.header.version)
  1023. await writeFile(expectedPath, expected)
  1024. }
  1025. const expectedHeader = JSON.parse(expected.split('\n').find(line => line.trim() !== '') ?? '{}') as {
  1026. id?: unknown
  1027. cwd?: unknown
  1028. }
  1029. const actualContext: NormalizeContext = { sessionIds: [String(session.id)], cwd: sessionCwd }
  1030. const expectedContext: NormalizeContext = {
  1031. sessionIds: typeof expectedHeader.id === 'string' ? [expectedHeader.id] : [],
  1032. cwd: typeof expectedHeader.cwd === 'string' ? expectedHeader.cwd : '\0no-cwd\0',
  1033. }
  1034. const actualSnapshot = normalizeSessionSnapshots([normalizeWebSessionVolatiles(actual)], actualContext)[0]
  1035. ?.split(harnessHome).join('{{harnessHome}}')
  1036. const expectedSnapshot = normalizeSessionSnapshots([normalizeWebSessionVolatiles(expected)], expectedContext)[0]
  1037. ?.split(harnessHome).join('{{harnessHome}}')
  1038. expect(actualSnapshot, `${fixturePath}: persisted replay`).toBe(expectedSnapshot)
  1039. if (manifest.header?.pin !== true) return
  1040. const normalizePrompt = (value: string): string => value
  1041. .split(REPO_ROOT).join('{{sourceRoot}}')
  1042. .split(webUrl).join('{{webUrl}}')
  1043. const prompts = normalizedSystemPrompts(actual, actualContext).map(normalizePrompt)
  1044. const schemas = normalizedToolSchemas(actual, actualContext)
  1045. const promptPath = join(fixtureDir, 'system-prompt.expected.md')
  1046. const schemaPath = join(fixtureDir, 'tool-schemas.expected.json')
  1047. const promptSnapshot = formatSystemPromptSnapshot(prompts[0] as string, prompts.slice(1))
  1048. const schemaSnapshot = formatToolSchemasSnapshot(schemas[0] as unknown[], schemas.slice(1))
  1049. if (mode === 'refresh') {
  1050. await Promise.all([writeFile(promptPath, promptSnapshot), writeFile(schemaPath, schemaSnapshot)])
  1051. }
  1052. expect(promptSnapshot, `${fixturePath}: system-prompt pin`).toBe(await readFile(promptPath, 'utf8'))
  1053. expect(schemaSnapshot, `${fixturePath}: tool-schema pin`).toBe(await readFile(schemaPath, 'utf8'))
  1054. }
  1055. /**
  1056. * Record-mode fixture write-back: harvest the live session, scrub the
  1057. * system-prompt text to {{system}} and header tool schemas to {{tools}},
  1058. * tokenize the run-local cwd, redact opaque identities with typed
  1059. * relationship-preserving tokens, and write the fixture.
  1060. * A manifest-retained historical generation makes the write-back a no-op.
  1061. * @param scaffold - the record-mode scaffold.
  1062. * @param sessionId - the driven session.
  1063. * @param fixturePath - the committed session.jsonl target.
  1064. */
  1065. export async function recordFixture(scaffold: WebScaffold, sessionId: SessionId, fixturePath: string): Promise<void> {
  1066. const agent = scaffold.ctx.agents.get(sessionId)
  1067. if (agent === undefined) throw new Error(`record harvest: no live agent for ${sessionId}`)
  1068. const manifestPath = join(dirname(fixturePath), 'snapshot.yml')
  1069. const manifest = parseSnapshotManifest(await readFile(manifestPath, 'utf8'), manifestPath)
  1070. if (!writesCurrentSessionFixtures(manifest, 'record')) return
  1071. const target = recordedSessionFixturePath(fixturePath, agent.session.header.version)
  1072. const existingPath = existsSync(target) ? target : fixturePath
  1073. const existing = existsSync(existingPath) ? await readFile(existingPath, 'utf8') : ''
  1074. await writeFile(target, stableSessionFixture(
  1075. agent.session,
  1076. existing,
  1077. scaffold.workspaceCwd,
  1078. scaffold.harnessHome,
  1079. ))
  1080. }
  1081. /**
  1082. * The user prompts recorded in a fixture, in order — the single source tying
  1083. * spec drive steps to recorded reality so script and fixture cannot drift.
  1084. * @param fixtureText - raw session.jsonl contents.
  1085. * @returns the recorded user prompt texts.
  1086. */
  1087. export function fixtureUserPrompts(fixtureText: string): string[] {
  1088. return parseSessionLog(fixtureText).flatMap((event) => {
  1089. if (event.type !== 'user/message' || event.data.source.kind !== 'user') return []
  1090. const text = event.data.content.filter(block => block.type === 'text').map(block => block.text).join('')
  1091. return text.length > 0 ? [text] : []
  1092. })
  1093. }
  1094. /** Deterministic UUID used when a seed fixture's typed identity token is materialized. */
  1095. export function fixtureIdentity(
  1096. kind: 'message' | 'approval' | 'workflow' | 'command' | 'rpc' | 'retry' | 'id',
  1097. ordinal: number,
  1098. ): string {
  1099. const hex = createHash('sha256').update(`${kind}:${ordinal}`).digest('hex').slice(0, 32).split('')
  1100. hex[12] = '4'
  1101. hex[16] = ['8', '9', 'a', 'b'][Number.parseInt(hex[16] as string, 16) % 4] as string
  1102. 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('')}`
  1103. }
  1104. /**
  1105. * Realize a recorded seed fixture against one scaffold: substitute the
  1106. * `{{sessionId}}`/`{{cwd}}`/`{{harnessHome}}` placeholders and rewrite the
  1107. * recorded cwd to the scaffold's workspace. Idempotent, so a caller may realize early (e.g. to
  1108. * price content exactly as the host will fold it) and still pass the result
  1109. * through {@link seedSession}.
  1110. * @param scaffold - the booted scaffold whose workspace the seed targets.
  1111. * @param fixtureText - the committed seed fixture text.
  1112. * @param id - the session id the seed is realized for.
  1113. * @returns the realized fixture text.
  1114. */
  1115. export function realizeSeedFixture(scaffold: WebScaffold, fixtureText: string, id: string): string {
  1116. const firstLine = fixtureText.split(/\r?\n/).find(line => line.trim().length > 0)
  1117. const fixtureCwd = firstLine === undefined
  1118. ? undefined
  1119. : (JSON.parse(firstLine) as { cwd?: unknown }).cwd
  1120. return fixtureText.split(/\r?\n/).map((line) => {
  1121. if (line.trim() === '') return line
  1122. const realized = mapJsonStringValues(JSON.parse(line), (value) => {
  1123. let result = typeof fixtureCwd === 'string'
  1124. ? value.split(fixtureCwd).join(scaffold.workspaceCwd)
  1125. : value
  1126. result = result
  1127. .split('{{sessionId}}').join(id)
  1128. .split('{{session:1}}').join(id)
  1129. .replace(/\{\{session:([2-9]\d*)\}\}/g, (_token, ordinal: string) => `${id}-child-${ordinal}`)
  1130. .replace(/\{\{(message|approval|workflow|command|rpc|retry|id):([1-9]\d*)\}\}/g, (_token, kind: string, ordinal: string) =>
  1131. fixtureIdentity(kind as 'message' | 'approval' | 'workflow' | 'command' | 'rpc' | 'retry' | 'id', Number(ordinal)))
  1132. .split('{{harnessHome}}').join(scaffold.harnessHome)
  1133. .split('{{cwd}}').join(scaffold.workspaceCwd)
  1134. return result
  1135. })
  1136. return JSON.stringify(realized)
  1137. }).join('\n')
  1138. }
  1139. /**
  1140. * Parse a committed web seed fixture through the replay reader.
  1141. * @param fixtureText - session JSONL fixture contents.
  1142. * @returns the current header line, parsed header, and logical events.
  1143. */
  1144. /** Give a migrated fixture stream positive relative timing before its final wall-clock rebase. */
  1145. function spreadMigratedSeedStream(
  1146. stream: SessionEvent<'assistant/message'>['data']['stream'],
  1147. ): SessionEvent<'assistant/message'>['data']['stream'] {
  1148. let nextTime = 0
  1149. return stream.map((record) => {
  1150. if ('time' in record) {
  1151. const timed = { ...record, time: nextTime }
  1152. nextTime += 1
  1153. return timed
  1154. }
  1155. const timed = { ...record, time0: nextTime }
  1156. nextTime += record.dt.reduce((total, delta) => total + delta, 0) + 1
  1157. return timed
  1158. })
  1159. }
  1160. export function parseSeedFixture(fixtureText: string): {
  1161. headerLine: string
  1162. header: Record<string, unknown>
  1163. events: SessionEvent[]
  1164. } {
  1165. const sourceHeaderLine = fixtureText.split(/\r?\n/).find(line => line.trim().length > 0)
  1166. if (sourceHeaderLine === undefined) throw new Error('seed fixture has no session header')
  1167. const sourceHeader = JSON.parse(sourceHeaderLine) as { version?: unknown }
  1168. const current = prepareSessionSnapshotFixtureForComparison(fixtureText)
  1169. const headerLine = current.split(/\r?\n/).find(line => line.trim().length > 0)
  1170. if (headerLine === undefined) throw new Error('seed fixture has no session header')
  1171. const header = JSON.parse(headerLine) as Record<string, unknown>
  1172. if (header.type !== 'session') throw new Error('seed fixture must start with a session header')
  1173. const events = parseSessionLog(current).map((event) => {
  1174. if (sourceHeader.version === SESSION_FORMAT_VERSION) return event
  1175. if (event.type === 'assistant/message') {
  1176. return { ...event, data: { ...event.data, stream: spreadMigratedSeedStream(event.data.stream) } }
  1177. }
  1178. if (event.type === 'assistant/attempt') {
  1179. return { ...event, data: { ...event.data, stream: spreadMigratedSeedStream(event.data.stream) } }
  1180. }
  1181. return event
  1182. })
  1183. return { headerLine, header, events }
  1184. }
  1185. /**
  1186. * Render logical events as an envelope-free web seed fixture.
  1187. * @param headerLine - original session header line.
  1188. * @param events - logical session events in order.
  1189. * @returns projected session JSONL.
  1190. */
  1191. export function renderSeedFixture(
  1192. headerLine: string,
  1193. events: readonly ({ readonly seq: number; readonly time: number } & object)[],
  1194. ): string {
  1195. return [
  1196. headerLine,
  1197. ...events.map(({ seq: _seq, time: _time, ...event }) => JSON.stringify(event)),
  1198. '',
  1199. ].join('\n')
  1200. }
  1201. /** Re-anchor one projected embedded stream while preserving every intra-stream gap. */
  1202. function rebaseSeedStream(
  1203. stream: SessionEvent<'assistant/message'>['data']['stream'],
  1204. startAt: number,
  1205. ): SessionEvent<'assistant/message'>['data']['stream'] {
  1206. const first = stream[0]
  1207. if (first === undefined) return stream
  1208. const sourceStart = 'time' in first ? first.time : first.time0
  1209. const delta = startAt - sourceStart
  1210. return stream.map(record => 'time' in record
  1211. ? { ...record, time: record.time + delta }
  1212. : { ...record, time0: record.time0 + delta })
  1213. }
  1214. /** Last logical timestamp carried by an embedded Assistant stream. */
  1215. function seedStreamEnd(
  1216. stream: SessionEvent<'assistant/message'>['data']['stream'],
  1217. ): number | undefined {
  1218. let end: number | undefined
  1219. for (const record of stream) {
  1220. const recordEnd = 'time' in record
  1221. ? record.time
  1222. : record.time0 + record.dt.reduce((total, delta) => total + delta, 0)
  1223. end = end === undefined ? recordEnd : Math.max(end, recordEnd)
  1224. }
  1225. return end
  1226. }
  1227. /**
  1228. * Seed a recorded session fixture into the scaffold's persistence root
  1229. * through the real Session and JSONL APIs.
  1230. * @param scaffold - the target scaffold.
  1231. * @param fixtureText - raw recorded session.jsonl contents.
  1232. * @param id - the seeded session id.
  1233. * @param agentPreset - preset recorded by scenarios that assert resumed composition.
  1234. * @param options - deterministic metadata overrides for ordering-sensitive scenarios.
  1235. * @returns the seeded id.
  1236. */
  1237. export async function seedSession(
  1238. scaffold: WebScaffold,
  1239. fixtureText: string,
  1240. id: string,
  1241. agentPreset?: string,
  1242. options: { readonly createdAt?: number } = {},
  1243. ): Promise<SessionId> {
  1244. const decoded = parseSeedFixture(realizeSeedFixture(scaffold, fixtureText, id))
  1245. const events = decoded.events
  1246. if (events.length === 0) throw new Error('seed fixture has no events')
  1247. const last = events[events.length - 1]!
  1248. // An open final turn would be mutated by resume's crash repair on first
  1249. // open; a committed seed must be a closed recording.
  1250. if (last.type !== 'turn/end') throw new Error(`seed fixture must end in turn/end, got ${last.type}`)
  1251. const createdAt = options.createdAt ?? Date.now() - 60_000
  1252. const meta: SessionHeader = {
  1253. version: SESSION_FORMAT_VERSION,
  1254. id: SessionId(id),
  1255. createdAt,
  1256. isSeeded: false,
  1257. cwd: scaffold.workspaceCwd,
  1258. delegationDepth: 0,
  1259. ...agentPreset === undefined ? {} : { agentPreset },
  1260. }
  1261. const fixtureCreatedAt = decoded.header.createdAt
  1262. if (typeof fixtureCreatedAt !== 'number') {
  1263. throw new Error('seed fixture requires a numeric createdAt header')
  1264. }
  1265. const timeAnchor = fixtureCreatedAt === 0 ? createdAt : fixtureCreatedAt
  1266. let nextTime = timeAnchor
  1267. const materializedEvents: SessionEvent[] = events.map((event) => {
  1268. const time = nextTime
  1269. if (event.type === 'assistant/message') {
  1270. const stream = rebaseSeedStream(event.data.stream, time)
  1271. const completedAt = Math.max(time, seedStreamEnd(stream) ?? time)
  1272. nextTime = completedAt + 1
  1273. return {
  1274. ...event,
  1275. time: completedAt,
  1276. data: { ...event.data, stream },
  1277. }
  1278. }
  1279. if (event.type === 'assistant/attempt') {
  1280. const stream = rebaseSeedStream(event.data.stream, time)
  1281. const completedAt = Math.max(time, seedStreamEnd(stream) ?? time)
  1282. nextTime = completedAt + 1
  1283. return {
  1284. ...event,
  1285. time: completedAt,
  1286. data: { ...event.data, stream },
  1287. }
  1288. }
  1289. nextTime = time + 1
  1290. return { ...event, time }
  1291. })
  1292. await persistSeedSession(scaffold, meta, materializedEvents)
  1293. return meta.id
  1294. }
  1295. /** Materialize one detached Session fixture through the shipped JSONL provider. */
  1296. async function persistSeedSession(
  1297. scaffold: WebScaffold,
  1298. meta: SessionHeader,
  1299. events: readonly SessionEvent[],
  1300. ): Promise<void> {
  1301. const seeder = new Context()
  1302. try {
  1303. // Same root as the booted tree with the plugin's own default compression,
  1304. // so the host's directory-scan list() sees one consistent encoding.
  1305. await seeder.plugin(JsonlSessionPersistence, { root: scaffold.persistenceRoot })
  1306. const handle = await seeder.sessionPersistence.create(meta)
  1307. await handle.append(events)
  1308. await handle.close()
  1309. } finally {
  1310. await seeder.fiber.dispose()
  1311. }
  1312. }
  1313. /**
  1314. * Read one stored session's physical event log through a throwaway read
  1315. * handle. The physical log carries no synthetic closers: a resumed session
  1316. * shows the closers the loop appended durably, and a never-resumed
  1317. * interrupted log stays interrupted.
  1318. * @param scaffold - the booted scaffold whose persistence holds the session.
  1319. * @param id - the stored session to read.
  1320. * @returns the stored events.
  1321. */
  1322. export async function readPersistedEvents(scaffold: WebScaffold, id: SessionId): Promise<readonly SessionEvent[]> {
  1323. const handle = await scaffold.ctx.sessionPersistence.open(id, 'read')
  1324. try {
  1325. return (await handle.read()).events
  1326. } finally {
  1327. await handle.close()
  1328. }
  1329. }
  1330. /**
  1331. * Normalize an aria snapshot: uuid, cwd, workspace-basename, duration,
  1332. * decode-throughput, and path-sensitive compaction estimates collapse to
  1333. * stable tokens.
  1334. *
  1335. * Throughput needs a token for the same reason durations do, and no fixture
  1336. * can supply one: the figure divides a replayed step's output tokens by the
  1337. * wall time the local run took to stream them, so it moves between two runs
  1338. * on one machine (measured 69 → 70 tok/s) and swings wildly on a fast replay
  1339. * (26333 tok/s for a 3 ms stream).
  1340. */
  1341. /**
  1342. * Relative-time buckets rendered by a dated row, in both dictionaries.
  1343. *
  1344. * Opt-in per capture: a session-tree golden asserts its own literal age (a
  1345. * fresh row reads `now`, an older one does not), so collapsing the vocabulary
  1346. * everywhere would delete that assertion. A region whose rows are dated from
  1347. * live wall-clock state asks for it instead. Anchored on an aria label's
  1348. * closing quote, where the bucket is always last.
  1349. */
  1350. const ARIA_AGE =
  1351. /(?:now|\d+min|\d+h|\d+d|\d+mo|\d+y|刚刚|\d+分钟|\d+小时|\d+天|\d+个月|\d+年)(?=")/g
  1352. function normalizeAria(snapshot: string, workspaceCwd: string, age: boolean): string {
  1353. // The session heading renders the workspace's basename, not the full
  1354. // path, so both spellings must collapse to the token.
  1355. const base = workspaceCwd.split('/').pop()!
  1356. return (age ? snapshot.replace(ARIA_AGE, '{{age}}') : snapshot)
  1357. .split(workspaceCwd).join('{{cwd}}')
  1358. .split(base).join('{{workspace}}')
  1359. .replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi, '{{uuid}}')
  1360. // The optional space in `\d+m ?\d+s` covers both minute spellings: the
  1361. // stats line's compact `2m42s` and the message-chrome template's `2m 42s`.
  1362. .replace(
  1363. /~\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,
  1364. duration => duration.startsWith('~') ? duration : '{{duration}}',
  1365. )
  1366. .replace(/\b\d[\d,]*(?:\.\d+)? ms\b/g, '{{duration}}')
  1367. .replace(
  1368. /约\d+(?:年(?:\d+个月)?|个月(?:\d+天)?)|\d+(?:天(?:\d+小时(?:\d+分\d+秒)?)?|小时\d+分\d+秒|分\d+秒|(?:\.\d+)?秒)/g,
  1369. duration => duration.startsWith('约') ? duration : '{{duration}}',
  1370. )
  1371. .replace(/\d+(?:\.\d+)?(?= tok\/s(?!\w))/g, '{{throughput}}')
  1372. // Seeded compaction prices realized file paths, whose length differs
  1373. // between local worktrees and CI scratch directories.
  1374. .replace(/(Compacted \d+ history items \(~)\d+( tokens\))/g, '$1{{tokens}}$2')
  1375. // Session summaries and Message IconActions clocks cross calendar
  1376. // boundaries; collapse every shape so goldens stay stable across them.
  1377. .replace(/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z/g, '{{timestamp}}')
  1378. .replace(/\d{4}年\d{1,2}月\d{1,2}日 \d{2}:\d{2}/g, '{{clock}}')
  1379. .replace(/\d{1,2}月\d{1,2}日 \d{2}:\d{2}/g, '{{clock}}')
  1380. .replace(/(?<!\d)\d{1,2}:\d{2}:\d{2}(?:\.\d+)?(?:\s*[AP]M)?(?!\d)/gi, '{{clock}}')
  1381. .replace(/(?<!\d)\d{2}:\d{2}(?!\d)/g, '{{clock}}')
  1382. }
  1383. /**
  1384. * Capture the region's aria snapshot at a settled milestone: poll until two
  1385. * consecutive normalized captures are equal — a single-shot capture races the
  1386. * last React commits.
  1387. * @param page - the page under test.
  1388. * @param selector - the region locator selector.
  1389. * @param workspaceCwd - normalization input.
  1390. * @param options - `normalizeAge` collapses relative-time buckets to `{{age}}`
  1391. * for a region whose rows are dated from live wall-clock state;
  1392. * `replacements` tokenizes scenario-owned values before generic normalization.
  1393. * @returns the stable normalized snapshot.
  1394. */
  1395. export async function captureStableAria(
  1396. page: Page,
  1397. selector: string,
  1398. workspaceCwd: string,
  1399. options: {
  1400. normalizeAge?: boolean
  1401. replacements?: readonly (readonly [value: string, token: string])[]
  1402. } = {},
  1403. ): Promise<string> {
  1404. const region = page.locator(selector).first()
  1405. const age = options.normalizeAge === true
  1406. const normalize = (snapshot: string): string => {
  1407. for (const [value, token] of options.replacements ?? []) {
  1408. snapshot = snapshot.split(value).join(token)
  1409. }
  1410. return normalizeAria(snapshot, workspaceCwd, age)
  1411. }
  1412. let previous = normalize(await region.ariaSnapshot())
  1413. await expect.poll(async () => {
  1414. const current = normalize(await region.ariaSnapshot())
  1415. const stable = current === previous
  1416. previous = current
  1417. return stable
  1418. }, { timeout: 5_000, message: 'aria snapshot did not stabilize' }).toBe(true)
  1419. return previous
  1420. }
  1421. /**
  1422. * Capture a stable aria snapshot with every eligible Turn process expanded,
  1423. * then restore the controls that were closed before the capture.
  1424. * @param page - the page under test.
  1425. * @param selector - the region locator selector.
  1426. * @param workspaceCwd - normalization input.
  1427. * @param options - optional user-visible state to establish before capture.
  1428. * @returns the stable normalized expanded snapshot.
  1429. */
  1430. export async function captureExpandedTurnProcessAria(
  1431. page: Page,
  1432. selector: string,
  1433. workspaceCwd: string,
  1434. options: { scrollToBottom?: boolean } = {},
  1435. ): Promise<string> {
  1436. const controls = page.locator('[data-turn-process]')
  1437. const count = await controls.count()
  1438. expect(count).toBeGreaterThan(0)
  1439. const opened: number[] = []
  1440. for (let index = 0; index < count; index++) {
  1441. const control = controls.nth(index)
  1442. if (!await control.isVisible() || await control.getAttribute('aria-expanded') === 'true') continue
  1443. await control.click()
  1444. opened.push(index)
  1445. }
  1446. try {
  1447. if (options.scrollToBottom === true) {
  1448. const backToBottom = page.getByRole('button', { name: 'Back to bottom', exact: true })
  1449. const scroll = page.locator('[data-conversation-scroll]')
  1450. await expect.poll(async () => {
  1451. const distanceFromBottom = await scroll.evaluate((host) => {
  1452. host.scrollTop = host.scrollHeight
  1453. return host.scrollHeight - host.clientHeight - host.scrollTop
  1454. })
  1455. return Math.abs(distanceFromBottom) <= 1 && await backToBottom.count() === 0
  1456. }, { timeout: 10_000 }).toBe(true)
  1457. }
  1458. return await captureStableAria(page, selector, workspaceCwd)
  1459. } finally {
  1460. for (const index of opened.reverse()) {
  1461. const control = controls.nth(index)
  1462. if (await control.getAttribute('aria-expanded') === 'true') await control.click()
  1463. }
  1464. }
  1465. }
  1466. /**
  1467. * Compare a normalized golden, or rewrite it under refresh. Refresh is the
  1468. * ONLY writer: a missing golden in replay mode fails with the healing command
  1469. * instead of silently self-bootstrapping.
  1470. * @param goldenPath - the committed ui.expected.md path.
  1471. * @param actual - the stable normalized snapshot.
  1472. * @param mode - the active snapshot mode.
  1473. */
  1474. export async function compareOrRefreshGolden(goldenPath: string, actual: string, mode: WebSnapshotMode): Promise<void> {
  1475. const payload = `${actual}\n`
  1476. if (mode === 'refresh') {
  1477. await writeFile(goldenPath, payload)
  1478. return
  1479. }
  1480. if (!existsSync(goldenPath)) {
  1481. throw new Error(`missing golden ${goldenPath} — run DSH_SNAPSHOT=refresh pnpm run test:web to generate it`)
  1482. }
  1483. expect(payload).toBe(await readFile(goldenPath, 'utf8'))
  1484. }
  1485. /**
  1486. * Fixture-inventory guard: the scenario directory holds exactly the expected
  1487. * files and every committed JSONL is a header-scrubbed, typed-redaction fixed point.
  1488. * @param dir - the scenario snapshot directory.
  1489. * @param expected - the exact expected file inventory.
  1490. */
  1491. export async function assertFixtureInventory(dir: string, expected: string[]): Promise<void> {
  1492. const entries = (await readdir(dir)).sort()
  1493. const ownsManifest = entries.includes('snapshot.yml')
  1494. const artifacts = entries.filter(name => name !== 'snapshot.yml')
  1495. const roleInventory = (names: readonly string[]): string[] => [...new Set(names.map((name) => {
  1496. const fixture = parseSessionFixtureName(name)
  1497. return fixture === undefined ? name : sessionFixtureName(fixture.index, 0)
  1498. }))].sort()
  1499. expect(roleInventory(artifacts)).toEqual(roleInventory(expected))
  1500. if (ownsManifest) {
  1501. const manifestPath = join(dir, 'snapshot.yml')
  1502. const manifest = parseSnapshotManifest(await readFile(manifestPath, 'utf8'), manifestPath)
  1503. expect(manifest.profile).toBe('web')
  1504. if (manifest.session === undefined) {
  1505. expect(
  1506. artifacts.some(name => parseSessionFixtureName(name)?.index === 0),
  1507. `${dir}: session owner must carry a canonical parent Session fixture`,
  1508. ).toBe(true)
  1509. } else {
  1510. expect(existsSync(resolve(dir, manifest.session.source)), `${dir}: session source`).toBe(true)
  1511. }
  1512. }
  1513. for (const entry of artifacts.filter(name => name.endsWith('.jsonl'))) {
  1514. const content = await readFile(join(dir, entry), 'utf8')
  1515. expect(scrubModelRequestBulk(content), `${dir}/${entry} carries prompt text or tool-schema bulk`).toBe(content)
  1516. expect(redactSessionSnapshotIds([content]), `${dir}/${entry} carries unredacted identities`).toEqual([content])
  1517. }
  1518. }
  1519. /**
  1520. * Console tripwires: reconnect/gap-repair self-healing or a pageerror must
  1521. * fail the scenario, not mask a dead wire behind eventual consistency.
  1522. * @param page - the page under test.
  1523. * @returns live warning/pageerror collectors to assert empty at scenario end.
  1524. */
  1525. export function watchConsole(page: Page): { warnings: string[]; pageErrors: string[] } {
  1526. const warnings: string[] = []
  1527. const pageErrors: string[] = []
  1528. page.on('console', (message) => {
  1529. const text = message.text()
  1530. if (/connection lost|gap repair|discontinuous/i.test(text)) warnings.push(text)
  1531. })
  1532. page.on('pageerror', (error) => { pageErrors.push(String(error)) })
  1533. return { warnings, pageErrors }
  1534. }
  1535. /**
  1536. * Remove only connection-loss warnings emitted after an intentional reload.
  1537. * Earlier warnings and all gap-repair/discontinuity warnings remain fatal.
  1538. * @param tripwire - the live console-warning collector.
  1539. * @param warningStart - warning count captured immediately before reloading.
  1540. */
  1541. export function acknowledgeReloadConnectionLoss(
  1542. tripwire: ReturnType<typeof watchConsole>,
  1543. warningStart: number,
  1544. ): void {
  1545. const reloadWarnings = tripwire.warnings.splice(warningStart)
  1546. tripwire.warnings.push(...reloadWarnings.filter(text => !/connection lost/i.test(text)))
  1547. }