Selaa lähdekoodia

refactor(web): clarify model input docs and strengthen tests

Yichen Jiang 1 kuukausi sitten
vanhempi
sitoutus
5d51ba5a9c

+ 2 - 2
.agents/notes/implemented/feature/2026-09-16-unified-model-input-controls.i18n.yaml

@@ -2,5 +2,5 @@
 # side as of the last confirmed-consistent state. Both languages carry equal authority;
 # after editing either side, bring the other along and re-record with:
 #   pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-09-16-unified-model-input-controls.md
-2026-09-16-unified-model-input-controls.md: 12f5f8ba7654115576f33e54d0c80bc54c5f1efd
-2026-09-16-unified-model-input-controls.zh.md: 4c5bd7fdcc7f3091da35865183cc19f25bd1c1d3
+2026-09-16-unified-model-input-controls.md: 73913880924577caf86b30990baef98efdbe751e
+2026-09-16-unified-model-input-controls.zh.md: 691ca5229c017919e708bf7df92285dee25ef6b4

+ 1 - 1
.agents/notes/implemented/feature/2026-09-16-unified-model-input-controls.md

@@ -18,7 +18,7 @@ An undeclared or empty input field displays the installed model input types, the
 
 **Independent model-row renderers.** Adapter-specific defaults and model discovery remain with their editors, but duplicate presentation creates avoidable visual drift. Shared rows keep those behaviors independent of field layout.
 
-**Keep the image-support selector.** Settings-file-only capability editing leaves custom vision models effectively text-only. A selector with an explicit Default option preserves visible pi-ai catalog inheritance; a two-state image switch would misrepresent inherited vision support as disabled. The requested checkbox interface instead exposes both input types directly, resolving inherited capabilities before enabling edits. Merely opening a row still preserves inheritance; restoring it after a checkbox edit requires removing the input field in settings or resetting the catalog override.
+**Keep the image-support selector.** Settings-file-only capability editing leaves custom vision models effectively text-only. A selector with an explicit Default option preserves visible pi-ai catalog inheritance; a two-state image switch would misrepresent inherited vision support as disabled. The checkbox interface exposes both input types directly, resolving inherited capabilities before enabling edits. Merely opening a row still preserves inheritance; restoring it after a checkbox edit requires removing the input field in settings or resetting the catalog override.
 
 **Allow no checked types.** DeepSeek rejects an empty list and pi-ai treats it as inheritance. Keeping a nonempty selection prevents the same gesture from meaning different things across adapters.
 

+ 1 - 1
.agents/notes/implemented/feature/2026-09-16-unified-model-input-controls.zh.md

@@ -18,7 +18,7 @@ DeepSeek 和 pi-ai 分别渲染模型行,导致标签、图标和间距不一
 
 **独立的模型行渲染器。** 适配器专属默认值和模型发现仍由各自编辑器负责,但重复的展示实现会造成可避免的视觉差异。共享模型行将这些行为与字段布局分离。
 
-**保留图片支持选择器。** 仅通过设置文件编辑能力,会让自定义视觉模型实际保持仅文本。带有显式「默认」选项的选择器会清楚展示 pi-ai 模型目录继承;两态图片开关则会将继承的视觉能力误表示为禁用。用户要求的复选框界面直接展示两种输入类型,并在允许编辑前解析继承的能力。仅打开模型行仍保留继承;修改复选框后,要恢复继承需在设置中移除输入字段,或重置整个模型目录覆盖。
+**保留图片支持选择器。** 仅通过设置文件编辑能力,会让自定义视觉模型实际保持仅文本。带有显式「默认」选项的选择器会清楚展示 pi-ai 模型目录继承;两态图片开关则会将继承的视觉能力误表示为禁用。复选框界面直接展示两种输入类型,并在允许编辑前解析继承的能力。仅打开模型行仍保留继承;修改复选框后,要恢复继承需在设置中移除输入字段,或重置整个模型目录覆盖。
 
 **允许全部取消。** DeepSeek 拒绝空列表,pi-ai 则将其视为继承。保留非空选择,避免同一个操作在两个适配器中具有不同含义。
 

+ 9 - 3
apps/web/tests/model-input-layout.ts

