settings-chrome.e2e.ts 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674
  1. // Web e2e scenarios: the settings surface — the modal shell (trigger, nav,
  2. // section switching, both close paths), the Appearance preference row (the
  3. // real theme gesture — click 深色 and the whole cascade runs: ThemeRuntime preference -> Host settings
  4. // -> theme/change -> ui-layout's presenter -> body attribute -> alias token +
  5. // browser theme-color metadata)
  6. // the Language row and busy-state Enter preference (both Host-backed), plus
  7. // Permission as the persisted default for subsequently created sessions.
  8. // Zero model calls: everything is pure client + persistence state on a blank
  9. // frame, so there is no fixture and a stray stream would fail loud on the
  10. // open llm seam.
  11. import { readFile } from 'node:fs/promises'
  12. import { fileURLToPath } from 'node:url'
  13. import type { Browser, Locator, Page } from 'playwright'
  14. import { chromium } from 'playwright'
  15. import { afterAll, beforeAll, describe, expect, it, onTestFailed, onTestFinished } from 'vitest'
  16. import { join } from 'node:path'
  17. import { SessionId } from '@deepseek-ai/dsh-session'
  18. import {
  19. acknowledgeReloadConnectionLoss, assertFixtureInventory, captureStableAria, compareOrRefreshGolden,
  20. launchWebScaffold, watchConsole, webSnapshotMode, type WebScaffold,
  21. } from './scaffold.ts'
  22. import { ZH_BROWSER_LOCALE, saveFailureShot } from './support.ts'
  23. const SNAPSHOT_DIR = fileURLToPath(new URL('./expected/settings-chrome', import.meta.url))
  24. const DIALOG_EXPECTED = join(SNAPSHOT_DIR, 'dialog.expected.md')
  25. const PLUGINS_EXPECTED = join(SNAPSHOT_DIR, 'plugins.expected.md')
  26. // The English fallback surface: a browser naming no shipped language.
  27. const DIALOG_EN_EXPECTED = join(SNAPSHOT_DIR, 'dialog-en.expected.md')
  28. const PLUGIN_ROW_SELECTOR = '[data-plugin-entry$="ui-settings"]'
  29. const MODE = webSnapshotMode()
  30. describe('web e2e: settings modal and General preferences', () => {
  31. let scaffold: WebScaffold
  32. let browser: Browser
  33. let page: Page
  34. let tripwire: ReturnType<typeof watchConsole>
  35. beforeAll(async () => {
  36. scaffold = await launchWebScaffold({})
  37. browser = await chromium.launch()
  38. // Chinese browser: the shared page asserts the localized settings surface
  39. // the client derives from it (the English default has its own spec below).
  40. page = await browser.newPage({ viewport: { width: 1680, height: 1000 }, locale: ZH_BROWSER_LOCALE })
  41. tripwire = watchConsole(page)
  42. await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
  43. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  44. }, 120_000)
  45. afterAll(async () => {
  46. await browser?.close()
  47. await scaffold?.close()
  48. })
  49. it('opens the settings dialog, switches sections, and closes by every path', async () => {
  50. onTestFailed(() => saveFailureShot(page, 'web-e2e-settings-shell'))
  51. const trigger = page.getByRole('button', { name: '设置', exact: true })
  52. expect(await trigger.getAttribute('aria-haspopup')).toBe('dialog')
  53. expect(await trigger.getAttribute('aria-expanded')).toBe('false')
  54. await trigger.click()
  55. const dialog = page.getByRole('dialog', { name: '设置' })
  56. await dialog.waitFor({ timeout: 10_000 })
  57. expect(await trigger.getAttribute('aria-expanded')).toBe('true')
  58. // General is active by default; Permission, Language and Appearance are functional.
  59. expect(await dialog.getByRole('button', { name: '通用设置' }).getAttribute('aria-current')).toBe('true')
  60. await dialog.getByRole('button', { name: '工作区内修改' }).waitFor({ timeout: 10_000 })
  61. await expect.poll(() => dialog.getByText('语言', { exact: true }).count(), { timeout: 5_000 }).toBe(1)
  62. await expect.poll(() => dialog.getByText('外观', { exact: true }).count(), { timeout: 5_000 }).toBe(1)
  63. const openDocument = dialog.getByRole('button', { name: '打开配置文件' })
  64. await openDocument.waitFor({ timeout: 10_000 })
  65. let openRequests = 0
  66. await page.route('**/api/settings/openSettingsDocument', async (route) => {
  67. const envelope = route.request().postDataJSON() as {
  68. rpcId: string
  69. payload: { args: Record<string, never> }
  70. }
  71. expect(envelope.payload).toEqual({ args: {} })
  72. openRequests += 1
  73. await route.fulfill({
  74. status: 200,
  75. contentType: 'application/json',
  76. body: JSON.stringify({
  77. type: 'server-response',
  78. rpcId: envelope.rpcId,
  79. result: { ok: true, value: { opened: true } },
  80. }),
  81. })
  82. })
  83. await openDocument.click()
  84. await expect.poll(() => openRequests, { timeout: 5_000 }).toBe(1)
  85. await expect.poll(() => openDocument.isEnabled(), { timeout: 5_000 }).toBe(true)
  86. await page.unroute('**/api/settings/openSettingsDocument')
  87. // Golden of the freshly opened dialog (default zh, General active).
  88. const snapshot = await captureStableAria(page, '[role="dialog"]', scaffold.workspaceCwd)
  89. await compareOrRefreshGolden(DIALOG_EXPECTED, snapshot, MODE)
  90. // Section switch: aria-current moves (the Models page itself has its own scenario file).
  91. await dialog.getByRole('button', { name: '模型' }).click()
  92. await expect.poll(() => dialog.getByRole('button', { name: '模型' }).getAttribute('aria-current'), { timeout: 5_000 }).toBe('true')
  93. expect(await dialog.getByRole('button', { name: '通用设置' }).getAttribute('aria-current')).toBeNull()
  94. // Plugins is a read-only projection of the same assembled Loader tree.
  95. // Capture one stable shipped row rather than the whole inventory so adding
  96. // an unrelated plugin does not rewrite this surface's golden.
  97. await dialog.getByRole('button', { name: '插件', exact: true }).click()
  98. await dialog.getByRole('heading', { name: '插件', exact: true }).waitFor({ timeout: 10_000 })
  99. await dialog.getByRole('tab', { name: '插件列表', exact: true }).click()
  100. // The preset group opens first with its display-only switcher; the global
  101. // plane starts collapsed and expands on demand.
  102. const presetSwitcher = dialog.getByRole('button', { name: '选择要查看的 Agent 预设' })
  103. await presetSwitcher.waitFor({ timeout: 10_000 })
  104. // The shipped default's zh display name comes from the zh dictionaries.
  105. expect(await presetSwitcher.textContent()).toBe('标准模式(默认)')
  106. await dialog.getByRole('button', { name: /^全局/ }).click()
  107. const pluginRow = dialog.locator(PLUGIN_ROW_SELECTOR)
  108. await pluginRow.waitFor({ timeout: 10_000 })
  109. const expectedPluginCount = [...scaffold.ctx.loader.entries()]
  110. .filter(entry => !entry.options.group)
  111. .length
  112. expect(await dialog.getByRole('searchbox', { name: '搜索插件' }).count()).toBe(1)
  113. // Every Loader entry appears exactly once in the global group — rows the
  114. // presets took over included, preset compositions excluded.
  115. expect(await dialog.locator('[data-plugin-scope="global"] [data-plugin-entry]').count())
  116. .toBe(expectedPluginCount)
  117. expect(await dialog.locator('[data-plugin-count]').getAttribute('data-plugin-count'))
  118. .toBe(String(expectedPluginCount))
  119. expect(await dialog.getByRole('button', { name: '插件', exact: true }).getAttribute('aria-current')).toBe('true')
  120. expect(await dialog.getByRole('tab', { name: '插件列表', exact: true }).getAttribute('aria-selected')).toBe('true')
  121. expect(await dialog.getByRole('button', { name: '模型' }).getAttribute('aria-current')).toBeNull()
  122. const pluginsSnapshot = await captureStableAria(
  123. page,
  124. PLUGIN_ROW_SELECTOR,
  125. scaffold.workspaceCwd,
  126. )
  127. await compareOrRefreshGolden(PLUGINS_EXPECTED, pluginsSnapshot, MODE)
  128. // Close path 1: Escape.
  129. await page.keyboard.press('Escape')
  130. await expect.poll(() => page.getByRole('dialog', { name: '设置' }).count(), { timeout: 5_000 }).toBe(0)
  131. expect(await trigger.getAttribute('aria-expanded')).toBe('false')
  132. // Close path 2: the header close button (focus lands there on open).
  133. await trigger.click()
  134. await page.getByRole('dialog', { name: '设置' }).getByRole('button', { name: '关闭' }).click()
  135. await expect.poll(() => page.getByRole('dialog', { name: '设置' }).count(), { timeout: 5_000 }).toBe(0)
  136. expect(tripwire.pageErrors).toEqual([])
  137. }, 60_000)
  138. it('stores Permission as the default for future sessions without changing an existing session', async () => {
  139. onTestFailed(() => saveFailureShot(page, 'web-e2e-settings-permission'))
  140. const existing = scaffold.ctx.sessions.create(SessionId('settings-permission-before'))
  141. expect(existing.snapshotEvents().find(event => event.type === 'permission/preset')?.data)
  142. .toEqual({ preset: 'workspace-write' })
  143. await page.getByRole('button', { name: '设置', exact: true }).click()
  144. const dialog = page.getByRole('dialog', { name: '设置' })
  145. await dialog.waitFor({ timeout: 10_000 })
  146. const selector = dialog.getByRole('button', { name: '工作区内修改' })
  147. await selector.waitFor({ timeout: 10_000 })
  148. await expect.poll(() => selector.isEnabled(), { timeout: 5_000 }).toBe(true)
  149. await selector.click()
  150. await page.getByRole('menuitem', { name: '仅可查看' }).click()
  151. await dialog.getByRole('button', { name: '仅可查看' }).waitFor({ timeout: 10_000 })
  152. const document = await readFile(join(scaffold.harnessHome, 'settings.yaml'), 'utf8')
  153. expect(document).toContain('permission:')
  154. expect(document).toContain('defaultPreset: read-only')
  155. expect(existing.snapshotEvents().find(event => event.type === 'permission/preset')?.data)
  156. .toEqual({ preset: 'workspace-write' })
  157. const created = scaffold.ctx.sessions.create(SessionId('settings-permission-after'))
  158. expect(created.snapshotEvents().map(event => [event.type, event.data])).toEqual([
  159. ['permission/preset', { preset: 'read-only' }],
  160. ['sandbox/mode', { mode: 'read-only' }],
  161. ['approval/policy', { policy: 'ask' }],
  162. ])
  163. await dialog.getByRole('button', { name: '仅可查看' }).click()
  164. await page.getByRole('menuitem', { name: '完全权限' }).click()
  165. const confirmation = page.getByRole('dialog', { name: '确认启用完全权限?' })
  166. const enable = confirmation.getByRole('button', { name: '启用完全权限' })
  167. expect(await enable.isDisabled()).toBe(true)
  168. await confirmation.getByRole('checkbox').click()
  169. await enable.click()
  170. await dialog.getByRole('button', { name: '完全权限' }).waitFor({ timeout: 10_000 })
  171. const confirmedDocument = await readFile(join(scaffold.harnessHome, 'settings.yaml'), 'utf8')
  172. expect(confirmedDocument).toContain('defaultPreset: danger-full-access')
  173. const confirmed = scaffold.ctx.sessions.create(SessionId('settings-permission-confirmed'))
  174. expect(confirmed.snapshotEvents().map(event => [event.type, event.data])).toEqual([
  175. ['permission/preset', { preset: 'danger-full-access' }],
  176. ['sandbox/mode', { mode: 'danger-full-access' }],
  177. ['approval/policy', { policy: 'never' }],
  178. ])
  179. await page.keyboard.press('Escape')
  180. expect(tripwire.pageErrors).toEqual([])
  181. }, 60_000)
  182. async function selectTheme(cube: Locator, preference: 'light' | 'dark' | 'system'): Promise<void> {
  183. // Optimistic UI and a file value from an earlier gesture do not prove this write finished.
  184. const [response] = await Promise.all([
  185. page.waitForResponse((candidate) => {
  186. if (candidate.request().method() !== 'POST'
  187. || new URL(candidate.url()).pathname !== '/api/settings/mutate') return false
  188. const { payload: { args } } = candidate.request().postDataJSON() as {
  189. payload: { args: { ns: string; ops: { op: string; path: string[]; value?: unknown }[] } }
  190. }
  191. return args.ns === 'ui-theme' && args.ops.some(op => op.op === 'set'
  192. && op.path.length === 1 && op.path[0] === 'preference' && op.value === preference)
  193. }, { timeout: 5_000 }),
  194. cube.click(),
  195. ])
  196. expect(response.ok()).toBe(true)
  197. expect(await response.json()).toMatchObject({
  198. result: { ok: true, value: { ns: 'ui-theme', value: { preference } } },
  199. })
  200. }
  201. it('uses the persisted dark preference while plugins are still loading', async () => {
  202. onTestFailed(() => saveFailureShot(page, 'web-e2e-settings-boot-theme'))
  203. await page.emulateMedia({ colorScheme: 'light' })
  204. await page.getByRole('button', { name: '设置', exact: true }).click()
  205. const initialDialog = page.getByRole('dialog', { name: '设置' })
  206. const darkCube = initialDialog.getByRole('button', { name: '深色' })
  207. await selectTheme(darkCube, 'dark')
  208. await expect.poll(() => darkCube.getAttribute('aria-pressed'), { timeout: 5_000 }).toBe('true')
  209. await expect.poll(async () => readFile(join(scaffold.harnessHome, 'settings.yaml'), 'utf8'), { timeout: 5_000 })
  210. .toMatch(/ui-theme:\n\s+preference: dark/)
  211. await page.keyboard.press('Escape')
  212. // Hold the real application batch so the shell-owned loading page remains observable.
  213. const pluginPattern = /\/plugins\/\?\?.+\/client\.js,.+\/client\.js&rev=[a-f\d]{12}$/
  214. let releaseBundles = (): void => {}
  215. const bundlesReleased = new Promise<void>((resolve) => { releaseBundles = resolve })
  216. await page.route(pluginPattern, async (route) => {
  217. await bundlesReleased
  218. await route.continue()
  219. })
  220. const warningStart = tripwire.warnings.length
  221. let reload: ReturnType<Page['reload']> | undefined
  222. try {
  223. reload = page.reload({ waitUntil: 'domcontentloaded' })
  224. const loading = page.getByText('Loading plugins…', { exact: true })
  225. await loading.waitFor({ timeout: 10_000 })
  226. const state = await loading.evaluate((element) => {
  227. const boot = element.parentElement?.parentElement
  228. if (boot === undefined || boot === null) throw new Error('loading hint is detached from the boot page')
  229. return {
  230. attr: document.body.hasAttribute('data-ds-dark-theme'),
  231. background: getComputedStyle(boot).backgroundColor,
  232. colorScheme: document.documentElement.style.colorScheme,
  233. }
  234. })
  235. expect(state).toEqual({
  236. attr: true,
  237. background: 'rgb(21, 21, 23)',
  238. colorScheme: 'dark',
  239. })
  240. } finally {
  241. releaseBundles()
  242. await reload
  243. await page.unroute(pluginPattern)
  244. }
  245. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  246. acknowledgeReloadConnectionLoss(tripwire, warningStart)
  247. await page.getByRole('button', { name: '设置', exact: true }).click()
  248. const restoredDialog = page.getByRole('dialog', { name: '设置' })
  249. const systemCube = restoredDialog.getByRole('button', { name: '跟随系统' })
  250. await selectTheme(systemCube, 'system')
  251. await expect.poll(() => systemCube.getAttribute('aria-pressed'), { timeout: 5_000 }).toBe('true')
  252. await expect.poll(() => page.evaluate(() => document.body.hasAttribute('data-ds-dark-theme')), {
  253. timeout: 5_000,
  254. }).toBe(false)
  255. await page.keyboard.press('Escape')
  256. expect(tripwire.pageErrors).toEqual([])
  257. }, 90_000)
  258. it('flips the theme through the Appearance cubes and persists across reload and a distinct port', async () => {
  259. onTestFailed(() => saveFailureShot(page, 'web-e2e-settings-appearance'))
  260. interface ThemeState {
  261. attr: boolean
  262. background: string
  263. /** Pre-migration localStorage key; the Host-backed world never writes it. */
  264. legacy: string | null
  265. themeColor: string | null
  266. themeColorCount: number
  267. token: string
  268. }
  269. const readState = async (target: Page = page): Promise<ThemeState> => await target.evaluate(() => {
  270. const metas = document.head.querySelectorAll<HTMLMetaElement>('meta[name="theme-color"]')
  271. const computed = getComputedStyle(document.body)
  272. return {
  273. attr: document.body.hasAttribute('data-ds-dark-theme'),
  274. background: computed.backgroundColor,
  275. legacy: localStorage.getItem('dsh.theme'),
  276. themeColor: metas[0]?.content ?? null,
  277. themeColorCount: metas.length,
  278. token: computed.getPropertyValue('--dsw-alias-bg-base').trim(),
  279. }
  280. })
  281. const expectThemeColorSynchronized = (state: ThemeState): void => {
  282. expect(state.themeColorCount).toBe(1)
  283. expect(state.background).not.toBe('rgba(0, 0, 0, 0)')
  284. expect(state.themeColor).toBe(state.background)
  285. }
  286. // Pin the OS scheme to light so the default `system` preference resolves
  287. // light and the dark flip below is unambiguously the gesture's doing.
  288. await page.emulateMedia({ colorScheme: 'light' })
  289. const light = await readState()
  290. expect(light.attr).toBe(false)
  291. expectThemeColorSynchronized(light)
  292. await page.getByRole('button', { name: '设置', exact: true }).click()
  293. const dialog = page.getByRole('dialog', { name: '设置' })
  294. await dialog.waitFor({ timeout: 10_000 })
  295. const darkCube = dialog.getByRole('button', { name: '深色' })
  296. expect(await darkCube.getAttribute('aria-pressed')).toBe('false')
  297. await selectTheme(darkCube, 'dark')
  298. // The full cascade: pressed state, Host-backed preference, body attribute,
  299. // alias token flip — all from one real user gesture.
  300. await expect.poll(() => darkCube.getAttribute('aria-pressed'), { timeout: 5_000 }).toBe('true')
  301. const dark = await readState()
  302. expect(dark.attr).toBe(true)
  303. expect(dark.legacy).toBeNull()
  304. expect(dark.token).not.toBe(light.token)
  305. expectThemeColorSynchronized(dark)
  306. await expect.poll(async () => readFile(join(scaffold.harnessHome, 'settings.yaml'), 'utf8'), { timeout: 5_000 })
  307. .toMatch(/ui-theme:\n\s+preference: dark/)
  308. await page.keyboard.press('Escape')
  309. // Reload: the preference survives the background Host read + presenter update.
  310. const warningStart = tripwire.warnings.length
  311. await page.reload({ waitUntil: 'load' })
  312. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  313. acknowledgeReloadConnectionLoss(tripwire, warningStart)
  314. await page.emulateMedia({ colorScheme: 'light' })
  315. await expect.poll(async () => (await readState()).attr, { timeout: 5_000 }).toBe(true)
  316. const reloaded = await readState()
  317. expect(reloaded.legacy).toBeNull()
  318. expectThemeColorSynchronized(reloaded)
  319. // A second live Host binds another ephemeral port but shares the same
  320. // user-settings home. Its fresh origin has no theme localStorage and still
  321. // converges to dark before the settings dialog opens.
  322. const second = await launchWebScaffold({ harnessHome: scaffold.harnessHome })
  323. const secondPage = await browser.newPage({ viewport: { width: 1680, height: 1000 }, locale: ZH_BROWSER_LOCALE })
  324. const secondTripwire = watchConsole(secondPage)
  325. try {
  326. expect(second.baseUrl).not.toBe(scaffold.baseUrl)
  327. await secondPage.emulateMedia({ colorScheme: 'light' })
  328. await secondPage.goto(second.authenticatedUrl, { waitUntil: 'load' })
  329. await secondPage.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  330. await expect.poll(async () => (await readState(secondPage)).attr, { timeout: 5_000 }).toBe(true)
  331. const secondState = await readState(secondPage)
  332. expect(secondState.legacy).toBeNull()
  333. expectThemeColorSynchronized(secondState)
  334. expect(secondTripwire.pageErrors).toEqual([])
  335. expect(secondTripwire.warnings).toEqual([])
  336. } finally {
  337. await secondPage.close()
  338. await second.close()
  339. }
  340. // `system` follows the emulated OS scheme (dark stays dark, light clears).
  341. await page.getByRole('button', { name: '设置', exact: true }).click()
  342. const systemCube = page.getByRole('dialog', { name: '设置' }).getByRole('button', { name: '跟随系统' })
  343. await selectTheme(systemCube, 'system')
  344. await expect.poll(() => systemCube.getAttribute('aria-pressed'), { timeout: 5_000 }).toBe('true')
  345. await expect.poll(async () => (await readState()).attr, { timeout: 5_000 }).toBe(false)
  346. expectThemeColorSynchronized(await readState())
  347. await page.emulateMedia({ colorScheme: 'dark' })
  348. await expect.poll(async () => (await readState()).attr, { timeout: 5_000 }).toBe(true)
  349. expectThemeColorSynchronized(await readState())
  350. // Restore for the specs that follow: light preference beats the emulated
  351. // dark OS scheme, leaving the shared page in the light default.
  352. await selectTheme(page.getByRole('dialog', { name: '设置' }).getByRole('button', { name: '浅色' }), 'light')
  353. await expect.poll(async () => (await readState()).attr, { timeout: 5_000 }).toBe(false)
  354. expectThemeColorSynchronized(await readState())
  355. await page.keyboard.press('Escape')
  356. expect(tripwire.pageErrors).toEqual([])
  357. }, 90_000)
  358. it('steps the content font size, applies it to body, and persists across reload', async () => {
  359. onTestFailed(() => saveFailureShot(page, 'web-e2e-settings-font-size'))
  360. onTestFinished(async () => {
  361. await page.keyboard.press('Escape')
  362. await page.getByRole('dialog', { name: '设置', exact: true }).waitFor({ state: 'hidden' })
  363. })
  364. const readFontSize = async (target: Page = page): Promise<string> => await target.evaluate(
  365. () => document.body.style.getPropertyValue('--dsh-content-font-size'),
  366. )
  367. // The secondary tier resolved by the real engine: a probe element's
  368. // font-size forces min/max/calc evaluation, which the CSS-text specs
  369. // cannot exercise. Setting −1 at ≤14, setting −2 above.
  370. const readSecondaryFontSize = async (): Promise<string> => await page.evaluate(() => {
  371. const probe = document.createElement('div')
  372. probe.style.fontSize = 'var(--dsh-content-font-size-secondary, 13px)'
  373. document.body.appendChild(probe)
  374. const size = getComputedStyle(probe).fontSize
  375. probe.remove()
  376. return size
  377. })
  378. // The displayed value is optimistic; wait for the write before the next step.
  379. const stepFontSize = async (button: Locator, px: number): Promise<void> => {
  380. const [response] = await Promise.all([
  381. page.waitForResponse((reply) => {
  382. if (new URL(reply.url()).pathname !== '/api/settings/mutate' || reply.request().method() !== 'POST') return false
  383. const request = reply.request().postDataJSON() as { payload: { args: { ns: string } } }
  384. return request.payload.args.ns === 'ui-theme'
  385. }),
  386. button.click(),
  387. ])
  388. expect(await response.finished()).toBeNull()
  389. const envelope = await response.json() as { result: { ok: boolean } }
  390. expect(envelope.result.ok).toBe(true)
  391. await expect.poll(async () => readFile(join(scaffold.harnessHome, 'settings.yaml'), 'utf8'), { timeout: 5_000 })
  392. .toMatch(new RegExp(`ui-theme:\n(?:\\s+\\w+: .*\n)*?\\s+fontSize: ${px}`))
  393. await page.getByRole('dialog', { name: '设置' }).getByText(String(px), { exact: true }).waitFor({ timeout: 5_000 })
  394. await expect.poll(readFontSize, { timeout: 5_000 }).toBe(`${px}px`)
  395. }
  396. expect(await readFontSize()).toBe('14px')
  397. expect(await readSecondaryFontSize()).toBe('13px')
  398. await page.getByRole('button', { name: '设置', exact: true }).click()
  399. const dialog = page.getByRole('dialog', { name: '设置' })
  400. await dialog.waitFor({ timeout: 10_000 })
  401. // The stepper reveals its arrows on hover; the up arrow steps 14 → 15 → 16.
  402. await dialog.getByText('14', { exact: true }).hover()
  403. const increase = dialog.getByRole('button', { name: '增大字号' })
  404. await stepFontSize(increase, 15)
  405. // 15 is the piecewise boundary: the secondary tier holds at 13px (−2)
  406. // where the ≤14 branch would have given 14px (−1).
  407. await expect.poll(readSecondaryFontSize, { timeout: 5_000 }).toBe('13px')
  408. await stepFontSize(increase, 16)
  409. await expect.poll(readSecondaryFontSize, { timeout: 5_000 }).toBe('14px')
  410. await page.keyboard.press('Escape')
  411. // Reload: the boot script embeds the durable size and ThemeRuntime seeds
  412. // its initial snapshot from the boot-written body variable, so activation
  413. // never flashes the default while the settings read is in flight.
  414. const warningStart = tripwire.warnings.length
  415. await page.reload({ waitUntil: 'load' })
  416. acknowledgeReloadConnectionLoss(tripwire, warningStart)
  417. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  418. await expect.poll(readFontSize, { timeout: 5_000 }).toBe('16px')
  419. expect(await readSecondaryFontSize()).toBe('14px')
  420. // Restore the default for the specs that follow (and the dialog golden).
  421. await page.getByRole('button', { name: '设置', exact: true }).click()
  422. const restored = page.getByRole('dialog', { name: '设置' })
  423. await restored.waitFor({ timeout: 10_000 })
  424. await restored.getByText('16', { exact: true }).hover()
  425. const decrease = restored.getByRole('button', { name: '减小字号' })
  426. await stepFontSize(decrease, 15)
  427. await stepFontSize(decrease, 14)
  428. await page.keyboard.press('Escape')
  429. expect(tripwire.pageErrors).toEqual([])
  430. }, 90_000)
  431. it('persists the completed-Turn transcript mode across reload', async () => {
  432. onTestFailed(() => saveFailureShot(page, 'web-e2e-settings-transcript-view'))
  433. await page.getByRole('button', { name: '设置', exact: true }).click()
  434. const dialog = page.getByRole('dialog', { name: '设置' })
  435. await dialog.waitFor({ timeout: 10_000 })
  436. await dialog.getByText('对话显示', { exact: true }).waitFor({ timeout: 10_000 })
  437. await dialog.getByRole('button', { name: '紧凑', exact: true }).click()
  438. await page.getByRole('menuitem', { name: '标准', exact: true }).click()
  439. await dialog.getByRole('button', { name: '标准', exact: true }).waitFor({ timeout: 10_000 })
  440. await expect.poll(async () => readFile(join(scaffold.harnessHome, 'settings.yaml'), 'utf8'), { timeout: 5_000 })
  441. .toMatch(/ui-chat:\n\s+transcriptView: normal/)
  442. await page.keyboard.press('Escape')
  443. const warningStart = tripwire.warnings.length
  444. await page.reload({ waitUntil: 'load' })
  445. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  446. acknowledgeReloadConnectionLoss(tripwire, warningStart)
  447. await page.getByRole('button', { name: '设置', exact: true }).click()
  448. const reloaded = page.getByRole('dialog', { name: '设置' })
  449. await reloaded.getByRole('button', { name: '标准', exact: true }).waitFor({ timeout: 10_000 })
  450. await reloaded.getByRole('button', { name: '标准', exact: true }).click()
  451. await page.getByRole('menuitem', { name: '紧凑', exact: true }).click()
  452. await reloaded.getByRole('button', { name: '紧凑', exact: true }).waitFor({ timeout: 10_000 })
  453. await expect.poll(async () => readFile(join(scaffold.harnessHome, 'settings.yaml'), 'utf8'), { timeout: 5_000 })
  454. .toMatch(/ui-chat:\n\s+transcriptView: compact/)
  455. await page.keyboard.press('Escape')
  456. expect(tripwire.pageErrors).toEqual([])
  457. }, 90_000)
  458. it('persists the busy-state Enter behavior across reload and a distinct port', async () => {
  459. onTestFailed(() => saveFailureShot(page, 'web-e2e-settings-enter-behavior'))
  460. await page.getByRole('button', { name: '设置', exact: true }).click()
  461. const dialog = page.getByRole('dialog', { name: '设置' })
  462. await dialog.waitFor({ timeout: 10_000 })
  463. await dialog.getByRole('button', { name: '排队发送' }).click()
  464. await page.getByRole('menuitem', { name: '插话发送' }).click()
  465. await dialog.getByRole('button', { name: '插话发送' }).waitFor({ timeout: 10_000 })
  466. expect(await page.evaluate(() => localStorage.getItem('dsh.conversation.busyEnter'))).toBeNull()
  467. await expect.poll(async () => readFile(join(scaffold.harnessHome, 'settings.yaml'), 'utf8'), { timeout: 5_000 })
  468. .toMatch(/ui-conversation:\n\s+busyEnter: steer/)
  469. await page.keyboard.press('Escape')
  470. const warningStart = tripwire.warnings.length
  471. await page.reload({ waitUntil: 'load' })
  472. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  473. acknowledgeReloadConnectionLoss(tripwire, warningStart)
  474. await page.getByRole('button', { name: '设置', exact: true }).click()
  475. const reloaded = page.getByRole('dialog', { name: '设置' })
  476. await reloaded.getByRole('button', { name: '插话发送' }).waitFor({ timeout: 10_000 })
  477. const second = await launchWebScaffold({ harnessHome: scaffold.harnessHome })
  478. const secondPage = await browser.newPage({ viewport: { width: 1680, height: 1000 }, locale: ZH_BROWSER_LOCALE })
  479. const secondTripwire = watchConsole(secondPage)
  480. try {
  481. expect(second.baseUrl).not.toBe(scaffold.baseUrl)
  482. await secondPage.goto(second.authenticatedUrl, { waitUntil: 'load' })
  483. await secondPage.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  484. await secondPage.getByRole('button', { name: '设置', exact: true }).click()
  485. await secondPage.getByRole('dialog', { name: '设置' })
  486. .getByRole('button', { name: '插话发送' }).waitFor({ timeout: 10_000 })
  487. expect(await secondPage.evaluate(() => localStorage.getItem('dsh.conversation.busyEnter'))).toBeNull()
  488. expect(secondTripwire.pageErrors).toEqual([])
  489. expect(secondTripwire.warnings).toEqual([])
  490. } finally {
  491. await secondPage.close()
  492. await second.close()
  493. }
  494. await reloaded.getByRole('button', { name: '插话发送' }).click()
  495. await page.getByRole('menuitem', { name: '排队发送' }).click()
  496. await reloaded.getByRole('button', { name: '排队发送' }).waitFor({ timeout: 10_000 })
  497. expect(await page.evaluate(() => localStorage.getItem('dsh.conversation.busyEnter'))).toBeNull()
  498. await expect.poll(async () => readFile(join(scaffold.harnessHome, 'settings.yaml'), 'utf8'), { timeout: 5_000 })
  499. .toMatch(/ui-conversation:\n\s+busyEnter: queue/)
  500. await page.keyboard.press('Escape')
  501. expect(tripwire.pageErrors).toEqual([])
  502. }, 90_000)
  503. it('persists the settings language across reload and a distinct port', async () => {
  504. onTestFailed(() => saveFailureShot(page, 'web-e2e-settings-language'))
  505. await page.getByRole('button', { name: '设置', exact: true }).click()
  506. const zhDialog = page.getByRole('dialog', { name: '设置' })
  507. await zhDialog.waitFor({ timeout: 10_000 })
  508. // The document language follows the active locale in the assembled app, not
  509. // only on a directly-mounted plugin. This is a zh browser, so the served
  510. // markup's `en` must already have been replaced — asserting it here (rather
  511. // than only in an English scenario) is what makes the check discriminating.
  512. expect(await page.evaluate(() => document.documentElement.lang)).toBe('zh-CN')
  513. // The Language selector pill shows the active locale's own name.
  514. const selector = zhDialog.getByRole('button', { name: '中文' })
  515. expect(await selector.getAttribute('aria-haspopup')).toBe('menu')
  516. await selector.click()
  517. await page.getByRole('menuitem', { name: 'English' }).click()
  518. // The settings-owned copy re-registers localized: dialog title, nav,
  519. // Appearance labels. (Only the settings namespaces are localized —
  520. // the rest of the app's copy is intentionally out of this row's scope.)
  521. const enDialog = page.getByRole('dialog', { name: 'Settings' })
  522. await enDialog.waitFor({ timeout: 10_000 })
  523. // ...and the attribute follows that switch, in the assembled app.
  524. await expect.poll(() => page.evaluate(() => document.documentElement.lang), { timeout: 5_000 }).toBe('en')
  525. expect(await enDialog.getByRole('button', { name: 'General' }).getAttribute('aria-current')).toBe('true')
  526. await expect.poll(() => enDialog.getByText('Appearance', { exact: true }).count(), { timeout: 5_000 }).toBe(1)
  527. expect(await page.evaluate(() => localStorage.getItem('dsh.locale'))).toBeNull()
  528. await expect.poll(async () => readFile(join(scaffold.harnessHome, 'settings.yaml'), 'utf8'), { timeout: 5_000 })
  529. .toMatch(/locale:\n\s+preference: en/)
  530. // Reload keeps English; then restore zh so shared page state (and the
  531. // other specs' 设置-anchored selectors + goldens) see the default again.
  532. const warningStart = tripwire.warnings.length
  533. await page.reload({ waitUntil: 'load' })
  534. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  535. acknowledgeReloadConnectionLoss(tripwire, warningStart)
  536. const enTrigger = page.getByRole('button', { name: 'Settings' })
  537. await enTrigger.waitFor({ timeout: 10_000 })
  538. // A Chinese browser on another port still receives the explicit English
  539. // preference from the shared Host settings document.
  540. const second = await launchWebScaffold({ harnessHome: scaffold.harnessHome })
  541. const secondPage = await browser.newPage({ viewport: { width: 1680, height: 1000 }, locale: ZH_BROWSER_LOCALE })
  542. const secondTripwire = watchConsole(secondPage)
  543. try {
  544. expect(second.baseUrl).not.toBe(scaffold.baseUrl)
  545. await secondPage.goto(second.authenticatedUrl, { waitUntil: 'load' })
  546. await secondPage.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  547. await secondPage.getByRole('button', { name: 'Settings', exact: true }).click()
  548. await secondPage.getByRole('dialog', { name: 'Settings' })
  549. .getByRole('button', { name: 'English' }).waitFor({ timeout: 10_000 })
  550. expect(await secondPage.evaluate(() => localStorage.getItem('dsh.locale'))).toBeNull()
  551. expect(secondTripwire.pageErrors).toEqual([])
  552. expect(secondTripwire.warnings).toEqual([])
  553. } finally {
  554. await secondPage.close()
  555. await second.close()
  556. }
  557. await enTrigger.click()
  558. await page.getByRole('dialog', { name: 'Settings' }).getByRole('button', { name: 'English' }).click()
  559. await page.getByRole('menuitem', { name: '中文' }).click()
  560. await page.getByRole('dialog', { name: '设置' }).waitFor({ timeout: 10_000 })
  561. expect(await page.evaluate(() => localStorage.getItem('dsh.locale'))).toBeNull()
  562. await expect.poll(async () => readFile(join(scaffold.harnessHome, 'settings.yaml'), 'utf8'), { timeout: 5_000 })
  563. .toMatch(/locale:\n\s+preference: zh/)
  564. await page.keyboard.press('Escape')
  565. expect(tripwire.pageErrors).toEqual([])
  566. }, 90_000)
  567. it('opens an English browser in English without any stored preference', async () => {
  568. // A fresh Host home has no locale preference, so its surface follows the
  569. // browser. English is also FALLBACK_LOCALE, so this scenario alone cannot
  570. // distinguish detection from the default — the zh scenarios above supply
  571. // the discriminating half (a Chinese browser must NOT land on the default).
  572. const fresh = await launchWebScaffold({})
  573. const enPage = await browser.newPage({ viewport: { width: 1680, height: 1000 }, locale: 'en-US' })
  574. const enTripwire = watchConsole(enPage)
  575. onTestFailed(() => saveFailureShot(enPage, 'web-e2e-settings-browser-language'))
  576. try {
  577. await enPage.goto(fresh.authenticatedUrl, { waitUntil: 'load' })
  578. await enPage.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  579. expect(await enPage.evaluate(() => localStorage.getItem('dsh.locale'))).toBeNull()
  580. await enPage.getByRole('button', { name: 'Settings', exact: true }).click()
  581. const dialog = enPage.getByRole('dialog', { name: 'Settings' })
  582. await dialog.waitFor({ timeout: 10_000 })
  583. await dialog.getByRole('button', { name: 'English' }).waitFor({ timeout: 10_000 })
  584. // The plugin list resolves shipped preset names through the en
  585. // dictionaries instead of echoing the preset files' Chinese metadata.
  586. await dialog.getByRole('button', { name: 'Plugins', exact: true }).click()
  587. await dialog.getByRole('tab', { name: 'Plugin list', exact: true }).click()
  588. const presetSwitcher = dialog.getByRole('button', { name: 'Choose the agent preset to inspect' })
  589. await presetSwitcher.waitFor({ timeout: 10_000 })
  590. expect(await presetSwitcher.textContent()).toBe('Standard mode (default)')
  591. // This page has no closing inventory spec to sweep its console, so the
  592. // scenario clears both tripwire channels itself.
  593. expect(enTripwire.pageErrors).toEqual([])
  594. expect(enTripwire.warnings).toEqual([])
  595. } finally {
  596. await enPage.close()
  597. await fresh.close()
  598. }
  599. }, 90_000)
  600. it('opens a browser asking for no shipped language in English', async () => {
  601. // The product default for "no usable signal": a French browser ships
  602. // neither zh nor en, so resolution falls to FALLBACK_LOCALE (en) rather
  603. // than to Chinese.
  604. const fresh = await launchWebScaffold({})
  605. const frPage = await browser.newPage({ viewport: { width: 1680, height: 1000 }, locale: 'fr-FR' })
  606. const frTripwire = watchConsole(frPage)
  607. onTestFailed(() => saveFailureShot(frPage, 'web-e2e-settings-unshipped-language'))
  608. try {
  609. await frPage.goto(fresh.authenticatedUrl, { waitUntil: 'load' })
  610. await frPage.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  611. expect(await frPage.evaluate(() => localStorage.getItem('dsh.locale'))).toBeNull()
  612. await frPage.getByRole('button', { name: 'Settings', exact: true }).click()
  613. const dialog = frPage.getByRole('dialog', { name: 'Settings' })
  614. await dialog.waitFor({ timeout: 10_000 })
  615. await dialog.getByRole('button', { name: 'English' }).waitFor({ timeout: 10_000 })
  616. // A locale-owned nav label proves the dictionaries resolved to en.
  617. await dialog.getByRole('button', { name: 'Agent presets' }).waitFor({ timeout: 10_000 })
  618. // The markup already ships `en`, so this alone cannot prove the sync ran
  619. // — the zh scenario above is the discriminating half. Asserted here too
  620. // so a future change that resolves en but writes the wrong tag is caught.
  621. expect(await frPage.evaluate(() => document.documentElement.lang)).toBe('en')
  622. // Golden of the English fallback dialog — the visible output this change
  623. // produces. The zh golden above covers the detected-locale surface, so
  624. // the pair pins both directions of the resolution.
  625. const snapshot = await captureStableAria(frPage, '[role="dialog"]', fresh.workspaceCwd)
  626. await compareOrRefreshGolden(DIALOG_EN_EXPECTED, snapshot, MODE)
  627. expect(frTripwire.pageErrors).toEqual([])
  628. expect(frTripwire.warnings).toEqual([])
  629. } finally {
  630. await frPage.close()
  631. await fresh.close()
  632. }
  633. }, 90_000)
  634. it.skipIf(MODE === 'record')('keeps the fixture inventory closed', async () => {
  635. expect(tripwire.warnings).toEqual([])
  636. await assertFixtureInventory(SNAPSHOT_DIR, ['dialog-en.expected.md', 'dialog.expected.md', 'plugins.expected.md'])
  637. })
  638. })