scaffold.ts 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859
  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; workspace-context
  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 } from 'node:fs'
  26. import { mkdir, mkdtemp, readFile, readdir, realpath, rm, utimes, writeFile } from 'node:fs/promises'
  27. import { tmpdir } from 'node:os'
  28. import { join } from 'node:path'
  29. import { pathToFileURL } from 'node:url'
  30. import type { Page } from 'playwright'
  31. import { expect } from 'vitest'
  32. import { Context } from '@deepseek-ai/cordis'
  33. import Loader from '@deepseek-ai/cordis-plugin-loader'
  34. import Include, { type PatchOptions } from '@deepseek-ai/cordis-plugin-include'
  35. import Group from '@deepseek-ai/cordis-plugin-group'
  36. import { scrubRequestHeaders, stabilizeFixtureMessageIds } from '@deepseek-ai/dsh-acp-snapshot'
  37. import {
  38. assertEntriesLoaded,
  39. composeEntries,
  40. healProfilesModuleFallback,
  41. loadOverlayPatches,
  42. } from '@deepseek-ai/dsh-app-boot'
  43. import { dshHomePath } from '@deepseek-ai/dsh-paths'
  44. // Client packages must not be imported here: these e2e type-check in the Host
  45. // aggregate, so a Client import pulls that package's whole project — and every
  46. // project it references — into the Host build graph. Mirrored from
  47. // packages/client/ui-settings-general/src/onboarding-copy.ts; a drift makes the
  48. // pre-acknowledgement stop suppressing the notice, which fails loudly.
  49. // import {
  50. // WELCOME_NOTICE_ACK_FIELD, WELCOME_NOTICE_SETTINGS_NAMESPACE, WELCOME_NOTICE_VERSION, WELCOME_NOTICE_COPY,
  51. // } from '@deepseek-ai/dsh-client-ui-settings-general'
  52. export const WELCOME_NOTICE_SETTINGS_NAMESPACE = 'ui-onboarding'
  53. export const WELCOME_NOTICE_ACK_FIELD = 'welcomeNoticeVersion'
  54. export const WELCOME_NOTICE_VERSION = '2026-07-30.7'
  55. export const WELCOME_NOTICE_COPY = { zh: { title: '内测声明', continueLabel: '继续' } } as const
  56. import { settingsNamespace } from '@deepseek-ai/dsh-settings'
  57. import { LlmAdapter } from '@deepseek-ai/dsh-llm'
  58. import type {
  59. LlmModelInfo, LlmProviderInfo, LlmResolvedModelInfo, StreamChunk,
  60. } from '@deepseek-ai/dsh-llm'
  61. import type { ReplayHandle } from '@deepseek-ai/dsh-llm-replay'
  62. import { installLlmReplay, parseSessionLog } from '@deepseek-ai/dsh-llm-replay'
  63. import SessionStore, {
  64. packChunkRuns,
  65. SESSION_FORMAT_VERSION,
  66. SessionId,
  67. type Session,
  68. type SessionEvent,
  69. type SessionHeader,
  70. } from '@deepseek-ai/dsh-session'
  71. import SessionPersistenceJsonl from '@deepseek-ai/dsh-session-persistence-jsonl'
  72. import * as ToolCordis from '@deepseek-ai/dsh-tool-cordis'
  73. // Empty type imports carry the httpServer/agents/sessionPersistence Context merges.
  74. import type {} from '@deepseek-ai/dsh-host-webserver'
  75. import type {} from '@deepseek-ai/dsh-agent'
  76. import { provideCmdline } from '@deepseek-ai/dsh-cmdline'
  77. import { REPO_ROOT, requireDist } from './support.ts'
  78. /** Snapshot mode for the lane, from $DSH_SNAPSHOT (same vocabulary as the other snapshot suites). */
  79. export type WebSnapshotMode = 'replay' | 'record' | 'refresh'
  80. /**
  81. * Resolve and validate the lane's snapshot mode.
  82. * @returns the active mode; unset/empty selects replay.
  83. */
  84. export function webSnapshotMode(): WebSnapshotMode {
  85. const value = process.env.DSH_SNAPSHOT
  86. if (value === undefined || value === '' || value === 'replay') return 'replay'
  87. if (value === 'record' || value === 'refresh') return value
  88. throw new Error(`DSH_SNAPSHOT must be replay, record, or refresh; got ${JSON.stringify(value)}`)
  89. }
  90. /** The shipped composition under test: the dsh-base and dsh-web-app bundle patches over the empty profile root. */
  91. const BASE_PATCH_PATH = join(REPO_ROOT, 'packages/bundle/base/cordis.patch.yml')
  92. const WEB_PATCH_PATH = join(REPO_ROOT, 'packages/bundle/web-app/cordis.patch.yml')
  93. /** The installation anchor whose dependency surface the profile module fallback mirrors. */
  94. const INSTALL_ANCHOR = join(REPO_ROOT, 'apps/cli/package.json')
  95. /** The deployment's own agent-preset root, shipped beside the app's config. */
  96. const SHIPPED_PRESET_DIR = join(REPO_ROOT, 'apps/cli/config/agent-presets')
  97. // Replay publishes the provider catalog the gateway routes to (providers
  98. // mode, never catch-all: with llm-deepseek disabled no adapter exists, so a
  99. // catch-all would leave resolveModelInfo unroutable and compact-basic's
  100. // post-step pressure check would warn every step). The published
  101. // contextWindow keeps that pressure path provably inert for small fixtures.
  102. const REPLAY_PROVIDERS = [{
  103. id: 'deepseek-official',
  104. name: 'DeepSeek',
  105. models: [{ id: 'deepseek-v4-flash', name: 'DeepSeek-V4-Flash', contextWindow: 128_000 }],
  106. }]
  107. /**
  108. * The routes a shipped composition always has, with no ability to stream.
  109. * A fixture-less keyless scenario issues no model calls, but its tree must
  110. * still answer `listProviders()` — surfaces legitimately gate on whether any
  111. * adapter serves a session's route, and an empty registry is a test artifact,
  112. * not a product state.
  113. */
  114. class RouteOnlyAdapter extends LlmAdapter {
  115. constructor(private readonly providers: typeof REPLAY_PROVIDERS) {
  116. super()
  117. }
  118. override providerInfo(provider: string): LlmProviderInfo {
  119. return { id: provider, name: this.providers.find(entry => entry.id === provider)?.name ?? provider }
  120. }
  121. override listModels(provider: string): Promise<readonly LlmModelInfo[]> {
  122. return Promise.resolve((this.providers.find(entry => entry.id === provider)?.models ?? [])
  123. .map(model => ({ provider, id: model.id, name: model.name })))
  124. }
  125. override resolveModel(provider: string, model: string): Promise<LlmResolvedModelInfo> {
  126. const listed = this.providers.find(entry => entry.id === provider)?.models
  127. .find(entry => entry.id === model)
  128. return Promise.resolve({
  129. provider,
  130. id: model,
  131. name: listed?.name ?? model,
  132. ...listed?.contextWindow === undefined ? {} : { contextWindow: listed.contextWindow },
  133. })
  134. }
  135. override async *stream(): AsyncIterable<StreamChunk> {
  136. throw new Error(
  137. 'web e2e scaffold: a model call was issued by a scenario that declared no replay fixture'
  138. + ' — pass replayFixture, or keep the scenario free of model calls',
  139. )
  140. }
  141. }
  142. function replayProviders(contextWindow: number | undefined): typeof REPLAY_PROVIDERS {
  143. if (contextWindow === undefined) return REPLAY_PROVIDERS
  144. return REPLAY_PROVIDERS.map(provider => ({
  145. ...provider,
  146. models: provider.models.map(model => ({ ...model, contextWindow })),
  147. }))
  148. }
  149. /** A booted web scaffold: real composition, mode-selected model backend, temp world. */
  150. export interface WebScaffold {
  151. /** The active snapshot mode this scaffold booted under. */
  152. mode: WebSnapshotMode
  153. /** Browser-facing origin for the bound test server. */
  154. baseUrl: string
  155. /** Settled root context (the in-process readiness barrier; headless event subscription is its sanctioned use). */
  156. ctx: Context
  157. /** Temp project directory sessions run in (bash/fs tool cwd). */
  158. workspaceCwd: string
  159. /** Temp persistence root (seeded sessions land here through the real API). */
  160. persistenceRoot: string
  161. /** Isolated harness home the settings/credentials rows write ($DSH_HOME double). */
  162. harnessHome: string
  163. /** Await a settled turn end: in-process turn/end, then the agent's idle flip (which follows the persistence flush). */
  164. whenTurnSettled(timeoutMs?: number): Promise<SessionId>
  165. /** Tear everything down; asserts the replay fixture was fully consumed first (replay/refresh). */
  166. close(): Promise<void>
  167. }
  168. /** Options for {@link launchWebScaffold}. */
  169. export interface LaunchOptions {
  170. /**
  171. * Optional product overlay applied after the shipped Web surface and before
  172. * the scaffold's hermetic test patches, matching the launcher's `--patch`
  173. * ordering.
  174. */
  175. extraOverlayPath?: string
  176. /**
  177. * Replay fixture (session.jsonl) served by the inserted dsh-llm-replay row
  178. * in replay/refresh modes; ignored in record mode (the real adapter
  179. * answers). Omit for scenarios issuing no model calls — a stray stream then
  180. * fails loud with NO_ADAPTER (llm-deepseek is disabled and no replay row
  181. * mounts).
  182. */
  183. replayFixture?: string
  184. /**
  185. * Recorded child logs assigned in child creation order. Each child owns its
  186. * own positional replay cursor across initial and continuation turns.
  187. */
  188. replayChildFixtures?: string[]
  189. /**
  190. * Optional replay.override.json sidecar (whole-script replacement or
  191. * `{ patches }` augmentation) for throw/hang scenarios not expressible as
  192. * recorded chunks; replay/refresh only.
  193. */
  194. replayOverride?: string
  195. /** Per-chunk replay pacing (ms) so the browser observes genuinely incremental SSE; replay/refresh only. */
  196. paceMs?: number
  197. /** Synthetic model capacity for UI scenarios whose seeded history must remain uncompacted. */
  198. replayContextWindow?: number
  199. /**
  200. * Tool presentation mode patched onto the shipped `tools` row (`code`
  201. * collapses the wire to run_code + the SDK prompt section). Omit for the
  202. * yml default. The code runtime row is always in the tree, so no extra
  203. * insertion is needed.
  204. */
  205. toolsMode?: 'native' | 'code' | 'both'
  206. /**
  207. * Insert the opt-in self-referential Cordis tools into the shipped tree.
  208. * Record and replay use the same tool surface, so captured request headers
  209. * remain reconstructable without making the tools a product default.
  210. */
  211. cordisTools?: boolean
  212. /**
  213. * Keep the shipped DeepSeek adapter mounted while masking the process
  214. * environment's DEEPSEEK_API_KEY for this scaffold lifetime. This is the
  215. * keyless first-run configuration lane; the default disables the adapter.
  216. */
  217. deepSeekMissingCredential?: boolean
  218. /**
  219. * Patch the shipped DeepSeek search row to a deterministic endpoint and
  220. * credential reference. Browser search scenarios keep the real provider and
  221. * credentials seam while avoiding external search traffic and ambient keys.
  222. */
  223. deepSeekSearch?: {
  224. /** Anthropic-compatible base URL; the provider appends `/messages`. */
  225. baseURL: string
  226. /** Credential reference resolved by the shipped search provider. */
  227. apiKeyEnv: string
  228. }
  229. /**
  230. * Replace the roster the scaffold mounts by default (the shipped directory
  231. * at `system` trust, default `standard`). Supply this only to change WHICH
  232. * presets a scenario sees — a writable user root, a different default —
  233. * never to turn the roster on: without one every session composes an agent
  234. * with no tools, no persona, and no token meter, which is not a shape the
  235. * product ever boots in. The patch lands after the default, so it wins.
  236. */
  237. agentPresets?: {
  238. /** Roots to discover, in precedence order; the shipped directory is `system`. */
  239. roots: { path: string; trust: 'system' | 'user' }[]
  240. /** The preset a session that names none is composed from. */
  241. default: string
  242. }
  243. /** Leave the current welcome notice unacknowledged; ordinary scenarios publish it as complete before browser boot. */
  244. welcomeNoticePending?: boolean
  245. /**
  246. * Mount the shipped telemetry row in FULL mode against this exporter URL
  247. * instead of disabling it. Used to pin a real backend disclosure in
  248. * assembled coverage; point the URL at a local dead endpoint so no record
  249. * leaves the process.
  250. */
  251. telemetryUrl?: string
  252. /**
  253. * Browse through a trusted non-loopback hostname that the browser resolves
  254. * to loopback (for example `*.localhost`). The test server stays bound to
  255. * 127.0.0.1; a non-resolving authority fails before Host trust is exercised.
  256. */
  257. remoteAuthority?: string
  258. /** Reuse an existing harness home so a second Host can verify user settings across origins. */
  259. harnessHome?: string
  260. }
  261. /** Dispose the booted tree and remove both owned temp roots, reporting every independent cleanup failure. */
  262. async function cleanupScaffoldWorld(ctx: Context, workspaceCwd: string, persistenceRoot: string): Promise<unknown[]> {
  263. const failures: unknown[] = []
  264. await Promise.resolve(ctx.fiber.dispose()).catch((error: unknown) => failures.push(error))
  265. await rm(workspaceCwd, { recursive: true, force: true }).catch((error: unknown) => failures.push(error))
  266. await rm(persistenceRoot, { recursive: true, force: true }).catch((error: unknown) => failures.push(error))
  267. return failures
  268. }
  269. /**
  270. * Boot the real web composition under the current snapshot mode.
  271. * @param options - replay fixture selection and pacing.
  272. * @returns the running scaffold.
  273. */
  274. export async function launchWebScaffold(options: LaunchOptions = {}): Promise<WebScaffold> {
  275. requireDist()
  276. const mode = webSnapshotMode()
  277. const browserHost = options.remoteAuthority ?? '127.0.0.1'
  278. if (mode === 'record') {
  279. // Both owning vitest configs (web unconditionally, snapshot in record
  280. // mode) load the repo-root .env before this file runs.
  281. if (process.env.DEEPSEEK_API_KEY === undefined || process.env.DEEPSEEK_API_KEY.length === 0) {
  282. throw new Error('web e2e record mode needs DEEPSEEK_API_KEY (env or repo-root .env)')
  283. }
  284. }
  285. if (mode === 'record' && options.deepSeekMissingCredential === true) {
  286. throw new Error('deepSeekMissingCredential is a keyless replay/refresh option')
  287. }
  288. const maskDeepSeekCredential = mode !== 'record' && options.deepSeekMissingCredential === true
  289. const originalDeepSeekCredential = process.env.DEEPSEEK_API_KEY
  290. let credentialEnvironmentRestored = false
  291. const restoreCredentialEnvironment = (): void => {
  292. if (credentialEnvironmentRestored || !maskDeepSeekCredential) return
  293. credentialEnvironmentRestored = true
  294. if (originalDeepSeekCredential === undefined) {
  295. Reflect.deleteProperty(process.env, 'DEEPSEEK_API_KEY')
  296. } else {
  297. process.env.DEEPSEEK_API_KEY = originalDeepSeekCredential
  298. }
  299. }
  300. const workspaceCwd = await realpath(await mkdtemp(join(tmpdir(), 'dsh-web-e2e-ws-')))
  301. // Isolated harness home: the settings/credentials rows resolve $DSH_HOME
  302. // paths at load, and an in-process boot must NEVER touch the developer's
  303. // real ~/.dsh document or credential file.
  304. const harnessHome = options.harnessHome ?? join(workspaceCwd, '.dsh-home')
  305. // Skill discovery is model-visible input, and its roots now resolve inside a
  306. // PRESET — a subtree this lane's include patches cannot reach, because the
  307. // roster mounts it directly per session rather than as a row of the booted
  308. // tree. The row's documented fallback is the environment, so pin that: the
  309. // whole scaffold lifetime, not just the boot, since presets mount when a
  310. // session is created. Without this a developer's real ~/.dsh/skills silently
  311. // enters replay requests and goldens while CI sees none. `DSH_HOME` follows
  312. // the resolved harness home so a scaffold sharing another's home — the
  313. // cross-port persistence scenario — pins the same roots the settings and
  314. // credentials rows were configured with.
  315. const skillRootEnvironment = {
  316. DSH_HOME: harnessHome,
  317. DSH_AGENTS_HOME: join(workspaceCwd, '.agents-home'),
  318. DSH_BUNDLED_SKILL_DIR: join(workspaceCwd, '.bundled-skills'),
  319. }
  320. const originalSkillRootEnvironment = Object.fromEntries(
  321. Object.keys(skillRootEnvironment).map(key => [key, process.env[key]]),
  322. )
  323. let skillRootEnvironmentRestored = false
  324. const restoreSkillRootEnvironment = (): void => {
  325. if (skillRootEnvironmentRestored) return
  326. skillRootEnvironmentRestored = true
  327. for (const [key, value] of Object.entries(originalSkillRootEnvironment)) {
  328. if (value === undefined) Reflect.deleteProperty(process.env, key)
  329. else process.env[key] = value
  330. }
  331. }
  332. Object.assign(process.env, skillRootEnvironment)
  333. let persistenceRoot: string
  334. try {
  335. persistenceRoot = await mkdtemp(join(tmpdir(), 'dsh-web-e2e-sessions-'))
  336. } catch (error) {
  337. const failures: unknown[] = [error]
  338. await rm(workspaceCwd, { recursive: true, force: true }).catch((cleanupError: unknown) => failures.push(cleanupError))
  339. restoreSkillRootEnvironment()
  340. if (failures.length > 1) throw new AggregateError(failures, 'web scaffold temp-root setup failed')
  341. throw error
  342. }
  343. if (maskDeepSeekCredential) Reflect.deleteProperty(process.env, 'DEEPSEEK_API_KEY')
  344. // The include patch set — the same layer stack the profile boot composes
  345. // (bundle patches in dsh.profile.bundles order), applied over the SAME empty root (a
  346. // patch id that stops matching a row fails the boot sweep loudly instead of
  347. // drifting).
  348. const basePatches = loadOverlayPatches('web e2e scaffold', BASE_PATCH_PATH)
  349. const surfacePatches = loadOverlayPatches('web e2e scaffold', WEB_PATCH_PATH)
  350. const extraOverlayPatches = options.extraOverlayPath === undefined
  351. ? []
  352. : loadOverlayPatches('web e2e scaffold', options.extraOverlayPath)
  353. const composedRows = composeEntries([basePatches, surfacePatches, extraOverlayPatches])
  354. const webRuntimeConfig = composedRows.find(row => row.id === 'web-runtime')?.config as {
  355. surfaceContext?: boolean
  356. } | undefined
  357. const surfaceContext = webRuntimeConfig?.surfaceContext !== false
  358. const patches: PatchOptions[] = [
  359. ...basePatches,
  360. ...surfacePatches,
  361. ...extraOverlayPatches,
  362. // The roster's `roots` is an assembly fact AppCLIEntry resolves and patches
  363. // in, exactly like `distIndex` on the webserver row — the shipped preset
  364. // directory sits beside the composition that names it, and no config author
  365. // chooses it. This lane boots the shipped tree WITHOUT AppCLIEntry, so it
  366. // has to supply the same fact or the roster resolves nothing and every
  367. // session composes an agent with no tools, no persona, and no token meter.
  368. // Only the shipped root: a developer's own `~/.dsh/.agent-presets` must not be
  369. // able to change a golden.
  370. {
  371. id: 'agent-presets',
  372. config: { default: 'standard', roots: [{ path: SHIPPED_PRESET_DIR, trust: 'system' }] },
  373. },
  374. { id: 'session-persistence-jsonl', config: { root: persistenceRoot } },
  375. { id: 'session-query-sqlite', config: { path: ':memory:', openAt: 'first-search' } },
  376. // storage-json's yml root is anchored to the real $DSH_HOME; pin the row
  377. // to an absolute temp root (removed with the workspace at close) so tests
  378. // never write the user's harness home.
  379. { id: 'storage-json', config: { root: join(workspaceCwd, '.dsh-storages') } },
  380. // Skill discovery is model-visible input. Pin every host-level root inside
  381. // the owned temp world so ~/.dsh, ~/.agents, and a bundled-root env setting
  382. // cannot change replay requests or conversation goldens. Project roots stay
  383. // enabled against the same empty temp workspace, preserving the real seam.
  384. {
  385. id: 'skill-local',
  386. config: {
  387. dshHome: join(workspaceCwd, '.dsh-home'),
  388. agentsHome: join(workspaceCwd, '.agents-home'),
  389. bundledSkillDir: join(workspaceCwd, '.bundled-skills'),
  390. watch: false,
  391. },
  392. },
  393. // fs/bash cwd default to process.cwd(); the gateway injects the same
  394. // value into session.cwd — chdir below anchors all three to the temp
  395. // workspace, keeping the composition untouched.
  396. { id: 'workspace-context', disabled: true },
  397. { id: 'session-title-llm', disabled: true },
  398. // Fixture sessions must never leave the process: the shipped row defaults
  399. // to the production OTLP endpoint (or whatever DSH_TELEMETRY_OTLP_URL
  400. // names in the ambient environment). A scenario that pins a real backend
  401. // disclosure passes a local dead endpoint instead of disabling the row.
  402. options.telemetryUrl === undefined
  403. ? { id: 'telemetry-otel', disabled: true }
  404. : { id: 'telemetry-otel', config: { exporter: { url: options.telemetryUrl }, shutdownTimeoutMillis: 1_000 } },
  405. {
  406. id: 'webserver',
  407. config: { host: '127.0.0.1', port: 0 },
  408. },
  409. // The bundle's web-runtime row resolves the same built dist under test
  410. // (apps/web IS @deepseek-ai/dsh-frontend); only the URL line is silenced.
  411. // Preserve the composed surface-context choice because a patch replaces
  412. // the row's complete config.
  413. { id: 'web-runtime', config: { printUrl: false, surfaceContext } },
  414. ...options.remoteAuthority === undefined
  415. ? []
  416. : [{ id: 'connection', config: { trustedHosts: [options.remoteAuthority] } }],
  417. { id: 'settings', config: { dshHome: harnessHome } },
  418. { id: 'credentials', config: { dshHome: harnessHome } },
  419. // The shipped directory-picker row is the -auto chooser, which resolves
  420. // the interaction from the RUNNING host (display, SSH launch, bind). The
  421. // lane's goldens are interaction-specific (workspace-management drives
  422. // the in-app browse dialog), so pin -browse deterministically on every
  423. // host: patch `name` is an assertion, not an override, hence the
  424. // disable+insert pair.
  425. { id: 'directory-picker', disabled: true },
  426. { insert: [
  427. { id: 'directory-picker-browse', name: '@deepseek-ai/dsh-host-directory-picker-browse' },
  428. { id: 'ui-directory-picker', name: '@deepseek-ai/dsh-client-ui-directory-picker' },
  429. ] },
  430. ...options.agentPresets === undefined
  431. ? []
  432. : [{ id: 'agent-presets', config: options.agentPresets }],
  433. ...options.toolsMode === undefined ? [] : [{ id: 'tools', config: { mode: options.toolsMode } }],
  434. ...options.cordisTools === true
  435. ? [{ insert: [{ id: 'tool-cordis', name: 'cordis:tool-cordis' }] }]
  436. : [],
  437. ...options.deepSeekSearch === undefined
  438. ? []
  439. : [{
  440. id: 'web-search-deepseek',
  441. config: {
  442. apiKeyEnv: options.deepSeekSearch.apiKeyEnv,
  443. baseURL: options.deepSeekSearch.baseURL,
  444. },
  445. }],
  446. ...mode === 'record' || options.deepSeekMissingCredential === true
  447. ? []
  448. : [{ id: 'llm-deepseek', disabled: true }],
  449. ]
  450. // Sessions inherit the gateway's process.cwd() default; run the boot from
  451. // the temp workspace so tool cwd, session cwd, and fixtures agree.
  452. const originalCwd = process.cwd()
  453. const ctx = new Context()
  454. let port = 0
  455. let replayHandle: ReplayHandle | undefined
  456. try {
  457. process.chdir(workspaceCwd)
  458. // The production module-resolution setup: an empty profile root inside the temp
  459. // harness home, with bare plugin names resolving through the flat module
  460. // fallback the launcher heals under <home>/profiles.
  461. healProfilesModuleFallback(INSTALL_ANCHOR, harnessHome)
  462. const profileDir = join(harnessHome, 'profiles', 'scaffold')
  463. await mkdir(profileDir, { recursive: true })
  464. const rootConfig = join(profileDir, 'cordis.yml')
  465. await writeFile(rootConfig, '[]\n')
  466. ctx.baseUrl = pathToFileURL(profileDir).href + '/'
  467. // This direct Loader harness supplies the same root-path capability as app-boot.
  468. ctx.provide('dshHomePath', dshHomePath)
  469. // A host with no command line still provides one: the web bundle's startup
  470. // row releases the rows waiting on it, and with no arguments each starts on
  471. // the values this scaffold composed above. An exit request can only come
  472. // from a rejected argument, which a fixed empty list has none of.
  473. provideCmdline(ctx, {
  474. args: [],
  475. exit: (code) => {
  476. throw new Error(`web e2e scaffold: the web app requested exit ${String(code)} with no arguments to reject`)
  477. },
  478. })
  479. await ctx.plugin(Loader)
  480. ctx.loader.builtins.include = Include
  481. // `cordis:group` beside it, exactly as `boot()` registers it: a group row is
  482. // how a preset gives one `isolate` realm to a provider and its consumers,
  483. // and a preset resolving package names from its own directory cannot reach
  484. // `@deepseek-ai/cordis-plugin-group` by name.
  485. ctx.loader.builtins.group = Group
  486. // The shipped CLI deliberately has no dependency on this opt-in package.
  487. // Keep the Loader row real without broadening the product installation.
  488. if (options.cordisTools === true) ctx.loader.builtins['tool-cordis'] = ToolCordis
  489. await ctx.loader.create({
  490. name: 'cordis:include',
  491. config: { path: pathToFileURL(rootConfig).href, patches },
  492. })
  493. await ctx.loader.await()
  494. assertEntriesLoaded(ctx, 'web e2e scaffold')
  495. if (options.welcomeNoticePending !== true) {
  496. await ctx.settings.mutate(settingsNamespace(WELCOME_NOTICE_SETTINGS_NAMESPACE), [{
  497. op: 'set', path: [WELCOME_NOTICE_ACK_FIELD], value: WELCOME_NOTICE_VERSION,
  498. }])
  499. }
  500. const boundPort = ctx.get('httpServer')?.port
  501. if (boundPort === undefined) {
  502. throw new Error('web e2e scaffold: httpServer service missing after settled boot')
  503. }
  504. port = boundPort
  505. // Fill the open llm seam on the settled root ctx. Ordinary keyless modes
  506. // disable llm-deepseek; the first-run lane keeps it mounted but has no
  507. // replay fixture and never streams. The direct install, unlike the plugin
  508. // row, returns the ReplayHandle for the teardown consumption check.
  509. if (mode !== 'record' && options.replayFixture !== undefined) {
  510. replayHandle = installLlmReplay(ctx, {
  511. file: options.replayFixture,
  512. providers: replayProviders(options.replayContextWindow),
  513. ...(options.replayOverride === undefined ? {} : { overrideFile: options.replayOverride }),
  514. ...(options.replayChildFixtures === undefined ? {} : { childFiles: options.replayChildFixtures }),
  515. ...(options.paceMs === undefined ? {} : { paceMs: options.paceMs }),
  516. })
  517. } else if (mode !== 'record' && options.deepSeekMissingCredential !== true) {
  518. // No fixture and no shipped adapter would leave the tree with ZERO
  519. // provider routes — a state no product composition has, and one the
  520. // composer refuses to type into. Register the same routes
  521. // a fixture would, with streaming that still fails loud: the scenario
  522. // issues no model calls, and one that slipped in must not pass quietly.
  523. ctx.effect(() => ctx.llm.registerAdapter(
  524. replayProviders(options.replayContextWindow).map(provider => provider.id),
  525. new RouteOnlyAdapter(replayProviders(options.replayContextWindow)),
  526. ), 'web e2e scaffold: route-only adapter')
  527. }
  528. } catch (error) {
  529. if (process.cwd() !== originalCwd) process.chdir(originalCwd)
  530. const cleanupFailures = await cleanupScaffoldWorld(ctx, workspaceCwd, persistenceRoot)
  531. restoreCredentialEnvironment()
  532. restoreSkillRootEnvironment()
  533. if (cleanupFailures.length > 0) {
  534. throw new AggregateError([error, ...cleanupFailures], 'web scaffold setup failed and cleanup was incomplete')
  535. }
  536. throw error
  537. } finally {
  538. if (process.cwd() !== originalCwd) process.chdir(originalCwd)
  539. }
  540. return {
  541. harnessHome,
  542. mode,
  543. baseUrl: `http://${browserHost}:${port}`,
  544. ctx,
  545. workspaceCwd,
  546. persistenceRoot,
  547. // Barrier stack: the in-process turn/end identifies the session, its
  548. // explicit flush makes the transcript durable, and the caller's browser
  549. // settled-poll comes last because host completion strictly precedes render.
  550. whenTurnSettled(timeoutMs = mode === 'record' ? 180_000 : 30_000): Promise<SessionId> {
  551. return new Promise<SessionId>((resolveSettled, reject) => {
  552. const timer = setTimeout(() => {
  553. off()
  554. reject(new Error(`no turn/end within ${timeoutMs}ms`))
  555. }, timeoutMs)
  556. const off = ctx.on('session/event', (session: Session, event: SessionEvent) => {
  557. if (event.type !== 'turn/end') return
  558. clearTimeout(timer)
  559. off()
  560. ctx.sessions.flush(session)
  561. .then(() => { resolveSettled(session.id) }, reject)
  562. })
  563. })
  564. },
  565. async close(): Promise<void> {
  566. const failures: unknown[] = []
  567. // Fixture-consumption check first, while the run's binding state is
  568. // still authoritative — a scenario that drove fewer model calls than
  569. // recorded fails here instead of drifting green.
  570. try {
  571. replayHandle?.assertConsumed()
  572. } catch (error) {
  573. failures.push(error)
  574. }
  575. try {
  576. failures.push(...await cleanupScaffoldWorld(ctx, workspaceCwd, persistenceRoot))
  577. } finally {
  578. restoreCredentialEnvironment()
  579. restoreSkillRootEnvironment()
  580. }
  581. if (failures.length > 0) throw new AggregateError(failures, 'web scaffold teardown failed')
  582. },
  583. }
  584. }
  585. /**
  586. * Serialize a live session to the canonical raw session-JSONL layout — the
  587. * in-memory record-mode harvest, so the on-disk zstd default never matters.
  588. */
  589. function rawSessionLog(session: Session): string {
  590. return [
  591. JSON.stringify({ type: 'session', ...session.header }),
  592. ...packChunkRuns(session.events).map(record => JSON.stringify(record)),
  593. '',
  594. ].join('\n')
  595. }
  596. /**
  597. * Record-mode fixture write-back: harvest the live session, scrub request
  598. * headers to {{system}}/{{tools}} (TODO(web-header-pin): the web lane pins no
  599. * header class — a deliberate deviation logged in the Agent Note's deferred
  600. * work), tokenize the run-local session id, cwd, and browser RPC id
  601. * ({{sessionId}}/{{cwd}}/{{rpcId}}, the committed fixture convention —
  602. * re-records then diff only on real content), and write the fixture.
  603. * @param scaffold - the record-mode scaffold.
  604. * @param sessionId - the driven session.
  605. * @param fixturePath - the committed session.jsonl / seed.jsonl target.
  606. */
  607. export async function recordFixture(scaffold: WebScaffold, sessionId: SessionId, fixturePath: string): Promise<void> {
  608. const agent = scaffold.ctx.agents.get(sessionId)
  609. if (agent === undefined) throw new Error(`record harvest: no live agent for ${sessionId}`)
  610. const fresh = scrubRequestHeaders(rawSessionLog(agent.session))
  611. .split(sessionId).join('{{sessionId}}')
  612. .split(scaffold.workspaceCwd).join('{{cwd}}')
  613. .replace(/"rpcId":"[^"]+"/g, '"rpcId":"{{rpcId}}"')
  614. const existing = existsSync(fixturePath) ? await readFile(fixturePath, 'utf8') : ''
  615. const stable = stabilizeFixtureMessageIds([fresh], [existing])[0]
  616. if (stable === undefined) throw new Error('record harvest: no stabilized fixture')
  617. await writeFile(fixturePath, stable)
  618. }
  619. /**
  620. * The user prompts recorded in a fixture, in order — the single source tying
  621. * spec drive steps to recorded reality so script and fixture cannot drift.
  622. * @param fixtureText - raw session.jsonl contents.
  623. * @returns the recorded user prompt texts.
  624. */
  625. export function fixtureUserPrompts(fixtureText: string): string[] {
  626. return parseSessionLog(fixtureText).flatMap((event) => {
  627. if (event.type !== 'user/message' || event.data.source.kind !== 'user') return []
  628. const text = event.data.content.filter(block => block.type === 'text').map(block => block.text).join('')
  629. return text.length > 0 ? [text] : []
  630. })
  631. }
  632. /**
  633. * Seed a recorded session fixture into the scaffold's persistence root
  634. * through the REAL backend API (throwaway Context + SessionStore + JSONL
  635. * plugin — the semantic-checkpoint precedent), never raw file writes: no
  636. * knowledge of bucket hashing, filename encoding, or compression, and
  637. * malformed session events fail loud at seed time. The fixture's tokenized identity
  638. * ({{sessionId}}/{{cwd}}) is realized for this world before parsing.
  639. * @param scaffold - the target scaffold.
  640. * @param fixtureText - raw recorded session.jsonl contents.
  641. * @param id - the seeded session id (stable for deterministic goldens).
  642. * @param agentPreset - the preset the recorded session was composed from,
  643. * for scenarios asserting what a resumed session reports running.
  644. * @returns the seeded id.
  645. */
  646. /**
  647. * Realize a recorded seed fixture against one scaffold: substitute the
  648. * `{{sessionId}}`/`{{cwd}}` placeholders and rewrite the recorded cwd to the
  649. * scaffold's workspace. Idempotent, so a caller may realize early (e.g. to
  650. * price content exactly as the host will fold it) and still pass the result
  651. * through {@link seedSession}.
  652. * @param scaffold - the booted scaffold whose workspace the seed targets.
  653. * @param fixtureText - the committed seed fixture text.
  654. * @param id - the session id the seed is realized for.
  655. * @returns the realized fixture text.
  656. */
  657. export function realizeSeedFixture(scaffold: WebScaffold, fixtureText: string, id: string): string {
  658. const realized = fixtureText
  659. .split('{{sessionId}}').join(id)
  660. .split('{{cwd}}').join(scaffold.workspaceCwd)
  661. const fixtureCwd = (JSON.parse(realized.split('\n', 1)[0]!) as { cwd?: string }).cwd
  662. return fixtureCwd === undefined
  663. ? realized
  664. : realized.split(fixtureCwd).join(scaffold.workspaceCwd)
  665. }
  666. export async function seedSession(
  667. scaffold: WebScaffold,
  668. fixtureText: string,
  669. id: string,
  670. agentPreset?: string,
  671. ): Promise<SessionId> {
  672. const events = parseSessionLog(realizeSeedFixture(scaffold, fixtureText, id))
  673. if (events.length === 0) throw new Error('seed fixture has no events')
  674. const last = events[events.length - 1]!
  675. // An open final turn would be mutated by resume's crash repair on first
  676. // open; a committed seed must be a closed recording.
  677. if (last.type !== 'turn/end') throw new Error(`seed fixture must end in turn/end, got ${last.type}`)
  678. const meta: SessionHeader = {
  679. version: SESSION_FORMAT_VERSION,
  680. id: SessionId(id),
  681. createdAt: Date.now() - 60_000,
  682. cwd: scaffold.workspaceCwd,
  683. delegationDepth: 0,
  684. ...agentPreset === undefined ? {} : { agentPreset },
  685. }
  686. const seeder = new Context()
  687. try {
  688. await seeder.plugin(SessionStore)
  689. // Same root as the booted tree with the plugin's own default compression,
  690. // so the host's directory-scan list() sees one consistent encoding.
  691. await seeder.plugin(SessionPersistenceJsonl, { root: scaffold.persistenceRoot })
  692. await seeder.sessionPersistence.create(meta)
  693. await seeder.sessionPersistence.append(meta.id, events)
  694. // Deterministic sidebar order: cold summaries take updatedAt from mtime.
  695. const located = seeder.sessionPersistence.locate(meta)
  696. if (located !== undefined) {
  697. const backdated = new Date(meta.createdAt)
  698. await utimes(located.path, backdated, backdated)
  699. }
  700. } finally {
  701. await seeder.fiber.dispose()
  702. }
  703. return meta.id
  704. }
  705. /**
  706. * Normalize an aria snapshot: uuid, cwd, workspace-basename, duration,
  707. * decode-throughput, and path-sensitive compaction estimates collapse to
  708. * stable tokens.
  709. *
  710. * Throughput needs a token for the same reason durations do, and no fixture
  711. * can supply one: the figure divides a replayed step's output tokens by the
  712. * wall time the local run took to stream them, so it moves between two runs
  713. * on one machine (measured 69 → 70 tok/s) and swings wildly on a fast replay
  714. * (26333 tok/s for a 3 ms stream).
  715. */
  716. function normalizeAria(snapshot: string, workspaceCwd: string): string {
  717. // The session heading renders the workspace's basename, not the full
  718. // path, so both spellings must collapse to the token.
  719. const base = workspaceCwd.split('/').pop()!
  720. return snapshot
  721. .split(workspaceCwd).join('{{cwd}}')
  722. .split(base).join('{{workspace}}')
  723. .replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi, '{{uuid}}')
  724. // The optional space in `\d+m ?\d+s` covers both minute spellings: the
  725. // stats line's compact `2m42s` and the message-chrome template's `2m 42s`.
  726. .replace(
  727. /~\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,
  728. duration => duration.startsWith('~') ? duration : '{{duration}}',
  729. )
  730. .replace(
  731. /约\d+(?:年(?:\d+个月)?|个月(?:\d+天)?)|\d+(?:天(?:\d+小时(?:\d+分\d+秒)?)?|小时\d+分\d+秒|分\d+秒|(?:\.\d+)?秒)/g,
  732. duration => duration.startsWith('约') ? duration : '{{duration}}',
  733. )
  734. .replace(/\d+(?:\.\d+)?(?= tok\/s(?!\w))/g, '{{throughput}}')
  735. // Seeded compaction prices realized file paths, whose length differs
  736. // between local worktrees and CI scratch directories.
  737. .replace(/(Compacted \d+ history items \(~)\d+( tokens\))/g, '$1{{tokens}}$2')
  738. // Message IconActions clocks widen by calendar day/year; collapse every
  739. // format so goldens stay stable across midnight and year changes.
  740. .replace(/\d{4}年\d{1,2}月\d{1,2}日 \d{2}:\d{2}/g, '{{clock}}')
  741. .replace(/\d{1,2}月\d{1,2}日 \d{2}:\d{2}/g, '{{clock}}')
  742. .replace(/(?<!\d)\d{1,2}:\d{2}:\d{2}(?:\.\d+)?(?:\s*[AP]M)?(?!\d)/gi, '{{clock}}')
  743. .replace(/(?<!\d)\d{2}:\d{2}(?!\d)/g, '{{clock}}')
  744. }
  745. /**
  746. * Capture the region's aria snapshot at a settled milestone: poll until two
  747. * consecutive normalized captures are equal — a single-shot capture races the
  748. * last React commits.
  749. * @param page - the page under test.
  750. * @param selector - the region locator selector.
  751. * @param workspaceCwd - normalization input.
  752. * @returns the stable normalized snapshot.
  753. */
  754. export async function captureStableAria(page: Page, selector: string, workspaceCwd: string): Promise<string> {
  755. const region = page.locator(selector).first()
  756. let previous = normalizeAria(await region.ariaSnapshot(), workspaceCwd)
  757. await expect.poll(async () => {
  758. const current = normalizeAria(await region.ariaSnapshot(), workspaceCwd)
  759. const stable = current === previous
  760. previous = current
  761. return stable
  762. }, { timeout: 5_000, message: 'aria snapshot did not stabilize' }).toBe(true)
  763. return previous
  764. }
  765. /**
  766. * Compare a normalized golden, or rewrite it under refresh. Refresh is the
  767. * ONLY writer: a missing golden in replay mode fails with the healing command
  768. * instead of silently self-bootstrapping.
  769. * @param goldenPath - the committed ui.expected.md path.
  770. * @param actual - the stable normalized snapshot.
  771. * @param mode - the active snapshot mode.
  772. */
  773. export async function compareOrRefreshGolden(goldenPath: string, actual: string, mode: WebSnapshotMode): Promise<void> {
  774. const payload = `${actual}\n`
  775. if (mode === 'refresh') {
  776. await writeFile(goldenPath, payload)
  777. return
  778. }
  779. if (!existsSync(goldenPath)) {
  780. throw new Error(`missing golden ${goldenPath} — run DSH_SNAPSHOT=refresh pnpm run test:web to generate it`)
  781. }
  782. expect(payload).toBe(await readFile(goldenPath, 'utf8'))
  783. }
  784. /**
  785. * Fixture-inventory guard: the scenario directory holds exactly the expected
  786. * files and every committed JSONL is a scrub fixed-point without a run-local
  787. * browser RPC id.
  788. * @param dir - the scenario snapshot directory.
  789. * @param expected - the exact expected file inventory.
  790. */
  791. export async function assertFixtureInventory(dir: string, expected: string[]): Promise<void> {
  792. const entries = (await readdir(dir)).sort()
  793. expect(entries).toEqual([...expected].sort())
  794. for (const entry of entries.filter(name => name.endsWith('.jsonl'))) {
  795. const content = await readFile(join(dir, entry), 'utf8')
  796. expect(scrubRequestHeaders(content), `${dir}/${entry} carries request-header bulk`).toBe(content)
  797. expect(content, `${dir}/${entry} carries a run-local rpcId`)
  798. .not.toMatch(/"rpcId":"(?!\{\{rpcId\}\})[^"]+"/)
  799. }
  800. }
  801. /**
  802. * Console tripwires: reconnect/gap-repair self-healing or a pageerror must
  803. * fail the scenario, not mask a dead wire behind eventual consistency.
  804. * @param page - the page under test.
  805. * @returns live warning/pageerror collectors to assert empty at scenario end.
  806. */
  807. export function watchConsole(page: Page): { warnings: string[]; pageErrors: string[] } {
  808. const warnings: string[] = []
  809. const pageErrors: string[] = []
  810. page.on('console', (message) => {
  811. const text = message.text()
  812. if (/connection lost|gap repair|discontinuous/i.test(text)) warnings.push(text)
  813. })
  814. page.on('pageerror', (error) => { pageErrors.push(String(error)) })
  815. return { warnings, pageErrors }
  816. }
  817. /**
  818. * Remove only connection-loss warnings emitted after an intentional reload.
  819. * Earlier warnings and all gap-repair/discontinuity warnings remain fatal.
  820. * @param tripwire - the live console-warning collector.
  821. * @param warningStart - warning count captured immediately before reloading.
  822. */
  823. export function acknowledgeReloadConnectionLoss(
  824. tripwire: ReturnType<typeof watchConsole>,
  825. warningStart: number,
  826. ): void {
  827. const reloadWarnings = tripwire.warnings.splice(warningStart)
  828. tripwire.warnings.push(...reloadWarnings.filter(text => !/connection lost/i.test(text)))
  829. }