support.ts 9.7 KB

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