settings-chrome.e2e.ts 41 KB

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