@@ -2,12 +2,18 @@
 import type { Locator, Page } from 'playwright'
 import { expect } from 'vitest'
 
-/** Verify the expanded row at the current viewport and a narrow viewport, restoring the caller's size. */
+/**
+ * Verify the expanded row at the current viewport and a narrow viewport.
+ * @param page - page with an explicit viewport, restored even when an assertion fails.
+ * @param editor - expanded model editor containing the capacity and input-type fields.
+ * @returns after checking both widths and restoring the caller's size.
+ */
 export async function assertModelInputLayout(page: Page, editor: Locator): Promise<void> {
   const original = page.viewportSize()
+  if (original === null) throw new Error('Model input layout checks require an explicit viewport')
   try {
     for (const viewport of [original, { width: 760, height: 1000 }]) {
-      if (viewport !== null) await page.setViewportSize(viewport)
+      await page.setViewportSize(viewport)
       const context = await editor.getByLabel('上下文窗口 1', { exact: true }).boundingBox()
       const output = await editor.getByLabel('最大输出 token 数 1', { exact: true }).boundingBox()
       const types = await editor.getByRole('group', { name: '输入类型 1' }).boundingBox()
@@ -20,6 +26,6 @@ export async function assertModelInputLayout(page: Page, editor: Locator): Promi
       expect(types.width).toBeGreaterThan(context.width)
     }
   } finally {
-    if (original !== null) await page.setViewportSize(original)
+    await page.setViewportSize(original)
   }
 }

+ 12 - 0
apps/web/tests/models-settings.e2e.ts

@@ -57,6 +57,18 @@ describe('web e2e: Models settings page configures a dormant provider', () => {
     await scaffold?.close()
   })
 
