smoke-real.e2e.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  1. // W5 real-host smoke: spawn `dsh web` with a real key, walk the full W5 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); the runner loads the repo-root .env explicitly because the CLI
  5. // only auto-loads .env from its cwd (a temp dir here, so sessions never land
  6. // 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-clickable / 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 (5 depends on 3's session), geometry
  15. // and theme after, reload recovery last. Tests run sequentially in-file.
  16. import type { ChildProcess } from 'node:child_process'
  17. import { spawn } from 'node:child_process'
  18. import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
  19. import { createServer } from 'node:http'
  20. import { createRequire } from 'node:module'
  21. import { tmpdir } from 'node:os'
  22. import { join } from 'node:path'
  23. import { pathToFileURL } from 'node:url'
  24. import type { Browser, Page } from 'playwright'
  25. import { chromium } from 'playwright'
  26. import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
  27. import { REPO_ROOT, probeFreePort, requireDist, saveFailureShot } from './support.ts'
  28. /** Repo-root .env → process.env (never overrides an already-set variable). */
  29. function loadRootEnv(): void {
  30. const envPath = join(REPO_ROOT, '.env')
  31. if (!existsSync(envPath)) return
  32. for (const line of readFileSync(envPath, 'utf8').split('\n')) {
  33. const m = /^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/.exec(line.trim())
  34. if (m !== null && process.env[m[1]!] === undefined) process.env[m[1]!] = m[2]
  35. }
  36. }
  37. loadRootEnv()
  38. function waitForReadyLine(child: ChildProcess): Promise<string> {
  39. return new Promise((resolveReady, reject) => {
  40. let out = ''
  41. const timer = setTimeout(() => { reject(new Error(`dsh web not ready in 90s; output:\n${out}`)) }, 90_000)
  42. const onData = (chunk: Buffer): void => {
  43. out += chunk.toString()
  44. const match = /dsh web: (http:\/\/[^\s]+)/.exec(out)
  45. if (match?.[1] !== undefined) {
  46. clearTimeout(timer)
  47. resolveReady(match[1])
  48. }
  49. }
  50. child.stdout?.on('data', onData)
  51. child.stderr?.on('data', onData)
  52. child.once('exit', (code) => {
  53. clearTimeout(timer)
  54. reject(new Error(`dsh web exited early (code ${code}); output:\n${out}`))
  55. })
  56. })
  57. }
  58. async function rpc<T>(baseUrl: string, method: string, payload: unknown): Promise<T> {
  59. const response = await fetch(`${baseUrl}/api/${method}`, {
  60. method: 'POST',
  61. headers: { 'content-type': 'application/json' },
  62. body: JSON.stringify({
  63. type: 'client-request',
  64. rpcId: `smoke-${method}`,
  65. method,
  66. payload,
  67. }),
  68. })
  69. if (!response.ok) throw new Error(`${method} failed over HTTP ${response.status}: ${await response.text()}`)
  70. const body = await response.json() as {
  71. result: { ok: true; value: T } | { ok: false; error: { code: string; message: string } }
  72. }
  73. if (!body.result.ok) throw new Error(`${method} failed: ${body.result.error.code}: ${body.result.error.message}`)
  74. return body.result.value
  75. }
  76. interface HistoryPage {
  77. events: { event: { type: string; data: unknown } }[]
  78. hasMore: boolean
  79. }
  80. function isRecord(value: unknown): value is Record<string, unknown> {
  81. return typeof value === 'object' && value !== null
  82. }
  83. function providerTitle(page: HistoryPage): string | undefined {
  84. for (let index = page.events.length - 1; index >= 0; index--) {
  85. const event = page.events[index]!.event
  86. if (event.type !== 'session/title' || !isRecord(event.data)) continue
  87. const source = event.data.source
  88. if (typeof event.data.title === 'string' && isRecord(source) && source.kind === 'provider') {
  89. return event.data.title
  90. }
  91. }
  92. return undefined
  93. }
  94. function hasAssistantMarker(page: HistoryPage, marker: string): boolean {
  95. return page.events.some(({ event }) => {
  96. if (event.type !== 'assistant/message' || !isRecord(event.data) || !Array.isArray(event.data.content)) return false
  97. return event.data.content.some(block =>
  98. isRecord(block) && block.type === 'text' && typeof block.text === 'string' && block.text.includes(marker))
  99. })
  100. }
  101. async function history(baseUrl: string, sessionId: string): Promise<HistoryPage> {
  102. return rpc<HistoryPage>(baseUrl, 'session.history', { sessionId, maxMessages: 10 })
  103. }
  104. async function waitForProviderTitle(baseUrl: string, sessionId: string): Promise<string> {
  105. let observed: string | undefined
  106. await expect.poll(async () => {
  107. observed = providerTitle(await history(baseUrl, sessionId))
  108. return observed
  109. }, { timeout: 90_000 }).toEqual(expect.any(String))
  110. if (observed === undefined) throw new Error('provider-backed session title was not observed')
  111. return observed
  112. }
  113. async function waitForAssistantMarker(baseUrl: string, sessionId: string, marker: string): Promise<void> {
  114. await expect.poll(async () => hasAssistantMarker(await history(baseUrl, sessionId), marker), {
  115. timeout: 120_000,
  116. }).toBe(true)
  117. }
  118. /** W5 screenshot: evidence for the figma comparison, not a failure artifact. */
  119. async function screen(page: Page, name: string): Promise<void> {
  120. await page.screenshot({ path: join(REPO_ROOT, '.artifacts', `w5-${name}.png`) })
  121. }
  122. /** First column track (px string) of the frame grid. */
  123. async function firstTrack(page: Page): Promise<string> {
  124. return (await page.locator('[class*="frame"]').evaluate(
  125. el => getComputedStyle(el).gridTemplateColumns)).split(' ')[0]!
  126. }
  127. /** Last column track (details) as a number of pixels. */
  128. async function detailsTrack(page: Page): Promise<number> {
  129. const cols = await page.locator('[class*="frame"]').evaluate(
  130. el => getComputedStyle(el).gridTemplateColumns)
  131. return Number(cols.split(' ').pop()!.replace('px', ''))
  132. }
  133. // Readiness gate: `dsh web` serves ALL nine manifest plugins; until every UI
  134. // plugin's client bundle exists and exports apply, the loader fail-louds and
  135. // the frame never appears.
  136. const UI_PLUGIN_DIRS = ['connection', 'runtime', 'ui-theme', 'i18n', 'ui-layout', 'ui-sidebar', 'ui-conversation', 'ui-question', 'ui-trajectory']
  137. const ROUND_DONE_MARKER = 'WEB_ROUND_DONE'
  138. const notReady = UI_PLUGIN_DIRS.filter((dir) => {
  139. const bundle = join(REPO_ROOT, 'packages/client', dir, 'lib/client.js')
  140. return !existsSync(bundle) || !readFileSync(bundle, 'utf8').includes('exports.apply')
  141. })
  142. if (notReady.length > 0) console.warn(`[smoke-real] skipped — client bundles not ready: ${notReady.join(', ')}`)
  143. describe('dsh web keyless CLI smoke', () => {
  144. it('listens on 127.0.0.1 by default', async () => {
  145. requireDist()
  146. const sessionsDir = mkdtempSync(join(tmpdir(), 'dsh-web-keyless-'))
  147. const tsxLoader = pathToFileURL(createRequire(join(REPO_ROOT, 'package.json')).resolve('tsx')).href
  148. const child = spawn(
  149. process.execPath,
  150. ['--import', tsxLoader, join(REPO_ROOT, 'apps/cli/src/bin.ts'), 'web', '--port', '0'],
  151. {
  152. cwd: sessionsDir,
  153. env: {
  154. ...process.env,
  155. DEEPSEEK_API_KEY: 'keyless-web-no-call',
  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('injects the invoking workspace AGENTS.md into the provider 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. let resolveProviderRequest!: (request: { messages?: { role?: string; content?: string }[] }) => void
  180. const providerRequest = new Promise<{ messages?: { role?: string; content?: string }[] }>((resolve) => {
  181. resolveProviderRequest = resolve
  182. })
  183. const provider = createServer((request, response) => {
  184. let body = ''
  185. request.setEncoding('utf8')
  186. request.on('data', (chunk: string) => { body += chunk })
  187. request.on('end', () => {
  188. resolveProviderRequest(JSON.parse(body) as { messages?: { role?: string; content?: string }[] })
  189. response.writeHead(200, { 'content-type': 'text/event-stream' })
  190. response.end([
  191. 'data: {"choices":[{"delta":{"role":"assistant","content":null,"reasoning_content":""}}]}',
  192. 'data: {"choices":[{"delta":{"content":"done"}}]}',
  193. 'data: {"choices":[{"delta":{"content":""},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":1}}',
  194. 'data: [DONE]',
  195. '',
  196. ].join('\n\n'))
  197. })
  198. })
  199. await new Promise<void>(resolve => provider.listen(0, '127.0.0.1', resolve))
  200. const address = provider.address()
  201. if (address === null || typeof address === 'string') throw new Error('mock provider did not bind a TCP port')
  202. const tsxLoader = pathToFileURL(createRequire(join(REPO_ROOT, 'package.json')).resolve('tsx')).href
  203. const child = spawn(
  204. process.execPath,
  205. ['--import', tsxLoader, join(REPO_ROOT, 'apps/cli/src/bin.ts'), 'web', '--port', '0'],
  206. {
  207. cwd: workspace,
  208. env: {
  209. ...process.env,
  210. DEEPSEEK_API_KEY: 'keyless-web-workspace',
  211. DEEPSEEK_BASE_URL: `http://127.0.0.1:${address.port}`,
  212. DSH_HOME: join(workspace, '.dsh'),
  213. TSX_TSCONFIG_PATH: join(REPO_ROOT, 'tsconfig.json'),
  214. },
  215. stdio: ['ignore', 'pipe', 'pipe'],
  216. },
  217. )
  218. try {
  219. const baseUrl = await waitForReadyLine(child)
  220. const created = await rpc<{ sessionId: string }>(baseUrl, 'session.create', {})
  221. await rpc<{ accepted: true }>(baseUrl, 'session.prompt', {
  222. sessionId: created.sessionId,
  223. mode: 'queue',
  224. content: [{ type: 'text', text: 'go' }],
  225. })
  226. const captured = await Promise.race([
  227. providerRequest,
  228. new Promise<never>((_resolve, reject) => {
  229. setTimeout(() => { reject(new Error('provider request not received in 10s')) }, 10_000).unref()
  230. }),
  231. ])
  232. const workspaceMessage = captured.messages?.find(message =>
  233. message.role === 'user' && message.content?.includes('web-workspace-context-probe'))
  234. expect(workspaceMessage).toMatchInlineSnapshot(`
  235. {
  236. "content": "<system-reminder>
  237. 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.
  238. Instructions from: AGENTS.md
  239. web-workspace-context-probe
  240. </system-reminder>",
  241. "role": "user",
  242. }
  243. `)
  244. } finally {
  245. const closed = child.exitCode === null
  246. ? new Promise<void>((resolveClose) => { child.once('close', () => { resolveClose() }) })
  247. : Promise.resolve()
  248. if (child.exitCode === null) child.kill('SIGTERM')
  249. await closed
  250. await new Promise<void>(resolveClose => provider.close(() => { resolveClose() }))
  251. rmSync(workspace, { recursive: true, force: true })
  252. }
  253. })
  254. })
  255. describe.skipIf(!process.env.DEEPSEEK_API_KEY || notReady.length > 0)('web smoke (real host, real key, W5)', () => {
  256. let child: ChildProcess
  257. let sessionsDir: string
  258. let baseUrl: string
  259. let browser: Browser
  260. let page: Page
  261. const pageErrors: string[] = []
  262. beforeAll(async () => {
  263. requireDist()
  264. sessionsDir = mkdtempSync(join(tmpdir(), 'dsh-web-w5-'))
  265. const port = await probeFreePort()
  266. // tsx boot mirrors demo:web — lib/ may be unbuilt in this worktree. cwd is a
  267. // temp dir (persistenceRoot is cwd-relative), so tsx needs the repo's loader
  268. // and tsconfig paths pointed at explicitly.
  269. const tsxLoader = pathToFileURL(createRequire(join(REPO_ROOT, 'package.json')).resolve('tsx')).href
  270. child = spawn(
  271. process.execPath,
  272. ['--import', tsxLoader, join(REPO_ROOT, 'apps/cli/src/bin.ts'), 'web', '--port', String(port)],
  273. {
  274. cwd: sessionsDir,
  275. env: { ...process.env, TSX_TSCONFIG_PATH: join(REPO_ROOT, 'tsconfig.json') },
  276. stdio: ['ignore', 'pipe', 'pipe'],
  277. },
  278. )
  279. baseUrl = (await waitForReadyLine(child)).replace('0.0.0.0', '127.0.0.1')
  280. browser = await chromium.launch()
  281. page = await browser.newPage({ viewport: { width: 1680, height: 1000 } })
  282. page.on('pageerror', e => pageErrors.push(String(e)))
  283. await page.goto(baseUrl, { waitUntil: 'load' })
  284. }, 120_000)
  285. afterAll(async () => {
  286. await browser?.close()
  287. if (child !== undefined && child.exitCode === null) {
  288. const gone = new Promise<void>(resolveExit => child.once('exit', () => { resolveExit() }))
  289. child.kill('SIGTERM')
  290. await Promise.race([gone, new Promise(r => setTimeout(r, 10_000).unref())])
  291. if (child.exitCode === null) child.kill('SIGKILL')
  292. }
  293. if (sessionsDir !== undefined) rmSync(sessionsDir, { recursive: true, force: true })
  294. })
  295. it('1 cold start: loading page settles into the three-column frame', async () => {
  296. onTestFailed(() => saveFailureShot(page, 'w5-cold-start'))
  297. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  298. expect(await page.locator('text=Failed to load plugins').count()).toBe(0)
  299. const template = await page.locator('[class*="frame"]').evaluate(el => getComputedStyle(el).gridTemplateColumns)
  300. expect(template.split(' ').length).toBe(3)
  301. await screen(page, '01-cold-start')
  302. })
  303. it('2+3 empty-state first send completes a real model round', async () => {
  304. onTestFailed(() => saveFailureShot(page, 'w5-first-round'))
  305. const input = page.locator('textarea').first()
  306. await input.waitFor({ timeout: 10_000 })
  307. await screen(page, '02-empty-state')
  308. const prompt = `Please answer this request carefully: explain event sourcing in two sentences, ending with exactly ${ROUND_DONE_MARKER}.`
  309. await input.fill(prompt)
  310. await input.press('Enter')
  311. // startSession chain: session mounts, composer moves to the bottom.
  312. // Regression pin (P0, 585671106): this send used to white-screen the tree
  313. // (scope tag lost to a duplicate inlined runtime instance) — body going
  314. // near-empty here means that class of bug is back.
  315. await page.waitForFunction(() => document.body.innerText.length > 50, undefined, { timeout: 15_000 })
  316. expect(pageErrors).toEqual([])
  317. await page.waitForFunction(
  318. () => document.title !== 'DeepSeek Harness' && document.title.endsWith(' — DeepSeek Harness'),
  319. undefined,
  320. { timeout: 15_000 },
  321. )
  322. await expect.poll(async () => (await rpc<{ items: { sessionId: string }[] }>(baseUrl, 'session.list', {})).items.length, {
  323. timeout: 15_000,
  324. }).toBe(1)
  325. const sessions = await rpc<{ items: { sessionId: string }[] }>(baseUrl, 'session.list', {})
  326. const sessionId = sessions.items[0]?.sessionId
  327. if (sessionId === undefined) throw new Error('created Web session was not listed')
  328. const durableTitle = await waitForProviderTitle(baseUrl, sessionId)
  329. await page.waitForFunction(
  330. expected => document.title === `${expected} — DeepSeek Harness`,
  331. durableTitle,
  332. { timeout: 15_000 },
  333. )
  334. const sessionTree = page.getByRole('tree', { name: 'Sessions' })
  335. const projectRow = sessionTree.getByRole('treeitem').first()
  336. if (await projectRow.getAttribute('aria-expanded') === 'false') await projectRow.click()
  337. await Promise.all([
  338. sessionTree.getByText(durableTitle, { exact: true }).waitFor({ timeout: 10_000 }),
  339. page.getByRole('navigation').getByText(durableTitle, { exact: true }).waitFor({ timeout: 10_000 }),
  340. ])
  341. await waitForAssistantMarker(baseUrl, sessionId, ROUND_DONE_MARKER)
  342. await page.locator('p').filter({ hasText: ROUND_DONE_MARKER }).waitFor({ timeout: 10_000 })
  343. await screen(page, '04-round-complete')
  344. }, 150_000)
  345. it('4 view tabs: Chat / Trajectory / Waterfall all switch', async () => {
  346. onTestFailed(() => saveFailureShot(page, 'w5-tabs'))
  347. await page.locator('button', { hasText: /Trajectory/i }).first().click()
  348. await screen(page, '05-trajectory-tab')
  349. await page.locator('button', { hasText: /Waterfall/i }).first().click()
  350. await screen(page, '06-waterfall-tab')
  351. await page.locator('button', { hasText: /^Chat$/i }).first().click()
  352. await screen(page, '07-back-to-chat')
  353. })
  354. it('5 bash differential rendering: tool row click opens the details column', async () => {
  355. onTestFailed(() => saveFailureShot(page, 'w5-tool-details'))
  356. const input = page.locator('textarea').first()
  357. await input.fill('请用 bash 工具运行命令 echo w5marker 然后告诉我结果')
  358. await input.press('Enter')
  359. // Wait for the tool ROW, not response text (the reply echoes any marker).
  360. // Bash renders through the third-party sample registration. Match that
  361. // exact row: other clickable variants (for example Think disclosure)
  362. // may precede the tool call in document order.
  363. const toolRow = page.locator('[data-sample="bash-global"]')
  364. await toolRow.waitFor({ timeout: 120_000 })
  365. await screen(page, '08-bash-round')
  366. expect(await detailsTrack(page)).toBe(0)
  367. await toolRow.click()
  368. // Selection channel: click writes selection + layout.openDetails.
  369. await page.waitForFunction(() => {
  370. const frame = document.querySelector('[class*="frame"]')
  371. if (frame === null) return false
  372. return Number(getComputedStyle(frame).gridTemplateColumns.split(' ').pop()!.replace('px', '')) > 0
  373. }, undefined, { timeout: 10_000 })
  374. await screen(page, '09-details-open')
  375. }, 150_000)
  376. it('6 sidebar drag widens the column and persists across reload', async () => {
  377. onTestFailed(() => saveFailureShot(page, 'w5-drag'))
  378. const before = await firstTrack(page)
  379. const handle = page.locator('[class*="handle"]').first()
  380. const box = await handle.boundingBox()
  381. expect(box).not.toBeNull()
  382. await page.mouse.move(box!.x + box!.width / 2, box!.y + 300)
  383. await page.mouse.down()
  384. await page.mouse.move(box!.x + 70, box!.y + 300, { steps: 6 })
  385. await page.mouse.up()
  386. const after = await firstTrack(page)
  387. expect(after).not.toBe(before)
  388. await screen(page, '10-sidebar-dragged')
  389. await page.reload({ waitUntil: 'load' })
  390. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  391. expect(await firstTrack(page)).toBe(after)
  392. })
  393. it('7 dark mode: the body attribute cascades the token sheets', async () => {
  394. onTestFailed(() => saveFailureShot(page, 'w5-dark'))
  395. // theme.apply === toggling this attribute (v3 §8); no switcher UI owns it
  396. // in P-I, so the acceptance drives the documented mechanism directly.
  397. const dark = await page.evaluate(() => {
  398. document.body.setAttribute('data-ds-dark-theme', '')
  399. return getComputedStyle(document.body).backgroundColor
  400. })
  401. await screen(page, '11-dark-mode')
  402. const light = await page.evaluate(() => {
  403. document.body.removeAttribute('data-ds-dark-theme')
  404. return getComputedStyle(document.body).backgroundColor
  405. })
  406. expect(dark).not.toBe(light)
  407. })
  408. it('8 reload recovery: history replays after a fresh boot', async () => {
  409. onTestFailed(() => saveFailureShot(page, 'w5-reload'))
  410. await page.reload({ waitUntil: 'load' })
  411. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  412. await page.locator('p').filter({ hasText: ROUND_DONE_MARKER }).waitFor({ timeout: 30_000 })
  413. await screen(page, '12-reload-recovery')
  414. })
  415. it('stayed clean: no page errors across every flow', () => {
  416. expect(pageErrors).toEqual([])
  417. })
  418. })