smoke-real.e2e.ts 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662
  1. // Real-host smoke: spawn `dsh web` with a real key, walk the full flow
  2. // list in a real chromium, screenshot every screen into .artifacts/ for the
  3. // figma comparison pass. Self-skips without DEEPSEEK_API_KEY (repo e2e
  4. // convention); vitest.web.config.ts loads the repo-root .env before this file
  5. // runs (the CLI only auto-loads .env from its cwd — a temp dir here, so
  6. // sessions never land in the repo's .sessions).
  7. //
  8. // Selector convention: CSS Modules hash as [hash]_[local], so class-substring
  9. // selectors are unreliable — anchor on data-* attributes (data-variant /
  10. // data-sample) or visible text. The one [class*=] use below
  11. // (frame/handle) rides local names that survive hashing as suffixes; prefer
  12. // data-* for anything new.
  13. //
  14. // Flow order matters: chat rounds first (the bash round reuses the first
  15. // send's session), geometry and theme after, reload recovery last. Tests run
  16. // sequentially in-file.
  17. import type { ChildProcess } from 'node:child_process'
  18. import { spawn } from 'node:child_process'
  19. import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
  20. import { createServer } from 'node:http'
  21. import { createRequire } from 'node:module'
  22. import { tmpdir } from 'node:os'
  23. import { join } from 'node:path'
  24. import { fileURLToPath, pathToFileURL } from 'node:url'
  25. import type { Browser, Page } from 'playwright'
  26. import { chromium } from 'playwright'
  27. import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
  28. import { REPO_ROOT, connectFreshWorkspace, newEnglishPage, probeFreePort, requireDist, saveFailureShot } from './support.ts'
  29. const WEB_SURFACE_PROMPT = fileURLToPath(new URL('./snapshots/web-runtime-context/web-surface-prompt.expected.md', import.meta.url))
  30. function waitForReadyLine(child: ChildProcess): Promise<string> {
  31. return new Promise((resolveReady, reject) => {
  32. let out = ''
  33. const timer = setTimeout(() => { reject(new Error(`dsh web not ready in 90s; output:\n${out}`)) }, 90_000)
  34. const onData = (chunk: Buffer): void => {
  35. out += chunk.toString()
  36. const match = /dsh web: (http:\/\/[^\s]+)/.exec(out)
  37. if (match?.[1] !== undefined) {
  38. clearTimeout(timer)
  39. resolveReady(match[1])
  40. }
  41. }
  42. child.stdout?.on('data', onData)
  43. child.stderr?.on('data', onData)
  44. child.once('exit', (code) => {
  45. clearTimeout(timer)
  46. reject(new Error(`dsh web exited early (code ${code}); output:\n${out}`))
  47. })
  48. })
  49. }
  50. async function rpc<T>(baseUrl: string, method: string, payload: unknown): Promise<T> {
  51. const response = await fetch(`${baseUrl}/api/${method}`, {
  52. method: 'POST',
  53. headers: { 'content-type': 'application/json' },
  54. body: JSON.stringify({
  55. type: 'client-request',
  56. rpcId: `smoke-${method}`,
  57. method,
  58. payload,
  59. }),
  60. })
  61. if (!response.ok) throw new Error(`${method} failed over HTTP ${response.status}: ${await response.text()}`)
  62. const body = await response.json() as {
  63. result: { ok: true; value: T } | { ok: false; error: { code: string; message: string } }
  64. }
  65. if (!body.result.ok) throw new Error(`${method} failed: ${body.result.error.code}: ${body.result.error.message}`)
  66. return body.result.value
  67. }
  68. interface HistoryPage {
  69. events: { event: { type: string; data: unknown } }[]
  70. hasMore: boolean
  71. }
  72. function isRecord(value: unknown): value is Record<string, unknown> {
  73. return typeof value === 'object' && value !== null
  74. }
  75. function providerTitle(page: HistoryPage): string | undefined {
  76. for (let index = page.events.length - 1; index >= 0; index--) {
  77. const event = page.events[index]!.event
  78. if (event.type !== 'session/title' || !isRecord(event.data)) continue
  79. const source = event.data.source
  80. if (typeof event.data.title === 'string' && isRecord(source) && source.kind === 'provider') {
  81. return event.data.title
  82. }
  83. }
  84. return undefined
  85. }
  86. function hasAssistantMarker(page: HistoryPage, marker: string): boolean {
  87. return page.events.some(({ event }) => {
  88. if (event.type !== 'assistant/message' || !isRecord(event.data) || !isRecord(event.data.message)) return false
  89. const content = event.data.message.content
  90. if (!Array.isArray(content)) return false
  91. return content.some(block =>
  92. isRecord(block) && block.type === 'text' && typeof block.text === 'string' && block.text.includes(marker))
  93. })
  94. }
  95. async function history(baseUrl: string, sessionId: string): Promise<HistoryPage> {
  96. return rpc<HistoryPage>(baseUrl, 'session.history', { sessionId, maxMessages: 10 })
  97. }
  98. async function waitForProviderTitle(baseUrl: string, sessionId: string): Promise<string> {
  99. let observed: string | undefined
  100. await expect.poll(async () => {
  101. observed = providerTitle(await history(baseUrl, sessionId))
  102. return observed
  103. }, { timeout: 90_000 }).toEqual(expect.any(String))
  104. if (observed === undefined) throw new Error('provider-backed session title was not observed')
  105. return observed
  106. }
  107. async function waitForAssistantMarker(baseUrl: string, sessionId: string, marker: string): Promise<void> {
  108. await expect.poll(async () => hasAssistantMarker(await history(baseUrl, sessionId), marker), {
  109. timeout: 120_000,
  110. }).toBe(true)
  111. }
  112. /** Real-host smoke screenshot: evidence for the figma comparison, not a failure artifact. */
  113. async function screen(page: Page, name: string): Promise<void> {
  114. await page.screenshot({ path: join(REPO_ROOT, '.artifacts', `w5-${name}.png`) })
  115. }
  116. /** First column track (px string) of the frame grid. */
  117. async function firstTrack(page: Page): Promise<string> {
  118. return (await page.locator('[class*="frame"]').evaluate(
  119. el => getComputedStyle(el).gridTemplateColumns)).split(' ')[0]!
  120. }
  121. /** Last column track (details) as a number of pixels. */
  122. async function detailsTrack(page: Page): Promise<number> {
  123. const cols = await page.locator('[class*="frame"]').evaluate(
  124. el => getComputedStyle(el).gridTemplateColumns)
  125. return Number(cols.split(' ').pop()!.replace('px', ''))
  126. }
  127. // Readiness gate: `dsh web` serves all ten production manifest plugins; until every UI
  128. // plugin's client bundle exists and exports apply, the loader fail-louds and
  129. // the frame never appears.
  130. const UI_PLUGIN_DIRS = [
  131. 'connection', 'runtime', 'ui-theme', 'locale', 'ui-layout', 'ui-sidebar',
  132. 'ui-settings', 'ui-settings-general', 'ui-models', 'ui-conversation',
  133. 'ui-model', 'ui-question', 'ui-trajectory',
  134. ]
  135. const ROUND_DONE_MARKER = 'WEB_ROUND_DONE'
  136. const notReady = UI_PLUGIN_DIRS.filter((dir) => {
  137. const bundle = join(REPO_ROOT, 'packages/client', dir, 'lib/client.js')
  138. return !existsSync(bundle) || !readFileSync(bundle, 'utf8').includes('exports.apply')
  139. })
  140. if (notReady.length > 0) console.warn(`[smoke-real] skipped — client bundles not ready: ${notReady.join(', ')}`)
  141. describe('dsh web keyless CLI smoke', () => {
  142. it('listens on 127.0.0.1 by default', async () => {
  143. requireDist()
  144. const sessionsDir = mkdtempSync(join(tmpdir(), 'dsh-web-keyless-'))
  145. const tsxLoader = pathToFileURL(createRequire(join(REPO_ROOT, 'package.json')).resolve('tsx')).href
  146. const child = spawn(
  147. process.execPath,
  148. ['--import', tsxLoader, join(REPO_ROOT, 'apps/cli/src/bin.ts'), 'web', '--port', '0'],
  149. {
  150. cwd: sessionsDir,
  151. env: {
  152. ...process.env,
  153. DEEPSEEK_API_KEY: 'keyless-web-no-call',
  154. DSH_HOME: join(sessionsDir, '.dsh'),
  155. DSH_AGENTS_HOME: join(sessionsDir, '.agents'),
  156. TSX_TSCONFIG_PATH: join(REPO_ROOT, 'tsconfig.json'),
  157. },
  158. stdio: ['ignore', 'pipe', 'pipe'],
  159. },
  160. )
  161. try {
  162. const readyUrl = await waitForReadyLine(child)
  163. expect(readyUrl).toMatch(/^http:\/\/127\.0\.0\.1:\d+$/)
  164. expect((await fetch(readyUrl)).status).toBe(200)
  165. } finally {
  166. const closed = child.exitCode === null
  167. ? new Promise<void>((resolveClose) => { child.once('close', () => { resolveClose() }) })
  168. : Promise.resolve()
  169. if (child.exitCode === null) child.kill('SIGTERM')
  170. await closed
  171. rmSync(sessionsDir, { recursive: true, force: true })
  172. }
  173. })
  174. it('routes web runtime context and workspace instructions through the real CLI request', async () => {
  175. requireDist()
  176. const workspace = mkdtempSync(join(tmpdir(), 'dsh-web-workspace-'))
  177. mkdirSync(join(workspace, '.git'))
  178. writeFileSync(join(workspace, 'AGENTS.md'), 'web-workspace-context-probe\n')
  179. interface NativeProviderRequest {
  180. messages?: { role?: string; content?: string }[]
  181. tools?: { function?: { name?: string } }[]
  182. }
  183. let resolveProviderRequests!: (requests: NativeProviderRequest[]) => void
  184. const requests: NativeProviderRequest[] = []
  185. const providerRequests = new Promise<NativeProviderRequest[]>((resolve) => {
  186. resolveProviderRequests = resolve
  187. })
  188. const provider = createServer((request, response) => {
  189. let body = ''
  190. request.setEncoding('utf8')
  191. request.on('data', (chunk: string) => { body += chunk })
  192. request.on('end', () => {
  193. const parsed = JSON.parse(body) as NativeProviderRequest
  194. if ((parsed.tools?.length ?? 0) > 0) requests.push(parsed)
  195. if (requests.length === 1) resolveProviderRequests(requests)
  196. response.writeHead(200, { 'content-type': 'text/event-stream' })
  197. response.end([
  198. 'data: {"choices":[{"delta":{"role":"assistant","content":null,"reasoning_content":""}}]}',
  199. 'data: {"choices":[{"delta":{"content":"done"}}]}',
  200. 'data: {"choices":[{"delta":{"content":""},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":1}}',
  201. 'data: [DONE]',
  202. '',
  203. ].join('\n\n'))
  204. })
  205. })
  206. await new Promise<void>(resolve => provider.listen(0, '127.0.0.1', resolve))
  207. const address = provider.address()
  208. if (address === null || typeof address === 'string') throw new Error('mock provider did not bind a TCP port')
  209. const tsxLoader = pathToFileURL(createRequire(join(REPO_ROOT, 'package.json')).resolve('tsx')).href
  210. const child = spawn(
  211. process.execPath,
  212. ['--import', tsxLoader, join(REPO_ROOT, 'apps/cli/src/bin.ts'), 'web', '--port', '0'],
  213. {
  214. cwd: workspace,
  215. env: {
  216. ...process.env,
  217. DEEPSEEK_API_KEY: 'keyless-web-workspace',
  218. DEEPSEEK_BASE_URL: `http://127.0.0.1:${address.port}`,
  219. DSH_HOME: join(workspace, '.dsh'),
  220. DSH_AGENTS_HOME: join(workspace, '.agents'),
  221. TSX_TSCONFIG_PATH: join(REPO_ROOT, 'tsconfig.json'),
  222. },
  223. stdio: ['ignore', 'pipe', 'pipe'],
  224. },
  225. )
  226. try {
  227. const baseUrl = await waitForReadyLine(child)
  228. const created = await rpc<{ sessionId: string }>(baseUrl, 'session.create', {})
  229. await rpc<{ accepted: true }>(baseUrl, 'session.prompt', {
  230. sessionId: created.sessionId,
  231. mode: 'queue',
  232. content: [{ type: 'text', text: 'go' }],
  233. })
  234. const capturedRequests = await Promise.race([
  235. providerRequests,
  236. new Promise<never>((_resolve, reject) => {
  237. setTimeout(() => { reject(new Error('provider request not received in 10s')) }, 10_000).unref()
  238. }),
  239. ])
  240. const captured = capturedRequests[0]
  241. if (captured === undefined) {
  242. throw new Error('provider did not receive the workspace projection request')
  243. }
  244. const workspaceMessage = captured.messages?.find(message =>
  245. message.role === 'user' && message.content?.includes('web-workspace-context-probe'))
  246. const systemMessage = captured.messages?.find(message => message.role === 'system')
  247. const expectedWebSection = readFileSync(WEB_SURFACE_PROMPT, 'utf8').trimEnd()
  248. .replace('{{webUrl}}', baseUrl)
  249. expect(systemMessage?.content).toContain(expectedWebSection)
  250. expect(workspaceMessage).toMatchInlineSnapshot(`
  251. {
  252. "content": "<system-reminder>
  253. The following workspace instructions may be relevant to your work. Use them as guidance when applicable. More specific instructions take precedence over broader ones. They do not override system, developer, or direct user instructions.
  254. Instructions from: AGENTS.md
  255. web-workspace-context-probe
  256. </system-reminder>",
  257. "role": "user",
  258. }
  259. `)
  260. expect(captured.tools?.map(tool => tool.function?.name)
  261. .filter(name => name === 'web_search' || name === 'web_fetch'))
  262. .toMatchInlineSnapshot(`
  263. [
  264. "web_search",
  265. ]
  266. `)
  267. } finally {
  268. const closed = child.exitCode === null
  269. ? new Promise<void>((resolveClose) => { child.once('close', () => { resolveClose() }) })
  270. : Promise.resolve()
  271. if (child.exitCode === null) child.kill('SIGTERM')
  272. await closed
  273. await new Promise<void>(resolveClose => provider.close(() => { resolveClose() }))
  274. rmSync(workspace, { recursive: true, force: true })
  275. }
  276. })
  277. it('retries a partial transport failure through the shipped Web composition', async () => {
  278. requireDist()
  279. const workspace = mkdtempSync(join(tmpdir(), 'dsh-web-retry-'))
  280. const promptMarker = 'WEB_RETRY_REQUEST'
  281. const recoveredMarker = 'WEB_RETRY_RECOVERED'
  282. let mainAttempts = 0
  283. const provider = createServer((request, response) => {
  284. let body = ''
  285. request.setEncoding('utf8')
  286. request.on('data', (chunk: string) => { body += chunk })
  287. request.on('end', () => {
  288. const parsed = JSON.parse(body) as { max_tokens?: number; messages?: unknown[] }
  289. const titleRequest = parsed.max_tokens === 64
  290. const mainRequest = !titleRequest && body.includes(promptMarker)
  291. response.writeHead(200, { 'content-type': 'text/event-stream' })
  292. if (!mainRequest) {
  293. response.end([
  294. 'data: {"choices":[{"delta":{"content":"Web retry title"}}]}',
  295. 'data: {"choices":[{"delta":{"content":""},"finish_reason":"stop"}],"usage":{"prompt_tokens":1,"completion_tokens":1}}',
  296. 'data: [DONE]',
  297. '',
  298. ].join('\n\n'))
  299. return
  300. }
  301. mainAttempts++
  302. if (mainAttempts === 1) {
  303. response.write('data: {"choices":[{"delta":{"content":"WEB_RETRY_DISCARDED"}}]}\n\n')
  304. setTimeout(() => { response.destroy() }, 20)
  305. return
  306. }
  307. response.end([
  308. `data: {"choices":[{"delta":{"content":"${recoveredMarker}"}}]}`,
  309. 'data: {"choices":[{"delta":{"content":""},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":1}}',
  310. 'data: [DONE]',
  311. '',
  312. ].join('\n\n'))
  313. })
  314. })
  315. await new Promise<void>(resolve => provider.listen(0, '127.0.0.1', resolve))
  316. const address = provider.address()
  317. if (address === null || typeof address === 'string') throw new Error('mock provider did not bind a TCP port')
  318. const tsxLoader = pathToFileURL(createRequire(join(REPO_ROOT, 'package.json')).resolve('tsx')).href
  319. const child = spawn(
  320. process.execPath,
  321. ['--import', tsxLoader, join(REPO_ROOT, 'apps/cli/src/bin.ts'), 'web', '--port', '0'],
  322. {
  323. cwd: workspace,
  324. env: {
  325. ...process.env,
  326. DEEPSEEK_API_KEY: 'keyless-web-retry',
  327. DEEPSEEK_BASE_URL: `http://127.0.0.1:${address.port}`,
  328. DSH_HOME: join(workspace, '.dsh'),
  329. TSX_TSCONFIG_PATH: join(REPO_ROOT, 'tsconfig.json'),
  330. },
  331. stdio: ['ignore', 'pipe', 'pipe'],
  332. },
  333. )
  334. try {
  335. const baseUrl = await waitForReadyLine(child)
  336. const created = await rpc<{ sessionId: string }>(baseUrl, 'session.create', {})
  337. await rpc<{ accepted: true }>(baseUrl, 'session.prompt', {
  338. sessionId: created.sessionId,
  339. mode: 'queue',
  340. content: [{ type: 'text', text: promptMarker }],
  341. })
  342. let page: HistoryPage | undefined
  343. await expect.poll(async () => {
  344. page = await history(baseUrl, created.sessionId)
  345. return hasAssistantMarker(page, recoveredMarker)
  346. }, { timeout: 20_000 }).toBe(true)
  347. if (page === undefined) throw new Error('retry history was not observed')
  348. const retry = page.events.find(({ event }) => event.type === 'llm/retry')?.event
  349. expect(mainAttempts).toBe(2)
  350. expect(retry?.data).toMatchObject({
  351. turn: 1,
  352. step: 1,
  353. retry: 1,
  354. maxRetries: 2,
  355. failure: { code: 'TRANSPORT' },
  356. })
  357. expect(JSON.stringify(page.events)).toContain('WEB_RETRY_DISCARDED')
  358. } finally {
  359. const closed = child.exitCode === null
  360. ? new Promise<void>((resolveClose) => { child.once('close', () => { resolveClose() }) })
  361. : Promise.resolve()
  362. if (child.exitCode === null) child.kill('SIGTERM')
  363. await closed
  364. await new Promise<void>(resolveClose => provider.close(() => { resolveClose() }))
  365. rmSync(workspace, { recursive: true, force: true })
  366. }
  367. }, 30_000)
  368. it('DSH_TOOLS_MODE=code collapses the provider wire tools to run_code with the SDK prompt section', async () => {
  369. requireDist()
  370. const workspace = mkdtempSync(join(tmpdir(), 'dsh-web-code-mode-'))
  371. interface CodeModeProviderRequest {
  372. messages?: { role?: string; content?: string }[]
  373. tools?: { function?: { name?: string } }[]
  374. }
  375. let resolveProviderRequest!: (request: CodeModeProviderRequest) => void
  376. const providerRequest = new Promise<CodeModeProviderRequest>((resolve) => {
  377. resolveProviderRequest = resolve
  378. })
  379. const provider = createServer((request, response) => {
  380. let body = ''
  381. request.setEncoding('utf8')
  382. request.on('data', (chunk: string) => { body += chunk })
  383. request.on('end', () => {
  384. resolveProviderRequest(JSON.parse(body) as CodeModeProviderRequest)
  385. response.writeHead(200, { 'content-type': 'text/event-stream' })
  386. response.end([
  387. 'data: {"choices":[{"delta":{"role":"assistant","content":null,"reasoning_content":""}}]}',
  388. 'data: {"choices":[{"delta":{"content":"done"}}]}',
  389. 'data: {"choices":[{"delta":{"content":""},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":1}}',
  390. 'data: [DONE]',
  391. '',
  392. ].join('\n\n'))
  393. })
  394. })
  395. await new Promise<void>(resolve => provider.listen(0, '127.0.0.1', resolve))
  396. const address = provider.address()
  397. if (address === null || typeof address === 'string') throw new Error('mock provider did not bind a TCP port')
  398. const tsxLoader = pathToFileURL(createRequire(join(REPO_ROOT, 'package.json')).resolve('tsx')).href
  399. const child = spawn(
  400. process.execPath,
  401. ['--import', tsxLoader, join(REPO_ROOT, 'apps/cli/src/bin.ts'), 'web', '--port', '0'],
  402. {
  403. cwd: workspace,
  404. env: {
  405. ...process.env,
  406. DEEPSEEK_API_KEY: 'keyless-web-code-mode',
  407. DEEPSEEK_BASE_URL: `http://127.0.0.1:${address.port}`,
  408. DSH_TOOLS_MODE: 'code',
  409. DSH_HOME: join(workspace, '.dsh'),
  410. DSH_AGENTS_HOME: join(workspace, '.agents'),
  411. TSX_TSCONFIG_PATH: join(REPO_ROOT, 'tsconfig.json'),
  412. },
  413. stdio: ['ignore', 'pipe', 'pipe'],
  414. },
  415. )
  416. try {
  417. const baseUrl = await waitForReadyLine(child)
  418. const created = await rpc<{ sessionId: string }>(baseUrl, 'session.create', {})
  419. await rpc<{ accepted: true }>(baseUrl, 'session.prompt', {
  420. sessionId: created.sessionId,
  421. mode: 'queue',
  422. content: [{ type: 'text', text: 'go' }],
  423. })
  424. const captured = await Promise.race([
  425. providerRequest,
  426. new Promise<never>((_resolve, reject) => {
  427. setTimeout(() => { reject(new Error('provider request not received in 10s')) }, 10_000).unref()
  428. }),
  429. ])
  430. expect(captured.tools?.map(tool => tool.function?.name)).toEqual(['run_code'])
  431. const system = captured.messages?.find(message => message.role === 'system')
  432. expect(system?.content).toContain('## Writing code for run_code')
  433. expect(system?.content).toContain('declare const tools')
  434. } finally {
  435. const closed = child.exitCode === null
  436. ? new Promise<void>((resolveClose) => { child.once('close', () => { resolveClose() }) })
  437. : Promise.resolve()
  438. if (child.exitCode === null) child.kill('SIGTERM')
  439. await closed
  440. await new Promise<void>(resolveClose => provider.close(() => { resolveClose() }))
  441. rmSync(workspace, { recursive: true, force: true })
  442. }
  443. })
  444. })
  445. describe.skipIf(!process.env.DEEPSEEK_API_KEY || notReady.length > 0)('web smoke (real host, real key)', () => {
  446. let child: ChildProcess
  447. let sessionsDir: string
  448. let baseUrl: string
  449. let browser: Browser
  450. let page: Page
  451. const pageErrors: string[] = []
  452. beforeAll(async () => {
  453. requireDist()
  454. sessionsDir = mkdtempSync(join(tmpdir(), 'dsh-web-w5-'))
  455. const port = await probeFreePort()
  456. // tsx boot mirrors the runtime half of the root dsh script. Isolate
  457. // the host-level Harness and shared-agent homes inside the temp world; tsx
  458. // also needs the repo's loader and tsconfig paths pointed at explicitly.
  459. const tsxLoader = pathToFileURL(createRequire(join(REPO_ROOT, 'package.json')).resolve('tsx')).href
  460. child = spawn(
  461. process.execPath,
  462. [
  463. '--import', tsxLoader, join(REPO_ROOT, 'apps/cli/src/bin.ts'), 'web',
  464. // Launcher flags come first: the first token the launcher does not own
  465. // starts the web app's own arguments.
  466. // Pin the in-browser picker: the shipped `-auto` row would resolve to
  467. // the native OS chooser on this bind, and no page can drive that.
  468. '--patch', fileURLToPath(new URL('./pin-browse-picker.overlay.yml', import.meta.url)),
  469. '--port', String(port),
  470. ],
  471. {
  472. cwd: sessionsDir,
  473. env: {
  474. ...process.env,
  475. DSH_HOME: join(sessionsDir, '.dsh'),
  476. DSH_AGENTS_HOME: join(sessionsDir, '.agents'),
  477. TSX_TSCONFIG_PATH: join(REPO_ROOT, 'tsconfig.json'),
  478. },
  479. stdio: ['ignore', 'pipe', 'pipe'],
  480. },
  481. )
  482. baseUrl = (await waitForReadyLine(child)).replace('0.0.0.0', '127.0.0.1')
  483. browser = await chromium.launch()
  484. page = await newEnglishPage(browser)
  485. page.on('pageerror', e => pageErrors.push(String(e)))
  486. await page.goto(baseUrl, { waitUntil: 'load' })
  487. }, 120_000)
  488. afterAll(async () => {
  489. await browser?.close()
  490. if (child !== undefined && child.exitCode === null) {
  491. const gone = new Promise<void>(resolveExit => child.once('exit', () => { resolveExit() }))
  492. child.kill('SIGTERM')
  493. await Promise.race([gone, new Promise(r => setTimeout(r, 10_000).unref())])
  494. if (child.exitCode === null) child.kill('SIGKILL')
  495. }
  496. if (sessionsDir !== undefined) rmSync(sessionsDir, { recursive: true, force: true })
  497. })
  498. it('cold start: loading page settles into the three-column frame', async () => {
  499. onTestFailed(() => saveFailureShot(page, 'w5-cold-start'))
  500. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  501. expect(await page.locator('text=Failed to load plugins').count()).toBe(0)
  502. const template = await page.locator('[class*="frame"]').evaluate(el => getComputedStyle(el).gridTemplateColumns)
  503. expect(template.split(' ').length).toBe(3)
  504. await screen(page, '01-cold-start')
  505. })
  506. it('empty-state first send completes a real model round', async () => {
  507. onTestFailed(() => saveFailureShot(page, 'w5-first-round'))
  508. // This scenario spawns its own server against a fresh $DSH_HOME, so the
  509. // first-run welcome notice is unacknowledged and its overlay owns pointer
  510. // events (the shared scaffold acknowledges it before boot instead). The
  511. // notice is anchored structurally, not by its copy: this spec sits in the
  512. // client TypeScript program, which does not reference the package that
  513. // owns the strings.
  514. const welcome = page.locator('[class*="onboardingOverlay"]')
  515. await welcome.waitFor({ timeout: 15_000 })
  516. await welcome.getByRole('button').click()
  517. await welcome.waitFor({ state: 'detached', timeout: 15_000 })
  518. // Fresh world: connect a Workspace so the composer starts live.
  519. await connectFreshWorkspace(page, sessionsDir)
  520. const input = page.locator('textarea').first()
  521. await input.waitFor({ timeout: 10_000 })
  522. await screen(page, '02-empty-state')
  523. const prompt = `Please answer this request carefully: explain event sourcing in two sentences, ending with exactly ${ROUND_DONE_MARKER}.`
  524. await input.fill(prompt)
  525. await input.press('Enter')
  526. // The first send must keep the session tree mounted; a near-empty body
  527. // reveals a duplicate runtime bundle with incompatible scope tags.
  528. await page.waitForFunction(() => document.body.innerText.length > 50, undefined, { timeout: 15_000 })
  529. expect(pageErrors).toEqual([])
  530. await page.waitForFunction(
  531. () => document.title !== 'DeepSeek Harness' && document.title.endsWith(' — DeepSeek Harness'),
  532. undefined,
  533. { timeout: 15_000 },
  534. )
  535. await expect.poll(async () => (await rpc<{ items: { sessionId: string }[] }>(baseUrl, 'session.list', {})).items.length, {
  536. timeout: 15_000,
  537. }).toBe(1)
  538. const sessions = await rpc<{ items: { sessionId: string }[] }>(baseUrl, 'session.list', {})
  539. const sessionId = sessions.items[0]?.sessionId
  540. if (sessionId === undefined) throw new Error('created Web session was not listed')
  541. const durableTitle = await waitForProviderTitle(baseUrl, sessionId)
  542. await page.waitForFunction(
  543. expected => document.title === `${expected} — DeepSeek Harness`,
  544. durableTitle,
  545. { timeout: 15_000 },
  546. )
  547. const sessionTree = page.getByRole('tree', { name: 'Sessions' })
  548. const projectRow = sessionTree.getByRole('treeitem').first()
  549. if (await projectRow.getAttribute('aria-expanded') === 'false') await projectRow.click()
  550. await Promise.all([
  551. sessionTree.getByText(durableTitle, { exact: true }).waitFor({ timeout: 10_000 }),
  552. page.getByRole('navigation').getByText(durableTitle, { exact: true }).waitFor({ timeout: 10_000 }),
  553. ])
  554. await waitForAssistantMarker(baseUrl, sessionId, ROUND_DONE_MARKER)
  555. await page.locator('p').filter({ hasText: ROUND_DONE_MARKER }).waitFor({ timeout: 10_000 })
  556. await screen(page, '04-round-complete')
  557. }, 150_000)
  558. it('view tabs: Chat and Trajectory switch', async () => {
  559. onTestFailed(() => saveFailureShot(page, 'w5-tabs'))
  560. await page.locator('button', { hasText: /Trajectory/i }).first().click()
  561. await screen(page, '05-trajectory-tab')
  562. await page.getByLabel('Trajectory timeline').waitFor()
  563. await expect.poll(() => page.getByRole('tab', { name: 'Waterfall' }).count()).toBe(0)
  564. await page.locator('button', { hasText: /^Chat$/i }).first().click()
  565. await screen(page, '07-back-to-chat')
  566. })
  567. it('bash differential rendering: tool row click leaves the default details column closed', async () => {
  568. onTestFailed(() => saveFailureShot(page, 'w5-tool-details'))
  569. const input = page.locator('textarea').first()
  570. await input.fill('请用 bash 工具运行命令 echo w5marker 然后告诉我结果')
  571. await input.press('Enter')
  572. // Wait for the tool ROW, not response text (the reply echoes any marker).
  573. // Bash renders through the third-party sample registration. Match that
  574. // exact row: other clickable variants (for example Think disclosure)
  575. // may precede the tool call in document order.
  576. const toolRow = page.locator('[data-sample="bash"]')
  577. await toolRow.waitFor({ timeout: 120_000 })
  578. await screen(page, '08-bash-round')
  579. expect(await detailsTrack(page)).toBe(0)
  580. await toolRow.click()
  581. // Tool rows do not drive layout.openDetails; the default column stays closed.
  582. expect(await detailsTrack(page)).toBe(0)
  583. await screen(page, '09-details-closed')
  584. }, 150_000)
  585. it('sidebar drag widens the column and resets across reload', async () => {
  586. onTestFailed(() => saveFailureShot(page, 'w5-drag'))
  587. const before = await firstTrack(page)
  588. const handle = page.locator('[class*="handle"]').first()
  589. const box = await handle.boundingBox()
  590. expect(box).not.toBeNull()
  591. await page.mouse.move(box!.x + box!.width / 2, box!.y + 300)
  592. await page.mouse.down()
  593. await page.mouse.move(box!.x + 70, box!.y + 300, { steps: 6 })
  594. await page.mouse.up()
  595. const after = await firstTrack(page)
  596. expect(after).not.toBe(before)
  597. await screen(page, '10-sidebar-dragged')
  598. await page.reload({ waitUntil: 'load' })
  599. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  600. expect(await firstTrack(page)).toBe(before)
  601. })
  602. it('dark mode: the body attribute cascades the token sheets', async () => {
  603. onTestFailed(() => saveFailureShot(page, 'w5-dark'))
  604. // The body attribute is the documented cascade mechanism; the Settings
  605. // gesture is owned by settings-chrome.e2e.ts — drive the attribute
  606. // directly here.
  607. const dark = await page.evaluate(() => {
  608. document.body.setAttribute('data-ds-dark-theme', '')
  609. return getComputedStyle(document.body).backgroundColor
  610. })
  611. await screen(page, '11-dark-mode')
  612. const light = await page.evaluate(() => {
  613. document.body.removeAttribute('data-ds-dark-theme')
  614. return getComputedStyle(document.body).backgroundColor
  615. })
  616. expect(dark).not.toBe(light)
  617. })
  618. it('reload recovery: history replays after a fresh boot', async () => {
  619. onTestFailed(() => saveFailureShot(page, 'w5-reload'))
  620. await page.reload({ waitUntil: 'load' })
  621. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  622. await page.locator('p').filter({ hasText: ROUND_DONE_MARKER }).waitFor({ timeout: 30_000 })
  623. await screen(page, '12-reload-recovery')
  624. })
  625. it('stayed clean: no page errors across every flow', () => {
  626. expect(pageErrors).toEqual([])
  627. })
  628. })