feat(ui-settings-models): pick retryable error codes from a labelled list
This commit is contained in:
1 parent
d0238f6892
commit
52dc37d9fe
7 files changed
+177
-22
No files matched your search
@@ -21,8 +21,8 @@
|
||||
en: f4817eb2e3537ed9
|
||||
zh: e589c193fa85473f
|
||||
/deepseek-ai-dsh-client-ui-settings-models/use-this-package/editing-a-provider:
|
||||
en: 57b27798e605dcb2
|
||||
zh: 04bacb88db40a237
|
||||
en: 00c034b43eef5741
|
||||
zh: 4eb3f646725dddbb
|
||||
/deepseek-ai-dsh-client-ui-settings-models/use-this-package/adding-and-deleting-providers:
|
||||
en: c0b04b2b11af60d3
|
||||
zh: d195eec281e445cb
|
||||
|
||||
@@ -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 **Transient errors** or **All errors** writes a user-layer policy. Transient mode edits the comma-separated error codes and the maximum retry count; both modes edit the initial delay, maximum delay, and jitter ratio under a **Backoff** fold, which starts open only when the stored policy customizes backoff. 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 same fold edits the provider's `retryPolicy` for both families. **Retry policy** defaults to the inherited policy and names its mode; choosing **Transient errors** or **All errors** writes a user-layer policy. Transient mode edits the maximum retry count and the retried error codes, ticked from a list that names each stable failure code in words (for example **Rate limited** for `RATE_LIMIT`) and also keeps any stored code outside it, shown verbatim; the last ticked code cannot be cleared, and ticking exactly the inherited codes keeps the field inherited; both modes edit the initial delay, maximum delay, and jitter ratio under a **Backoff** fold, which starts open only when the stored policy customizes backoff. 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`.
|
||||
|
||||
|
||||
@@ -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`。**重试策略**默认沿用继承的策略并显示其模式;选择**仅临时错误**或**所有错误**会写入用户层策略。临时错误模式编辑最大重试次数和要重试的错误码,错误码从以文字命名各稳定失败码的列表中勾选(例如 `RATE_LIMIT` 显示为**请求限流**),列表也保留已存储的列表外错误码并原样显示;最后一个勾选项不能取消,勾选的错误码与继承值完全相同时字段保持继承;两种模式都在**退避**折叠区中编辑初始延迟、最大延迟和抖动比例,只有已存储策略自定义了退避时该折叠区才默认展开。每个空字段显示并保留继承值,先取组合层的值,再取 schema 默认值。字段中有适配器会拒绝的值时,应用按钮不可用:负数或小数重试次数、空的错误码列表、空白或非文本的错误码、重复的错误码、非正或超过 schema 上限的延迟、初始延迟大于最大延迟,或抖动比例不在 0 到 1 之间。拒绝原因显示在字段下方;折叠区收起时显示在卡片操作按钮上方。未设置模式的已存储策略显示继承的模式,没有可继承的模式时显示临时错误模式,应用时会保存该模式。清空字段会取消该字段的设置,从而重新使用继承值;重新选择默认会移除用户层策略。
|
||||
|
||||
`llm-deepseek` 的 DeepSeek 卡片编辑端点、凭据、重试策略和模型目录。它使用 Messages,默认端点占位符为 `https://api.deepseek.com/anthropic`。
|
||||
|
||||
|
||||
@@ -638,6 +638,13 @@
|
||||
margin-top: 4px;
|
||||
}
|
||||
|
||||
/* Code checkboxes in as many even columns as fit. */
|
||||
.retryCodeChoices {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
|
||||
gap: 6px 16px;
|
||||
}
|
||||
|
||||
/* One backoff column wide, so the count lines up with the delay fields below. */
|
||||
.retryCount {
|
||||
width: max(112px, calc((100% - 16px) / 3));
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
|
||||
import { useState } from 'react'
|
||||
import type { ReactNode } from 'react'
|
||||
import { Checkbox } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import type { SettingsSchemaOperations } from './schema-operations.ts'
|
||||
import type { ModelsKey } from './locales.ts'
|
||||
import styles from './ModelsSection.module.css'
|
||||
@@ -21,7 +22,7 @@ const INITIAL_DELAY = ['backoff', 'initialDelayMs'] as const
|
||||
const MAX_DELAY = ['backoff', 'maxDelayMs'] as const
|
||||
const JITTER = ['backoff', 'jitterRatio'] as const
|
||||
|
||||
type FieldPath = typeof CODES | typeof MAX_RETRIES | typeof INITIAL_DELAY | typeof MAX_DELAY | typeof JITTER
|
||||
type FieldPath = typeof MAX_RETRIES | typeof INITIAL_DELAY | typeof MAX_DELAY | typeof JITTER
|
||||
|
||||
/** Backoff fields of both modes, as `[policy path, label]`. */
|
||||
const BACKOFF_FIELDS: readonly (readonly [FieldPath, ModelsKey])[] = [
|
||||
@@ -30,6 +31,22 @@ const BACKOFF_FIELDS: readonly (readonly [FieldPath, ModelsKey])[] = [
|
||||
[JITTER, 'retryJitter'],
|
||||
]
|
||||
|
||||
/**
|
||||
* Stable `LlmFailure` codes offered as retryable choices, with their labels: the
|
||||
* transient defaults of `dsh-llm`, then the other request failures a retry can
|
||||
* plausibly recover. A stored code outside this list stays listed after them.
|
||||
*/
|
||||
const CODE_CHOICES: ReadonlyMap<string, ModelsKey> = new Map([
|
||||
['EMPTY_RESPONSE', 'retryCodeEmptyResponse'],
|
||||
['RATE_LIMIT', 'retryCodeRateLimit'],
|
||||
['SERVER', 'retryCodeServer'],
|
||||
['TIMEOUT', 'retryCodeTimeout'],
|
||||
['TRANSPORT', 'retryCodeTransport'],
|
||||
['STREAM_CLOSED', 'retryCodeStreamClosed'],
|
||||
['MALFORMED_RESPONSE', 'retryCodeMalformedResponse'],
|
||||
['QUOTA', 'retryCodeQuota'],
|
||||
])
|
||||
|
||||
/** Plain decimal text; prefixed forms such as `0x10` stay invalid text. */
|
||||
const DECIMAL = /^[+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?$/iu
|
||||
|
||||
@@ -149,12 +166,11 @@ export interface RetryPolicyEditorProps {
|
||||
}
|
||||
|
||||
function textOf(value: unknown): string {
|
||||
if (Array.isArray(value)) return value.join(', ')
|
||||
return typeof value === 'number' || typeof value === 'string' ? String(value) : ''
|
||||
}
|
||||
|
||||
/** Set or remove one field of a plain policy object, dropping an emptied `backoff`. */
|
||||
function withField(policy: Record<string, unknown>, path: FieldPath, value: unknown): Record<string, unknown> {
|
||||
function withField(policy: Record<string, unknown>, path: FieldPath | typeof CODES, value: unknown): Record<string, unknown> {
|
||||
const assign = (target: Record<string, unknown>, key: string, next: unknown): void => {
|
||||
if (next === undefined) Reflect.deleteProperty(target, key)
|
||||
else target[key] = next
|
||||
@@ -194,11 +210,8 @@ export function RetryPolicyEditor(props: RetryPolicyEditorProps): ReactNode {
|
||||
const edit = (path: FieldPath, text: string): void => {
|
||||
const trimmed = text.trim()
|
||||
setTexts(previous => ({ ...previous, [path.join('.')]: trimmed.length === 0 ? '' : text }))
|
||||
const value = path === CODES
|
||||
? trimmed.split(',').map(code => code.trim()).filter(code => code.length > 0)
|
||||
: DECIMAL.test(trimmed) ? Number(trimmed) : trimmed
|
||||
const empty = Array.isArray(value) ? value.length === 0 : value === ''
|
||||
props.onChange(withField(current, path, empty ? undefined : value))
|
||||
const value = DECIMAL.test(trimmed) ? Number(trimmed) : trimmed
|
||||
props.onChange(withField(current, path, value === '' ? undefined : value))
|
||||
}
|
||||
const field = (path: FieldPath, label: ModelsKey, className = styles['modelField']): ReactNode => {
|
||||
const invalid = failure?.path?.join('.') === path.join('.')
|
||||
@@ -208,7 +221,7 @@ export function RetryPolicyEditor(props: RetryPolicyEditorProps): ReactNode {
|
||||
<input
|
||||
className={styles['input']}
|
||||
type="text"
|
||||
inputMode={path === CODES ? 'text' : path === MAX_RETRIES ? 'numeric' : 'decimal'}
|
||||
inputMode={path === MAX_RETRIES ? 'numeric' : 'decimal'}
|
||||
value={textAt(path)}
|
||||
placeholder={textOf(defaults.value(path))}
|
||||
aria-invalid={invalid}
|
||||
@@ -219,6 +232,43 @@ export function RetryPolicyEditor(props: RetryPolicyEditorProps): ReactNode {
|
||||
</label>
|
||||
)
|
||||
}
|
||||
const codesField = (): ReactNode => {
|
||||
const strings = (value: unknown): string[] => Array.isArray(value) ? value.filter(code => typeof code === 'string') : []
|
||||
const inherited = strings(defaults.value(CODES))
|
||||
const stored = current['retryableCodes']
|
||||
const selected = Array.isArray(stored) ? strings(stored) : inherited
|
||||
const choices = [...new Set([...CODE_CHOICES.keys(), ...inherited, ...selected])]
|
||||
const invalid = failure?.path?.join('.') === CODES.join('.')
|
||||
return (
|
||||
<fieldset
|
||||
className={styles['modelInputTypes']}
|
||||
aria-invalid={invalid}
|
||||
aria-describedby={invalid ? props.failureId : undefined}
|
||||
>
|
||||
<legend className={styles['modelFieldLabel']}>{t('retryCodes')}</legend>
|
||||
<div className={styles['retryCodeChoices']}>
|
||||
{choices.map((code) => {
|
||||
const labelKey = CODE_CHOICES.get(code)
|
||||
return (
|
||||
<Checkbox
|
||||
key={code}
|
||||
// A stored code the list does not name shows verbatim.
|
||||
label={labelKey === undefined ? code : t(labelKey)}
|
||||
checked={selected.includes(code)}
|
||||
disabled={disabled || (selected.length === 1 && selected.includes(code))}
|
||||
onChange={(checked) => {
|
||||
const next = choices.filter(value => value === code ? checked : selected.includes(value))
|
||||
// Selecting exactly the inherited codes keeps the field inherited.
|
||||
const inherits = next.length === inherited.length && next.every(value => inherited.includes(value))
|
||||
props.onChange(withField(current, CODES, inherits ? undefined : next))
|
||||
}}
|
||||
/>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</fieldset>
|
||||
)
|
||||
}
|
||||
const labelId = `${props.failureId}-label`
|
||||
const modeLabel = (value: 'normal' | 'always'): string => t(value === 'normal' ? 'retryModeNormal' : 'retryModeAlways')
|
||||
return (
|
||||
@@ -256,7 +306,7 @@ export function RetryPolicyEditor(props: RetryPolicyEditorProps): ReactNode {
|
||||
{mode === 'normal'
|
||||
? <>
|
||||
{field(MAX_RETRIES, 'retryMaxRetries', `${styles['modelField']} ${styles['retryCount']}`)}
|
||||
{field(CODES, 'retryCodes')}
|
||||
{codesField()}
|
||||
</>
|
||||
: null}
|
||||
<details className={styles['retryFold']} open={backoffOpen}>
|
||||
|
||||
@@ -63,6 +63,14 @@ export const en = {
|
||||
retryAlwaysHint: 'Failed requests retry until they succeed or the turn is stopped.',
|
||||
retryMaxRetries: 'Max retries',
|
||||
retryCodes: 'Error codes',
|
||||
retryCodeEmptyResponse: 'Empty response',
|
||||
retryCodeRateLimit: 'Rate limited',
|
||||
retryCodeServer: 'Server error',
|
||||
retryCodeTimeout: 'Timeout',
|
||||
retryCodeTransport: 'Network error',
|
||||
retryCodeStreamClosed: 'Stream closed early',
|
||||
retryCodeMalformedResponse: 'Malformed response',
|
||||
retryCodeQuota: 'Quota exceeded',
|
||||
retryInitialDelay: 'Initial delay (ms)',
|
||||
retryMaxDelay: 'Max delay (ms)',
|
||||
retryJitter: 'Jitter ratio',
|
||||
@@ -224,6 +232,14 @@ export const zh: { [Key in keyof typeof en]: string } = {
|
||||
retryAlwaysHint: '失败的请求会持续重试,直到成功或本轮被停止。',
|
||||
retryMaxRetries: '最大重试次数',
|
||||
retryCodes: '错误码',
|
||||
retryCodeEmptyResponse: '空响应',
|
||||
retryCodeRateLimit: '请求限流',
|
||||
retryCodeServer: '服务器错误',
|
||||
retryCodeTimeout: '超时',
|
||||
retryCodeTransport: '网络错误',
|
||||
retryCodeStreamClosed: '流提前结束',
|
||||
retryCodeMalformedResponse: '响应格式错误',
|
||||
retryCodeQuota: '配额已用尽',
|
||||
retryInitialDelay: '初始延迟 (ms)',
|
||||
retryMaxDelay: '最大延迟 (ms)',
|
||||
retryJitter: '抖动比例',
|
||||
@@ -382,6 +398,14 @@ export const ja = {
|
||||
'retryAlwaysHint': '失敗したリクエストは、成功するかターンが停止されるまで再試行されます。',
|
||||
'retryMaxRetries': '最大再試行回数',
|
||||
'retryCodes': 'エラーコード',
|
||||
'retryCodeEmptyResponse': '空のレスポンス',
|
||||
'retryCodeRateLimit': 'レート制限',
|
||||
'retryCodeServer': 'サーバーエラー',
|
||||
'retryCodeTimeout': 'タイムアウト',
|
||||
'retryCodeTransport': 'ネットワークエラー',
|
||||
'retryCodeStreamClosed': 'ストリームの途中終了',
|
||||
'retryCodeMalformedResponse': '不正なレスポンス',
|
||||
'retryCodeQuota': 'クォータ超過',
|
||||
'retryInitialDelay': '初期遅延 (ms)',
|
||||
'retryMaxDelay': '最大遅延 (ms)',
|
||||
'retryJitter': 'ジッター比率',
|
||||
@@ -540,6 +564,14 @@ export const es = {
|
||||
retryAlwaysHint: 'Las solicitudes fallidas se reintentan hasta que tienen éxito o se detiene el turno.',
|
||||
retryMaxRetries: 'Reintentos máximos',
|
||||
retryCodes: 'Códigos de error',
|
||||
retryCodeEmptyResponse: 'Respuesta vacía',
|
||||
retryCodeRateLimit: 'Límite de frecuencia',
|
||||
retryCodeServer: 'Error del servidor',
|
||||
retryCodeTimeout: 'Tiempo agotado',
|
||||
retryCodeTransport: 'Error de red',
|
||||
retryCodeStreamClosed: 'Flujo cerrado antes de tiempo',
|
||||
retryCodeMalformedResponse: 'Respuesta mal formada',
|
||||
retryCodeQuota: 'Cuota agotada',
|
||||
retryInitialDelay: 'Retraso inicial (ms)',
|
||||
retryMaxDelay: 'Retraso máximo (ms)',
|
||||
retryJitter: 'Proporción de jitter',
|
||||
@@ -698,6 +730,14 @@ export const fr = {
|
||||
retryAlwaysHint: "Les requêtes en échec sont réessayées jusqu'à ce qu'elles réussissent ou que le tour soit arrêté.",
|
||||
retryMaxRetries: 'Tentatives max.',
|
||||
retryCodes: "Codes d'erreur",
|
||||
retryCodeEmptyResponse: 'Réponse vide',
|
||||
retryCodeRateLimit: 'Limite de débit',
|
||||
retryCodeServer: 'Erreur serveur',
|
||||
retryCodeTimeout: 'Délai dépassé',
|
||||
retryCodeTransport: 'Erreur réseau',
|
||||
retryCodeStreamClosed: 'Flux interrompu',
|
||||
retryCodeMalformedResponse: 'Réponse mal formée',
|
||||
retryCodeQuota: 'Quota dépassé',
|
||||
retryInitialDelay: 'Délai initial (ms)',
|
||||
retryMaxDelay: 'Délai maximum (ms)',
|
||||
retryJitter: 'Ratio de gigue',
|
||||
@@ -856,6 +896,14 @@ export const de = {
|
||||
retryAlwaysHint: 'Fehlgeschlagene Anfragen werden wiederholt, bis sie erfolgreich sind oder der Durchlauf gestoppt wird.',
|
||||
retryMaxRetries: 'Max. Wiederholungen',
|
||||
retryCodes: 'Fehlercodes',
|
||||
retryCodeEmptyResponse: 'Leere Antwort',
|
||||
retryCodeRateLimit: 'Ratenbegrenzung',
|
||||
retryCodeServer: 'Serverfehler',
|
||||
retryCodeTimeout: 'Zeitüberschreitung',
|
||||
retryCodeTransport: 'Netzwerkfehler',
|
||||
retryCodeStreamClosed: 'Stream vorzeitig beendet',
|
||||
retryCodeMalformedResponse: 'Fehlerhafte Antwort',
|
||||
retryCodeQuota: 'Kontingent erschöpft',
|
||||
retryInitialDelay: 'Anfangsverzögerung (ms)',
|
||||
retryMaxDelay: 'Max. Verzögerung (ms)',
|
||||
retryJitter: 'Jitter-Anteil',
|
||||
@@ -1014,6 +1062,14 @@ export const ru = {
|
||||
retryAlwaysHint: 'Неудачные запросы повторяются до успеха или до остановки хода.',
|
||||
retryMaxRetries: 'Макс. число повторов',
|
||||
retryCodes: 'Коды ошибок',
|
||||
retryCodeEmptyResponse: 'Пустой ответ',
|
||||
retryCodeRateLimit: 'Лимит запросов',
|
||||
retryCodeServer: 'Ошибка сервера',
|
||||
retryCodeTimeout: 'Тайм-аут',
|
||||
retryCodeTransport: 'Ошибка сети',
|
||||
retryCodeStreamClosed: 'Поток прерван',
|
||||
retryCodeMalformedResponse: 'Некорректный ответ',
|
||||
retryCodeQuota: 'Квота исчерпана',
|
||||
retryInitialDelay: 'Начальная задержка (ms)',
|
||||
retryMaxDelay: 'Макс. задержка (ms)',
|
||||
retryJitter: 'Коэффициент джиттера',
|
||||
@@ -1172,6 +1228,14 @@ export const pt = {
|
||||
retryAlwaysHint: 'As solicitações com falha são repetidas até terem sucesso ou até o turno ser interrompido.',
|
||||
retryMaxRetries: 'Máx. de novas tentativas',
|
||||
retryCodes: 'Códigos de erro',
|
||||
retryCodeEmptyResponse: 'Resposta vazia',
|
||||
retryCodeRateLimit: 'Limite de taxa',
|
||||
retryCodeServer: 'Erro do servidor',
|
||||
retryCodeTimeout: 'Tempo esgotado',
|
||||
retryCodeTransport: 'Erro de rede',
|
||||
retryCodeStreamClosed: 'Fluxo encerrado cedo',
|
||||
retryCodeMalformedResponse: 'Resposta malformada',
|
||||
retryCodeQuota: 'Cota esgotada',
|
||||
retryInitialDelay: 'Atraso inicial (ms)',
|
||||
retryMaxDelay: 'Atraso máximo (ms)',
|
||||
retryJitter: 'Proporção de jitter',
|
||||
|
||||
@@ -71,6 +71,15 @@ function setup(namespace: SettingsNamespaceView, settingsPath: string[] = []) {
|
||||
|
||||
const mode = () => screen.getByRole<HTMLSelectElement>('combobox', { name: en.retryPolicy })
|
||||
const input = (label: string) => screen.getByLabelText<HTMLInputElement>(label)
|
||||
const CODE_LABELS: Record<string, string> = {
|
||||
EMPTY_RESPONSE: en.retryCodeEmptyResponse,
|
||||
RATE_LIMIT: en.retryCodeRateLimit,
|
||||
SERVER: en.retryCodeServer,
|
||||
TIMEOUT: en.retryCodeTimeout,
|
||||
TRANSPORT: en.retryCodeTransport,
|
||||
STREAM_CLOSED: en.retryCodeStreamClosed,
|
||||
}
|
||||
const code_ = (code: string) => screen.getByRole<HTMLInputElement>('checkbox', { name: CODE_LABELS[code] ?? code })
|
||||
const apply = () => screen.getByText<HTMLButtonElement>(en.apply)
|
||||
|
||||
describe('retry policy fields', () => {
|
||||
@@ -82,13 +91,14 @@ describe('retry policy fields', () => {
|
||||
|
||||
fireEvent.change(mode(), { target: { value: 'normal' } })
|
||||
expect(input(en.retryMaxRetries).placeholder).toBe('5')
|
||||
expect(input(en.retryCodes).placeholder).toBe('EMPTY_RESPONSE, RATE_LIMIT, SERVER, TIMEOUT, TRANSPORT')
|
||||
expect(['EMPTY_RESPONSE', 'RATE_LIMIT', 'SERVER', 'TIMEOUT', 'TRANSPORT'].every(code => code_(code).checked)).toBe(true)
|
||||
expect(code_('STREAM_CLOSED').checked).toBe(false)
|
||||
expect(input(en.retryInitialDelay).placeholder).toBe('500')
|
||||
expect(input(en.retryMaxDelay).placeholder).toBe('10000')
|
||||
expect(input(en.retryJitter).placeholder).toBe('0.1')
|
||||
|
||||
fireEvent.change(input(en.retryMaxRetries), { target: { value: '3' } })
|
||||
fireEvent.change(input(en.retryCodes), { target: { value: ' RATE_LIMIT, ,SERVER ' } })
|
||||
for (const code of ['EMPTY_RESPONSE', 'TIMEOUT', 'TRANSPORT']) fireEvent.click(code_(code))
|
||||
fireEvent.change(input(en.retryJitter), { target: { value: '0.' } })
|
||||
expect(input(en.retryJitter).value).toBe('0.')
|
||||
fireEvent.change(input(en.retryJitter), { target: { value: '0.25' } })
|
||||
@@ -108,7 +118,6 @@ describe('retry policy fields', () => {
|
||||
[en.retryMaxRetries, '-1', en.retryMaxRetriesInvalid],
|
||||
[en.retryMaxRetries, '1.5', en.retryMaxRetriesInvalid],
|
||||
[en.retryMaxRetries, 'many', en.retryMaxRetriesInvalid],
|
||||
[en.retryCodes, 'SERVER, SERVER', en.retryCodesDuplicate],
|
||||
[en.retryInitialDelay, '0', delayInvalid],
|
||||
[en.retryInitialDelay, '0x10', delayInvalid],
|
||||
[en.retryMaxDelay, '3000000000', delayInvalid],
|
||||
@@ -174,15 +183,38 @@ describe('retry policy fields', () => {
|
||||
})
|
||||
|
||||
it.each([
|
||||
['an empty code list', []],
|
||||
['a blank code', ['']],
|
||||
['a numeric code', [500]],
|
||||
])('refuses a stored policy with %s', (_name, codes) => {
|
||||
['an empty code list', [], en.retryCodesInvalid],
|
||||
['a blank code', [''], en.retryCodesInvalid],
|
||||
['a numeric code', [500], en.retryCodesInvalid],
|
||||
['a repeated code', ['SERVER', 'SERVER'], en.retryCodesDuplicate],
|
||||
])('refuses a stored policy with %s', (_name, codes, message) => {
|
||||
setup(deepSeekNamespace({ user: { retryPolicy: { mode: 'normal', retryableCodes: codes } } }))
|
||||
expect(screen.getByText(en.retryCodesInvalid)).toBeTruthy()
|
||||
expect(screen.getByText(message)).toBeTruthy()
|
||||
expect(screen.getByRole('group', { name: en.retryCodes }).getAttribute('aria-invalid')).toBe('true')
|
||||
expect(apply().disabled).toBe(true)
|
||||
})
|
||||
|
||||
it('picks codes from a list, keeps stored custom codes, and inherits an unchanged selection', async () => {
|
||||
const { writeSettings } = setup(deepSeekNamespace({
|
||||
base: { retryPolicy: { mode: 'normal', retryableCodes: ['SERVER', 'CUSTOM'] } },
|
||||
user: { retryPolicy: { mode: 'normal' } },
|
||||
}))
|
||||
expect(code_('CUSTOM').checked).toBe(true)
|
||||
expect(code_('RATE_LIMIT').checked).toBe(false)
|
||||
fireEvent.click(code_('CUSTOM'))
|
||||
expect(code_('SERVER').disabled).toBe(true)
|
||||
fireEvent.click(code_('STREAM_CLOSED'))
|
||||
fireEvent.click(code_('STREAM_CLOSED'))
|
||||
fireEvent.click(code_('CUSTOM'))
|
||||
expect(apply().disabled).toBe(false)
|
||||
fireEvent.click(code_('RATE_LIMIT'))
|
||||
fireEvent.click(apply())
|
||||
await waitFor(() => { expect(writeSettings).toHaveBeenCalled() })
|
||||
expect(writeSettings.mock.calls[0]?.[1]).toEqual([
|
||||
{ op: 'set', path: ['retryPolicy', 'retryableCodes'], value: ['RATE_LIMIT', 'SERVER', 'CUSTOM'] },
|
||||
])
|
||||
})
|
||||
|
||||
it('refuses a stored policy that is not an object', () => {
|
||||
setup(deepSeekNamespace({ user: { retryPolicy: 'sometimes' } }))
|
||||
expect(mode().value).toBe('')
|
||||
@@ -254,6 +286,8 @@ describe('retry policy fields', () => {
|
||||
setup({ ...namespace, schema: json(Schema.object({ retryPolicy: always })) })
|
||||
fireEvent.change(mode(), { target: { value: 'always' } })
|
||||
expect(input(en.retryMaxDelay).placeholder).toBe('')
|
||||
fireEvent.change(mode(), { target: { value: 'normal' } })
|
||||
expect(code_('SERVER').checked).toBe(false)
|
||||
})
|
||||
|
||||
it('renders no retry fields when the namespace schema has no retry policy', () => {
|
||||
|
||||
Reference in new issue
Block a user