onboarding-deepseek-config.e2e.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. // Keyless browser e2e: the shipped DeepSeek adapter stays mounted while its
  2. // credential is absent, both ordered steps share the shipped modal chrome,
  3. // and the inline key write lands in an isolated harness home without a reload
  4. // or model call.
  5. import { randomBytes } from 'node:crypto'
  6. import { readFile } from 'node:fs/promises'
  7. import { fileURLToPath } from 'node:url'
  8. import { join } from 'node:path'
  9. import type { Browser, Page } from 'playwright'
  10. import { chromium } from 'playwright'
  11. import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
  12. import { settingsNamespace } from '@deepseek-ai/dsh-settings'
  13. import {
  14. acknowledgeReloadConnectionLoss, assertFixtureInventory, captureStableAria, compareOrRefreshGolden,
  15. launchWebScaffold, watchConsole, webSnapshotMode, type WebScaffold,
  16. WELCOME_NOTICE_ACK_FIELD, WELCOME_NOTICE_COPY, WELCOME_NOTICE_SETTINGS_NAMESPACE,
  17. WELCOME_NOTICE_VERSION,
  18. } from './scaffold.ts'
  19. import { ZH_BROWSER_LOCALE, connectFreshWorkspaceZh, saveFailureShot } from './support.ts'
  20. const SNAPSHOT_DIR = fileURLToPath(new URL('./expected/onboarding-deepseek-config', import.meta.url))
  21. const WELCOME_EXPECTED = join(SNAPSHOT_DIR, 'welcome.expected.md')
  22. const MISSING_EXPECTED = join(SNAPSHOT_DIR, 'missing.expected.md')
  23. const MODELS_EXPECTED = join(SNAPSHOT_DIR, 'models.expected.md')
  24. const MODE = webSnapshotMode()
  25. describe.skipIf(MODE === 'record')('web e2e: first-run DeepSeek credential setup', () => {
  26. let scaffold: WebScaffold
  27. let browser: Browser
  28. let page: Page
  29. let tripwire: ReturnType<typeof watchConsole>
  30. const browserConsole: string[] = []
  31. beforeAll(async () => {
  32. scaffold = await launchWebScaffold({ deepSeekMissingCredential: true, welcomeNoticePending: true })
  33. browser = await chromium.launch()
  34. // The scenario asserts the shipped Chinese copy, so the browser asks for it.
  35. page = await browser.newPage({ viewport: { width: 1440, height: 960 }, locale: ZH_BROWSER_LOCALE })
  36. tripwire = watchConsole(page)
  37. page.on('console', message => browserConsole.push(message.text()))
  38. await page.goto(scaffold.baseUrl, { waitUntil: 'load' })
  39. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  40. }, 120_000)
  41. afterAll(async () => {
  42. await browser?.close()
  43. await scaffold?.close()
  44. })
  45. it('stores a key write-only and observes configured state without restarting', async () => {
  46. onTestFailed(() => saveFailureShot(page, 'web-e2e-onboarding-deepseek-config'))
  47. const welcome = page.getByRole('dialog', { name: WELCOME_NOTICE_COPY.zh.title })
  48. await welcome.waitFor({ timeout: 15_000 })
  49. expect(await page.locator('#root').evaluate(root => (root as HTMLElement).inert)).toBe(true)
  50. for (const paragraph of WELCOME_NOTICE_COPY.zh.body.split('\n\n')) {
  51. expect(await welcome.getByText(paragraph, { exact: true }).count()).toBe(1)
  52. }
  53. expect(await welcome.getByRole('button').allTextContents()).toEqual([
  54. WELCOME_NOTICE_COPY.zh.continueLabel,
  55. ])
  56. const welcomeAria = await captureStableAria(page, '[role="dialog"]', scaffold.workspaceCwd)
  57. await compareOrRefreshGolden(WELCOME_EXPECTED, welcomeAria, MODE)
  58. // Observation is not acknowledgement: the exact version is persisted
  59. // only by the explicit action, so a reload still presents this dialog.
  60. const firstReloadWarnings = tripwire.warnings.length
  61. await page.reload({ waitUntil: 'load' })
  62. acknowledgeReloadConnectionLoss(tripwire, firstReloadWarnings)
  63. await welcome.waitFor({ timeout: 15_000 })
  64. await welcome.getByRole('button', { name: WELCOME_NOTICE_COPY.zh.continueLabel }).click()
  65. await welcome.waitFor({ state: 'detached', timeout: 15_000 })
  66. const credentialStep = page.getByRole('dialog', { name: '添加一个 API Key 开始使用' })
  67. await credentialStep.waitFor({ timeout: 15_000 })
  68. const keyInput = credentialStep.getByLabel('API 密钥', { exact: true })
  69. await keyInput.waitFor({ timeout: 10_000 })
  70. const initial = await captureStableAria(page, '[role="dialog"]', scaffold.workspaceCwd)
  71. await compareOrRefreshGolden(MISSING_EXPECTED, initial, MODE)
  72. const secret = `dsh_onboarding_${randomBytes(12).toString('hex')}`
  73. await keyInput.fill(secret)
  74. await credentialStep.getByRole('button', { name: '保存并继续' }).click()
  75. await credentialStep.waitFor({ state: 'detached', timeout: 15_000 })
  76. expect(await page.locator('#root').evaluate(root => (root as HTMLElement).inert)).toBe(false)
  77. const stored = await readFile(join(scaffold.harnessHome, '.credentials.yaml'), 'utf8')
  78. expect(stored.includes(`DEEPSEEK_API_KEY: ${secret}`)).toBe(true)
  79. expect((await page.content()).includes(secret)).toBe(false)
  80. expect((await page.locator('body').ariaSnapshot()).includes(secret)).toBe(false)
  81. expect(browserConsole.some(line => line.includes(secret))).toBe(false)
  82. const acknowledgedSettings = await readFile(join(scaffold.harnessHome, 'settings.yaml'), 'utf8')
  83. expect(acknowledgedSettings).toContain(`${WELCOME_NOTICE_ACK_FIELD}: ${WELCOME_NOTICE_VERSION}`)
  84. // The ordinary Models surface reuses the refreshed join and exposes the
  85. // configured write-only placeholder without a reload.
  86. await page.getByRole('button', { name: '设置', exact: true }).click()
  87. const settings = page.getByRole('dialog', { name: '设置' })
  88. await settings.waitFor({ timeout: 10_000 })
  89. await settings.getByRole('button', { name: '模型' }).click()
  90. const deepSeekRow = settings.getByText('DeepSeek', { exact: true }).first()
  91. await deepSeekRow.waitFor({ timeout: 10_000 })
  92. await deepSeekRow.locator('xpath=ancestor::li').getByRole('button', { name: '编辑' }).click()
  93. const configuredInput = settings.getByLabel('API 密钥', { exact: true })
  94. await configuredInput.waitFor({ timeout: 10_000 })
  95. await expect.poll(
  96. () => configuredInput.getAttribute('placeholder'),
  97. { timeout: 10_000 },
  98. ).toBe('已配置——输入新值可替换')
  99. const secondReloadWarnings = tripwire.warnings.length
  100. await page.reload({ waitUntil: 'load' })
  101. acknowledgeReloadConnectionLoss(tripwire, secondReloadWarnings)
  102. await page.waitForSelector('[class*="frame"]', { timeout: 15_000 })
  103. expect(await page.getByRole('dialog', { name: WELCOME_NOTICE_COPY.zh.title }).count()).toBe(0)
  104. expect(await page.getByRole('dialog', { name: '添加一个 API Key 开始使用' }).count()).toBe(0)
  105. // An old acknowledgement means materially revised copy: welcome returns,
  106. // while the already-configured provider step remains complete.
  107. await scaffold.ctx.settings.mutate(settingsNamespace(WELCOME_NOTICE_SETTINGS_NAMESPACE), [{
  108. op: 'set', path: [WELCOME_NOTICE_ACK_FIELD], value: 'previous-copy-version',
  109. }])
  110. const thirdReloadWarnings = tripwire.warnings.length
  111. await page.reload({ waitUntil: 'load' })
  112. acknowledgeReloadConnectionLoss(tripwire, thirdReloadWarnings)
  113. await welcome.waitFor({ timeout: 15_000 })
  114. await welcome.getByRole('button', { name: WELCOME_NOTICE_COPY.zh.continueLabel }).click()
  115. await welcome.waitFor({ state: 'detached', timeout: 15_000 })
  116. expect(await page.getByRole('dialog', { name: '添加一个 API Key 开始使用' }).count()).toBe(0)
  117. expect((await page.content()).includes(secret)).toBe(false)
  118. expect((await page.locator('body').ariaSnapshot()).includes(secret)).toBe(false)
  119. expect(browserConsole.some(line => line.includes(secret))).toBe(false)
  120. expect(tripwire.warnings).toEqual([])
  121. expect(tripwire.pageErrors).toEqual([])
  122. }, 60_000)
  123. it('never paints the takeover chrome on a configured reload, even with the settings join held open', async () => {
  124. onTestFailed(() => saveFailureShot(page, 'web-e2e-onboarding-configured-reload'))
  125. // Regression pin for the reload flash: both steps are satisfied, yet each
  126. // must load private facts before deciding not to show. Dialog chrome lives
  127. // inside each visible branch, so the deciding window paints and blocks
  128. // nothing. Holding settings.describe widens that window from loopback
  129. // RTT scale to a deterministic hundreds of milliseconds, removing all
  130. // timing dependence from the sampler assertions below.
  131. //
  132. // The sampler init script persists across this shared page's later
  133. // navigations (init scripts re-run per navigation); that stays harmless
  134. // because no later scenario in this file legitimately shows the
  135. // takeover, and only this test reads __takeoverSightings.
  136. await page.addInitScript(() => {
  137. const sightings: string[] = []
  138. ;(window as unknown as { __takeoverSightings: string[] }).__takeoverSightings = sightings
  139. setInterval(() => {
  140. if (document.querySelector(
  141. '[role="dialog"][aria-label="内测声明"], '
  142. + '[role="dialog"][aria-label="添加一个 API Key 开始使用"]',
  143. ) !== null) {
  144. sightings.push('chrome')
  145. }
  146. if (document.getElementById('root')?.inert === true) sightings.push('inert')
  147. }, 8)
  148. })
  149. // EVERY settings.describe issued before the release is held — not just
  150. // the first — so the pin cannot silently collapse back to loopback
  151. // timing if a second boot-time consumer of the join ever appears.
  152. let released = false
  153. const heldRoutes: Array<() => void> = []
  154. const releaseDescribe = (): void => {
  155. released = true
  156. for (const resolve of heldRoutes.splice(0)) resolve()
  157. }
  158. await page.route('**/api/settings.describe', async (route) => {
  159. if (!released) await new Promise<void>((resolve) => { heldRoutes.push(resolve) })
  160. await route.continue()
  161. })
  162. const warningsBefore = tripwire.warnings.length
  163. await page.reload({ waitUntil: 'commit' })
  164. await page.waitForSelector('[class*="frame"]', { timeout: 15_000 })
  165. // The app is painted and interactive while the steps are still deciding.
  166. await page.waitForTimeout(600)
  167. releaseDescribe()
  168. await page.waitForTimeout(400)
  169. await page.unroute('**/api/settings.describe')
  170. acknowledgeReloadConnectionLoss(tripwire, warningsBefore)
  171. expect(await page.evaluate(() =>
  172. (window as unknown as { __takeoverSightings: string[] }).__takeoverSightings)).toEqual([])
  173. expect(await page.getByRole('dialog', { name: WELCOME_NOTICE_COPY.zh.title }).count()).toBe(0)
  174. expect(await page.getByRole('dialog', { name: '添加一个 API Key 开始使用' }).count()).toBe(0)
  175. expect(tripwire.pageErrors).toEqual([])
  176. }, 60_000)
  177. it('configures arbitrary DeepSeek models and prompts after the selected model is removed', async () => {
  178. onTestFailed(() => saveFailureShot(page, 'web-e2e-onboarding-deepseek-models'))
  179. // Opened here rather than inherited: the credential test reloads the page
  180. // after configuring the key, so nothing carries an open dialog across.
  181. await page.getByRole('button', { name: '设置', exact: true }).click()
  182. const settings = page.getByRole('dialog', { name: '设置' })
  183. await settings.waitFor({ timeout: 10_000 })
  184. await settings.getByRole('button', { name: '模型' }).click()
  185. const deepSeek = settings.getByText('DeepSeek', { exact: true }).first()
  186. await deepSeek.waitFor({ timeout: 10_000 })
  187. await deepSeek.locator('xpath=ancestor::li').getByRole('button', { name: '编辑' }).click()
  188. await settings.getByText('自定义设置').click()
  189. await settings.getByRole('button', { name: /删除模型/ }).first().click()
  190. await settings.getByRole('button', { name: '添加模型' }).click()
  191. const customModelId = settings.getByLabel('模型 ID 3')
  192. await customModelId.fill('private-preview')
  193. await settings.getByLabel('显示名称 3').fill('Private Preview')
  194. // Capacities live behind the row's own disclosure, as in the pi-ai form.
  195. await settings.getByRole('button', { name: '容量 3' }).click()
  196. await settings.getByLabel('上下文窗口 3').fill('131072')
  197. await settings.getByLabel('最大输出 token 数 3').fill('64K')
  198. const modelEditor = await captureStableAria(page, '[role="dialog"]', scaffold.workspaceCwd)
  199. await compareOrRefreshGolden(MODELS_EXPECTED, modelEditor, MODE)
  200. await settings.getByRole('button', { name: '保存', exact: true }).click()
  201. await customModelId.waitFor({ state: 'detached', timeout: 15_000 })
  202. const document = await readFile(join(scaffold.harnessHome, 'settings.yaml'), 'utf8')
  203. expect(document).toContain('id: deepseek-v4-pro')
  204. expect(document).toContain('id: deepseek-v4-flash-vision-exp')
  205. expect(document).toContain('inputModalities:')
  206. expect(document).toContain('- image')
  207. expect(document).toContain('id: private-preview')
  208. expect(document).toContain('name: Private Preview')
  209. expect(document).toContain('contextWindow: 131072')
  210. expect(document).toContain('maxTokens: 64000')
  211. expect(document).not.toMatch(/^\s*- id: deepseek-v4-flash$/m)
  212. await page.keyboard.press('Escape')
  213. // A connected Workspace is what puts a live composer — and its model
  214. // trigger — on the page; the scaffold boots without one.
  215. await connectFreshWorkspaceZh(page, scaffold.workspaceCwd, 'model-fallback-e2e')
  216. const modelTrigger = page.getByRole('button', { name: /^选择模型/ })
  217. await modelTrigger.waitFor({ timeout: 10_000 })
  218. await modelTrigger.click()
  219. await page.getByRole('menuitem', { name: /模型/ }).click()
  220. expect(await page.getByText('deepseek-v4-flash', { exact: true }).count()).toBe(0)
  221. await page.getByRole('menuitemradio', { name: 'DeepSeek-V4-Flash-Vision-Exp' }).waitFor({ timeout: 10_000 })
  222. await page.getByRole('menuitemradio', { name: 'Private Preview' }).waitFor({ timeout: 10_000 })
  223. expect(tripwire.warnings).toEqual([])
  224. expect(tripwire.pageErrors).toEqual([])
  225. }, 60_000)
  226. it('keeps the fixture inventory closed', async () => {
  227. await assertFixtureInventory(
  228. SNAPSHOT_DIR,
  229. ['welcome.expected.md', 'missing.expected.md', 'models.expected.md'],
  230. )
  231. })
  232. })