default-model.e2e.ts 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. // Web e2e scenario: switching models in the composer is how this deployment's
  2. // default is chosen. The gesture writes the shared `agent-default-model` settings section, a
  3. // session created afterwards starts from it, and a session that already logged
  4. // a route keeps deriving from its own log — the tier order the gateway
  5. // resolves on every read.
  6. // Zero model calls: the switch is settings/llm-domain traffic only, so there
  7. // is no fixture and a stray stream would fail loud because the adapter registry is empty. Both
  8. // routes are declared host-side (not through the UI, which has its own
  9. // scenario) through the pi-ai adapter the shipped tree already mounts: a
  10. // fixture-less scaffold registers no adapter at all, so the routes the
  11. // picker offers — and the one the composer must start on — have to come from
  12. // somewhere, and settings profiles are the product's own way to add them.
  13. import { readFile } from 'node:fs/promises'
  14. import { fileURLToPath } from 'node:url'
  15. import { join } from 'node:path'
  16. import type { Browser, Page } from 'playwright'
  17. import { chromium } from 'playwright'
  18. import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
  19. import { SessionId } from '@deepseek-ai/dsh-session'
  20. import { settingsNamespace } from '@deepseek-ai/dsh-settings'
  21. import { launchWebScaffold, watchConsole, type WebScaffold } from './scaffold.ts'
  22. import { ZH_BROWSER_LOCALE, connectFreshWorkspaceZh, saveFailureShot } from './support.ts'
  23. /** Points the shipped shared Agent default at this scenario's own route. */
  24. const OVERLAY = fileURLToPath(new URL('./default-model.overlay.yml', import.meta.url))
  25. /** The route this scenario starts on, patched over the shipped default. */
  26. const START_ROUTE = 'origin-gateway'
  27. const START_MODEL = 'origin-large'
  28. /** The route the switch lands on, which then becomes the saved default. */
  29. const ROUTE = 'acme-gateway'
  30. const MODEL = 'acme-large'
  31. describe('web e2e: the composer model switch is the default for later sessions', () => {
  32. let scaffold: WebScaffold
  33. let browser: Browser
  34. let page: Page
  35. let tripwire: ReturnType<typeof watchConsole>
  36. /** Create one session and its agent through the same wire face the browser uses. */
  37. const createSession = async (sessionId: string): Promise<string> => {
  38. const response = await scaffold.ctx.apiProxy.sessions.create({
  39. rpcId: `default-model-create-${sessionId}` as never,
  40. payload: { sessionId: SessionId(sessionId), cwd: scaffold.workspaceCwd },
  41. })
  42. if (!response.result.ok) throw new Error(`session.create failed: ${response.result.error.message}`)
  43. return response.result.value.sessionId
  44. }
  45. /** The route the gateway reports for one session, through the real wire face. */
  46. const currentOf = async (sessionId: string): Promise<unknown> => {
  47. const response = await scaffold.ctx.apiProxy.sessions.models({
  48. rpcId: `default-model-${sessionId}` as never,
  49. payload: { sessionId: SessionId(sessionId) },
  50. })
  51. if (!response.result.ok) throw new Error(`session.models failed: ${response.result.error.message}`)
  52. return response.result.value.current
  53. }
  54. beforeAll(async () => {
  55. scaffold = await launchWebScaffold({ extraOverlayPath: OVERLAY })
  56. // Two routes so the picker has somewhere to start and somewhere to go.
  57. // Declared through the settings seam rather than the Models page: this
  58. // scenario is about the composer, and the declaring flow is covered by
  59. // models-settings.e2e.
  60. await scaffold.ctx.settings.update(settingsNamespace('llm-pi-ai'), {
  61. providers: {
  62. [START_ROUTE]: {
  63. displayName: 'Origin Gateway',
  64. api: 'openai-completions',
  65. baseURL: 'https://gateway.origin.example/v1',
  66. models: [{ id: START_MODEL, name: 'Origin Large' }],
  67. },
  68. [ROUTE]: {
  69. displayName: 'Acme Gateway',
  70. api: 'openai-completions',
  71. baseURL: 'https://gateway.acme.example/v1',
  72. models: [{ id: MODEL, name: 'Acme Large' }],
  73. },
  74. },
  75. })
  76. browser = await chromium.launch()
  77. page = await browser.newPage({ viewport: { width: 1680, height: 1000 }, locale: ZH_BROWSER_LOCALE })
  78. tripwire = watchConsole(page)
  79. await page.goto(scaffold.baseUrl, { waitUntil: 'load' })
  80. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  81. // The composer's seats only exist once a workspace is connected: without
  82. // one the input is the locked placeholder and no session scope is open.
  83. await connectFreshWorkspaceZh(page, scaffold.workspaceCwd)
  84. }, 120_000)
  85. afterAll(async () => {
  86. await browser?.close()
  87. await scaffold?.close()
  88. })
  89. it('writes the switched model as the default and leaves a logged session alone', async () => {
  90. onTestFailed(() => saveFailureShot(page, 'web-e2e-default-model'))
  91. // A session that has already run a turn, spelled as the fact a turn
  92. // leaves behind: its own logged route.
  93. const loggedId = await createSession('default-model-logged')
  94. scaffold.ctx.sessions.get(SessionId(loggedId))?.append('request/header', {
  95. header: { config: { provider: START_ROUTE, model: START_MODEL } },
  96. reason: 'initial',
  97. })
  98. const trigger = page.getByRole('button', { name: /^选择模型/ })
  99. await trigger.waitFor({ timeout: 15_000 })
  100. await trigger.click()
  101. await page.getByRole('menuitem', { name: /模型/ }).click()
  102. await page.getByRole('menuitemradio', { name: 'Acme Large' }).click()
  103. // The switch is what sets the default: the shared Agent-route settings section
  104. // now names it, beside the provider profiles the Models page writes.
  105. await expect.poll(
  106. async () => readFile(join(scaffold.harnessHome, 'settings.yaml'), 'utf8'),
  107. { timeout: 10_000 },
  108. ).toContain('agent-default-model:')
  109. const document = await readFile(join(scaffold.harnessHome, 'settings.yaml'), 'utf8')
  110. expect(document).toContain(`provider: ${ROUTE}`)
  111. expect(document).toContain(`model: ${MODEL}`)
  112. // A session created after the switch starts from it...
  113. expect(await currentOf(await createSession('default-model-after')))
  114. .toEqual({ provider: ROUTE, model: MODEL })
  115. // ...while the one holding a logged route keeps deriving from its log.
  116. expect(await currentOf(loggedId)).toEqual({ provider: START_ROUTE, model: START_MODEL })
  117. expect(tripwire.pageErrors).toEqual([])
  118. }, 60_000)
  119. it('goes inert when the route the default names stops being served', async () => {
  120. onTestFailed(() => saveFailureShot(page, 'web-e2e-default-model-blocked'))
  121. const box = page.locator('textarea[data-input-phase], textarea').first()
  122. await expect.poll(async () => box.isEnabled(), { timeout: 10_000 }).toBe(true)
  123. // What removing the provider on the Models page leaves behind: the saved
  124. // default still names the route, and nothing serves it any more.
  125. // `replace`, not `update`: a merge patch of `{providers: {}}` leaves every
  126. // stored profile in place.
  127. await scaffold.ctx.settings.replace(settingsNamespace('llm-pi-ai'), { providers: {} })
  128. await expect.poll(async () => box.isEnabled(), { timeout: 15_000 }).toBe(false)
  129. expect(await box.getAttribute('placeholder')).toBe('当前模型不可用,请先选择模型')
  130. // The block is an affordance; the refusal is the Host's. A client that
  131. // never disabled anything still cannot start a turn on a dead route.
  132. const refused = await scaffold.ctx.apiProxy.sessions.prompt({
  133. rpcId: 'default-model-refused' as never,
  134. payload: {
  135. sessionId: SessionId(await createSession('default-model-refusal')),
  136. mode: 'queue' as const,
  137. content: [{ type: 'text' as const, text: 'hi' }],
  138. },
  139. })
  140. expect(refused.result).toMatchObject({ ok: false, error: { code: 'model-unavailable' } })
  141. // The way out stays open. Locking the model seat with everything else
  142. // would leave the composer asking for the one thing it prevents.
  143. const seat = page.getByRole('button', { name: /^选择模型/ })
  144. expect(await seat.isEnabled()).toBe(true)
  145. await seat.click()
  146. await page.getByRole('menuitem', { name: /模型/ }).click()
  147. await page.getByRole('menuitemradio').first().click()
  148. await expect.poll(async () => box.isEnabled(), { timeout: 15_000 }).toBe(true)
  149. expect(tripwire.pageErrors).toEqual([])
  150. }, 60_000)
  151. })