From 0920903b472beb8d31c2fa81dcab89d1c46bae09 Mon Sep 17 00:00:00 2001 From: Turtle Date: Fri, 23 Oct 2026 13:32:29 +0800 Subject: [PATCH] fix(ui-settings-models): write retry-policy fields individually and refuse empty codes --- apps/web/tests/models-settings.e2e.ts | 7 +- .../ui-settings-models/README.i18n.yaml | 12 +-- packages/client/ui-settings-models/README.md | 6 +- .../client/ui-settings-models/README.zh.md | 6 +- .../src/client/ProviderEditor.tsx | 39 ++++++--- .../src/client/RetryPolicyEditor.tsx | 56 +++++++------ .../ui-settings-models/src/client/locales.ts | 8 ++ .../tests/components.client.spec.tsx | 4 + .../tests/retry-policy.client.spec.tsx | 80 ++++++++++++++++--- 9 files changed, 159 insertions(+), 59 deletions(-) diff --git a/apps/web/tests/models-settings.e2e.ts b/apps/web/tests/models-settings.e2e.ts index ac0de149af..fbaebbf240 100644 --- a/apps/web/tests/models-settings.e2e.ts +++ b/apps/web/tests/models-settings.e2e.ts @@ -6,8 +6,8 @@ // while the settings document records only that reference. Each saved row // appears after route topology invalidation without presenting liveness as // provider status. The customized-settings fold writes its curated fields — -// the endpoint, a declared route's own name and protocol, and the reasoning -// levels of its models — as merge patches against the stored profile. Zero +// the endpoint, the retry policy, a declared route's own name and protocol, and +// the reasoning levels of its models — as merge patches against the stored profile. Zero // model calls: configuration is pure settings/credentials/llm-domain traffic, // so there is no fixture and a stray stream would fail loud because the // adapter registry is empty. The provider under test is @@ -228,6 +228,8 @@ describe('web e2e: Models settings page configures a dormant provider', () => { const url = dialog.getByLabel('API 地址') await url.waitFor({ timeout: 10_000 }) await url.fill('https://gateway.minimax.example/v1') + await dialog.getByLabel('重试模式', { exact: true }).selectOption('normal') + await dialog.getByLabel('最大重试次数', { exact: true }).fill('3') await dialog.getByRole('button', { name: '保存', exact: true }).click() // The editor closes back to the row; the fold's write merged into the // stored profile beside the reference. @@ -236,6 +238,7 @@ describe('web e2e: Models settings page configures a dormant provider', () => { const document = await readFile(join(scaffold.harnessHome, 'profiles', 'scaffold', 'cordis.patch.yml'), 'utf8') expect(document).toContain('baseURL: https://gateway.minimax.example/v1') expect(document).toContain('apiKeyEnv: MINIMAX_CN_API_KEY') + expect(document).toMatch(/retryPolicy:\n\s+mode: normal\n\s+maxRetries: 3\n/u) const snapshot = await captureStableAria(page, '[role="dialog"]', scaffold.workspaceCwd) await compareOrRefreshGolden(CONFIGURED_EXPECTED, snapshot, MODE) expect(tripwire.pageErrors).toEqual([]) diff --git a/packages/client/ui-settings-models/README.i18n.yaml b/packages/client/ui-settings-models/README.i18n.yaml index 71fe226184..e4d09ffcb1 100644 --- a/packages/client/ui-settings-models/README.i18n.yaml +++ b/packages/client/ui-settings-models/README.i18n.yaml @@ -21,8 +21,8 @@ en: f4817eb2e3537ed9 zh: e589c193fa85473f /deepseek-ai-dsh-client-ui-settings-models/use-this-package/editing-a-provider: - en: ac1fc6f822d8c779 - zh: 0587c714d3af21f0 + en: f18b4e60ceed5704 + zh: 757d5f4726eec4f2 /deepseek-ai-dsh-client-ui-settings-models/use-this-package/adding-and-deleting-providers: en: c0b04b2b11af60d3 zh: d195eec281e445cb @@ -36,8 +36,8 @@ en: a87afbec5e339b36 zh: 6348c81af7e650e1 /deepseek-ai-dsh-client-ui-settings-models/understand-the-implementation/validation: - en: 74948a88fe1f9aac - zh: 8ad2200fa74c12c9 + en: 1695ec7430ad88e1 + zh: 1df96b8ae82c2e26 /deepseek-ai-dsh-client-ui-settings-models/understand-the-implementation/concurrency-and-credentials: en: 6e04c00818f014cd zh: 2d57f8d8944e67ed @@ -54,8 +54,8 @@ en: ca75c51c89c2c9b0 zh: 9779c98fff4c949a /deepseek-ai-dsh-client-ui-settings-models/known-limitations-and-deferred-work: - en: cc69c9934bf22302 - zh: 4ea896f4b54aa203 + en: 480bf2ddd4b76779 + zh: dfda0c29be636f84 /deepseek-ai-dsh-client-ui-settings-models/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: 3bb0c20c93f16f98 diff --git a/packages/client/ui-settings-models/README.md b/packages/client/ui-settings-models/README.md index 0427c8d357..dfc0bea959 100644 --- a/packages/client/ui-settings-models/README.md +++ b/packages/client/ui-settings-models/README.md @@ -55,7 +55,7 @@ An endpoint without a fixed catalog default shows the provider's `baseURLEnv` co The collapsed 自定义设置 fold carries the curated extras: `baseURL` for both families (the placeholder shows the endpoint the profile resolves to, the public endpoint for deepseek, else the `defaultBaseURL` the configurable-provider directory reports for a pi-ai catalog route), each adapter's model catalog, and the **display name** and **API protocol** of a pi-ai route the adapter does not ship. Profile `headers` remain deployment configuration in `cordis.patch.yml` or Cordis config and have no Models-page editor. The Provider ID stays fixed: it is the settings key, the name every other namespace and every logged session references, and the stem of a credential reference the page cannot read back to move. There is no provider-scoped reasoning-effort field: effort is a per-model capability, so a provider-scoped control could only be set to a value some models reject. Each model row edits `id`, optional display `name`, optional `contextWindow`/`maxTokens`, input types, and, on a hand-declared pi-ai route, reasoning levels; unrelated model fields survive edits. -The same fold edits the provider's `retryPolicy` for both families. **Retry policy** defaults to the inherited policy and names its mode; choosing **Retry transient errors** or **Retry every error** writes a user-layer policy. Transient mode edits the maximum retry count and the comma-separated retryable error codes; both modes edit the initial delay, maximum delay, and jitter ratio. Each empty field shows and keeps the inherited value, read from the composition layer, then the schema default. Apply is disabled while a field holds a value the adapter refuses: a negative or fractional retry count, a repeated code, a delay that is not positive or exceeds the schema maximum, an initial delay above the maximum delay, or a jitter ratio outside 0 to 1. The refusal appears below the fields, or above the card actions while the fold is closed. A stored policy without a mode edits under the inherited mode. Choosing the default again removes the user-layer policy. +The same fold edits the provider's `retryPolicy` for both families. **Retry policy** defaults to the inherited policy and names its mode; choosing **Retry transient errors** or **Retry every error** writes a user-layer policy. Transient mode edits the maximum retry count and the comma-separated retryable error codes; both modes edit the initial delay, maximum delay, and jitter ratio. Each empty field shows and keeps the inherited value, read from the composition layer, then the schema default. Apply is disabled while a field holds a value the adapter refuses: a negative or fractional retry count, an empty code list, a blank or non-text code, a repeated code, a delay that is not positive or exceeds the schema maximum, an initial delay above the maximum delay, or a jitter ratio outside 0 to 1. The refusal appears below the fields, or above the card actions while the fold is closed. A stored policy without a mode shows the inherited mode, or transient mode when none is inherited, and Apply saves that mode. Clearing a field unsets it, so the inherited value applies again; choosing the default again removes the user-layer policy. The DeepSeek card edits the `llm-deepseek` endpoint, credentials, retry policy, and model catalog. It uses Messages, with the default endpoint placeholder `https://api.deepseek.com/anthropic`. @@ -93,7 +93,7 @@ The page never holds a full settings section: it holds only the REDACTED descrip ### Validation -A typed API key is judged on its own field: after trimming, it must be non-empty and every character must be printable ASCII (`[\x21-\x7E]`), which is exactly what an HTTP header value can carry — the twin of `normalizeApiKey` in `@deepseek-ai/dsh-llm`, mirrored here because the source-plane split forbids importing it. A value matching a pasted `NAME=value` environment line or wrapped in matching quotes is refused as the same format failure. Empty ids, duplicate ids, empty explicit names, and unreadable, non-positive, or fractional capacities fail before any write. DeepSeek's `models` is one replace-by-value array: the editor shows inherited effective rows until the first model edit materializes the complete array in the user layer, while reset unsets that override. +A typed API key is judged on its own field: after trimming, it must be non-empty and every character must be printable ASCII (`[\x21-\x7E]`), which is exactly what an HTTP header value can carry — the twin of `normalizeApiKey` in `@deepseek-ai/dsh-llm`, mirrored here because the source-plane split forbids importing it. A value matching a pasted `NAME=value` environment line or wrapped in matching quotes is refused as the same format failure. Empty ids, duplicate ids, empty explicit names, and unreadable, non-positive, or fractional capacities fail before any write. A drafted `retryPolicy` passes the checks of `resolveRetryPolicy` in `@deepseek-ai/dsh-llm`, mirrored for the same reason, because `llm-deepseek` only logs a warning for a live policy it refuses. Switching to always mode keeps the transient-only fields, which the adapter accepts and ignores, except a retry count that is not a number and could no longer be corrected. The card writes the policy field by field, so an unchanged inherited field stays inherited. DeepSeek's `models` is one replace-by-value array: the editor shows inherited effective rows until the first model edit materializes the complete array in the user layer, while reset unsets that override. ### Concurrency and credentials @@ -140,7 +140,7 @@ None; this package neither assembles nor sends a provider request. These limits define the editor's field coverage and the page's reach; they are current package constraints, not a settings roadmap. -- **Only the API key and curated fold fields are editable on the card** — the hand-written editor traded schema-generic field coverage for the mockup layout. Retry policy, timeouts, DeepSeek model descriptions, and other advanced fields remain in `cordis.patch.yml`; existing model fields the editor does not show are preserved. +- **Only the API key and curated fold fields are editable on the card** — the hand-written editor traded schema-generic field coverage for the mockup layout. Timeouts, DeepSeek model descriptions, and other advanced fields remain in `cordis.patch.yml`; existing model fields the editor does not show are preserved. - **Credential cleanup is intentionally narrow** — deleting a row removes the configured, writable credential only when its reference is the exact `_API_KEY` target this page derives. Custom references, environment credentials, and unidentifiable targets are retained because the row cannot prove ownership of them. - **Only pi-ai routes can be hand-declared** — the custom-API form writes into `llm-pi-ai`, the one namespace whose profiles describe a whole provider. A `llm-deepseek` route is a composition fact, not something this page can create. - **The catalog select lists route identifiers** — `moonshotai`, `zai`, and the other pi-ai catalog ids appear as they are, with no product names, aliases, or search. A searchable picker with the custom form as one pinned entry would let the mode switch go; it needs the directory to carry display names first. diff --git a/packages/client/ui-settings-models/README.zh.md b/packages/client/ui-settings-models/README.zh.md index 4a4e929429..0428c09088 100644 --- a/packages/client/ui-settings-models/README.zh.md +++ b/packages/client/ui-settings-models/README.zh.md @@ -55,7 +55,7 @@ API 密钥输入框初始为空,并通过 `autocomplete="new-password"` 请求 收起的「自定义设置」折叠区承载精选的额外字段:两个家族都有 `baseURL`(占位符显示 profile 解析出的端点,deepseek 即公共端点;没有时显示可配置提供商目录为 pi-ai 内置路由报告的 `defaultBaseURL`)、各适配器自己的模型目录,以及适配器未提供的 pi-ai 路由的**显示名称**与 **API 协议**。Profile `headers` 仍是 `cordis.patch.yml` 或 Cordis 配置中的部署配置,Models 页面不提供编辑器。Provider ID 保持固定:它是 settings 的键、其他每个 namespace 与每一条已记录会话引用的名字,也是页面读不回、因而搬不走的凭据引用词干。这里没有提供商级的推理等级字段:它是按模型的能力,提供商级的控件只可能被设成某些模型会拒绝的值。每个模型行可编辑 `id`、可选显示 `name`、可选 `contextWindow`/`maxTokens`、输入类型,以及手工声明的 pi-ai 路由上的推理等级;无关的模型字段在编辑后仍会保留。 -同一折叠区还为两个家族编辑提供商的 `retryPolicy`。**重试策略**默认沿用继承的策略并显示其模式;选择**仅重试临时错误**或**重试所有错误**会写入用户层策略。临时错误模式编辑最大重试次数和逗号分隔的可重试错误码;两种模式都编辑初始延迟、最大延迟和抖动比例。每个空字段显示并保留继承值,先取组合层的值,再取 schema 默认值。字段中有适配器会拒绝的值时,应用按钮不可用:负数或小数重试次数、重复的错误码、非正或超过 schema 上限的延迟、初始延迟大于最大延迟,或抖动比例不在 0 到 1 之间。拒绝原因显示在字段下方;折叠区收起时显示在卡片操作按钮上方。未设置模式的已存储策略按继承的模式编辑。重新选择默认会移除用户层策略。 +同一折叠区还为两个家族编辑提供商的 `retryPolicy`。**重试策略**默认沿用继承的策略并显示其模式;选择**仅重试临时错误**或**重试所有错误**会写入用户层策略。临时错误模式编辑最大重试次数和逗号分隔的可重试错误码;两种模式都编辑初始延迟、最大延迟和抖动比例。每个空字段显示并保留继承值,先取组合层的值,再取 schema 默认值。字段中有适配器会拒绝的值时,应用按钮不可用:负数或小数重试次数、空的错误码列表、空白或非文本的错误码、重复的错误码、非正或超过 schema 上限的延迟、初始延迟大于最大延迟,或抖动比例不在 0 到 1 之间。拒绝原因显示在字段下方;折叠区收起时显示在卡片操作按钮上方。未设置模式的已存储策略显示继承的模式,没有可继承的模式时显示临时错误模式,应用时会保存该模式。清空字段会取消该字段的设置,从而重新使用继承值;重新选择默认会移除用户层策略。 `llm-deepseek` 的 DeepSeek 卡片编辑端点、凭据、重试策略和模型目录。它使用 Messages,默认端点占位符为 `https://api.deepseek.com/anthropic`。 @@ -93,7 +93,7 @@ Models 页面包含 **DeepSeek 账号**(`deepseek-account`,英文为 **DeepS ### 校验 -键入的 API 密钥按其自身字段判定:去除首尾空白后必须非空,且每个字符都必须是可打印 ASCII(`[\x21-\x7E]`),这正是 HTTP 头值能够携带的字符集——与 `@deepseek-ai/dsh-llm` 中的 `normalizeApiKey` 互为镜像,此处复刻是因为源平面拆分禁止导入它。与粘贴的 `NAME=value` 环境行一致或包裹在匹配引号内的值,会作为同样的格式失败被拒绝。空 id、重复 id、空显式名称以及不可读、非正数或小数的容量都会在任何写入之前失败。DeepSeek 的 `models` 是一个按值整体替换的数组:编辑器先显示继承的有效行,直到第一次模型编辑把完整数组物化进用户层,重置则取消该覆盖。 +键入的 API 密钥按其自身字段判定:去除首尾空白后必须非空,且每个字符都必须是可打印 ASCII(`[\x21-\x7E]`),这正是 HTTP 头值能够携带的字符集——与 `@deepseek-ai/dsh-llm` 中的 `normalizeApiKey` 互为镜像,此处复刻是因为源平面拆分禁止导入它。与粘贴的 `NAME=value` 环境行一致或包裹在匹配引号内的值,会作为同样的格式失败被拒绝。空 id、重复 id、空显式名称以及不可读、非正数或小数的容量都会在任何写入之前失败。草稿中的 `retryPolicy` 须通过 `@deepseek-ai/dsh-llm` 中 `resolveRetryPolicy` 的检查,出于同样原因在此复刻,因为 `llm-deepseek` 对它拒绝的实时策略只记录警告。切换到重试所有错误模式时保留仅临时错误模式使用的字段,适配器接受并忽略它们;但不是数字的重试次数会被移除,因为切换后无法再修正。卡片按字段写入策略,因此未修改的继承字段保持继承。DeepSeek 的 `models` 是一个按值整体替换的数组:编辑器先显示继承的有效行,直到第一次模型编辑把完整数组物化进用户层,重置则取消该覆盖。 ### 并发与凭据 @@ -140,7 +140,7 @@ Models 页面包含 **DeepSeek 账号**(`deepseek-account`,英文为 **DeepS 这些限制定义编辑器的字段覆盖范围与本页的触达范围;它们是当前包约束,不是设置路线图。 -- **卡片上只有 API 密钥与精选折叠字段可编辑**:手写编辑器以 schema 通用字段覆盖换取了 mockup 布局。重试策略、超时、DeepSeek 模型说明及其他进阶字段仍留在 `cordis.patch.yml` 中;编辑器未展示的现有模型字段会予以保留。 +- **卡片上只有 API 密钥与精选折叠字段可编辑**:手写编辑器以 schema 通用字段覆盖换取了 mockup 布局。超时、DeepSeek 模型说明及其他进阶字段仍留在 `cordis.patch.yml` 中;编辑器未展示的现有模型字段会予以保留。 - **凭据清理范围刻意保持狭窄**:删除一行时,仅当其引用与页面派生的 `_API_KEY` 目标完全一致,才会清除已配置且可写的凭据。自定义引用、环境凭据与无法识别的目标会保留,因为该行无法证明自己拥有它们。 - **只有 pi-ai 路由可以手工声明**:自定义模型 API 表单写入 `llm-pi-ai`——唯一一个其 profile 描述整个提供商的 namespace。`llm-deepseek` 路由是组合面的事实,不是本页能创建的东西。 - **目录选择框列出的是路由标识符**:`moonshotai`、`zai` 等 pi-ai catalog id 原样显示,没有产品名、别名或搜索。一个把自定义表单作为置顶项的可搜索选择器可以取代方式切换;前提是目录先携带显示名称。 diff --git a/packages/client/ui-settings-models/src/client/ProviderEditor.tsx b/packages/client/ui-settings-models/src/client/ProviderEditor.tsx index a0f65f61d7..4b7fe7449d 100644 --- a/packages/client/ui-settings-models/src/client/ProviderEditor.tsx +++ b/packages/client/ui-settings-models/src/client/ProviderEditor.tsx @@ -8,9 +8,9 @@ * provider-native authentication); * the collapsed 自定义设置 area carries the per-family extras (`baseURL` and * `retryPolicy` for both families, DeepSeek's id/name/context-window model - * catalog, and the display name and wire protocol of a pi-ai route the adapter does not ship — - * the two fields the create card asked that route for, editable here for the - * same reason). + * catalog, and the display name and wire protocol of a pi-ai route the + * adapter does not ship — the two fields the create card asked that route + * for, editable here for the same reason). * Reasoning effort is deliberately absent: it is a per-MODEL capability, and * the models under one provider disagree about it, so a provider-scoped * control can only be set to a value some of them reject. The composer's @@ -122,11 +122,17 @@ function draftAt( return structuredClone(subtree) as Record } +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value) +} + /** * The minimal path ops carrying `after` over `before`, both as the card sees * them. Only keys the card observed are named; fields absent from both sides * produce no op, which is why edits are path-addressed rather than a rebuilt - * section. + * section. Objects are diffed field by field, so an omitted field keeps the + * value an unset restores from the inherited layer instead of a whole-object + * set discarding it. * @param base - path of the edited subtree inside the user section. * @param before - the subtree as loaded, or undefined when it is new. * @param after - the subtree as edited. @@ -137,13 +143,13 @@ export function pathOps( before: unknown, after: Record, ): SettingsPathOpView[] { - const previous = typeof before === 'object' && before !== null && !Array.isArray(before) - ? before as Record - : {} + const previous = isRecord(before) ? before : {} const ops: SettingsPathOpView[] = [] for (const [key, value] of Object.entries(after)) { - if (JSON.stringify(previous[key]) === JSON.stringify(value)) continue - ops.push({ op: 'set', path: [...base, key], value: value as JsonValue }) + const prior = previous[key] + if (JSON.stringify(prior) === JSON.stringify(value)) continue + if (isRecord(value) && (prior === undefined || isRecord(prior))) ops.push(...pathOps([...base, key], prior, value)) + else ops.push({ op: 'set', path: [...base, key], value: value as JsonValue }) } for (const key of Object.keys(previous)) { if (!(key in after)) ops.push({ op: 'unset', path: [...base, key] }) @@ -179,7 +185,15 @@ function refFor( */ export function ProviderEditor(props: ProviderEditorProps): ReactNode { const { namespace, schema, settingsPath, operations, t } = props - const [draft, setDraft] = useState>(() => draftAt(schema, namespace, settingsPath)) + const [draft, setDraft] = useState>(() => { + const loaded = draftAt(schema, namespace, settingsPath) + const policy = loaded['retryPolicy'] + // A stored retry policy without a mode edits under the mode it inherits; + // the draft names it so a saved policy always carries one. + if (!isRecord(policy) || policy['mode'] !== undefined) return loaded + const mode = schema.getPath(namespace.base, [...settingsPath, 'retryPolicy', 'mode']) ?? 'normal' + return { ...loaded, retryPolicy: { ...policy, mode } } + }) const [keyDraft, setKeyDraft] = useState('') const [busy, setBusy] = useState(false) const [listBusy, setListBusy] = useState(false) @@ -237,7 +251,10 @@ export function ProviderEditor(props: ProviderEditorProps): ReactNode { const validateModels = (value: unknown): DeepSeekModelsValidationFailure | ReasoningEffortsFailure | undefined => validateDeepSeekModels(value) ?? (editsReasoning ? validateReasoningEfforts(value) : undefined) const modelFailure = validateModels(schema.getPath(draft, ['models'])) - const retryNode = useMemo(() => schema.nodeAtPath(root, [...settingsPath, 'retryPolicy']), [root, schema, settingsPath]) + const retryNode = useMemo( + () => layout === 'unknown' ? undefined : schema.nodeAtPath(root, [...settingsPath, 'retryPolicy']), + [layout, root, schema, settingsPath], + ) const retryDefaults = retryNode === undefined ? undefined : retryPolicyDefaults(schema, retryNode, schema.getPath(namespace.base, [...settingsPath, 'retryPolicy'])) diff --git a/packages/client/ui-settings-models/src/client/RetryPolicyEditor.tsx b/packages/client/ui-settings-models/src/client/RetryPolicyEditor.tsx index 075cc17b64..8a0bb2fb1f 100644 --- a/packages/client/ui-settings-models/src/client/RetryPolicyEditor.tsx +++ b/packages/client/ui-settings-models/src/client/RetryPolicyEditor.tsx @@ -81,7 +81,7 @@ export interface RetryPolicyFailure { /** * The first refused field of a drafted policy, checked as `resolveRetryPolicy` - * checks the merged policy: fields the draft leaves empty, including `mode`, inherit. + * checks the merged policy: fields the draft leaves empty inherit. * @param schema - settings schema operations. * @param node - the `retryPolicy` schema union, which bounds every field. * @param policy - the drafted user-layer policy; undefined inherits. @@ -97,17 +97,25 @@ export function retryPolicyFailure( t: (key: ModelsKey) => string, ): RetryPolicyFailure | undefined { if (policy === undefined) return undefined + if (typeof policy !== 'object' || policy === null || Array.isArray(policy)) { + const message = schema.validate(node, policy) + return message === undefined ? undefined : { message } + } const fail = (key: ModelsKey, path: readonly string[]): RetryPolicyFailure => ({ message: t(key), path }) const number = (path: readonly string[]): number => { const value = schema.getPath(policy, path) ?? defaults.value(path) return typeof value === 'number' ? value : NaN } - const mode = schema.getPath(policy, ['mode']) ?? defaults.mode - if (mode === 'normal') { + if (schema.getPath(policy, ['mode']) === 'normal') { const retries = number(MAX_RETRIES) if (!Number.isSafeInteger(retries) || retries < 0) return fail('retryMaxRetriesInvalid', MAX_RETRIES) const codes = schema.getPath(policy, CODES) - if (Array.isArray(codes) && new Set(codes).size !== codes.length) return fail('retryCodesDuplicate', CODES) + if (Array.isArray(codes)) { + if (codes.length === 0 || codes.some(code => typeof code !== 'string' || code.length === 0)) { + return fail('retryCodesInvalid', CODES) + } + if (new Set(codes).size !== codes.length) return fail('retryCodesDuplicate', CODES) + } } for (const path of [INITIAL_DELAY, MAX_DELAY]) { const delay = number(path) @@ -117,7 +125,7 @@ export function retryPolicyFailure( if (number(INITIAL_DELAY) > number(MAX_DELAY)) return fail('retryDelayOrder', INITIAL_DELAY) const jitter = number(JITTER) if (!(jitter >= 0 && jitter <= 1)) return fail('retryJitterInvalid', JITTER) - const message = schema.validate(node, { ...policy as Record, mode }) + const message = schema.validate(node, policy) return message === undefined ? undefined : { message } } @@ -146,19 +154,23 @@ function textOf(value: unknown): string { return typeof value === 'number' || typeof value === 'string' ? String(value) : '' } -/** Set or remove one nested field of a plain policy object, dropping emptied parents. */ -function withField(policy: Record, path: readonly string[], value: unknown): Record { - const [key, ...rest] = path as [string, ...string[]] - const next = { ...policy } - const child = rest.length === 0 - ? value - : withField(typeof next[key] === 'object' && next[key] !== null ? next[key] as Record : {}, rest, value) - if (child === undefined || (typeof child === 'object' && child !== null && Object.keys(child).length === 0)) { - Reflect.deleteProperty(next, key) - } else { - next[key] = child +/** Set or remove one field of a plain policy object, dropping an emptied `backoff`. */ +function withField(policy: Record, path: FieldPath, value: unknown): Record { + const assign = (target: Record, key: string, next: unknown): void => { + if (next === undefined) Reflect.deleteProperty(target, key) + else target[key] = next } - return next + const result = { ...policy } + if (path.length === 1) { + assign(result, path[0], value) + return result + } + const [parent, key] = path + const prior = result[parent] + const child = typeof prior === 'object' && prior !== null ? { ...prior as Record } : {} + assign(child, key, value) + assign(result, parent, Object.keys(child).length === 0 ? undefined : child) + return result } /** @@ -173,8 +185,6 @@ export function RetryPolicyEditor(props: RetryPolicyEditorProps): ReactNode { : undefined const current = policy ?? {} const mode = current['mode'] - // A stored policy without a mode inherits the mode beneath it. - const shownMode = mode ?? (policy === undefined ? undefined : defaults.mode) // Raw text keeps partial input such as `0.` visible while it is typed. const [texts, setTexts] = useState>({}) const textAt = (path: FieldPath): string => texts[path.join('.')] ?? textOf(path.reduce( @@ -237,12 +247,12 @@ export function RetryPolicyEditor(props: RetryPolicyEditorProps): ReactNode { - {shownMode === 'always' ? {t('retryAlwaysHint')} : null} - {shownMode === 'normal' || shownMode === 'always' + {mode === 'always' ? {t('retryAlwaysHint')} : null} + {mode === 'normal' || mode === 'always' ? (
- {shownMode === 'normal' ? field(CODES, 'retryCodes') : null} - {NUMBER_FIELDS.filter(([path]) => shownMode === 'normal' || path !== MAX_RETRIES).map(([path, label]) => field(path, label))} + {mode === 'normal' ? field(CODES, 'retryCodes') : null} + {NUMBER_FIELDS.filter(([path]) => mode === 'normal' || path !== MAX_RETRIES).map(([path, label]) => field(path, label))}
) : null} diff --git a/packages/client/ui-settings-models/src/client/locales.ts b/packages/client/ui-settings-models/src/client/locales.ts index 01df4731c1..1c9eed2b28 100644 --- a/packages/client/ui-settings-models/src/client/locales.ts +++ b/packages/client/ui-settings-models/src/client/locales.ts @@ -68,6 +68,7 @@ export const en = { retryMaxDelay: 'Max delay (ms)', retryJitter: 'Jitter ratio', retryMaxRetriesInvalid: 'Max retries must be a whole number, 0 or more.', + retryCodesInvalid: 'Error codes must be non-empty text.', retryCodesDuplicate: 'Each error code may appear once.', retryDelayInvalid: 'Delays must be positive and at most {max} ms.', retryDelayOrder: 'Initial delay cannot exceed max delay.', @@ -228,6 +229,7 @@ export const zh: { [Key in keyof typeof en]: string } = { retryMaxDelay: '最大延迟 (ms)', retryJitter: '抖动比例', retryMaxRetriesInvalid: '最大重试次数必须是不小于 0 的整数。', + retryCodesInvalid: '错误码必须是非空文本。', retryCodesDuplicate: '每个错误码只能出现一次。', retryDelayInvalid: '延迟必须是正数,且不超过 {max} ms。', retryDelayOrder: '初始延迟不能大于最大延迟。', @@ -385,6 +387,7 @@ export const ja = { 'retryMaxDelay': '最大遅延 (ms)', 'retryJitter': 'ジッター比率', 'retryMaxRetriesInvalid': '最大再試行回数は0以上の整数で指定してください。', + 'retryCodesInvalid': 'エラーコードは空でないテキストにしてください。', 'retryCodesDuplicate': '各エラーコードは1回のみ指定できます。', 'retryDelayInvalid': '遅延は {max} ms 以下の正の値で指定してください。', 'retryDelayOrder': '初期遅延は最大遅延以下にしてください。', @@ -542,6 +545,7 @@ export const es = { retryMaxDelay: 'Retraso máximo (ms)', retryJitter: 'Proporción de variación aleatoria', retryMaxRetriesInvalid: 'Los reintentos máximos deben ser un número entero igual o mayor que 0.', + retryCodesInvalid: 'Los códigos de error deben ser texto no vacío.', retryCodesDuplicate: 'Cada código de error solo puede aparecer una vez.', retryDelayInvalid: 'Los retrasos deben ser positivos y como máximo de {max} ms.', retryDelayOrder: 'El retraso inicial no puede superar el retraso máximo.', @@ -699,6 +703,7 @@ export const fr = { retryMaxDelay: 'Délai maximum (ms)', retryJitter: 'Ratio de gigue', retryMaxRetriesInvalid: 'Le nombre maximum de tentatives doit être un entier supérieur ou égal à 0.', + retryCodesInvalid: "Les codes d'erreur doivent être du texte non vide.", retryCodesDuplicate: "Chaque code d'erreur ne peut apparaître qu'une fois.", retryDelayInvalid: 'Les délais doivent être positifs et ne pas dépasser {max} ms.', retryDelayOrder: 'Le délai initial ne peut pas dépasser le délai maximum.', @@ -856,6 +861,7 @@ export const de = { retryMaxDelay: 'Maximale Verzögerung (ms)', retryJitter: 'Jitter-Anteil', retryMaxRetriesInvalid: 'Die maximale Anzahl an Wiederholungen muss eine ganze Zahl ab 0 sein.', + retryCodesInvalid: 'Fehlercodes müssen nicht leerer Text sein.', retryCodesDuplicate: 'Jeder Fehlercode darf nur einmal vorkommen.', retryDelayInvalid: 'Verzögerungen müssen positiv sein und dürfen höchstens {max} ms betragen.', retryDelayOrder: 'Die anfängliche Verzögerung darf die maximale Verzögerung nicht überschreiten.', @@ -1013,6 +1019,7 @@ export const ru = { retryMaxDelay: 'Максимальная задержка (ms)', retryJitter: 'Коэффициент джиттера', retryMaxRetriesInvalid: 'Максимальное количество повторных попыток должно быть целым числом не меньше 0.', + retryCodesInvalid: 'Коды ошибок должны быть непустым текстом.', retryCodesDuplicate: 'Каждый код ошибки может встречаться только один раз.', retryDelayInvalid: 'Задержки должны быть положительными и не превышать {max} ms.', retryDelayOrder: 'Начальная задержка не может превышать максимальную.', @@ -1170,6 +1177,7 @@ export const pt = { retryMaxDelay: 'Atraso máximo (ms)', retryJitter: 'Proporção de jitter', retryMaxRetriesInvalid: 'O máximo de novas tentativas deve ser um número inteiro maior ou igual a 0.', + retryCodesInvalid: 'Os códigos de erro devem ser texto não vazio.', retryCodesDuplicate: 'Cada código de erro só pode aparecer uma vez.', retryDelayInvalid: 'Os atrasos devem ser positivos e de no máximo {max} ms.', retryDelayOrder: 'O atraso inicial não pode exceder o atraso máximo.', diff --git a/packages/client/ui-settings-models/tests/components.client.spec.tsx b/packages/client/ui-settings-models/tests/components.client.spec.tsx index 08ce75a428..c23e423256 100644 --- a/packages/client/ui-settings-models/tests/components.client.spec.tsx +++ b/packages/client/ui-settings-models/tests/components.client.spec.tsx @@ -825,6 +825,10 @@ describe('ModelsSection', () => { .toEqual([{ op: 'set', path: ['b'], value: 2 }, { op: 'set', path: ['d'], value: 3 }]) expect(pathOps([], undefined, {})).toEqual([]) expect(pathOps([], { a: 1 }, { a: 1 })).toEqual([]) + expect(pathOps([], { p: { m: 'x', n: 1 } }, { p: { m: 'y' } })) + .toEqual([{ op: 'set', path: ['p', 'm'], value: 'y' }, { op: 'unset', path: ['p', 'n'] }]) + expect(pathOps([], {}, { p: { m: 'x' } })).toEqual([{ op: 'set', path: ['p', 'm'], value: 'x' }]) + expect(pathOps([], { p: 'x' }, { p: { m: 'x' } })).toEqual([{ op: 'set', path: ['p'], value: { m: 'x' } }]) }) it('stores a typed key write-only from the setup card without touching settings', async () => { diff --git a/packages/client/ui-settings-models/tests/retry-policy.client.spec.tsx b/packages/client/ui-settings-models/tests/retry-policy.client.spec.tsx index 49d7bf6794..3a25dc45af 100644 --- a/packages/client/ui-settings-models/tests/retry-policy.client.spec.tsx +++ b/packages/client/ui-settings-models/tests/retry-policy.client.spec.tsx @@ -95,15 +95,17 @@ describe('retry policy fields', () => { fireEvent.click(apply()) await waitFor(() => { expect(onClose).toHaveBeenCalledWith(true) }) - expect(writeSettings).toHaveBeenCalledWith('llm-deepseek', [{ - op: 'set', - path: ['retryPolicy'], - value: { mode: 'normal', maxRetries: 3, retryableCodes: ['RATE_LIMIT', 'SERVER'], backoff: { jitterRatio: 0.25 } }, - }], 3) + expect(writeSettings).toHaveBeenCalledWith('llm-deepseek', [ + { op: 'set', path: ['retryPolicy', 'mode'], value: 'normal' }, + { op: 'set', path: ['retryPolicy', 'maxRetries'], value: 3 }, + { op: 'set', path: ['retryPolicy', 'retryableCodes'], value: ['RATE_LIMIT', 'SERVER'] }, + { op: 'set', path: ['retryPolicy', 'backoff', 'jitterRatio'], value: 0.25 }, + ], 3) }) const delayInvalid = en.retryDelayInvalid.replace('{max}', '2147483647') it.each([ + [en.retryMaxRetries, '-1', en.retryMaxRetriesInvalid], [en.retryMaxRetries, '1.5', en.retryMaxRetriesInvalid], [en.retryMaxRetries, 'many', en.retryMaxRetriesInvalid], [en.retryCodes, 'SERVER, SERVER', en.retryCodesDuplicate], @@ -136,14 +138,70 @@ describe('retry policy fields', () => { await waitFor(() => { expect(document.getElementById('route-retry-failure')?.closest('details')).not.toBeNull() }) }) - it('edits a stored policy without a mode under the inherited mode', () => { - setup(deepSeekNamespace({ base: { retryPolicy: { mode: 'normal' } }, user: { retryPolicy: { backoff: { maxDelayMs: 2_000 } } } })) - expect(mode().value).toBe('') + it.each([ + ['the inherited mode', { mode: 'always' }, 'always'], + ['normal mode when nothing is inherited', undefined, 'normal'], + ])('names %s for a stored policy without a mode', async (_name, inherited, expected) => { + const { writeSettings } = setup(deepSeekNamespace({ + ...inherited === undefined ? {} : { base: { retryPolicy: inherited } }, + user: { retryPolicy: { backoff: { maxDelayMs: 2_000 } } }, + })) + expect(mode().value).toBe(expected) expect(input(en.retryMaxDelay).value).toBe('2000') - expect(input(en.retryMaxRetries).placeholder).toBe('5') + fireEvent.click(apply()) + await waitFor(() => { expect(writeSettings).toHaveBeenCalled() }) + expect(writeSettings.mock.calls[0]?.[1]).toEqual([{ op: 'set', path: ['retryPolicy', 'mode'], value: expected }]) + }) + + it('removes a stored policy without a mode when Default is chosen', async () => { + const { writeSettings } = setup(deepSeekNamespace({ user: { retryPolicy: { backoff: { maxDelayMs: 2_000 } } } })) + fireEvent.change(mode(), { target: { value: '' } }) + fireEvent.click(apply()) + await waitFor(() => { expect(writeSettings).toHaveBeenCalled() }) + expect(writeSettings.mock.calls[0]?.[1]).toEqual([{ op: 'unset', path: ['retryPolicy'] }]) + }) + + it('unsets a cleared field so the inherited value applies again', async () => { + const { writeSettings } = setup(deepSeekNamespace({ + base: { retryPolicy: { mode: 'normal', maxRetries: 7 } }, + user: { retryPolicy: { mode: 'normal', maxRetries: 1 } }, + })) + fireEvent.change(input(en.retryMaxRetries), { target: { value: '' } }) + expect(input(en.retryMaxRetries).placeholder).toBe('7') + fireEvent.click(apply()) + await waitFor(() => { expect(writeSettings).toHaveBeenCalled() }) + expect(writeSettings.mock.calls[0]?.[1]).toEqual([{ op: 'unset', path: ['retryPolicy', 'maxRetries'] }]) + }) + + it.each([ + ['an empty code list', []], + ['a blank code', ['']], + ['a numeric code', [500]], + ])('refuses a stored policy with %s', (_name, codes) => { + setup(deepSeekNamespace({ user: { retryPolicy: { mode: 'normal', retryableCodes: codes } } })) + expect(screen.getByText(en.retryCodesInvalid)).toBeTruthy() + expect(apply().disabled).toBe(true) + }) + + it('refuses a stored policy that is not an object', () => { + setup(deepSeekNamespace({ user: { retryPolicy: 'sometimes' } })) + expect(mode().value).toBe('') + expect(apply().disabled).toBe(true) + }) + + it('treats a stored null policy as inheriting', () => { + setup(deepSeekNamespace({ user: { retryPolicy: null } })) + expect(mode().value).toBe('') expect(apply().disabled).toBe(false) }) + it('offers no retry fields on a namespace without a curated editor', () => { + const namespace = deepSeekNamespace({ user: { retryPolicy: { mode: 'sometimes' } } }) + setup({ ...namespace, ns: 'llm-plain' }) + expect(screen.queryByRole('group', { name: en.retryPolicy })).toBeNull() + expect(document.getElementById('route-retry-failure')).toBeNull() + }) + it('drops an uncorrectable retry count when switching to always', async () => { const { writeSettings } = setup(deepSeekNamespace()) fireEvent.change(mode(), { target: { value: 'normal' } }) @@ -154,7 +212,7 @@ describe('retry policy fields', () => { expect(apply().disabled).toBe(false) fireEvent.click(apply()) await waitFor(() => { expect(writeSettings).toHaveBeenCalled() }) - expect(writeSettings.mock.calls[0]?.[1]).toEqual([{ op: 'set', path: ['retryPolicy'], value: { mode: 'always' } }]) + expect(writeSettings.mock.calls[0]?.[1]).toEqual([{ op: 'set', path: ['retryPolicy', 'mode'], value: 'always' }]) }) it('shows inherited values and removes the user policy when Default is chosen', async () => { @@ -186,7 +244,7 @@ describe('retry policy fields', () => { fireEvent.click(apply()) await waitFor(() => { expect(writeSettings).toHaveBeenCalled() }) expect(writeSettings.mock.calls[0]?.[1]).toEqual([ - { op: 'set', path: ['providers', 'openai', 'retryPolicy'], value: { mode: 'always' } }, + { op: 'set', path: ['providers', 'openai', 'retryPolicy', 'mode'], value: 'always' }, ]) })