default-model.e2e.ts 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  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 { launchWebScaffold, watchConsole, type WebScaffold } from './scaffold.ts'
  21. import { ZH_BROWSER_LOCALE, connectFreshWorkspaceZh, saveFailureShot } from './support.ts'
  22. /** Points the shipped shared Agent default at this scenario's own route. */
  23. const OVERLAY = fileURLToPath(new URL('./default-model.overlay.yml', import.meta.url))
  24. /** The route this scenario starts on, patched over the shipped default. */
  25. const START_ROUTE = 'origin-gateway'
  26. const START_MODEL = 'origin-large'
  27. /** The route the switch lands on, which then becomes the saved default. */
  28. const ROUTE = 'acme-gateway'
  29. const MODEL = 'acme-large'
  30. describe('web e2e: the composer model switch is the default for later sessions', () => {
  31. let scaffold: WebScaffold
  32. let browser: Browser
  33. let page: Page
  34. let tripwire: ReturnType<typeof watchConsole>
  35. /** Create one session and its agent through the same wire face the browser uses. */
  36. const createSession = async (sessionId: string): Promise<string> => {
  37. const response = await scaffold.ctx.sessionController.create({
  38. sessionId: SessionId(sessionId),
  39. cwd: scaffold.workspaceCwd,
  40. })
  41. return response.sessionId
  42. }
  43. /** The route the Client derives from the Session projection and Host default. */
  44. const currentOf = (sessionId: string): Promise<unknown> => {
  45. const session = scaffold.ctx.sessions.get(SessionId(sessionId))
  46. if (session === undefined) throw new Error(`session "${sessionId}" is not live`)
  47. return Promise.resolve(
  48. scaffold.ctx.sessionProjections.snapshot(session).values.modelSelection?.next
  49. ?? scaffold.ctx.agentDefaultModel.currentSelection(),
  50. )
  51. }
  52. beforeAll(async () => {
  53. scaffold = await launchWebScaffold({ extraOverlayPath: OVERLAY })
  54. // Two routes so the picker has somewhere to start and somewhere to go.
  55. // Declared through the settings seam rather than the Models page: this
  56. // scenario is about the composer, and the declaring flow is covered by
  57. // models-settings.e2e.
  58. await scaffold.ctx.settings.update('llm-pi-ai', {
  59. providers: {
  60. [START_ROUTE]: {
  61. displayName: 'Origin Gateway',
  62. api: 'openai-completions',
  63. baseURL: 'https://gateway.origin.example/v1',
  64. models: [{ id: START_MODEL, name: 'Origin Large' }],
  65. },
  66. [ROUTE]: {
  67. displayName: 'Acme Gateway',
  68. api: 'openai-completions',
  69. baseURL: 'https://gateway.acme.example/v1',
  70. models: [{ id: MODEL, name: 'Acme Large' }],
  71. },
  72. },
  73. })
  74. browser = await chromium.launch()
  75. page = await browser.newPage({ viewport: { width: 1680, height: 1000 }, locale: ZH_BROWSER_LOCALE })
  76. tripwire = watchConsole(page)
  77. await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
  78. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  79. // The composer's seats only exist once a workspace is connected: without
  80. // one the input is the locked placeholder and no session scope is open.
  81. await connectFreshWorkspaceZh(page, scaffold.workspaceCwd)
  82. }, 120_000)
  83. afterAll(async () => {
  84. await browser?.close()
  85. await scaffold?.close()
  86. })
  87. it('writes the switched model as the default and leaves a logged session alone', async () => {
  88. onTestFailed(() => saveFailureShot(page, 'web-e2e-default-model'))
  89. // A session that has already run a turn, spelled as the fact a turn
  90. // leaves behind: its own logged route.
  91. const loggedId = await createSession('default-model-logged')
  92. scaffold.ctx.sessions.get(SessionId(loggedId))?.append('request/header', {
  93. header: { config: { provider: START_ROUTE, model: START_MODEL } },
  94. reason: 'initial',
  95. })
  96. const trigger = page.getByRole('button', { name: /^选择模型/ })
  97. await trigger.waitFor({ timeout: 15_000 })
  98. await trigger.click()
  99. await page.getByRole('menuitem', { name: /模型/ }).click()
  100. await page.getByRole('menuitemradio', { name: 'Acme Large' }).click()
  101. // The switch is what sets the default: the shared Agent-route settings section
  102. // now names it, beside the provider profiles the Models page writes.
  103. await expect.poll(
  104. async () => readFile(join(scaffold.harnessHome, 'settings.yaml'), 'utf8'),
  105. { timeout: 10_000 },
  106. ).toContain('agent-default-model:')
  107. const document = await readFile(join(scaffold.harnessHome, 'settings.yaml'), 'utf8')
  108. expect(document).toContain(`provider: ${ROUTE}`)
  109. expect(document).toContain(`model: ${MODEL}`)
  110. // A session created after the switch starts from it...
  111. expect(await currentOf(await createSession('default-model-after')))
  112. .toEqual({ provider: ROUTE, model: MODEL })
  113. // ...while the one holding a logged route keeps deriving from its log.
  114. expect(await currentOf(loggedId)).toEqual({ provider: START_ROUTE, model: START_MODEL })
  115. expect(tripwire.pageErrors).toEqual([])
  116. }, 60_000)
  117. it('goes inert when the route the default names stops being served', async () => {
  118. onTestFailed(() => saveFailureShot(page, 'web-e2e-default-model-blocked'))
  119. const box = page.locator('[data-composer-input]').first()
  120. await expect.poll(async () => box.isEnabled(), { timeout: 10_000 }).toBe(true)
  121. // What removing the provider on the Models page leaves behind: the saved
  122. // default still names the route, and nothing serves it any more.
  123. // `replace`, not `update`: a merge patch of `{providers: {}}` leaves every
  124. // stored profile in place.
  125. await scaffold.ctx.settings.replace('llm-pi-ai', { providers: {} })
  126. await expect.poll(async () => box.isEnabled(), { timeout: 15_000 }).toBe(false)
  127. expect(await box.getAttribute('data-placeholder')).toBe('当前模型不可用,请先选择模型')
  128. // The block is an affordance; the refusal is the Host's. A client that
  129. // never disabled anything still cannot start a turn on a dead route.
  130. await expect(scaffold.ctx.sessionController.prompt({
  131. requestId: 'default-model-refused' as never,
  132. sessionId: SessionId(await createSession('default-model-refusal')),
  133. mode: 'queue',
  134. content: [{ type: 'text', text: 'hi' }],
  135. }, new AbortController().signal)).rejects.toMatchObject({ code: 'session/model-unavailable' })
  136. // The way out stays open. Locking the model seat with everything else
  137. // would leave the composer asking for the one thing it prevents.
  138. const seat = page.getByRole('button', { name: /^选择模型/ })
  139. expect(await seat.isEnabled()).toBe(true)
  140. await seat.click()
  141. await page.getByRole('menuitem', { name: /模型/ }).click()
  142. await page.getByRole('menuitemradio').first().click()
  143. await expect.poll(async () => box.isEnabled(), { timeout: 15_000 }).toBe(true)
  144. expect(tripwire.pageErrors).toEqual([])
  145. }, 60_000)
  146. })