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