smoke-real.e2e.ts 23 KB

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