settings-chrome.e2e.ts 39 KB

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