+  it('rejects layout checks without an explicit viewport before resizing the page', async () => {
+    const context = await browser.newContext({ viewport: null })
+    try {
+      const unsized = await context.newPage()
+      await expect(assertModelInputLayout(unsized, unsized.locator('body')))
+        .rejects.toThrow('Model input layout checks require an explicit viewport')
+      expect(unsized.viewportSize()).toBeNull()
+    } finally {
+      await context.close()
+    }
+  })
+
   it('opens the add card over the dormant directory vocabulary', async () => {
     onTestFailed(() => saveFailureShot(page, 'web-e2e-models-empty'))
     await page.getByRole('button', { name: '设置', exact: true }).click()

+ 0 - 4
packages/client/ui-settings-models/src/client/ModelsSection.module.css

@@ -426,10 +426,6 @@
   line-height: 18px;
 }
 
-/* The rules use this stylesheet's token vocabulary —
-   `--dsw-alias-border-subtle`, `--dsw-alias-text-tertiary`, and
-   `--dsw-alias-text-primary` are undefined here and would resolve to their
-   light-mode literals. */
 .modelList {
   display: flex;
   flex-direction: column;

+ 25 - 1
packages/client/ui-settings-models/tests/model-list-catalog.client.spec.tsx

@@ -1,6 +1,6 @@
 // @vitest-environment jsdom
 /** Catalog reads preserve draft ownership and discard responses for a previous provider. */
-import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
 import { afterEach, expect, it, vi } from 'vitest'
 import { ModelListEditor } from '../src/client/ModelListEditor.tsx'
 import type { ModelDiscoveryOutcome, ModelsOperations } from '../src/client/operations.ts'
@@ -81,3 +81,27 @@ it('inherits catalog inputs once an incomplete draft has a model id', async () =
   expect(image.checked).toBe(true)
   expect(onChange).toHaveBeenCalledTimes(1)
 })
+
+it('restores inherited image input after a failed catalog read is retried manually', async () => {
+  const discover = vi.fn<ModelsOperations['discoverModels']>()
+    .mockResolvedValueOnce({ kind: 'refused', message: 'Catalog unavailable' })
+    .mockResolvedValueOnce({ kind: 'found', models: [{ id: 'vision', inputModalities: ['text', 'image'] }] })
+  const onChange = vi.fn()
+  render(<ModelListEditor
+    models={[{ id: 'vision' }]} onChange={onChange} catalogProvider="openai"
+    probe={{ settingsNs: 'llm-pi-ai', provider: 'openai' }} disabled={false} t={key => en[key]}
+    operations={operations(discover)}
+  />)
+  await screen.findByText('Catalog unavailable')
+  fireEvent.click(screen.getByRole('button', { name: `${en.modelAdvanced} 1` }))
+  const image = screen.getByRole<HTMLInputElement>('checkbox', { name: en.modelInputImage })
+  expect(image.checked).toBe(false)
+
+  fireEvent.click(screen.getByRole('button', { name: en.fetchModels }))
+  const picker = await screen.findByRole('dialog', { name: en.fetchTitle })
+  fireEvent.click(within(picker).getByRole('button', { name: en.cancel }))
+  expect(image.checked).toBe(true)
+  expect(screen.queryByText('Catalog unavailable')).toBeNull()
+  expect(discover).toHaveBeenCalledTimes(2)
+  expect(onChange).not.toHaveBeenCalled()
+})

+ 1 - 1
packages/llm/llm-pi-ai/tests/discovery.spec.ts

@@ -78,7 +78,7 @@ describe('catalog-route model discovery', () => {
     const ctx = await harness()
     const models = await ctx.llm.discoverModels('llm-pi-ai', { provider: 'openai' })
     const installed = getBuiltinModels('openai').find(model => model.id === 'gpt-6-astra')
-    expect(installed?.input).toEqual(['text', 'image'])
+    expect(installed?.input).toContain('image')
     expect(models.find(model => model.id === 'gpt-6-astra')).toMatchObject({ inputModalities: installed?.input })
   })
 

+ 2 - 2
packages/llm/llm/README.i18n.yaml

@@ -2,5 +2,5 @@
 # side as of the last confirmed-consistent state. Both languages carry equal authority;
 # after editing either side, bring the other along and re-record with:
 #   pnpm run verify-translation-pairing --write packages/llm/llm/README.md
-README.md: cec84812483effd080029e46ee39d6c83b7973cd
-README.zh.md: 7f35b86049c38daa8c93d86910e19b1ddae2dce8
+README.md: 7192ee58eaffb153231268095feb3d9c7ddda37a
+README.zh.md: 6898833c6eb5199ce8a93b7ec33cbf4ce7a31cb3

+ 1 - 1
packages/llm/llm/README.md

@@ -61,7 +61,7 @@ After a successful mount, `ctx.llm.listProviders()` reports the registered route
 - **Stream one model call** — `ctx.llm.stream(options)` yields raw chunks (token-level deltas) for any registered provider and model; consumers assemble them with `BlockAssembler`.
 - **Register provider adapters** — an adapter owns one or more provider routes, and its registration captures that route's retry policy; registering the same route twice fails with `DUPLICATE_ADAPTER`.
 - **Expose and activate providers through configuration** — adapters declare configurable-provider routes plus a settings namespace, so configuration surfaces can activate dormant providers and edit connection facts without a restart. `LlmConfigurableProvider.error` reports a configuration diagnostic for repair; unaffected models can remain serviceable.
-- **Discover and resolve models** — Discovery candidates preserve optional `inputModalities`; absence means unknown. List the models an adapter advertises, interrogate an endpoint for the models it serves, and resolve one exact model's context window, output default, reasoning efforts, input modalities, and system prompt update mode: `LlmResolvedModelInfo.systemPromptUpdate` is `'in-history'` when the model reads the latest `system` message at any position as the effective system prompt and absent when only a leading system message is read; `normalizeModelInfo` rejects any other value with `INVALID_MODEL_INFO`.
+- **Discover and resolve models** — List the models an adapter advertises, interrogate an endpoint for the models it serves (candidates carry optional `inputModalities`; absence means unknown), and resolve one exact model's context window, output default, reasoning efforts, input modalities, and system prompt update mode: `LlmResolvedModelInfo.systemPromptUpdate` is `'in-history'` when the model reads the latest `system` message at any position as the effective system prompt and absent when only a leading system message is read; `normalizeModelInfo` rejects any other value with `INVALID_MODEL_INFO`.
 - **Validate call config** — an explicit or configured reasoning effort is checked against the exact model before any provider I/O, and an adapter-configured output cap is materialized when the request omits one.
 - **Read an embedded Assistant stream without expanding it** — `assistantStreamFirstTokenTime` (first token), `assistantStreamHasVisibleContent` (any visible content), and `assistantStreamHasVisibleText` (any visible text) answer their questions from the compact records with early exit; `lastAssistantStreamChunk` scans backward to the last raw chunk of one type, `assistantStreamChunks` and `joinAssistantStreamText` scan the whole stream, and `assembleAssistantStream` feeds a `BlockAssembler` one joined delta per run with the same blocks, usage, and replay state as the per-member expansion. `runFirstTokenTime` and `runFirstVisibleTime` do the early-exit scan for one packed run, and `isTokenDelta`, `isVisibleChunk`, and `chunkHasVisibleText` define the token and visibility rules for a single chunk. `expandAssistantStream` remains the validating path for records read at a durable boundary; it is not memoized, because a retained expansion costs roughly ten times the compact stream for as long as the event lives.
 

+ 1 - 1
packages/llm/llm/README.zh.md

@@ -61,7 +61,7 @@ for await (const chunk of ctx.llm.stream({
 - **流式发起一次模型调用**——`ctx.llm.stream(options)` 为任何已注册提供方与模型产出原始分片(token 级增量);消费方用 `BlockAssembler` 组装。
 - **注册提供方适配器**——一个适配器拥有一个或多个提供方路由,其注册会捕获该路由的重试策略;重复注册同一路由会以 `DUPLICATE_ADAPTER` 失败。
 - **通过配置暴露并激活提供方**——适配器声明可配置提供方路由与 settings namespace,配置界面因此可以激活休眠提供方并编辑连接信息,无需重启。`LlmConfigurableProvider.error` 报告供修复的配置诊断;未受影响的模型仍可提供服务。
-- **发现与解析模型**——发现候选保留可选的 `inputModalities`;缺省表示未知。列出适配器公布的模型、询问端点它提供哪些模型,并解析某个精确模型的上下文窗口、输出默认值、推理(reasoning)强度、输入模态与系统提示词更新模式:当模型把任意位置最新的 `system` 消息读作有效系统提示词时,`LlmResolvedModelInfo.systemPromptUpdate` 为 `'in-history'`;只读取开头 system 消息时该字段缺失;`normalizeModelInfo` 以 `INVALID_MODEL_INFO` 拒绝任何其他值。
+- **发现与解析模型**——列出适配器公布的模型、询问端点它提供哪些模型(候选携带可选的 `inputModalities`;缺省表示未知),并解析某个精确模型的上下文窗口、输出默认值、推理(reasoning)强度、输入模态与系统提示词更新模式:当模型把任意位置最新的 `system` 消息读作有效系统提示词时,`LlmResolvedModelInfo.systemPromptUpdate` 为 `'in-history'`;只读取开头 system 消息时该字段缺失;`normalizeModelInfo` 以 `INVALID_MODEL_INFO` 拒绝任何其他值。
 - **校验调用配置**——显式或配置的推理强度会在任何提供方 I/O 之前对照精确模型校验;请求省略输出上限时,会填入适配器配置的输出上限。
 - **不展开即读取内嵌 Assistant 流**——`assistantStreamFirstTokenTime`(首 token)、`assistantStreamHasVisibleContent`(任一可见内容)与 `assistantStreamHasVisibleText`(任一可见文本)通过可提前退出的扫描直接从紧凑记录得出结果;`lastAssistantStreamChunk` 反向扫描到某一类型的最后一个原始 chunk,`assistantStreamChunks` 与 `joinAssistantStreamText` 扫描整个流,`assembleAssistantStream` 向 `BlockAssembler` 每个 run 喂一段拼接 delta,blocks/usage/replayState 与逐成员展开相同。`runFirstTokenTime` 与 `runFirstVisibleTime` 对单个打包 run 做提前退出扫描,`isTokenDelta`、`isVisibleChunk` 与 `chunkHasVisibleText` 定义单个 chunk 的 token 与可见性规则。`expandAssistantStream` 仍是持久边界读取记录的校验路径;它不被记忆化,因为保留的展开在事件生命周期内约花费紧凑流的十倍内存。