settings-chrome.e2e.ts 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713
  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. // The boot palette precedes the settings mirror's saved preference.
  282. const restoredDarkCube = restoredDialog.getByRole('button', { name: '深色' })
  283. await expect.poll(() => restoredDarkCube.getAttribute('aria-pressed'), { timeout: 5_000 }).toBe('true')
  284. await selectTheme(systemCube, 'system')
  285. await expect.poll(() => systemCube.getAttribute('aria-pressed'), { timeout: 5_000 }).toBe('true')
  286. await expect.poll(() => page.evaluate(() => document.body.hasAttribute('data-ds-dark-theme')), {
  287. timeout: 5_000,
  288. }).toBe(false)
  289. await page.keyboard.press('Escape')
  290. expect(tripwire.pageErrors).toEqual([])
  291. }, 90_000)
  292. it('flips the theme through the Appearance cubes and persists across reload and a distinct port', async () => {
  293. onTestFailed(() => saveFailureShot(page, 'web-e2e-settings-appearance'))
  294. interface ThemeState {
  295. attr: boolean
  296. background: string
  297. /** Pre-migration localStorage key; the Host-backed world never writes it. */
  298. legacy: string | null
  299. themeColor: string | null
  300. themeColorCount: number
  301. token: string
  302. }
  303. const readState = async (target: Page = page): Promise<ThemeState> => await target.evaluate(() => {
  304. const metas = document.head.querySelectorAll<HTMLMetaElement>('meta[name="theme-color"]')
  305. const computed = getComputedStyle(document.body)
  306. return {
  307. attr: document.body.hasAttribute('data-ds-dark-theme'),
  308. background: computed.backgroundColor,
  309. legacy: localStorage.getItem('dsh.theme'),
  310. themeColor: metas[0]?.content ?? null,
  311. themeColorCount: metas.length,
  312. token: computed.getPropertyValue('--dsw-alias-bg-base').trim(),
  313. }
  314. })
  315. const expectThemeColorSynchronized = (state: ThemeState): void => {
  316. expect(state.themeColorCount).toBe(1)
  317. expect(state.background).not.toBe('rgba(0, 0, 0, 0)')
  318. expect(state.themeColor).toBe(state.background)
  319. }
  320. // Pin the OS scheme to light so the default `system` preference resolves
  321. // light and the dark flip below is unambiguously the gesture's doing.
  322. await page.emulateMedia({ colorScheme: 'light' })
  323. const light = await readState()
  324. expect(light.attr).toBe(false)
  325. expectThemeColorSynchronized(light)
  326. await page.getByRole('button', { name: '设置', exact: true }).click()
  327. const dialog = page.getByRole('dialog', { name: '设置' })
  328. await dialog.waitFor({ timeout: 10_000 })
  329. const darkCube = dialog.getByRole('button', { name: '深色' })
  330. expect(await darkCube.getAttribute('aria-pressed')).toBe('false')
  331. await selectTheme(darkCube, 'dark')
  332. // The full cascade: pressed state, Host-backed preference, body attribute,
  333. // alias token flip — all from one real user gesture.
  334. await expect.poll(() => darkCube.getAttribute('aria-pressed'), { timeout: 5_000 }).toBe('true')
  335. const dark = await readState()
  336. expect(dark.attr).toBe(true)
  337. expect(dark.legacy).toBeNull()
  338. expect(dark.token).not.toBe(light.token)
  339. expectThemeColorSynchronized(dark)
  340. await expect.poll(async () => readFile(join(scaffold.harnessHome, 'settings.yaml'), 'utf8'), { timeout: 5_000 })
  341. .toMatch(/ui-theme:\n\s+preference: dark/)
  342. await page.keyboard.press('Escape')
  343. // Reload: the preference survives the background Host read + presenter update.
  344. const warningStart = tripwire.warnings.length
  345. await page.reload({ waitUntil: 'load' })
  346. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  347. acknowledgeReloadConnectionLoss(tripwire, warningStart)
  348. await page.emulateMedia({ colorScheme: 'light' })
  349. await expect.poll(async () => (await readState()).attr, { timeout: 5_000 }).toBe(true)
  350. const reloaded = await readState()
  351. expect(reloaded.legacy).toBeNull()
  352. expectThemeColorSynchronized(reloaded)
  353. // A second live Host binds another ephemeral port but shares the same
  354. // user-settings home. Its fresh origin has no theme localStorage and still
  355. // converges to dark before the settings dialog opens.
  356. const second = await launchWebScaffold({ harnessHome: scaffold.harnessHome })
  357. const secondPage = await browser.newPage({ viewport: { width: 1680, height: 1000 }, locale: ZH_BROWSER_LOCALE })
  358. const secondTripwire = watchConsole(secondPage)
  359. try {
  360. expect(second.baseUrl).not.toBe(scaffold.baseUrl)
  361. await secondPage.emulateMedia({ colorScheme: 'light' })
  362. await secondPage.goto(second.authenticatedUrl, { waitUntil: 'load' })
  363. await secondPage.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  364. await expect.poll(async () => (await readState(secondPage)).attr, { timeout: 5_000 }).toBe(true)
  365. const secondState = await readState(secondPage)
  366. expect(secondState.legacy).toBeNull()
  367. expectThemeColorSynchronized(secondState)
  368. expect(secondTripwire.pageErrors).toEqual([])
  369. expect(secondTripwire.warnings).toEqual([])
  370. } finally {
  371. await secondPage.close()
  372. await second.close()
  373. }
  374. // `system` follows the emulated OS scheme (dark stays dark, light clears).
  375. await page.getByRole('button', { name: '设置', exact: true }).click()
  376. const systemCube = page.getByRole('dialog', { name: '设置' }).getByRole('button', { name: '跟随系统' })
  377. await selectTheme(systemCube, 'system')
  378. await expect.poll(() => systemCube.getAttribute('aria-pressed'), { timeout: 5_000 }).toBe('true')
  379. await expect.poll(async () => (await readState()).attr, { timeout: 5_000 }).toBe(false)
  380. expectThemeColorSynchronized(await readState())
  381. await page.emulateMedia({ colorScheme: 'dark' })
  382. await expect.poll(async () => (await readState()).attr, { timeout: 5_000 }).toBe(true)
  383. expectThemeColorSynchronized(await readState())
  384. // Restore for the specs that follow: light preference beats the emulated
  385. // dark OS scheme, leaving the shared page in the light default.
  386. await selectTheme(page.getByRole('dialog', { name: '设置' }).getByRole('button', { name: '浅色' }), 'light')
  387. await expect.poll(async () => (await readState()).attr, { timeout: 5_000 }).toBe(false)
  388. expectThemeColorSynchronized(await readState())
  389. await page.keyboard.press('Escape')
  390. expect(tripwire.pageErrors).toEqual([])
  391. }, 90_000)
  392. it('steps the content font size, applies it to body, and persists across reload', async () => {
  393. onTestFailed(() => saveFailureShot(page, 'web-e2e-settings-font-size'))
  394. onTestFinished(async () => {
  395. await page.keyboard.press('Escape')
  396. await page.getByRole('dialog', { name: '设置', exact: true }).waitFor({ state: 'hidden' })
  397. })
  398. const readFontSize = async (target: Page = page): Promise<string> => await target.evaluate(
  399. () => document.body.style.getPropertyValue('--dsh-content-font-size'),
  400. )
  401. // The secondary tier resolved by the real engine: a probe element's
  402. // font-size forces min/max/calc evaluation, which the CSS-text specs
  403. // cannot exercise. Setting −1 at ≤14, setting −2 above.
  404. const readSecondaryFontSize = async (): Promise<string> => await page.evaluate(() => {
  405. const probe = document.createElement('div')
  406. probe.style.fontSize = 'var(--dsh-content-font-size-secondary, 13px)'
  407. document.body.appendChild(probe)
  408. const size = getComputedStyle(probe).fontSize
  409. probe.remove()
  410. return size
  411. })
  412. // The displayed value is optimistic; wait for the write before the next step.
  413. const stepFontSize = async (button: Locator, px: number): Promise<void> => {
  414. const [response] = await Promise.all([
  415. page.waitForResponse((reply) => {
  416. if (new URL(reply.url()).pathname !== '/api/settings/mutate' || reply.request().method() !== 'POST') return false
  417. const request = reply.request().postDataJSON() as { payload: { args: { ns: string } } }
  418. return request.payload.args.ns === 'ui-theme'
  419. }),
  420. button.click(),
  421. ])
  422. expect(await response.finished()).toBeNull()
  423. const envelope = await response.json() as { result: { ok: boolean } }
  424. expect(envelope.result.ok).toBe(true)
  425. await expect.poll(async () => readFile(join(scaffold.harnessHome, 'settings.yaml'), 'utf8'), { timeout: 5_000 })
  426. .toMatch(new RegExp(`ui-theme:\n(?:\\s+\\w+: .*\n)*?\\s+fontSize: ${px}`))
  427. await page.getByRole('dialog', { name: '设置' }).getByText(String(px), { exact: true }).waitFor({ timeout: 5_000 })
  428. await expect.poll(readFontSize, { timeout: 5_000 }).toBe(`${px}px`)
  429. }
  430. expect(await readFontSize()).toBe('14px')
  431. expect(await readSecondaryFontSize()).toBe('13px')
  432. await page.getByRole('button', { name: '设置', exact: true }).click()
  433. const dialog = page.getByRole('dialog', { name: '设置' })
  434. await dialog.waitFor({ timeout: 10_000 })
  435. // The stepper reveals its arrows on hover; the up arrow steps 14 → 15 → 16.
  436. await dialog.getByText('14', { exact: true }).hover()
  437. const increase = dialog.getByRole('button', { name: '增大字号' })
  438. await stepFontSize(increase, 15)
  439. // 15 is the piecewise boundary: the secondary tier holds at 13px (−2)
  440. // where the ≤14 branch would have given 14px (−1).
  441. await expect.poll(readSecondaryFontSize, { timeout: 5_000 }).toBe('13px')
  442. await stepFontSize(increase, 16)
  443. await expect.poll(readSecondaryFontSize, { timeout: 5_000 }).toBe('14px')
  444. await page.keyboard.press('Escape')
  445. // Reload: the boot script embeds the durable size and ThemeRuntime seeds
  446. // its initial snapshot from the boot-written body variable, so activation
  447. // never flashes the default while the settings read is in flight.
  448. const warningStart = tripwire.warnings.length
  449. await page.reload({ waitUntil: 'load' })
  450. acknowledgeReloadConnectionLoss(tripwire, warningStart)
  451. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  452. await expect.poll(readFontSize, { timeout: 5_000 }).toBe('16px')
  453. expect(await readSecondaryFontSize()).toBe('14px')
  454. // Restore the default for the specs that follow (and the dialog golden).
  455. await page.getByRole('button', { name: '设置', exact: true }).click()
  456. const restored = page.getByRole('dialog', { name: '设置' })
  457. await restored.waitFor({ timeout: 10_000 })
  458. await restored.getByText('16', { exact: true }).hover()
  459. const decrease = restored.getByRole('button', { name: '减小字号' })
  460. await stepFontSize(decrease, 15)
  461. await stepFontSize(decrease, 14)
  462. await page.keyboard.press('Escape')
  463. expect(tripwire.pageErrors).toEqual([])
  464. }, 90_000)
  465. it('persists the completed-Turn transcript mode across reload', async () => {
  466. onTestFailed(() => saveFailureShot(page, 'web-e2e-settings-transcript-view'))
  467. await page.getByRole('button', { name: '设置', exact: true }).click()
  468. const dialog = page.getByRole('dialog', { name: '设置' })
  469. await dialog.waitFor({ timeout: 10_000 })
  470. await dialog.getByText('对话显示', { exact: true }).waitFor({ timeout: 10_000 })
  471. await dialog.getByRole('button', { name: '紧凑', exact: true }).click()
  472. await page.getByRole('menuitem', { name: '标准', exact: true }).click()
  473. await dialog.getByRole('button', { name: '标准', exact: true }).waitFor({ timeout: 10_000 })
  474. await expect.poll(async () => readFile(join(scaffold.harnessHome, 'settings.yaml'), 'utf8'), { timeout: 5_000 })
  475. .toMatch(/ui-chat:\n\s+transcriptView: normal/)
  476. await page.keyboard.press('Escape')
  477. const warningStart = tripwire.warnings.length
  478. await page.reload({ waitUntil: 'load' })
  479. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  480. acknowledgeReloadConnectionLoss(tripwire, warningStart)
  481. await page.getByRole('button', { name: '设置', exact: true }).click()
  482. const reloaded = page.getByRole('dialog', { name: '设置' })
  483. await reloaded.getByRole('button', { name: '标准', exact: true }).waitFor({ timeout: 10_000 })
  484. await reloaded.getByRole('button', { name: '标准', exact: true }).click()
  485. await page.getByRole('menuitem', { name: '紧凑', exact: true }).click()
  486. await reloaded.getByRole('button', { name: '紧凑', exact: true }).waitFor({ timeout: 10_000 })
  487. await expect.poll(async () => readFile(join(scaffold.harnessHome, 'settings.yaml'), 'utf8'), { timeout: 5_000 })
  488. .toMatch(/ui-chat:\n\s+transcriptView: compact/)
  489. await page.keyboard.press('Escape')
  490. expect(tripwire.pageErrors).toEqual([])
  491. }, 90_000)
  492. it('persists the busy-state Enter behavior across reload and a distinct port', async () => {
  493. onTestFailed(() => saveFailureShot(page, 'web-e2e-settings-enter-behavior'))
  494. await page.getByRole('button', { name: '设置', exact: true }).click()
  495. const dialog = page.getByRole('dialog', { name: '设置' })
  496. await dialog.waitFor({ timeout: 10_000 })
  497. await dialog.getByRole('button', { name: '排队发送' }).click()
  498. await page.getByRole('menuitem', { name: '插话发送' }).click()
  499. await dialog.getByRole('button', { name: '插话发送' }).waitFor({ timeout: 10_000 })
  500. expect(await page.evaluate(() => localStorage.getItem('dsh.conversation.busyEnter'))).toBeNull()
  501. await expect.poll(async () => readFile(join(scaffold.harnessHome, 'settings.yaml'), 'utf8'), { timeout: 5_000 })
  502. .toMatch(/ui-conversation:\n\s+busyEnter: steer/)
  503. await page.keyboard.press('Escape')
  504. const warningStart = tripwire.warnings.length
  505. await page.reload({ waitUntil: 'load' })
  506. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  507. acknowledgeReloadConnectionLoss(tripwire, warningStart)
  508. await page.getByRole('button', { name: '设置', exact: true }).click()
  509. const reloaded = page.getByRole('dialog', { name: '设置' })
  510. await reloaded.getByRole('button', { name: '插话发送' }).waitFor({ timeout: 10_000 })
  511. const second = await launchWebScaffold({ harnessHome: scaffold.harnessHome })
  512. const secondPage = await browser.newPage({ viewport: { width: 1680, height: 1000 }, locale: ZH_BROWSER_LOCALE })
  513. const secondTripwire = watchConsole(secondPage)
  514. try {
  515. expect(second.baseUrl).not.toBe(scaffold.baseUrl)
  516. await secondPage.goto(second.authenticatedUrl, { waitUntil: 'load' })
  517. await secondPage.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  518. await secondPage.getByRole('button', { name: '设置', exact: true }).click()
  519. await secondPage.getByRole('dialog', { name: '设置' })
  520. .getByRole('button', { name: '插话发送' }).waitFor({ timeout: 10_000 })
  521. expect(await secondPage.evaluate(() => localStorage.getItem('dsh.conversation.busyEnter'))).toBeNull()
  522. expect(secondTripwire.pageErrors).toEqual([])
  523. expect(secondTripwire.warnings).toEqual([])
  524. } finally {
  525. await secondPage.close()
  526. await second.close()
  527. }
  528. await reloaded.getByRole('button', { name: '插话发送' }).click()
  529. await page.getByRole('menuitem', { name: '排队发送' }).click()
  530. await reloaded.getByRole('button', { name: '排队发送' }).waitFor({ timeout: 10_000 })
  531. expect(await page.evaluate(() => localStorage.getItem('dsh.conversation.busyEnter'))).toBeNull()
  532. await expect.poll(async () => readFile(join(scaffold.harnessHome, 'settings.yaml'), 'utf8'), { timeout: 5_000 })
  533. .toMatch(/ui-conversation:\n\s+busyEnter: queue/)
  534. await page.keyboard.press('Escape')
  535. expect(tripwire.pageErrors).toEqual([])
  536. }, 90_000)
  537. it('persists the settings language across reload and a distinct port', async () => {
  538. onTestFailed(() => saveFailureShot(page, 'web-e2e-settings-language'))
  539. await page.getByRole('button', { name: '设置', exact: true }).click()
  540. const zhDialog = page.getByRole('dialog', { name: '设置' })
  541. await zhDialog.waitFor({ timeout: 10_000 })
  542. // The document language follows the active locale in the assembled app, not
  543. // only on a directly-mounted plugin. This is a zh browser, so the served
  544. // markup's `en` must already have been replaced — asserting it here (rather
  545. // than only in an English scenario) is what makes the check discriminating.
  546. expect(await page.evaluate(() => document.documentElement.lang)).toBe('zh-CN')
  547. // The Language selector pill shows the active locale's own name.
  548. const selector = zhDialog.getByRole('button', { name: '中文' })
  549. expect(await selector.getAttribute('aria-haspopup')).toBe('menu')
  550. await selector.click()
  551. await page.getByRole('menuitem', { name: 'English' }).click()
  552. // The settings-owned copy re-registers localized: dialog title, nav,
  553. // Appearance labels. (Only the settings namespaces are localized —
  554. // the rest of the app's copy is intentionally out of this row's scope.)
  555. const enDialog = page.getByRole('dialog', { name: 'Settings' })
  556. await enDialog.waitFor({ timeout: 10_000 })
  557. // ...and the attribute follows that switch, in the assembled app.
  558. await expect.poll(() => page.evaluate(() => document.documentElement.lang), { timeout: 5_000 }).toBe('en')
  559. expect(await enDialog.getByRole('button', { name: 'General' }).getAttribute('aria-current')).toBe('true')
  560. await expect.poll(() => enDialog.getByText('Appearance', { exact: true }).count(), { timeout: 5_000 }).toBe(1)
  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: en/)
  564. // Reload keeps English; then restore zh so shared page state (and the
  565. // other specs' 设置-anchored selectors + goldens) see the default again.
  566. const warningStart = tripwire.warnings.length
  567. await page.reload({ waitUntil: 'load' })
  568. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  569. acknowledgeReloadConnectionLoss(tripwire, warningStart)
  570. const enTrigger = page.getByRole('button', { name: 'Settings' })
  571. await enTrigger.waitFor({ timeout: 10_000 })
  572. // A Chinese browser on another port still receives the explicit English
  573. // preference from the shared Host settings document.
  574. const second = await launchWebScaffold({ harnessHome: scaffold.harnessHome })
  575. const secondPage = await browser.newPage({ viewport: { width: 1680, height: 1000 }, locale: ZH_BROWSER_LOCALE })
  576. const secondTripwire = watchConsole(secondPage)
  577. try {
  578. expect(second.baseUrl).not.toBe(scaffold.baseUrl)
  579. await secondPage.goto(second.authenticatedUrl, { waitUntil: 'load' })
  580. await secondPage.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  581. await secondPage.getByRole('button', { name: 'Settings', exact: true }).click()
  582. await secondPage.getByRole('dialog', { name: 'Settings' })
  583. .getByRole('button', { name: 'English' }).waitFor({ timeout: 10_000 })
  584. expect(await secondPage.evaluate(() => localStorage.getItem('dsh.locale'))).toBeNull()
  585. expect(secondTripwire.pageErrors).toEqual([])
  586. expect(secondTripwire.warnings).toEqual([])
  587. } finally {
  588. await secondPage.close()
  589. await second.close()
  590. }
  591. await enTrigger.click()
  592. await page.getByRole('dialog', { name: 'Settings' }).getByRole('button', { name: 'English' }).click()
  593. await page.getByRole('menuitem', { name: '中文' }).click()
  594. await page.getByRole('dialog', { name: '设置' }).waitFor({ timeout: 10_000 })
  595. expect(await page.evaluate(() => localStorage.getItem('dsh.locale'))).toBeNull()
  596. await expect.poll(async () => readFile(join(scaffold.harnessHome, 'settings.yaml'), 'utf8'), { timeout: 5_000 })
  597. .toMatch(/locale:\n\s+preference: zh/)
  598. await page.keyboard.press('Escape')
  599. expect(tripwire.pageErrors).toEqual([])
  600. }, 90_000)
  601. it('opens an English browser in English without any stored preference', async () => {
  602. // A fresh Host home has no locale preference, so its surface follows the
  603. // browser. English is also FALLBACK_LOCALE, so this scenario alone cannot
  604. // distinguish detection from the default — the zh scenarios above supply
  605. // the discriminating half (a Chinese browser must NOT land on the default).
  606. const fresh = await launchWebScaffold({})
  607. const enPage = await browser.newPage({ viewport: { width: 1680, height: 1000 }, locale: 'en-US' })
  608. const enTripwire = watchConsole(enPage)
  609. onTestFailed(() => saveFailureShot(enPage, 'web-e2e-settings-browser-language'))
  610. try {
  611. await enPage.goto(fresh.authenticatedUrl, { waitUntil: 'load' })
  612. await enPage.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  613. expect(await enPage.evaluate(() => localStorage.getItem('dsh.locale'))).toBeNull()
  614. await enPage.getByRole('button', { name: 'Settings', exact: true }).click()
  615. const dialog = enPage.getByRole('dialog', { name: 'Settings' })
  616. await dialog.waitFor({ timeout: 10_000 })
  617. await dialog.getByRole('button', { name: 'English' }).waitFor({ timeout: 10_000 })
  618. // The plugin list resolves shipped preset names through the en
  619. // dictionaries instead of echoing the preset files' Chinese metadata.
  620. await dialog.getByRole('button', { name: 'Plugins', exact: true }).click()
  621. await dialog.getByRole('tab', { name: 'Plugin list', exact: true }).click()
  622. const presetSwitcher = dialog.getByRole('button', { name: 'Choose the agent preset to inspect' })
  623. await presetSwitcher.waitFor({ timeout: 10_000 })
  624. expect(await presetSwitcher.textContent()).toBe('Standard mode (default)')
  625. // This page has no closing inventory spec to sweep its console, so the
  626. // scenario clears both tripwire channels itself.
  627. expect(enTripwire.pageErrors).toEqual([])
  628. expect(enTripwire.warnings).toEqual([])
  629. } finally {
  630. await enPage.close()
  631. await fresh.close()
  632. }
  633. }, 90_000)
  634. it('opens a browser asking for no shipped language in English', async () => {
  635. // The product default for "no usable signal": a French browser ships
  636. // neither zh nor en, so resolution falls to FALLBACK_LOCALE (en) rather
  637. // than to Chinese.
  638. const fresh = await launchWebScaffold({})
  639. const frPage = await browser.newPage({ viewport: { width: 1680, height: 1000 }, locale: 'fr-FR' })
  640. const frTripwire = watchConsole(frPage)
  641. onTestFailed(() => saveFailureShot(frPage, 'web-e2e-settings-unshipped-language'))
  642. try {
  643. await frPage.goto(fresh.authenticatedUrl, { waitUntil: 'load' })
  644. await frPage.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  645. expect(await frPage.evaluate(() => localStorage.getItem('dsh.locale'))).toBeNull()
  646. await frPage.getByRole('button', { name: 'Settings', exact: true }).click()
  647. const dialog = frPage.getByRole('dialog', { name: 'Settings' })
  648. await dialog.waitFor({ timeout: 10_000 })
  649. await dialog.getByRole('button', { name: 'English' }).waitFor({ timeout: 10_000 })
  650. // A locale-owned nav label proves the dictionaries resolved to en.
  651. await dialog.getByRole('button', { name: 'Agent presets' }).waitFor({ timeout: 10_000 })
  652. // The markup already ships `en`, so this alone cannot prove the sync ran
  653. // — the zh scenario above is the discriminating half. Asserted here too
  654. // so a future change that resolves en but writes the wrong tag is caught.
  655. expect(await frPage.evaluate(() => document.documentElement.lang)).toBe('en')
  656. // Golden of the English fallback dialog — the visible output this change
  657. // produces. The zh golden above covers the detected-locale surface, so
  658. // the pair pins both directions of the resolution.
  659. const snapshot = await captureStableAria(frPage, '[role="dialog"]', fresh.workspaceCwd)
  660. await compareOrRefreshGolden(DIALOG_EN_EXPECTED, snapshot, MODE)
  661. expect(frTripwire.pageErrors).toEqual([])
  662. expect(frTripwire.warnings).toEqual([])
  663. } finally {
  664. await frPage.close()
  665. await fresh.close()
  666. }
  667. }, 90_000)
  668. it.skipIf(MODE === 'record')('keeps the fixture inventory closed', async () => {
  669. expect(tripwire.warnings).toEqual([])
  670. await assertFixtureInventory(SNAPSHOT_DIR, [
  671. 'dialog-en.expected.md',
  672. 'dialog.expected.md',
  673. 'plugin-instances.expected.md',
  674. 'plugins.expected.md',
  675. ])
  676. })
  677. })