settings-chrome.e2e.ts 41 KB

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