support.ts 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. // Shared plumbing for the web smoke tests (dist location, free port, failure shots).
  2. import { existsSync, mkdirSync } from 'node:fs'
  3. import { createServer } from 'node:net'
  4. import { join } from 'node:path'
  5. import { fileURLToPath } from 'node:url'
  6. import type { Browser, Locator, Page } from 'playwright'
  7. /** The built page under test; `pnpm run test:web` rebuilds it before running. */
  8. export const DIST_INDEX = fileURLToPath(new URL('../dist/index.html', import.meta.url))
  9. export const REPO_ROOT = fileURLToPath(new URL('../../..', import.meta.url))
  10. /**
  11. * Browser language a page must advertise to boot into the product's Chinese
  12. * surface: with no stored preference the client derives its initial locale
  13. * from the browser, and Playwright's default browser asks for English.
  14. */
  15. export const ZH_BROWSER_LOCALE = 'zh-CN'
  16. /**
  17. * Open the standard browser-test page advertising English before client boot.
  18. * This keeps role locators and goldens deterministic while leaving the Host
  19. * settings document free to override the provisional browser-derived locale;
  20. * scenarios asserting the Chinese surface advertise
  21. * {@link ZH_BROWSER_LOCALE} instead.
  22. * @param browser - Playwright browser owning the page.
  23. * @param height - Viewport height; width is fixed to the lane baseline.
  24. * @returns the initialized page.
  25. */
  26. export async function newEnglishPage(browser: Browser, height = 1000): Promise<Page> {
  27. return await browser.newPage({ viewport: { width: 1680, height }, locale: 'en-US' })
  28. }
  29. /**
  30. * Expand every currently eligible Turn-process group so a Tool-focused
  31. * scenario can exercise the original row contract beneath product-default
  32. * compact Chat presentation.
  33. * @param page - page containing the Chat view.
  34. */
  35. export async function expandTurnProcesses(page: Page): Promise<void> {
  36. const controls = page.locator('[data-turn-process]')
  37. await controls.first().waitFor({ state: 'visible', timeout: 10_000 })
  38. const count = await controls.count()
  39. for (let index = 0; index < count; index++) {
  40. const control = controls.nth(index)
  41. if (await control.getAttribute('aria-expanded') !== 'true') await control.click()
  42. }
  43. }
  44. /**
  45. * Expand the Turn-process group containing one possibly hidden descendant.
  46. * @param page - page containing the Chat view.
  47. * @param target - descendant whose owning Turn process should open.
  48. */
  49. export async function expandOwningTurnProcess(page: Page, target: Locator): Promise<void> {
  50. const turn = await target.evaluate(element => element.closest<HTMLElement>('[data-chat-turn]')?.dataset.chatTurn)
  51. if (turn === undefined || await target.isVisible()) return
  52. const control = page.locator(`[data-turn-process="${turn}"]`)
  53. await control.waitFor({ state: 'visible', timeout: 10_000 })
  54. if (await control.getAttribute('aria-expanded') !== 'true') await control.click()
  55. }
  56. /** Fail loud on a stale checkout instead of testing yesterday's bundle. */
  57. export function requireDist(): void {
  58. if (!existsSync(DIST_INDEX)) {
  59. throw new Error('web app dist not built — run `pnpm run build` from the repository root (`pnpm run test:web` does this first)')
  60. }
  61. }
  62. /** OS-assigned free port, released before use (the spawned `dsh web` needs a concrete --port). */
  63. export function probeFreePort(): Promise<number> {
  64. return new Promise((resolvePort, reject) => {
  65. const probe = createServer()
  66. probe.once('error', reject)
  67. probe.listen(0, '127.0.0.1', () => {
  68. const address = probe.address()
  69. if (address === null || typeof address === 'string') {
  70. probe.close(() => { reject(new Error('port probe returned no address')) })
  71. return
  72. }
  73. probe.close(() => { resolvePort(address.port) })
  74. })
  75. })
  76. }
  77. /**
  78. * Drive the hero's workspace picker through the composed directory dialog
  79. * until the live composer unlocks. A fresh world has no Workspace, so the boot
  80. * lands in the Workspace-trigger view state (startup auto-selection has nothing to
  81. * select); every scenario that types into the composer must connect one
  82. * first. With nothing to list, activating the composer surface raises the dialog directly —
  83. * adding a workspace is the picker's only entry. The directory is staged here
  84. * and adopted through the path editor, which is idempotent across the repeated
  85. * connects a scenario may make; creating a folder from inside the dialog (the
  86. * product's other half of the same route) is covered by
  87. * workspace-management.e2e.ts. The default name 'workspace' keeps the session
  88. * header cwd at <root>/workspace, the materialization proof several scenarios
  89. * assert.
  90. * @param page - the page under test.
  91. * @param root - host directory the workspace folder is staged in (the scaffold's `workspaceCwd`).
  92. * @param name - folder name staged and adopted as the workspace.
  93. */
  94. export async function connectFreshWorkspace(page: Page, root: string, name = 'workspace'): Promise<void> {
  95. mkdirSync(join(root, name), { recursive: true })
  96. await page.getByRole('textbox', { name: 'Choose workspace' }).click()
  97. const dialog = page.getByRole('dialog', { name: 'Select Workspace Directory' })
  98. await dialog.waitFor({ timeout: 10_000 })
  99. await dialog.getByRole('button', { name: 'Edit path' }).click()
  100. const pathInput = dialog.getByRole('textbox', { name: 'Edit path' })
  101. await pathInput.fill(join(root, name))
  102. await pathInput.press('Enter')
  103. await dialog.getByRole('button', { name: 'Open', exact: true }).click()
  104. // The pick connected the workspace: the blank session's live composer
  105. // replaces the locked placeholder and enables.
  106. await page.locator('[data-composer-input][contenteditable="true"][data-placeholder="Describe what you want to build... / commands, @ files or sessions"]')
  107. .waitFor({ timeout: 15_000 })
  108. }
  109. /**
  110. * {@link connectFreshWorkspace} over a page that advertises
  111. * {@link ZH_BROWSER_LOCALE}: the English helper's anchors assume the locale
  112. * most other scenarios boot, so a scenario that deliberately keeps zh needs
  113. * the localized picker copy.
  114. * @param page - the browser page under test.
  115. * @param root - workspace parent directory.
  116. * @param name - directory created under `root` and connected.
  117. */
  118. export async function connectFreshWorkspaceZh(page: Page, root: string, name = 'workspace'): Promise<void> {
  119. mkdirSync(join(root, name), { recursive: true })
  120. await page.getByRole('textbox', { name: '选择工作区' }).click()
  121. const dialog = page.getByRole('dialog', { name: '选择工作区目录' })
  122. await dialog.waitFor({ timeout: 10_000 })
  123. await dialog.getByRole('button', { name: '编辑路径' }).click()
  124. const pathInput = dialog.getByRole('textbox', { name: '编辑路径' })
  125. await pathInput.fill(join(root, name))
  126. await pathInput.press('Enter')
  127. await dialog.getByRole('button', { name: '打开', exact: true }).click()
  128. await page.locator('[data-composer-input][contenteditable="true"][data-placeholder="描述你想要构建的内容… / 调用指令 @ 文件或对话"]')
  129. .waitFor({ timeout: 15_000 })
  130. }
  131. /**
  132. * Replace the composer draft through per-key gestures. `fill()` issues
  133. * select-all and insertText inside one task; directly after a trigger-menu or
  134. * chip interaction Lexical's internal selection has not yet absorbed the DOM
  135. * selection, and the batched edit lands on a null selection and is silently
  136. * dropped, leaving the previous draft in place. Real keystrokes leave room for
  137. * `selectionchange` between keys, which is also what a user's typing does.
  138. *
  139. * Waits for the surface to be editable first. While the input machine is
  140. * adjudicating or submitting a send — and in every locked state (removed
  141. * session, no workspace, an owner block) — the composer renders read-only
  142. * with `contenteditable="false"` on the same element. `fill()` throws
  143. * immediately on that element, and `isEnabled()` reports `true` for a
  144. * `<div>` regardless of the attribute — so a gesture directly after a
  145. * submit must gate on the attribute, not on enablement. A running turn by
  146. * itself keeps the composer editable (that is what queueing types into).
  147. * @param page - the page under test.
  148. * @param input - the `[data-composer-input]` surface locator.
  149. * @param text - the replacement draft; `''` clears the draft. Must not
  150. * contain a newline: typed Enter submits the composer.
  151. */
  152. export async function writeComposerDraft(
  153. page: Page,
  154. input: ReturnType<Page['locator']>,
  155. text: string,
  156. ): Promise<void> {
  157. await input.and(page.locator('[contenteditable="true"]')).waitFor({ timeout: 15_000 })
  158. await input.click()
  159. await page.keyboard.press('ControlOrMeta+A')
  160. if (text === '') await page.keyboard.press('Backspace')
  161. else await page.keyboard.type(text)
  162. }
  163. /** Failure evidence goes to the gitignored .artifacts/ (repo convention). */
  164. export async function saveFailureShot(page: Page, name: string): Promise<void> {
  165. const dir = fileURLToPath(new URL('../../../.artifacts', import.meta.url))
  166. mkdirSync(dir, { recursive: true })
  167. try {
  168. await page.screenshot({ path: `${dir}/${name}.png`, fullPage: true })
  169. } catch {
  170. // Best-effort evidence: a dead page/browser at failure time must not mask the real assertion error.
  171. }
  172. }
  173. /**
  174. * The conversation engine's Context key format, restated here rather than
  175. * imported: these specs live in the Host compiler aggregate, which must not
  176. * reach the Client plane. The engine's own copy is
  177. * `conversationContextKey` in ui-conversation; a drift between them makes
  178. * the key miss its rendered node, so the assertion fails loudly.
  179. * @param kind - Definition kind.
  180. * @param id - Definition-local business identity.
  181. * @returns the engine-owned Context key.
  182. */
  183. export function conversationContextKey(kind: string, id: string): string {
  184. return `${kind.length}:${kind}${id}`
  185. }