1
0

scaffold.ts 59 KB

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