diff --git a/docs-site/src/content/docs/es/guides/combos.md b/docs-site/src/content/docs/es/guides/combos.md index 1f2fec02ffd..93eaa42daf3 100644 --- a/docs-site/src/content/docs/es/guides/combos.md +++ b/docs-site/src/content/docs/es/guides/combos.md @@ -618,6 +618,8 @@ Consulte [Superficie del subagente](/es/guides/sub-agent-surface/) para ver los ### Panel +**Modelos → Combos** abre primero una vista general con una fila por combo: canales en orden, cuota restante por proveedor, ventana de contexto, menú de estrategia e interruptor. **Avanzado** abre el espacio de trabajo completo descrito a continuación. + Abra el panel de control local y elija **Modelos → Combos**. El espacio de trabajo crea, edita, renombra y elimina combos. Sus selectores de modelos incluyen modelos ocultos: la visibilidad del catálogo solo controla las listas de modelos externos, no la selección Combo interna, y seleccionar un modelo oculto no lo hace visible externamente. El selector de destino aún excluye los proveedores deshabilitados, los combos anidados y el proveedor JEV solo para credenciales. **Crear JEV Auto** abre el mismo editor Combo con una plantilla de destino de decisión editable; en lugar de crear un duplicado se informa de un id o alias `jev-auto` existente. Un JEV Combo también muestra **Servicio de decisión** (TypeSafe JEV o un proveedor configurado `jev-decision`) y **Tiempo de espera de decisión (ms)**, y la vista general de Combos enumera cada servicio de decisión, punto final y tiempo de espera de JEV Combo. Cada objetivo también muestra una insignia de cuota en vivo: **Disponible**, **Fuera de cuota** o **Cuota desconocida**. El editor bloquea Guardar y Crear para la cuota solo cuando cada destino utilizable tiene un límite de inferencia agotado confirmado por el servidor actual para su credencial configurada. La cuenta, el modelo, la búsqueda y la cuota MCP de solo visualización, o la evidencia de enrutamiento faltante o caducada, no causan este bloque. El bloqueo expira en el límite de reinicio o frescura aplicable y se vuelve a verificar cuando la página se vuelve activa o visible; Actualizar recarga tanto los datos combinados como la cuota. El editor del panel de control aún no expone `cooldownMs` o `waitForCooldownMs`; use el archivo de configuración o la administración API hasta que la interfaz de usuario de seguimiento termine. diff --git a/docs-site/src/content/docs/fr/guides/combos.md b/docs-site/src/content/docs/fr/guides/combos.md index 43c8488cf42..8dcf41f3a4d 100644 --- a/docs-site/src/content/docs/fr/guides/combos.md +++ b/docs-site/src/content/docs/fr/guides/combos.md @@ -285,6 +285,8 @@ flux de travail des tâches. ### Tableau de bord +**Modèles → Combos** ouvre d’abord une vue d’ensemble avec une ligne par combo : canaux dans l’ordre, quota restant par fournisseur, fenêtre de contexte, menu de stratégie et interrupteur. **Avancé** ouvre l’espace de travail complet décrit ci-dessous. + Ouvrez le tableau de bord local et choisissez **Modèles → Combos**. L'espace de travail crée, modifie, renomme et supprime les combos. Les sélecteurs de modèles incluent les modèles masqués : la visibilité ne concerne que les listes externes, pas la sélection interne des combos. Sélectionner un modèle masqué ne le rend pas visible. Le sélecteur de cible exclut toujours les fournisseurs désactivés, les combos imbriqués et les fournisseurs JEV réservés au service de décision. diff --git a/docs-site/src/content/docs/guides/combos.md b/docs-site/src/content/docs/guides/combos.md index 0819609df69..fbe53c32db7 100644 --- a/docs-site/src/content/docs/guides/combos.md +++ b/docs-site/src/content/docs/guides/combos.md @@ -982,8 +982,36 @@ task workflow. ### Dashboard -Open the local dashboard and choose **Models → Combos**. The workspace creates, edits, renames, and removes -combos. Its model selectors include hidden models: catalog visibility only controls external model +Open the local dashboard and choose **Models → Combos**. It opens on an overview with one row per +combo: its channels in routing order (last-resort members marked), how much quota each subscription +provider has left (API-key providers read as pay per use), the context window, a strategy menu, and an +on/off switch. Picking a strategy saves it at once, except JEV, which opens the full editor so the +decision service is chosen explicitly. Switching a combo off keeps its settings and only stops listing it +to clients. Click a row to reorder, add, remove, or mark channels fallback only (`lastResort`). +**More settings** opens under the channels: the capability policy, a switch that makes fallback +channels wait until nothing else works (`cooldownWaitPolicy: "before-last-resort"`), and each +member's context window, input types and effort levels next to the combo's combined values. +Each value is tagged with where it comes from: manual, probed, the provider's report, inferred from a +same-name model, or unknown. A missing value with a same-name estimate reads like "inferred 1M (based +on anthropic built-in table)"; **Adopt** saves it as a manual setting. Estimates never route: the +combined row counts them only when labelled "includes inferred". **Edit** on a member changes that provider's per-model settings (the same +`PUT /api/model-settings` write as the Models page), so every combo using that model changes with +it; context accepts `200000`, `200K` or `1M`. **Use the provider's values** clears what was set by +hand. **Test it** calls `POST /api/providers/probe-capabilities` to check image input and effort levels +on that relay and saves conclusive results; for a pay-per-use provider it first asks, naming how many +small requests it will send. A failed plain request changes nothing. Context is inferred from the +model name, never probed. Click the context tag on a row to open it directly. + +**Suggested combos** sits above the rows when two or more of your providers serve a model under the +same name (`claude-opus-5.5` and `claude-opus-5-5`, or `gpt-6.1-sol-high` and `gpt-6.1-sol`, count as +one; snapshot dates do not). **Generate** opens a failover draft with subscriptions from the model's +maker first, then other subscriptions, Vertex credit, and pay-per-use keys and relays last; rename, +reorder, or drop members, then **Save combo**. When an existing combo for that model is missing a +provider that serves it, the card offers **Add to combo** instead. **Dismiss** hides a suggestion in this +browser only; nothing is written to the config. + +**Advanced** opens the full workspace (`#models/combos/advanced`), which creates, edits, renames, and +removes combos. Its model selectors include hidden models: catalog visibility only controls external model lists, not internal Combo selection, and selecting a hidden model does not make it visible externally. The target picker still excludes disabled providers, nested combos, and the credential-only JEV provider. **Create JEV Auto** opens the same Combo editor with an editable decision target template; an existing `jev-auto` id or alias is reported instead of creating a duplicate. A JEV Combo also shows diff --git a/docs-site/src/content/docs/ja/guides/combos.md b/docs-site/src/content/docs/ja/guides/combos.md index b86d67b61b4..f510d833e1c 100644 --- a/docs-site/src/content/docs/ja/guides/combos.md +++ b/docs-site/src/content/docs/ja/guides/combos.md @@ -192,6 +192,8 @@ v1/base/v2 モードと完全な暗号化タスクのワークフローについ ### ダッシュボード +**モデル → コンボ** はまず概要を開きます。コンボごとに 1 行で、チャネルの順序、プロバイダーごとの残りクォータ、コンテキストウィンドウ、戦略メニュー、オン/オフを表示します。**詳細** で以下の完全なワークスペースを開きます。 + ローカル ダッシュボードを開き、**Models → コンボ**を選択します。ワークスペースではコンボの作成、編集、名前変更、削除ができます。モデル選択には非表示モデルも含まれます。表示設定は外部のモデル一覧にのみ適用され、コンボ内部の選択には影響しません。非表示モデルを選択しても外部には表示されません。ターゲット選択では、無効なプロバイダー、ネストされたコンボ、決定サービス専用の JEV プロバイダーは引き続き除外されます。 各ターゲットには **利用可能**、**クォータを使い切りました**、**クォータ不明** のライブバッジも表示されます。 diff --git a/docs-site/src/content/docs/ko/guides/combos.md b/docs-site/src/content/docs/ko/guides/combos.md index 53589443fda..67c8910ec37 100644 --- a/docs-site/src/content/docs/ko/guides/combos.md +++ b/docs-site/src/content/docs/ko/guides/combos.md @@ -202,6 +202,8 @@ v1/base/v2 모드와 암호화된 작업의 전체 흐름은 [Sub-agent Surface] ### 대시보드 +**모델 → 콤보**는 먼저 개요를 엽니다. 콤보마다 한 행으로 채널 순서, 공급자별 남은 할당량, 컨텍스트 창, 전략 메뉴, 켜기/끄기를 보여 줍니다. **고급**은 아래에 설명한 전체 작업 공간을 엽니다. + 로컬 대시보드를 열고 **Models → Combos**를 선택합니다. 워크스페이스에서 콤보를 만들고, 편집하고, 이름을 바꾸고, 제거할 수 있습니다. 모델 선택기에는 숨겨진 모델도 포함됩니다. 표시 설정은 외부 모델 목록에만 적용되며 콤보 내부 선택에는 영향을 주지 않습니다. 숨겨진 모델을 선택해도 외부에 표시되지 않습니다. 대상 선택기에서는 비활성 공급자, 중첩 콤보, 결정 서비스 전용 JEV 공급자를 계속 제외합니다. 각 대상에는 **사용 가능**, **할당량 소진**, **할당량 알 수 없음** 실시간 배지도 표시됩니다. 편집기는 사용 가능한 모든 대상에 대해 설정된 인증 정보의 추론 한도가 소진되었다는 서버 확인이 현재 유효할 때만 할당량을 이유로 저장과 만들기를 차단합니다. 표시 전용 계정·모델·검색·MCP 할당량이나 누락되거나 만료된 라우팅 근거 정보는 이 차단을 일으키지 않습니다. 차단은 해당 한도의 초기화 시점이나 데이터 유효기간이 끝나면 해제되며 페이지가 활성화되거나 표시될 때 다시 확인됩니다. 새로 고침은 콤보 데이터와 할당량을 모두 다시 불러옵니다. 대시보드 편집기에서는 아직 `cooldownMs`나 `waitForCooldownMs`를 설정할 수 없습니다. 후속 UI 작업이 완료될 때까지 구성 파일이나 관리 API를 사용하세요. diff --git a/docs-site/src/content/docs/ru/guides/combos.md b/docs-site/src/content/docs/ru/guides/combos.md index a76f46e2bbc..7f2fceaff92 100644 --- a/docs-site/src/content/docs/ru/guides/combos.md +++ b/docs-site/src/content/docs/ru/guides/combos.md @@ -240,6 +240,8 @@ Failover намеренно ограничен. Он помогает при п ### Дашборд +**Модели → Комбо** сначала открывает обзор: по строке на комбо с порядком каналов, остатком квоты по провайдерам, окном контекста, меню стратегии и переключателем. **Расширенно** открывает полное рабочее пространство, описанное ниже. + Откройте локальный дашборд и выберите **Models → Combos**. Рабочая область умеет создавать, редактировать, переименовывать и удалять combo. Селекторы моделей включают скрытые модели: видимость влияет только на внешние списки, а не на внутренний выбор в combo. Выбор скрытой модели не делает её видимой снаружи. Селектор целей по-прежнему исключает отключённых провайдеров, вложенные combo и провайдеров JEV, предназначенных только для сервиса принятия решений. diff --git a/docs-site/src/content/docs/tr/guides/combos.md b/docs-site/src/content/docs/tr/guides/combos.md index 8890281219b..1fdde21e470 100644 --- a/docs-site/src/content/docs/tr/guides/combos.md +++ b/docs-site/src/content/docs/tr/guides/combos.md @@ -311,6 +311,8 @@ Arayüzü](/tr/guides/sub-agent-surface/) sayfasına bakın. ### Kontrol Paneli +**Modeller → Kombolar** önce her kombo için bir satır içeren bir genel bakış açar: kanal sırası, sağlayıcı başına kalan kota, bağlam penceresi, strateji menüsü ve açma/kapama anahtarı. **Gelişmiş**, aşağıda anlatılan tam çalışma alanını açar. + Yerel kontrol panelini açın ve **Modeller → Kombolar** seçeneğini belirleyin. Çalışma alanı komboları oluşturur, düzenler, yeniden adlandırır ve kaldırır; model seçicileri gizli modelleri de içerir. Görünürlük yalnızca dış model listelerini etkiler, diff --git a/docs-site/src/content/docs/zh-cn/guides/combos.md b/docs-site/src/content/docs/zh-cn/guides/combos.md index 4b2316f031f..0a9975f9206 100644 --- a/docs-site/src/content/docs/zh-cn/guides/combos.md +++ b/docs-site/src/content/docs/zh-cn/guides/combos.md @@ -222,6 +222,8 @@ combo 失败分为 **跳转** 失败和 **终止** 失败。 ### Dashboard +**模型 → 组合** 默认先打开总览:每个组合一行,显示通道顺序、各供应商剩余额度、上下文窗口、策略下拉和开关。点 **高级** 打开下面介绍的完整工作区。总览上方的 **推荐组合** 会列出两家以上提供方都提供的同名模型:**生成** 打开一个故障转移草稿(原厂订阅在前,其次其他订阅、Vertex 赠金,按量 key 和中转站最后),确认后保存;已有组合缺某一家时显示 **加进组合**;**忽略** 只记在本浏览器里,不写配置。 + 打开本地 dashboard 并选择 **Models → Combos**。该工作区可以创建、编辑、重命名和删除 combo。模型选择器使用包含隐藏模型的完整目录:显示/隐藏设置只影响对外模型列表,不影响 Combo 内部选择,选中隐藏模型也不会将其对外显示。目标选择器仍排除已禁用的提供方、嵌套 combo 和仅用于决策服务的 JEV 提供方。 每个目标还会显示实时额度徽章:**可用**、**额度已用尽**或**额度未知**。只有当每个可用目标均有当前有效的服务器确认,表明其所配置凭据的推理限额已耗尽时,编辑器才会因额度而禁止保存和创建。仅供显示的账户、模型、搜索和 MCP 额度,以及缺失或已过期的路由依据,都不会触发此限制。此限制会在适用的重置时间或数据有效期结束时解除,并在页面变为活动或可见状态时重新检查;刷新会同时重新加载 Combo 数据和额度。dashboard 编辑器目前还不能设置 `cooldownMs` 或 `waitForCooldownMs`;在后续 UI 完成前,请使用配置文件或管理 API。 diff --git a/docs-site/src/content/docs/zh-tw/guides/combos.md b/docs-site/src/content/docs/zh-tw/guides/combos.md index 8e38a59bf00..19673f39d1e 100644 --- a/docs-site/src/content/docs/zh-tw/guides/combos.md +++ b/docs-site/src/content/docs/zh-tw/guides/combos.md @@ -226,6 +226,8 @@ Codex v2 子代理有一個重要限制([issue #92](https://github.com/lidge-j ### 儀表板 +**模型 → 組合** 預設先開啟總覽:每個組合一列,顯示通道順序、各供應商剩餘額度、上下文視窗、策略選單和開關。點 **進階** 開啟下面介紹的完整工作區。 + 開啟本機儀表板並選擇 **Combos**。該工作區可建立、編輯、重新命名與移除 combo。模型選擇器包含隱藏模型;顯示/隱藏設定僅影響對外模型清單,不影響 Combo 內部選擇,選取隱藏模型也不會將其對外顯示。目標選擇器仍排除已停用的供應商、巢狀 combo 與僅提供決策服務的 JEV 供應商。 每個目標也會顯示即時額度徽章:**可用**、**額度已用盡**或**額度未知**。只有當每個可用目標均有目前有效的伺服器確認,顯示其所設定憑證的推論限額已耗盡時,編輯器才會因配額而停用儲存與建立。僅供顯示的帳戶、模型、搜尋與 MCP 配額,以及缺失或已過期的路由依據,都不會觸發此限制。此限制會在適用的重設時間或資料有效期限結束時解除,並在頁面變為作用中或可見狀態時重新檢查;重新整理會同時重新載入 Combo 資料與配額。 diff --git a/gui/classic/src/pages/Combos.tsx b/gui/classic/src/pages/Combos.tsx new file mode 100644 index 00000000000..616de085480 --- /dev/null +++ b/gui/classic/src/pages/Combos.tsx @@ -0,0 +1,466 @@ +import { useCallback, useEffect, useMemo, useState } from "react"; +import ComboWorkspace from "../components/ComboWorkspace"; +import { comboVisionSidecarTargets } from "../combo-capabilities"; +import { + type ComboItem, + comboModelId, + parseComboList, + providerQuotaStatesFromReports, + nextProviderQuotaStateExpiration, + toPutBody, +} from "../combo-workspace-data"; +import { hostDocumentHidden, onHostVisibilityChange } from "../host-visibility"; +import { hideRedundantChatGptForwardProviders } from "../provider-workspace/catalog"; +import { readSessionListCacheEntry, writeSessionListCacheEntry } from "../session-list-cache"; +import { Notice } from "../ui"; +import { useT } from "../i18n/shared"; +import { useDataSurface } from "../data-surface"; +import { DataSurfaceSkeleton } from "../components/data-surface"; +import { replaceHash } from "../hash-routing"; +import { jevAutoCreateDecisionProvider } from "../app-routing"; +import type { ComboAddIntent } from "../components/combo-workspace-types"; + +type ProviderOption = { + name: string; + disabled?: boolean; + hiddenFromPicker?: boolean; + authMode?: string; + adapter?: string; + baseUrl?: string; + defaultModel?: string; + models?: string[]; +}; +type ModelOption = { + provider: string; + id: string; + namespaced?: string; + reasoningEfforts?: string[]; + inputModalities?: string[]; + inputModalitiesDeclared?: string[]; + visionSidecarConsumer?: boolean; +}; +type ProviderDto = { + adapter: string; + baseUrl: string; + disabled?: boolean; + defaultModel?: string; + models?: string[]; + authMode?: string; +}; +type ConfigDto = { providers?: Record }; +type CachedCombosPage = { + combos: ComboItem[]; + providers: ProviderOption[]; + models: ModelOption[]; + capabilityModels?: ModelOption[]; + cataloguedComboIds: string[]; +}; +type ProviderQuotasDto = { reports?: unknown }; + +function responseError(data: unknown): string | undefined { + if (!data || typeof data !== "object" || Array.isArray(data)) return undefined; + const error = (data as { error?: unknown }).error; + return typeof error === "string" && error.trim() ? error : undefined; +} + +function responseSucceeded(data: unknown): boolean { + return !!data && typeof data === "object" && !Array.isArray(data) + && (data as { success?: unknown }).success === true; +} + +function seedCombos(cacheKey: string): CachedCombosPage | null { + return readSessionListCacheEntry(cacheKey)?.data ?? null; +} + +function seedCombosCachedAt(cacheKey: string): number | null { + return readSessionListCacheEntry(cacheKey)?.cachedAt ?? null; +} + +export default function Combos({ + apiBase, + active = true, + onCountChange, +}: { + apiBase: string; + /** + * False while this panel is mounted but hidden behind another Models tab. It gates + * the NETWORK only — the rendered tree stays put so unsaved editor drafts survive a + * tab hop. Defaults true so the standalone page keeps its existing behaviour. + */ + active?: boolean; + /** Reports the combo count up to the tab strip. */ + onCountChange?: (count: number) => void; +}) { + const t = useT(); + const cacheKey = `ocx.combos.workspace.v2:${apiBase}`; + const cached = useMemo(() => seedCombos(cacheKey), [cacheKey]); + + /* + * The last coherent payload, kept so a hidden panel can keep rendering. + * + * While `active` is false the resource is disabled and reports `data: undefined` with + * no skeleton and no error. Falling back to empty arrays there swaps the whole + * ComboWorkspace for a first-run empty state and takes every unsaved draft with it — + * proven in a browser: type into a combo, switch tabs, come back, field blank. + * + * State rather than a ref: this repo avoids render-time ref reads under React + * Compiler, and a ref would not re-render when the retained payload changes. Written + * on the load success path, never during render and never from an effect. + */ + const [retainedData, setRetainedData] = useState(cached ?? null); + const [status, setStatus] = useState(""); + const [statusOk, setStatusOk] = useState(false); + const [addIntent, setAddIntent] = useState(() => ( + jevAutoCreateDecisionProvider(window.location.hash) !== undefined ? "jev-auto" : null + )); + // A self-hosted decision row's "Create JEV Auto" pre-fills that row as the decision service. + const [addDecisionProvider, setAddDecisionProvider] = useState( + () => jevAutoCreateDecisionProvider(window.location.hash) ?? null, + ); + + const closeAdd = useCallback(() => { + setAddIntent(null); + setAddDecisionProvider(null); + if (jevAutoCreateDecisionProvider(window.location.hash) !== undefined) { + replaceHash("models/combos"); + } + }, []); + + const notify = (msg: string, ok: boolean) => { + setStatus(msg); + setStatusOk(ok); + }; + + // Success banners are transient; errors stay until the next notify. + useEffect(() => { + if (!status || !statusOk) return; + const timer = window.setTimeout(() => { + setStatus(""); + setStatusOk(false); + }, 5000); + return () => window.clearTimeout(timer); + }, [status, statusOk]); + + const loadCombos = useCallback(async (signal?: AbortSignal): Promise => { + // Keep all three requests parallel: this workspace is only coherent once every input arrives. + const [combosRes, configRes, modelsRes] = await Promise.all([ + // Signals were missing entirely, so resource cleanup could not cancel these. + fetch(`${apiBase}/api/combos`, { signal }), + fetch(`${apiBase}/api/config`, { signal }), + fetch(`${apiBase}/api/models`, { signal }), + ]); + if (!combosRes.ok || !configRes.ok || !modelsRes.ok) { + throw new Error("combo workspace load failed"); + } + const combosJson = await combosRes.json(); + const configJson = await configRes.json() as ConfigDto; + // /api/models returns a bare array (not { models: [...] }). + const modelsRaw = await modelsRes.json() as unknown; + const modelRows = Array.isArray(modelsRaw) + ? modelsRaw + : Array.isArray((modelsRaw as { models?: unknown })?.models) + ? (modelsRaw as { models: unknown[] }).models + : []; + + const combos = parseComboList(combosJson); + const allProviders = configJson.providers ?? {}; + // Collapse canonical forward aliases only in the new-member picker. Validation keeps + // every configured provider id, including legacy chatgpt members already in a combo. + const visibleProviders = hideRedundantChatGptForwardProviders(allProviders); + const providers = Object.entries(allProviders).map(([name, p]) => ({ + name, + disabled: !!p.disabled, + hiddenFromPicker: p.adapter === "jev-decision" || !Object.hasOwn(visibleProviders, name), + authMode: p.authMode, + adapter: p.adapter, + baseUrl: p.baseUrl, + ...(typeof p.defaultModel === "string" ? { defaultModel: p.defaultModel } : {}), + ...(Array.isArray(p.models) ? { models: p.models.filter((model): model is string => typeof model === "string") } : {}), + })); + + const models: ModelOption[] = []; + const capabilityModels: ModelOption[] = []; + const catalogued = new Set(); + const parseModalities = (raw: unknown): string[] | undefined => + Array.isArray(raw) + ? raw.flatMap((modality) => { + const trimmed = typeof modality === "string" ? modality.trim() : ""; + return trimmed ? [trimmed] : []; + }) + : undefined; + for (const row of modelRows) { + if (!row || typeof row !== "object") continue; + const model = row as { + provider?: unknown; + id?: unknown; + namespaced?: unknown; + disabled?: unknown; + reasoningEfforts?: unknown; + inputModalities?: unknown; + inputModalitiesDeclared?: unknown; + visionSidecarConsumer?: unknown; + }; + if (typeof model.provider !== "string" || typeof model.id !== "string") continue; + const provider = model.provider.trim(); + const id = model.id.trim(); + if (!provider || !id) continue; + if (provider === "combo") { + catalogued.add(id); + continue; // combos cannot nest other combos as targets + } + const reasoningEfforts = Array.isArray(model.reasoningEfforts) + ? model.reasoningEfforts.filter((effort): effort is string => typeof effort === "string") + : undefined; + const inputModalities = parseModalities(model.inputModalities); + const inputModalitiesDeclared = parseModalities(model.inputModalitiesDeclared); + const option: ModelOption = { + provider, + id, + namespaced: typeof model.namespaced === "string" ? model.namespaced : undefined, + ...(reasoningEfforts ? { reasoningEfforts } : {}), + ...(inputModalities && inputModalities.length > 0 ? { inputModalities } : {}), + ...(inputModalitiesDeclared && inputModalitiesDeclared.length > 0 ? { inputModalitiesDeclared } : {}), + visionSidecarConsumer: model.visionSidecarConsumer === true, + }; + capabilityModels.push(option); + models.push(option); // Catalog visibility does not restrict internal Combo selection. + } + + // Add a default placeholder only when the catalog has no row, including disabled rows. + for (const [name, provider] of Object.entries(allProviders)) { + const defaultModel = typeof provider.defaultModel === "string" ? provider.defaultModel.trim() : ""; + if (!defaultModel || provider.disabled) continue; + if (!capabilityModels.some(model => model.provider === name && model.id === defaultModel)) { + models.push({ provider: name, id: defaultModel, namespaced: `${name}/${defaultModel}` }); + } + } + + const next = { combos, providers, models, capabilityModels, cataloguedComboIds: [...catalogued] } satisfies CachedCombosPage; + writeSessionListCacheEntry(cacheKey, next); + // Retain the coherent payload here — one place, on the success path, never during + // render. See the `retainedData` note below. + setRetainedData(next); + return next; + }, [apiBase, cacheKey]); + + const resource = useDataSurface( + cacheKey, + [apiBase], + loadCombos, + /* + * Gate the network, never the tree. A hidden panel must not fetch, but the rendered + * workspace has to stay mounted so an unsaved editor draft survives a tab hop. + * Disabling reports `data: undefined`, so `retainedData` below keeps the last good + * payload and the subtree never unmounts. + */ + { + isEmpty: () => false, + initialData: cached ?? undefined, + initialDataCachedAt: seedCombosCachedAt(cacheKey), + staleAfterMs: 60_000, + enabled: active, + }, + ); + const { state } = resource; + + /* + * Vision Sidecar enabled state for the enrollment warning. Deliberately + * separate from the workspace payload: a failure here must never block or + * fail the combo workspace, so errors are swallowed and `undefined` + * (unknown) renders no warning. + */ + const [visionEnabled, setVisionEnabled] = useState(undefined); + useEffect(() => { + if (!active) return; + let cancelled = false; + fetch(`${apiBase}/api/sidecar-settings`) + .then((res) => (res.ok ? res.json() : null)) + .then((data: unknown) => { + if (cancelled || !data || typeof data !== "object") return; + const vision = (data as { vision?: { enabled?: unknown } }).vision; + if (!vision || typeof vision !== "object") return; + setVisionEnabled(vision.enabled !== false); + }) + .catch(() => { /* unknown stays warning-free */ }); + return () => { cancelled = true; }; + }, [active, apiBase]); + + const [quotaNow, setQuotaClock] = useState(() => Date.now()); + const loadProviderQuotas = useCallback(async (signal?: AbortSignal): Promise => { + const response = await fetch(`${apiBase}/api/provider-quotas`, { signal }); + if (!response.ok) throw new Error("combo quota load failed"); + const payload = await response.json() as unknown; + if (!signal?.aborted) setQuotaClock(Date.now()); + return payload && typeof payload === "object" && !Array.isArray(payload) + ? payload as ProviderQuotasDto + : {}; + }, [apiBase]); + const quotaResource = useDataSurface( + `ocx.combos.provider-quotas.v1:${apiBase}`, + [apiBase], + loadProviderQuotas, + { + isEmpty: () => false, + pollMs: 60_000, + pauseWhenHidden: true, + enabled: active, + }, + ); + const quotaReports = active && quotaResource.lastAttemptOk ? quotaResource.data?.reports : undefined; + const providerQuotaStates = providerQuotaStatesFromReports(quotaReports, quotaNow); + const quotaExpiry = nextProviderQuotaStateExpiration(quotaReports, quotaNow); + useEffect(() => { + if (!active) return; + const recheck = () => setQuotaClock(Date.now()); + // The render may cross this boundary before effects run. Keep its deadline and wake now. + // A new snapshot may be newer than this clock, so unknown state also gets one immediate check. + const timer = window.setTimeout(recheck, + quotaExpiry === undefined ? 0 : Math.max(0, quotaExpiry - Date.now())); + const onVisible = () => { if (!hostDocumentHidden()) recheck(); }; + const unsubscribeVisibility = onHostVisibilityChange(onVisible); + return () => { + window.clearTimeout(timer); + unsubscribeVisibility(); + }; + }, [active, apiBase, quotaResource.data, quotaResource.lastAttemptOk, quotaExpiry]); + + const data = state.data ?? retainedData ?? undefined; + const combos = data?.combos ?? []; + + /* + * Report the count up to the tab strip from an effect keyed on the list length, not + * during render, so a parent re-render cannot refire it. + */ + useEffect(() => { + if (!data) return; + onCountChange?.(combos.length); + }, [combos.length, data, onCountChange]); + const providers = data?.providers ?? []; + const models = data?.models ?? []; + const capabilityModels = data?.capabilityModels ?? models; + const cataloguedComboIds = new Set(data?.cataloguedComboIds ?? []); + + const saveCombo = async (item: ComboItem, isCreate: boolean, renameFrom?: string) => { + try { + const res = await fetch(`${apiBase}/api/combos`, { + method: "PUT", + headers: { "content-type": "application/json" }, + body: JSON.stringify(toPutBody(item, { + ...(renameFrom ? { renameFrom } : {}), + // Enabling images declares text-only members for the Vision Sidecar so the + // operator never has to hand-edit provider config for a multimodal combo. + ...(item.imageInput !== "disabled" + ? { visionSidecarTargets: comboVisionSidecarTargets(item.targets, capabilityModels) } + : {}), + })), + }); + const data = res.ok + ? await res.json() as unknown + : await res.json().catch(() => null) as unknown; + const serverError = responseError(data); + if (!res.ok || serverError || !responseSucceeded(data)) { + const err = serverError || t("cws.saveFailed"); + notify(err, false); + return { ok: false as const, error: err }; + } + resource.refresh(); + notify( + renameFrom + ? t("cws.renamed", { from: comboModelId(renameFrom), to: item.model }) + : isCreate ? t("cws.created", { model: item.model }) : t("cws.saved"), + true, + ); + return { ok: true as const }; + } catch { + const err = t("cws.saveFailed"); + notify(err, false); + return { ok: false as const, error: err }; + } + }; + + const removeCombo = async (id: string) => { + try { + const res = await fetch(`${apiBase}/api/combos?id=${encodeURIComponent(id)}`, { method: "DELETE" }); + const data = res.ok + ? await res.json() as unknown + : await res.json().catch(() => null) as unknown; + const serverError = responseError(data); + if (!res.ok || serverError || !responseSucceeded(data)) { + const err = serverError || t("cws.removeFailed"); + notify(err, false); + return { ok: false as const, error: err }; + } + resource.refresh(); + notify(t("cws.removed", { id }), true); + return { ok: true as const }; + } catch { + const err = t("cws.removeFailed"); + notify(err, false); + return { ok: false as const, error: err }; + } + }; + + // The skeleton owns the live region until a session seed or live workspace is available. + if (state.showSkeleton && !data) { + return ; + } + + /* + * `!data` matters. Disabling the only subscriber schedules store eviction, so a + * reactivation whose fetch fails is classified `failed-cold` even when this component + * still holds a coherent retained payload — and replacing the workspace there would + * unmount the editor and destroy the very draft retention exists to protect. With + * retained data the workspace stays up and the failure shows in the stale banner below. + */ + if (state.kind === "failed-cold" && !data) { + const reason = state.error instanceof Error ? state.error.message : t("cws.loadFailed"); + return ( + <> + {reason} + + + ); + } + + return ( +
+ {status && ( +
+ {status} +
+ )} + {state.showError && ( +
+ {t("cws.loadFailed")} +
+ )} + {/* Revalidation is silent by design: existing combos stay visible, and the + shell announces the in-flight refresh to assistive tech only. */} +
+ + {state.refreshing ? t("common.loading") : ""} + + { resource.refresh(); quotaResource.refresh(); }} + onSave={saveCombo} + onRemove={removeCombo} + onAdd={(intent = "blank") => setAddIntent(intent)} + adding={addIntent !== null} + addIntent={addIntent ?? undefined} + addDecisionProvider={addDecisionProvider} + onCloseAdd={closeAdd} + onCreated={() => resource.refresh()} + /> +
+
+ ); +} diff --git a/gui/src/app-routing.ts b/gui/src/app-routing.ts index 1a92cf20bfe..2a2b6a115c0 100644 --- a/gui/src/app-routing.ts +++ b/gui/src/app-routing.ts @@ -1,6 +1,7 @@ /** Pure hash → page resolution used by App route state. */ import { normalizeHashPath, splitHashQuery } from "./hash-routing"; +import { COMBOS_ADVANCED_HASH } from "./pages/combos-advanced-hash"; export type Page = | "home" @@ -184,6 +185,7 @@ export function hashBelongsToPage(rawHash: string, page: Page): boolean { || (page === "models" && ( (MODELS_TAB_HASHES as readonly string[]).includes(rawHash) || rawHash === JEV_AUTO_CREATE_HASH + || rawHash === COMBOS_ADVANCED_HASH )) || (page === "dashboard" && (rawHash === DASHBOARD_UPDATE_HASH || (DASHBOARD_TAB_HASHES as readonly string[]).includes(rawHash))) diff --git a/gui/src/combo-suggestions.ts b/gui/src/combo-suggestions.ts new file mode 100644 index 00000000000..9ebc7727599 --- /dev/null +++ b/gui/src/combo-suggestions.ts @@ -0,0 +1,256 @@ +/** + * Combo suggestions for the Combos overview: models that two or more providers serve under the + * same name, offered as a ready-made failover combo, and existing combos that a provider serving + * their model is missing from. Pure: no React, no fetch, no storage. + * + * The idea of merging one model across providers by a normalized name follows Magpie's found + * groups (`internal/catalog/samemodel.go`, MIT, Copyright (c) 2026 yetone). No code is taken + * from it. Unlike Magpie, a snapshot date stays part of the name (two snapshots can differ in + * capability) and a trailing reasoning-effort suffix is dropped. + */ +import { COMBO_ID_RE, emptyDraft, newComboTarget, type ComboItem } from "./combo-workspace-data"; + +export interface SuggestionProvider { + name: string; + disabled?: boolean; + hiddenFromPicker?: boolean; + authMode?: string; + adapter?: string; + baseUrl?: string; +} + +export interface SuggestionModel { + provider: string; + id: string; +} + +/** + * Order members are suggested in: a subscription from the model's own maker, any other + * subscription, Vertex credit, then pay-per-use keys and relays. + */ +export type ChannelTier = "own-subscription" | "subscription" | "vertex" | "metered"; +const TIER_RANK: Record = { "own-subscription": 0, subscription: 1, vertex: 2, metered: 3 }; + +export interface SuggestedMember { + provider: string; + model: string; + tier: ChannelTier; + /** Lowest remaining percent across the provider's reported windows for this model. */ + remainingPercent?: number; +} + +export type ComboSuggestion = + | { + kind: "create"; + /** Dismissal key, stable across reloads. */ + key: string; + /** Normalized model name the members share. */ + model: string; + /** Free combo id for the draft. */ + comboId: string; + members: SuggestedMember[]; + /** At least one member is listed in the model catalog rather than hidden from it. */ + listed: boolean; + } + | { + kind: "extend"; + key: string; + model: string; + comboId: string; + /** Providers serving the combo's model that the combo does not route to yet. */ + members: SuggestedMember[]; + }; + +const EFFORT_SUFFIX = /-(?:minimal|low|medium|high|xhigh|max)$/; + +/** + * One model's name across providers: no `provider/` prefix, lowercase, runs of spaces, + * underscores and dashes as one dash, a version dot as a dash (`claude-opus-5.5` is + * `claude-opus-5-5`), and no trailing effort suffix (`gpt-6.1-sol-high` is `gpt-6-1-sol`). + */ +export function normalizeModelName(id: string): string { + let name = id.trim().toLowerCase(); + name = name.slice(name.lastIndexOf("/") + 1); + name = name.replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, ""); + name = name.replace(/(\d)\.(?=\d)/g, "$1-"); + return name.replace(EFFORT_SUFFIX, ""); +} + +/** The id spelled as the provider writes it, minus prefix and effort suffix: the combo id candidate. */ +function spelling(id: string): string { + const bare = id.trim().slice(id.trim().lastIndexOf("/") + 1).toLowerCase(); + return bare.replace(EFFORT_SUFFIX, ""); +} + +const MODEL_MAKERS: ReadonlyArray<[RegExp, string]> = [ + [/^claude/, "anthropic"], + [/^(?:gpt|o\d|codex|chatgpt)/, "openai"], + [/^(?:gemini|gemma)/, "google"], + [/^grok/, "xai"], + [/^deepseek/, "deepseek"], +]; + +const PROVIDER_MAKERS: ReadonlyArray<[RegExp, string]> = [ + [/(?:^|\.)anthropic\.com$/, "anthropic"], + [/(?:^|\.)(?:openai\.com|chatgpt\.com)$/, "openai"], + [/(?:^|\.)googleapis\.com$/, "google"], + [/(?:^|\.)x\.ai$/, "xai"], + [/(?:^|\.)deepseek\.com$/, "deepseek"], +]; + +function hostOf(baseUrl: string | undefined): string { + if (!baseUrl) return ""; + try { + return new URL(baseUrl).hostname.toLowerCase(); + } catch { + return ""; + } +} + +export function channelTier(provider: SuggestionProvider, model: string): ChannelTier { + const host = hostOf(provider.baseUrl); + if (host.startsWith("aiplatform.") || /vertex/i.test(provider.name)) return "vertex"; + if (provider.authMode !== "oauth" && provider.authMode !== "forward") return "metered"; + const modelMaker = MODEL_MAKERS.find(([re]) => re.test(normalizeModelName(model)))?.[1]; + const providerMaker = PROVIDER_MAKERS.find(([re]) => re.test(host))?.[1]; + return modelMaker !== undefined && modelMaker === providerMaker ? "own-subscription" : "subscription"; +} + +/** Tier first; within a tier more quota left first, unknown quota after; then catalog order. */ +export function orderMembers(members: readonly SuggestedMember[]): SuggestedMember[] { + return members + .map((member, index) => ({ member, index })) + .sort((a, b) => { + const tier = TIER_RANK[a.member.tier] - TIER_RANK[b.member.tier]; + if (tier !== 0) return tier; + const left = a.member.remainingPercent ?? -1; + const right = b.member.remainingPercent ?? -1; + return right - left || a.index - b.index; + }) + .map(({ member }) => member); +} + +/** The combo is about one model: its id names it, or every member serves it. */ +function comboModel(combo: ComboItem): string | undefined { + const byId = normalizeModelName(combo.id); + const names = new Set(combo.targets.map((target) => normalizeModelName(target.model))); + if (names.size === 1) return [...names][0]; + return names.has(byId) ? byId : undefined; +} + +/** `base`, else `base-2`, `base-3`, … that no combo id or alias already takes (case-insensitive). */ +export function freeComboId(base: string, combos: readonly ComboItem[]): string { + const taken = new Set(combos.flatMap((combo) => [combo.id, combo.alias ?? ""]).map((id) => id.toLowerCase())); + if (!taken.has(base.toLowerCase())) return base; + for (let n = 2; ; n++) { + const candidate = `${base}-${n}`; + if (!taken.has(candidate.toLowerCase())) return candidate; + } +} + +export interface SuggestionInput { + combos: readonly ComboItem[]; + /** Catalog rows, combos excluded, hidden rows included: hiding a model only hides it from pickers. */ + models: readonly SuggestionModel[]; + /** `provider/model` keys hidden from the model catalog (`disabledModels`). */ + hiddenModels?: ReadonlySet; + providers: readonly SuggestionProvider[]; + remainingPercent?: (provider: string, model: string) => number | undefined; + dismissed?: ReadonlySet; + /** Providers the operator left out of suggestions: they join no suggested combo. */ + excludedProviders?: ReadonlySet; +} + +export function suggestionKey(kind: ComboSuggestion["kind"], model: string, comboId?: string): string { + return kind === "create" ? `create:${model}` : `extend:${comboId}:${model}`; +} + +export function buildComboSuggestions(input: SuggestionInput): ComboSuggestion[] { + const providers = new Map(input.providers.map((provider) => [provider.name, provider])); + /** model name → provider → that provider's id for it (the shortest spelling wins). */ + const byModel = new Map>(); + for (const row of input.models) { + const provider = providers.get(row.provider); + if (!provider || provider.disabled || provider.hiddenFromPicker || input.excludedProviders?.has(row.provider)) continue; + const name = normalizeModelName(row.id); + if (!name) continue; + const served = byModel.get(name) ?? new Map(); + const current = served.get(row.provider); + if (current === undefined || row.id.length < current.length) served.set(row.provider, row.id); + byModel.set(name, served); + } + + const member = (provider: string, model: string): SuggestedMember => { + const remaining = input.remainingPercent?.(provider, model); + return { + provider, + model, + tier: channelTier(providers.get(provider)!, model), + ...(remaining !== undefined ? { remainingPercent: remaining } : {}), + }; + }; + + const covering = new Map(); + for (const combo of input.combos) { + const name = comboModel(combo); + if (name !== undefined && !covering.has(name)) covering.set(name, combo); + } + + const creates: Array = []; + const extends_: Array = []; + for (const [name, served] of byModel) { + if (served.size < 2) continue; + const combo = covering.get(name); + if (combo) { + const routed = new Set(combo.targets.map((target) => target.provider)); + const missing = [...served].filter(([provider]) => !routed.has(provider)); + const key = suggestionKey("extend", name, combo.id); + if (missing.length === 0 || input.dismissed?.has(key)) continue; + extends_.push({ kind: "extend", key, model: name, comboId: combo.id, members: orderMembers(missing.map(([p, m]) => member(p, m))) }); + continue; + } + const key = suggestionKey("create", name); + if (input.dismissed?.has(key)) continue; + const spellings = [...served.values()].map(spelling); + const counts = new Map(); + for (const value of spellings) counts.set(value, (counts.get(value) ?? 0) + 1); + const preferred = spellings.reduce((best, value) => (counts.get(value)! > counts.get(best)! ? value : best)); + creates.push({ + kind: "create", + key, + model: name, + comboId: freeComboId(COMBO_ID_RE.test(preferred) ? preferred : name, input.combos), + members: orderMembers([...served].map(([p, m]) => member(p, m))), + listed: [...served].some(([provider, model]) => !input.hiddenModels?.has(`${provider}/${model}`)), + }); + } + creates.sort((a, b) => Number(b.listed) - Number(a.listed) || b.members.length - a.members.length || a.model.localeCompare(b.model)); + extends_.sort((a, b) => a.comboId.localeCompare(b.comboId)); + // A model nobody lists in the catalog is usually an older version: after the hints for live combos. + return [...creates.filter((s) => s.listed), ...extends_, ...creates.filter((s) => !s.listed)]; +} + +/** The failover combo a create suggestion saves, members in the order given. */ +export function suggestionDraft(comboId: string, members: readonly SuggestedMember[]): ComboItem { + return { + ...emptyDraft(comboId), + targets: members.map((entry) => newComboTarget({ provider: entry.provider, model: entry.model })), + }; +} + +/** + * The combo with each suggested member placed before the first of its own members in a lower + * tier (a subscription goes ahead of pay-per-use keys), else last. Its own members keep their order. + */ +export function extendedCombo( + combo: ComboItem, + members: readonly SuggestedMember[], + tierOf: (provider: string, model: string) => ChannelTier, +): ComboItem { + const targets = [...combo.targets]; + for (const entry of members) { + const at = targets.findIndex((target) => TIER_RANK[tierOf(target.provider, target.model)] > TIER_RANK[entry.tier]); + targets.splice(at < 0 ? targets.length : at, 0, newComboTarget({ provider: entry.provider, model: entry.model })); + } + return { ...combo, targets }; +} diff --git a/gui/src/components/ComboWorkspace.tsx b/gui/src/components/ComboWorkspace.tsx index 32ac369178b..6c2c894bf4a 100644 --- a/gui/src/components/ComboWorkspace.tsx +++ b/gui/src/components/ComboWorkspace.tsx @@ -1,4 +1,4 @@ -import { useCallback, useMemo, useState } from "react"; +import { useCallback, useEffect, useMemo, useState } from "react"; import { type ComboItem, comboModelId, @@ -37,6 +37,8 @@ export default function ComboWorkspace({ addDecisionProvider, onCloseAdd, onCreated, + selectRequest, + onDraftComboChange, }: ComboWorkspaceProps) { const t = useT(); const providerMap = useMemo( @@ -109,6 +111,16 @@ export default function ComboWorkspace({ setPendingSelect(id); }, [activeId, detailDirty]); + const draftComboId = detailDirty ? activeId : null; + useEffect(() => { onDraftComboChange?.(draftComboId); }, [draftComboId, onDraftComboChange]); + + // Starts unseen so a request that mounts the workspace is honoured too. + const [seenSelectSeq, setSeenSelectSeq] = useState(undefined); + if (selectRequest && selectRequest.seq !== seenSelectSeq) { + setSeenSelectSeq(selectRequest.seq); + trySelect(selectRequest.id); + } + const confirmDiscard = () => { if (pendingSelect === undefined) return; setSelectedId(pendingSelect); diff --git a/gui/src/components/combo-workspace-types.ts b/gui/src/components/combo-workspace-types.ts index d2b613dd7f5..ac44852243f 100644 --- a/gui/src/components/combo-workspace-types.ts +++ b/gui/src/components/combo-workspace-types.ts @@ -21,6 +21,8 @@ export type ModelOption = { inputModalitiesDeclared?: string[]; /** Authoritative runtime verdict from /api/models: the Vision Sidecar describes this model's images. */ visionSidecarConsumer?: boolean; + /** Catalog context window in tokens, when the model row reports one. */ + contextWindow?: number; }; export type ComboAddIntent = "blank" | "jev-auto"; @@ -49,4 +51,8 @@ export interface ComboWorkspaceProps { addDecisionProvider?: string | null; onCloseAdd: () => void; onCreated: (id: string) => void; + /** Select this combo when `seq` changes (the overview's "open in Advanced"); dirty drafts still prompt. */ + selectRequest?: { id: string; seq: number }; + /** The existing combo with an unsaved draft in the detail editor, or null. */ + onDraftComboChange?: (id: string | null) => void; } diff --git a/gui/src/components/provider-workspace/ProviderModels.tsx b/gui/src/components/provider-workspace/ProviderModels.tsx index e8a10189520..df19f1ec060 100644 --- a/gui/src/components/provider-workspace/ProviderModels.tsx +++ b/gui/src/components/provider-workspace/ProviderModels.tsx @@ -11,6 +11,8 @@ import { createBoundedFetch } from "../../bounded-fetch"; import { catalogRefreshPending, parseCustomModelCreated, parseCustomModelInventory, type CustomModelRecord } from "../../provider-workspace/model-inventory"; import { encodedModelIdCollides } from "../../../../src/providers/slug-codec"; import ProviderModelChip from "./ProviderModelChip"; +import { latestPerFamilyBy } from "../../lib/model-family"; +import { useLatestPerFamilyPref } from "../../lib/latest-per-family-pref"; type Mutation = { revision: string; @@ -49,6 +51,7 @@ function ProviderModelInventory({ item, apiBase, availableModels, selectedModels const [query, setQuery] = useState(""); // Free-only narrowing for this provider's inventory (#3666), mirroring the Models page. const [freeOnly, setFreeOnly] = useState(false); + const [latestOnly, setLatestOnly] = useLatestPerFamilyPref(); const [draft, setDraft] = useState(""); const [ownershipEpoch, setOwnershipEpoch] = useState(0); const ownershipKey = JSON.stringify([apiBase, item.name, modelRevision, ownershipEpoch]); @@ -87,7 +90,8 @@ function ProviderModelInventory({ item, apiBase, availableModels, selectedModels // prices, and a stale `freeOnly` would otherwise keep filtering an inventory in which nothing // can classify as free. const freeOnlyActive = freeOnlyInForce(freeOnly, visible); - const priced = filterFreeModelRows(visible, freeOnlyActive); + const newest = latestOnly ? latestPerFamilyBy(visible, row => row.id) : visible; + const priced = filterFreeModelRows(newest, freeOnlyActive); const normalizedQuery = query.trim().toLowerCase(); const filtered = priced.filter(row => [row.id, row.namespaced].some(value => value.toLowerCase().includes(normalizedQuery))); const labels = new Map(); @@ -274,9 +278,11 @@ function ProviderModelInventory({ item, apiBase, availableModels, selectedModels } {/* Above the search box, matching the Models page group: the same filter must not sit on opposite sides of the search input on the two surfaces that offer it. */} - {pricingKnown &&
- setFreeOnly(!freeOnly)} label={t("models.freeOnly")} showLabel /> -
} +
+ {pricingKnown && setFreeOnly(!freeOnly)} label={t("models.freeOnly")} showLabel />} + setLatestOnly(!latestOnly)} label={t("models.latestPerFamily")} + title={t("models.latestPerFamilyHint")} showLabel /> +
setQuery(event.target.value)} aria-label={t("pws.modelSearchPlaceholder")} /> {modelRows !== null && visible.length === 0 ?

{t("pws.noModels")}

diff --git a/gui/src/components/route-board/ChannelEditor.tsx b/gui/src/components/route-board/ChannelEditor.tsx new file mode 100644 index 00000000000..c2520785ba9 --- /dev/null +++ b/gui/src/components/route-board/ChannelEditor.tsx @@ -0,0 +1,328 @@ +import { useEffect, useLayoutEffect, useRef, useState, type PointerEvent as ReactPointerEvent } from "react"; +import { flushSync } from "react-dom"; +import { COMBO_EFFORTS, COMBO_TARGETS_HINT_KEYS, type ComboStrategy } from "../../combo-workspace-data"; +import { useT } from "../../i18n/shared"; +import { formatProviderDisplayName } from "../../provider-icons"; +import { + capabilityPatch, + channelKey, + combineLists, + comboContextWindow, + withInferredGaps, + memberFacts, + moveChannel, + type CapabilityPolicy, + type ChannelQuota, + type ComboCapabilitySettings, + type ComboSettingsPatch, + type MemberModel, + type RouteChannel, + type UnservablePolicy, +} from "../../route-board-model"; +import { Select, Switch } from "../../ui"; +import { latestPerFamilyBy } from "../../lib/model-family"; +import { useLatestPerFamilyPref } from "../../lib/latest-per-family-pref"; +import { ProviderIcon } from "../provider-workspace/ProviderRail"; +import type { ModelOption, ProviderOption } from "../combo-workspace-types"; +import type { ProbeMemberModel } from "./MemberProbe"; +import { MemberTable, type SaveMemberModel } from "./MemberTable"; +import { QuotaLine } from "./QuotaLine"; +import { dragRows } from "./drag-rows"; + +export type EditableChannel = Pick; + +const SLIDE_MS = 160; +const MODALITY_ORDER = ["text", "image"]; + +/** + * Slide rows to their new place after a reorder (FLIP): measure where each row was, let React + * move it, then start it from the old spot and transition to zero. No library; a reorder + * during the slide simply restarts it from wherever the row is drawn. + */ +function useSlideOnReorder(order: readonly string[]) { + const nodes = useRef(new Map()); + const previous = useRef(new Map()); + /** Set by a drag commit: the rows are already drawn where they land, so nothing slides. */ + const still = useRef(false); + useLayoutEffect(() => { + const next = new Map(); + const skip = still.current; + still.current = false; + for (const [key, node] of nodes.current) { + const top = node.getBoundingClientRect().top; + next.set(key, top); + const before = previous.current.get(key); + if (skip || before === undefined || before === top || typeof node.animate !== "function") continue; + node.animate([{ transform: `translateY(${before - top}px)` }, { transform: "translateY(0)" }], { + duration: SLIDE_MS, + easing: "ease-out", + }); + } + previous.current = next; + }, [order]); + const ref = (key: string) => (node: HTMLElement | null) => { + if (node) nodes.current.set(key, node); else nodes.current.delete(key); + }; + return { ref, still }; +} + + +/** + * Inline channel editor under an expanded row: reorder (drag, with the other rows making room + * as you go, or the move buttons from the keyboard), mark fallback-only, remove, add, and a + * "More settings" section that opens in place. Nothing is written until Save. + */ +export function ChannelEditor({ + comboModel, + strategy, + channels: initial, + quotaFor, + providers, + models, + lastResortActive, + labels, + capability: initialCapability, + catalogContext, + moreOpen: moreOpenInitially = false, + saving, + onSave, + onSaveModel, + onProbeModel, + onCancel, +}: { + comboModel: string; + strategy: ComboStrategy; + channels: readonly EditableChannel[]; + quotaFor: (provider: string) => ChannelQuota; + providers: readonly ProviderOption[]; + models: readonly (ModelOption & MemberModel)[]; + /** The combo sets `cooldownWaitPolicy`, so fallback-only marks are in effect. */ + lastResortActive: boolean; + /** Row-level provider labels, so two providers sharing a display name stay distinct here too. */ + labels?: ReadonlyMap; + capability: ComboCapabilitySettings; + /** The context window the server advertises for this combo today. */ + catalogContext?: number; + /** Open "More settings" and bring it into view (the row's context tag asks for this). */ + moreOpen?: boolean; + saving: boolean; + onSave: (channels: EditableChannel[], settings: ComboSettingsPatch) => void; + /** Writes one member model's per-provider settings (shared by every combo using it). */ + onSaveModel?: SaveMemberModel; + /** Probes what one member's relay accepts (image input, effort levels). */ + onProbeModel?: ProbeMemberModel; + onCancel: () => void; +}) { + const t = useT(); + const [channels, setChannels] = useState(() => [...initial]); + const listRef = useRef(null); + const [moreOpen, setMoreOpen] = useState(moreOpenInitially); + const moreRef = useRef(null); + const slide = useSlideOnReorder(channels.map((channel) => channel.key)); + const pickable = providers.filter((provider) => !provider.hiddenFromPicker); + const [addProvider, setAddProvider] = useState(() => pickable[0]?.name ?? ""); + const used = new Set(channels.map((channel) => channel.key)); + const [latestOnly, setLatestOnly] = useLatestPerFamilyPref(); + const providerModels = models.filter((model) => model.provider === addProvider); + const addModels = (latestOnly ? latestPerFamilyBy(providerModels, (model) => model.id) : providerModels) + .filter((model) => !used.has(channelKey(model.provider, model.id))); + const [addModel, setAddModel] = useState(""); + const chosenModel = addModels.some((model) => model.id === addModel) ? addModel : addModels[0]?.id ?? ""; + const [capability, setCapability] = useState(initialCapability); + const [fallbackOnly, setFallbackOnly] = useState(lastResortActive); + const settings: ComboSettingsPatch = { + ...capabilityPatch(initialCapability, capability), + ...(fallbackOnly !== lastResortActive ? { cooldownWaitPolicy: fallbackOnly ? "before-last-resort" as const : null } : {}), + }; + const dirty = channels.length !== initial.length + || channels.some((channel, index) => channel.key !== initial[index]?.key || channel.lastResort !== initial[index]?.lastResort) + || Object.keys(settings).length > 0; + const choice = (value: string, name: string, hint: string) => ({ + value, + textValue: name, + label: {name}{hint}, + }); + + useEffect(() => { + if (moreOpenInitially) moreRef.current?.scrollIntoView?.({ block: "nearest", behavior: "smooth" }); + }, [moreOpenInitially]); + + const move = (from: number, to: number) => setChannels((list) => moveChannel(list, from, to)); + /** + * The row itself follows the pointer and the others slide aside (Magpie's sorter, `drag-rows.ts`); + * the order changes once, on release. Presses on the row's own controls stay clicks. + */ + const startDrag = (event: ReactPointerEvent, from: number) => { + const list = listRef.current; + const target = event.target as Element; + if (!list || target.closest("button, input, a, [role=combobox]")) return; + // On touch only the grip drags, so the rest of the row still scrolls the page. + if (event.pointerType === "touch" && !target.closest(".rb-channel-grip")) return; + const rows = Array.from(list.children) as HTMLElement[]; + dragRows(event.nativeEvent, event.currentTarget, event.currentTarget, list, rows, (to) => { + slide.still.current = true; + flushSync(() => setChannels((current) => moveChannel(current, from, to))); + }); + }; + const add = () => { + if (!addProvider || !chosenModel) return; + setChannels((list) => [...list, { key: channelKey(addProvider, chosenModel), provider: addProvider, model: chosenModel, lastResort: false }]); + }; + + const facts = channels.map((channel) => memberFacts(models, channel.provider, channel.model)); + const policy = capability.capabilityPolicy; + /** Estimates fill gaps in the combined row only, and the row says so; they never route. */ + const combined = withInferredGaps(facts); + const context = comboContextWindow(combined.members, policy, catalogContext); + const modalities = combineLists(combined.members.map((fact) => fact.inputModalities), policy, MODALITY_ORDER); + const efforts = combineLists(combined.members.map((fact) => fact.reasoningEfforts), policy, COMBO_EFFORTS); + + return ( +
+
    + {channels.map((channel, index) => { + const providerName = labels?.get(channel.provider) ?? formatProviderDisplayName(channel.provider, t); + const name = `${providerName} ${channel.model}`; + return ( +
  1. startDrag(event, index)} + > + + {index + 1} + + + {providerName} + {channel.model} + + + + + + + + + + +
  2. + ); + })} +
+
+ 0 + ? addModels.map((model) => ({ value: model.id, label: model.id })) + : [{ value: "", label: t("routeBoard.edit.noModels"), disabled: true }]} + onChange={setAddModel} + /> + setLatestOnly(!latestOnly)} label={t("models.latestPerFamily")} + title={t("models.latestPerFamilyHint")} showLabel /> + +
+

{t(COMBO_TARGETS_HINT_KEYS[strategy])}

+ +
+ + {moreOpen && ( +
+
+
+ {t("routeBoard.cap.title")} + {t(policy === "union" ? "routeBoard.cap.unionHint" : "routeBoard.cap.intersectionHint")} +
+ setCapability((current) => ({ ...current, onUnservable: next as UnservablePolicy }))} + /> +
+ )} +
+
+ {t("routeBoard.more.fallbackOnly")} + {t("routeBoard.more.fallbackOnlyHint")} +
+ setFallbackOnly((on) => !on)} /> +
+ + +
+ )} +
+ +
+ + {dirty && {t("routeBoard.edit.unsaved")}} + + +
+
+ ); +} diff --git a/gui/src/components/route-board/ComboSuggestions.tsx b/gui/src/components/route-board/ComboSuggestions.tsx new file mode 100644 index 00000000000..d16ca8028e8 --- /dev/null +++ b/gui/src/components/route-board/ComboSuggestions.tsx @@ -0,0 +1,282 @@ +import { useState } from "react"; +import { + buildComboSuggestions, + channelTier, + extendedCombo, + suggestionDraft, + type ChannelTier, + type ComboSuggestion, + type SuggestedMember, + type SuggestionModel, + type SuggestionProvider, +} from "../../combo-suggestions"; +import { isValidComboId, type ComboDraftError, type ComboItem } from "../../combo-workspace-data"; +import { useT, type TKey } from "../../i18n/shared"; +import { makeCollapseStore } from "../../pages/collapse-store"; +import { formatProviderDisplayName } from "../../provider-icons"; +import { moveChannel } from "../../route-board-model"; +import { ProviderIcon } from "../provider-workspace/ProviderRail"; +import { SuggestionExcludeProviders } from "./SuggestionExcludeProviders"; + +type SaveResult = { ok: boolean; error?: string }; + +const dismissedStore = makeCollapseStore("ocx.combos.suggestions.dismissed.v1"); +const COLLAPSED_COUNT = 3; + +const TIER_LABEL: Record = { + "own-subscription": "comboSuggest.tier.ownSubscription", + subscription: "comboSuggest.tier.subscription", + vertex: "comboSuggest.tier.vertex", + metered: "comboSuggest.tier.metered", +}; + +export interface ComboSuggestionsProps { + combos: readonly ComboItem[]; + models: readonly SuggestionModel[]; + hiddenModels: ReadonlySet; + providers: readonly SuggestionProvider[]; + remainingPercent: (provider: string, model: string) => number | undefined; + validate: (item: ComboItem, isCreate: boolean) => ComboDraftError | null; + errorText: (code: ComboDraftError, item: ComboItem) => string; + onCreate: (item: ComboItem) => Promise; + onExtend: (item: ComboItem) => Promise; + /** Providers left out of suggestions (config.json); with `onExcludedChange`, offers to change them. */ + excludedProviders?: readonly string[]; + onExcludedChange?: (next: readonly string[]) => Promise; +} + +/** Suggested combos above the overview: same-name models across providers, one click to a draft. */ +export function ComboSuggestions(props: ComboSuggestionsProps) { + const t = useT(); + const [dismissed, setDismissed] = useState>(() => dismissedStore.read() ?? new Set()); + const [showAll, setShowAll] = useState(false); + const [draftKey, setDraftKey] = useState(null); + const excluded = props.excludedProviders ?? []; + const suggestions = buildComboSuggestions({ ...props, dismissed, excludedProviders: new Set(excluded) }); + if (suggestions.length === 0 && excluded.length === 0) return null; + + const dismiss = (key: string) => { + const next = new Set(dismissed).add(key); + dismissedStore.write(next); + setDismissed(next); + if (draftKey === key) setDraftKey(null); + }; + const providerByName = new Map(props.providers.map((provider) => [provider.name, provider])); + const tierOf = (provider: string, model: string): ChannelTier => { + const known = providerByName.get(provider); + return known ? channelTier(known, model) : "metered"; + }; + const shown = showAll ? suggestions : suggestions.slice(0, COLLAPSED_COUNT); + + return ( +
+
+ {t("comboSuggest.title")} + {t("comboSuggest.lede")} + {props.onExcludedChange && ( + !provider.disabled && !provider.hiddenFromPicker).map((provider) => provider.name)} + excluded={excluded} + onChange={props.onExcludedChange} + /> + )} +
+ {suggestions.length === 0 &&

{t("comboSuggest.exclude.none")}

} +
    + {shown.map((suggestion) => ( + setDraftKey(open ? suggestion.key : null)} + onDismiss={() => dismiss(suggestion.key)} + /> + ))} +
+ {suggestions.length > COLLAPSED_COUNT && ( + + )} +
+ ); +} + +function MemberChips({ members }: { members: readonly SuggestedMember[] }) { + const t = useT(); + return ( + + {members.map((member, index) => ( + + {index > 0 && } + {formatProviderDisplayName(member.provider, t)} + {t(TIER_LABEL[member.tier])} + + ))} + + ); +} + +function SuggestionCard({ + suggestion, + drafting, + combos, + tierOf, + validate, + errorText, + onCreate, + onExtend, + onDraft, + onDismiss, +}: { + suggestion: ComboSuggestion; + drafting: boolean; + combos: readonly ComboItem[]; + tierOf: (provider: string, model: string) => ChannelTier; + validate: ComboSuggestionsProps["validate"]; + errorText: ComboSuggestionsProps["errorText"]; + onCreate: ComboSuggestionsProps["onCreate"]; + onExtend: ComboSuggestionsProps["onExtend"]; + onDraft: (open: boolean) => void; + onDismiss: () => void; +}) { + const t = useT(); + const [busy, setBusy] = useState(false); + const [message, setMessage] = useState(null); + + const save = async (item: ComboItem, isCreate: boolean) => { + const error = validate(item, isCreate); + if (error) return setMessage(errorText(error, item)); + setBusy(true); + setMessage(null); + try { + const result = await (isCreate ? onCreate(item) : onExtend(item)); + if (!result.ok) setMessage(result.error ?? t("cws.saveFailed")); + else if (isCreate) onDraft(false); + } finally { + setBusy(false); + } + }; + + const providers = [...new Set(suggestion.members.map((member) => member.provider))]; + const target = suggestion.kind === "extend" ? combos.find((combo) => combo.id === suggestion.comboId) : undefined; + return ( +
  • +
    + + + {suggestion.kind === "create" ? ( + <> + + {suggestion.comboId} + {t("comboSuggest.servedBy", { count: suggestion.members.length })} + + + + ) : ( + <> + + {suggestion.comboId} + + {t("comboSuggest.canAdd", { providers: providers.map((provider) => formatProviderDisplayName(provider, t)).join(", ") })} + + + + + )} + + + {suggestion.kind === "create" ? ( + + ) : ( + + )} + + +
    + {message &&

    {message}

    } + {drafting && suggestion.kind === "create" && ( + void save(item, true)} + onCancel={() => { setMessage(null); onDraft(false); }} + /> + )} +
  • + ); +} + +function SuggestionDraft({ + suggestion, + busy, + onSave, + onCancel, +}: { + suggestion: ComboSuggestion & { kind: "create" }; + busy: boolean; + onSave: (item: ComboItem) => void; + onCancel: () => void; +}) { + const t = useT(); + const [comboId, setComboId] = useState(suggestion.comboId); + const [members, setMembers] = useState(suggestion.members); + const idOk = isValidComboId(comboId.trim()); + return ( +
    + +

    {t("comboSuggest.draft.orderHint")}

    +
      + {members.map((member, index) => ( +
    1. + + {formatProviderDisplayName(member.provider, t)} + {member.model} + {t(TIER_LABEL[member.tier])} + {member.remainingPercent !== undefined && ( + {t("comboSuggest.draft.left", { percent: Math.round(member.remainingPercent) })} + )} + + + + + +
    2. + ))} +
    +
    + {t("comboSuggest.draft.strategy")} + + +
    +
    + ); +} diff --git a/gui/src/components/route-board/MemberProbe.tsx b/gui/src/components/route-board/MemberProbe.tsx new file mode 100644 index 00000000000..a29b9ad1976 --- /dev/null +++ b/gui/src/components/route-board/MemberProbe.tsx @@ -0,0 +1,93 @@ +import { useEffect, useRef } from "react"; +import { useT } from "../../i18n/shared"; +import type { TKey } from "../../i18n/en"; +import type { ProbeOutcome } from "../../route-board-model"; + +/** Runs one capability probe; `confirmed` repeats it with the operator's consent to metered requests. */ +export type ProbeMemberModel = (provider: string, modelId: string, confirmed: boolean) => Promise; + +export type ProbeState = { phase: "running" } | { phase: "settled"; outcome: ProbeOutcome }; + +const REASON_KEYS: Record = { + disabled: "routeBoard.probe.reason.disabled", + forward_auth: "routeBoard.probe.reason.forward_auth", + oauth_auth: "routeBoard.probe.reason.oauth_auth", + unsupported_adapter: "routeBoard.probe.reason.unsupported_adapter", + unsupported_transport: "routeBoard.probe.reason.unsupported_transport", +}; + +const STATUS_KEYS: Record<"accepted" | "rejected" | "inconclusive", TKey> = { + accepted: "routeBoard.probe.accepted", + rejected: "routeBoard.probe.rejected", + inconclusive: "routeBoard.probe.inconclusive", +}; + +/** + * What a "Test it" press is doing or found, under the member's row. A metered provider asks first + * (with the number of requests), an inconclusive baseline changes nothing, and context is never + * probed: it comes from the model name. + */ +export function ProbeResult({ state, onConfirm, onDismiss }: { state: ProbeState; onConfirm: () => void; onDismiss: () => void }) { + const t = useT(); + const confirmRef = useRef(null); + const asking = state.phase === "settled" && state.outcome.kind === "confirm"; + useEffect(() => { if (asking) confirmRef.current?.focus(); }, [asking]); + + const body = (() => { + if (state.phase === "running") return

    {t("routeBoard.probe.running")}

    ; + const outcome = state.outcome; + switch (outcome.kind) { + case "confirm": + return ( +
    +

    {t("routeBoard.probe.confirm", { count: outcome.planned })}

    +
    + + +
    +
    + ); + case "inapplicable": + return

    {t(REASON_KEYS[outcome.reason] ?? "routeBoard.probe.reason.other")}

    ; + case "busy": + return

    {t("routeBoard.probe.busy")}

    ; + case "failed": + return

    {t("routeBoard.probe.failed")}

    ; + case "done": { + if (!outcome.baselineOk) return

    {t("routeBoard.probe.uncertain")}

    ; + const applied = [ + ...(outcome.applied.inputModalities ? [t("routeBoard.probe.appliedInput", { value: outcome.applied.inputModalities.join(" · ") })] : []), + ...(outcome.applied.reasoningEfforts ? [t("routeBoard.probe.appliedEfforts", { value: outcome.applied.reasoningEfforts.join(" · ") || "—" })] : []), + ]; + return ( +
      + {outcome.image &&
    • {t("routeBoard.probe.image", { status: t(STATUS_KEYS[outcome.image]) })}
    • } + {outcome.accepted.length + outcome.rejected.length + outcome.inconclusive.length > 0 && ( +
    • + {t("routeBoard.probe.efforts", { + accepted: outcome.accepted.join(" · ") || "—", + rejected: outcome.rejected.join(" · ") || "—", + inconclusive: outcome.inconclusive.join(" · ") || "—", + })} +
    • + )} +
    • {applied.length > 0 ? applied.join("; ") : t("routeBoard.probe.nothingApplied")}
    • +
    + ); + } + } + })(); + + return ( +
    + {body} +

    {t("routeBoard.probe.contextNote")}

    + {!asking && state.phase === "settled" && ( +
    + + +
    + )} +
    + ); +} diff --git a/gui/src/components/route-board/MemberTable.tsx b/gui/src/components/route-board/MemberTable.tsx new file mode 100644 index 00000000000..3d1b897523d --- /dev/null +++ b/gui/src/components/route-board/MemberTable.tsx @@ -0,0 +1,294 @@ +import { Fragment, useState, type ReactNode } from "react"; +import { useT } from "../../i18n/shared"; +import type { TKey } from "../../i18n/en"; +import { REASONING_EFFORT_LEVELS } from "../../pages/models-shared"; +import { formatProviderDisplayName } from "../../provider-icons"; +import { + formatContextWindow, + memberRestorePatch, + memberSettingsPatch, + type CapabilitySource, + type ContextBasis, + type InferredValue, + type MemberDraft, + type MemberFacts, + type ProbeOutcome, +} from "../../route-board-model"; +import type { EditableChannel } from "./ChannelEditor"; +import { ProbeResult, type ProbeMemberModel, type ProbeState } from "./MemberProbe"; + +const MODALITIES = ["text", "image"]; + +const SOURCE_KEYS: Record = { + manual: "routeBoard.source.manual", + probed: "routeBoard.source.probed", + reported: "routeBoard.source.reported", + inferred: "routeBoard.source.inferred", + unknown: "routeBoard.source.unknown", +}; + +const BASIS_KEYS: Record["basis"]["source"], TKey> = { + registry: "routeBoard.basis.registry", + vendor: "routeBoard.basis.vendor", + provider: "routeBoard.basis.provider", + aggregator: "routeBoard.basis.aggregator", +}; + +/** Saves one member model's settings; resolves to an error message, or null once saved and reloaded. */ +export type SaveMemberModel = (provider: string, modelId: string, patch: Record) => Promise; + +interface Editing { + key: string; + draft: MemberDraft; + error?: string; + saving?: boolean; +} + +/** + * What each channel can take (context, input, effort levels) and what that makes the combo. + * Every cell says where its value comes from. A gap with a same-name estimate shows it and can + * adopt it as a manual declaration; a row opens in place to change the provider's per-model + * settings, which every combo using that model shares; "Test it" probes what the relay accepts. + */ +export function MemberTable({ + channels, + facts, + labels, + combo, + onSaveModel, + onProbeModel, +}: { + channels: readonly EditableChannel[]; + facts: readonly MemberFacts[]; + labels?: ReadonlyMap; + combo: { context?: number; basis: ContextBasis; modalities?: readonly string[]; efforts?: readonly string[]; includesInferred?: boolean }; + onSaveModel?: SaveMemberModel; + onProbeModel?: ProbeMemberModel; +}) { + const t = useT(); + const [editing, setEditing] = useState(null); + const [adopting, setAdopting] = useState(null); + const [adoptError, setAdoptError] = useState<{ key: string; message: string } | null>(null); + const [probes, setProbes] = useState>({}); + const providerName = (provider: string) => labels?.get(provider) ?? formatProviderDisplayName(provider, t); + const modalityWord = (value: string) => value === "text" ? t("routeBoard.members.text") : value === "image" ? t("routeBoard.members.image") : value; + const listText = (list: readonly string[] | undefined, word?: (value: string) => string) => + list === undefined ? t("routeBoard.members.unknown") : list.length === 0 ? t("routeBoard.members.none") : list.map((v) => word ? word(v) : v).join(" · "); + const sourceTag = (source: CapabilitySource | undefined) => ( + {t(SOURCE_KEYS[source ?? "unknown"])} + ); + + const open = (channel: EditableChannel, fact: MemberFacts) => setEditing({ + key: channel.key, + draft: { + context: fact.contextWindow ? String(fact.contextWindow) : "", + input: fact.inputModalities ?? [], + efforts: fact.reasoningEfforts ?? [], + }, + }); + const toggle = (list: readonly string[], value: string) => list.includes(value) ? list.filter((v) => v !== value) : [...list, value]; + const send = async (channel: EditableChannel, patch: Record) => { + if (!onSaveModel || Object.keys(patch).length === 0) { setEditing(null); return; } + setEditing((current) => current && { ...current, saving: true, error: undefined }); + const error = await onSaveModel(channel.provider, channel.model, patch); + setEditing((current) => current?.key !== channel.key ? current : error ? { ...current, saving: false, error } : null); + }; + /** An estimate becomes the operator's declaration through the same per-model settings write. */ + const adopt = async (channel: EditableChannel, field: string, value: unknown) => { + if (!onSaveModel) return; + setAdopting(`${channel.key}:${field}`); + setAdoptError(null); + const error = await onSaveModel(channel.provider, channel.model, { [field]: value }); + setAdopting(null); + if (error) setAdoptError({ key: channel.key, message: error }); + }; + const probe = async (channel: EditableChannel, confirmed: boolean) => { + if (!onProbeModel) return; + setProbes((all) => ({ ...all, [channel.key]: { phase: "running" } })); + const outcome: ProbeOutcome = await onProbeModel(channel.provider, channel.model, confirmed); + setProbes((all) => ({ ...all, [channel.key]: { phase: "settled", outcome } })); + }; + + /** One cell: the value with its source, or the estimate for the gap with an "Adopt" button. */ + const cell = ( + channel: EditableChannel, + name: string, + known: ReactNode | undefined, + source: CapabilitySource | undefined, + inferred: InferredValue | undefined, + shown: string | undefined, + field: string, + ) => { + const adoptable = inferred !== undefined && onSaveModel !== undefined && (known === undefined || source === "inferred"); + return ( + + {known !== undefined ? <>{known} {sourceTag(source)} : inferred && shown ? ( + + {t("routeBoard.inferred.cell", { + value: shown, + basis: t(BASIS_KEYS[inferred.basis.source], { provider: inferred.basis.provider }), + })} + + ) : sourceTag("unknown")} + {adoptable && ( + + )} + + ); + }; + + return ( + + + + + + + + + + + + + {channels.map((channel, index) => { + const fact = facts[index] ?? {}; + const name = `${providerName(channel.provider)} ${channel.model}`; + const probeState = probes[channel.key]; + const blocked = probeState?.phase === "settled" && probeState.outcome.kind === "inapplicable"; + const inferred = fact.inferred; + const row = ( + + + {cell(channel, name, fact.contextWindow ? formatContextWindow(fact.contextWindow) : undefined, fact.sources?.context, + inferred?.context, inferred?.context ? formatContextWindow(inferred.context.value) : undefined, "contextWindow")} + {cell(channel, name, fact.inputModalities ? listText(fact.inputModalities, modalityWord) : undefined, fact.sources?.input, + inferred?.input, inferred?.input ? listText(inferred.input.value, modalityWord) : undefined, "inputModalities")} + {cell(channel, name, fact.reasoningEfforts ? listText(fact.reasoningEfforts) : undefined, fact.sources?.efforts, + inferred?.efforts, inferred?.efforts ? listText(inferred.efforts.value) : undefined, "reasoningEfforts")} + + + ); + const extra: ReactNode[] = []; + if (adoptError?.key === channel.key) { + extra.push( + + + , + ); + } + if (probeState) { + extra.push( + + + , + ); + } + if (editing?.key === channel.key) { + const { draft } = editing; + const set = (next: Partial) => setEditing({ ...editing, draft: { ...draft, ...next }, error: undefined }); + const restore = memberRestorePatch(fact.sources); + const save = () => { + const result = memberSettingsPatch(fact, draft, REASONING_EFFORT_LEVELS); + if (result.invalid) { setEditing({ ...editing, error: t("routeBoard.members.contextInvalid") }); return; } + void send(channel, result.patch); + }; + extra.push( + + + , + ); + } + return {row}{extra}; + })} + + + + + + + + + +
    {t("routeBoard.members.title")}
    {t("routeBoard.members.channel")}{t("routeBoard.members.context")}{t("routeBoard.members.input")}{t("routeBoard.members.efforts")}{t("routeBoard.members.actions")}
    + {providerName(channel.provider)} + {channel.model} + + {onProbeModel && ( + + )} + {onSaveModel && editing?.key !== channel.key && ( + + )} +

    {adoptError.message}

    + void probe(channel, true)} + onDismiss={() => setProbes((all) => { + const { [channel.key]: _closed, ...rest } = all; + return rest; + })} + /> +
    +
    + +
    + {t("routeBoard.members.input")} + + {MODALITIES.map((modality) => ( + + ))} + +
    +
    + {t("routeBoard.members.efforts")} + + {REASONING_EFFORT_LEVELS.map((level) => ( + + ))} + +
    +

    {t("routeBoard.members.scopeNote", { name })}

    + {editing.error &&

    {editing.error}

    } +
    + {Object.keys(restore).length > 0 && ( + + )} + + + +
    +
    +
    + {t("routeBoard.members.combo")} + {combo.includesInferred && {t("routeBoard.members.includesInferred")}} + + {combo.context ? formatContextWindow(combo.context) : t("routeBoard.members.unknown")} + {combo.basis !== "catalog" && {t(combo.basis === "max" ? "routeBoard.contextBasis.max" : "routeBoard.contextBasis.min")}} + {listText(combo.modalities, modalityWord)}{listText(combo.efforts)} +
    + ); +} diff --git a/gui/src/components/route-board/ModelRouteRow.tsx b/gui/src/components/route-board/ModelRouteRow.tsx new file mode 100644 index 00000000000..0c77f48890e --- /dev/null +++ b/gui/src/components/route-board/ModelRouteRow.tsx @@ -0,0 +1,116 @@ +import { useT } from "../../i18n/shared"; +import { formatProviderDisplayName } from "../../provider-icons"; +import { distinctProviderLabels, formatContextWindow, type RouteRow } from "../../route-board-model"; +import type { ComboStrategy } from "../../combo-workspace-data"; +import { Switch } from "../../ui"; +import { ProviderIcon } from "../provider-workspace/ProviderRail"; +import { QuotaLine } from "./QuotaLine"; +import { StrategyMenu } from "./StrategyMenu"; + +const MAX_STACKED_ICONS = 4; + +/** One combo: icons, name + public id, channel order, quota line, tags, context, strategy, switch. */ +export function ModelRouteRow({ + row, + expanded, + busy, + locked = false, + lastResortActive = false, + onOpenContext, + message, + onToggleExpanded, + onStrategy, + onEnabled, + children, +}: { + row: RouteRow; + expanded: boolean; + busy: boolean; + locked?: boolean; + /** The combo sets `cooldownWaitPolicy`; otherwise fallback-only marks are inert. */ + lastResortActive?: boolean; + onOpenContext?: () => void; + message: string | null; + onToggleExpanded: () => void; + onStrategy: (next: ComboStrategy) => void; + onEnabled: (next: boolean) => void; + children?: React.ReactNode; +}) { + const t = useT(); + const separator = row.combo.strategy === "failover" ? "→" : "·"; + const providers = [...new Set(row.channels.map((channel) => channel.provider))]; + const labels = distinctProviderLabels(providers, (provider) => formatProviderDisplayName(provider, t)); + const offChannels = row.channels.filter((channel) => channel.providerDisabled).length; + const panelId = `rb-panel-${row.combo.id}`; + return ( +
  • +
    + +
    + {locked && {t("routeBoard.locked")}} + {offChannels > 0 && {t("routeBoard.tag.channelsOff", { count: offChannels })}} + {row.combo.strategy === "round-robin" && row.combo.stickyLimit > 1 && ( + {t("routeBoard.tag.sticky", { count: row.combo.stickyLimit })} + )} + {row.combo.imageInput === "disabled" && {t("routeBoard.tag.noImages")}} + {row.contextWindow !== undefined && ( + + )} + + onEnabled(!row.enabled)} + /> +
    +
    + {message &&

    {message}

    } + +
  • + ); +} diff --git a/gui/src/components/route-board/QuotaLine.tsx b/gui/src/components/route-board/QuotaLine.tsx new file mode 100644 index 00000000000..58352027cd0 --- /dev/null +++ b/gui/src/components/route-board/QuotaLine.tsx @@ -0,0 +1,52 @@ +import { formatProviderDisplayName } from "../../provider-icons"; +import { useT, type TFn, type TKey } from "../../i18n/shared"; +import { quotaFamilyWindow, type ProviderQuotaLine, type QuotaWindowView } from "../../route-board-model"; + +const WINDOW_NAME_KEYS: Partial> = { + "quota.weeklyLimit": "routeBoard.window.weekly", + "quota.fiveHourLimit": "routeBoard.window.fiveHour", + "quota.monthlyLimit": "routeBoard.window.monthly", +}; + +function windowName(window: QuotaWindowView, t: TFn): string { + const key = window.labelKey ? WINDOW_NAME_KEYS[window.labelKey] ?? window.labelKey : undefined; + if (key) return t(key); + const pool = quotaFamilyWindow(window.label ?? ""); + if (pool) return t("routeBoard.quota.family", { family: pool.family, window: t(pool.weekly ? "routeBoard.window.weekly" : "routeBoard.window.fiveHour") }); + return window.label ?? window.id; +} + +/** "Anthropic (2 accounts): weekly 51% left · 5h 83% left · Anthropic API: metered" */ +export function QuotaLine({ quotas, labels }: { quotas: readonly ProviderQuotaLine[]; labels?: ReadonlyMap }) { + const t = useT(); + return ( +

    + {quotas.map((line) => { + const name = labels?.get(line.provider) ?? formatProviderDisplayName(line.provider, t); + const quota = line.quota; + return ( + + + {line.accounts !== undefined && line.accounts.active > 0 + ? t("routeBoard.quota.accounts", { provider: name, count: line.accounts.active }) + : name} + {line.accounts !== undefined && line.accounts.paused > 0 && ( + {t("routeBoard.quota.paused", { count: line.accounts.paused })} + )} + + {quota.kind === "windows" && quota.windows.map((window) => ( + + {t("routeBoard.quota.left", { + window: windowName(window, t), + percent: Math.floor(window.remainingPercent), + })} + + ))} + {quota.kind === "metered" && {t("routeBoard.quota.metered")}} + {quota.kind === "unknown" && {t("routeBoard.quota.unknown")}} + + ); + })} +

    + ); +} diff --git a/gui/src/components/route-board/RouteBoard.tsx b/gui/src/components/route-board/RouteBoard.tsx new file mode 100644 index 00000000000..7a8a22b656d --- /dev/null +++ b/gui/src/components/route-board/RouteBoard.tsx @@ -0,0 +1,164 @@ +import { useState } from "react"; +import type { ComboDraftError, ComboItem, ComboStrategy } from "../../combo-workspace-data"; +import { useT } from "../../i18n/shared"; +import { formatProviderDisplayName } from "../../provider-icons"; +import { + buildRouteRows, + distinctProviderLabels, + channelQuota, + quotaWindowsByProvider, + planStrategyChange, + DEFAULT_CAPABILITY_SETTINGS, + type AccountCount, + type ComboCapabilitySettings, + type ComboCatalogMeta, + type ComboSettingsPatch, + type RouteBoardProvider, +} from "../../route-board-model"; +import type { ModelOption, ProviderOption } from "../combo-workspace-types"; +import { ChannelEditor, type EditableChannel } from "./ChannelEditor"; +import type { SaveMemberModel } from "./MemberTable"; +import type { ProbeMemberModel } from "./MemberProbe"; +import { ModelRouteRow } from "./ModelRouteRow"; + +type SaveResult = { ok: boolean; error?: string }; + +export interface RouteBoardProps { + combos: readonly ComboItem[]; + catalog: Readonly>; + lastResort: Readonly>; + /** Combo ids that defer last-resort channels (`cooldownWaitPolicy: "before-last-resort"`). */ + lastResortActive: ReadonlySet; + providers: readonly (ProviderOption & RouteBoardProvider)[]; + models: readonly ModelOption[]; + quotaReports: unknown; + accountCounts?: Readonly>; + capability?: Readonly>; + validate: (item: ComboItem) => ComboDraftError | null; + errorText: (code: ComboDraftError, item: ComboItem) => string; + onSave: ( + item: ComboItem, + channels?: readonly EditableChannel[], + settings?: ComboSettingsPatch, + ) => Promise; + onSetEnabled: (id: string, enabled: boolean) => Promise; + /** Open the full workspace, optionally on one combo. */ + onOpenAdvanced: (id?: string, reason?: "jev") => void; + /** Combo with an unsaved draft in the advanced editor: read-only here until it is saved there. */ + lockedId?: string | null; + /** Writes one member model's per-provider settings from the editor's member table. */ + onSaveModel?: SaveMemberModel; + onProbeModel?: ProbeMemberModel; +} + +/** Combos overview: one row per combo, inline strategy and on/off, click a row to edit its channels. */ +export function RouteBoard(props: RouteBoardProps) { + const t = useT(); + const [expanded, setExpanded] = useState(null); + /** Row whose editor opened from its context tag, with "More settings" already open. */ + const [moreFor, setMoreFor] = useState(null); + const [busy, setBusy] = useState(null); + const [messages, setMessages] = useState>({}); + const rows = buildRouteRows({ + combos: props.combos, + catalog: props.catalog, + lastResort: props.lastResort, + providers: props.providers, + quotaReports: props.quotaReports, + accountCounts: props.accountCounts, + models: props.models, + capability: props.capability, + }); + const reported = quotaWindowsByProvider(props.quotaReports); + const providerByName = new Map(props.providers.map((provider) => [provider.name, provider])); + + const setMessage = (id: string, text: string | null) => setMessages((current) => { + const next = { ...current }; + if (text) next[id] = text; else delete next[id]; + return next; + }); + + const run = async (id: string, work: () => Promise): Promise => { + setBusy(id); + setMessage(id, null); + try { + const result = await work(); + if (!result.ok) setMessage(id, result.error ?? t("cws.saveFailed")); + return result.ok; + } finally { + setBusy(null); + } + }; + + const changeStrategy = (combo: ComboItem, next: ComboStrategy) => { + const plan = planStrategyChange(combo, next, props.validate); + if (plan.kind === "unchanged") return; + if (plan.kind === "open-advanced") return props.onOpenAdvanced(combo.id, "jev"); + if (plan.kind === "invalid") return setMessage(combo.id, t("routeBoard.notSaved", { reason: props.errorText(plan.error, plan.item) })); + void run(combo.id, () => props.onSave(plan.item)); + }; + + const saveChannels = async (combo: ComboItem, channels: EditableChannel[], settings: ComboSettingsPatch) => { + const targets = channels.map((channel) => { + const existing = combo.targets.find((target) => target.provider === channel.provider && target.model === channel.model); + return existing ?? { provider: channel.provider, model: channel.model }; + }); + const item = { ...combo, targets }; + const error = props.validate(item); + if (error) return setMessage(combo.id, t("routeBoard.notSaved", { reason: props.errorText(error, item) })); + if (await run(combo.id, () => props.onSave(item, channels, settings))) setExpanded(null); + }; + + if (rows.length === 0) { + return ( +
    +

    {t("routeBoard.empty")}

    + +
    + ); + } + + return ( +
      + {rows.map((row) => ( + { setMoreFor(row.combo.id); setExpanded(row.combo.id); }} + busy={busy === row.combo.id} + locked={props.lockedId === row.combo.id} + message={messages[row.combo.id] ?? null} + onToggleExpanded={() => { setMoreFor(null); setExpanded((current) => current === row.combo.id ? null : row.combo.id); }} + onStrategy={(next) => changeStrategy(row.combo, next)} + onEnabled={(next) => void run(row.combo.id, () => props.onSetEnabled(row.combo.id, next))} + > + channelQuota( + providerByName.get(provider), + reported.get(provider), + row.channels.filter((channel) => channel.provider === provider).map((channel) => channel.model), + )} + providers={props.providers} + models={props.models} + lastResortActive={props.lastResortActive.has(row.combo.id)} + labels={distinctProviderLabels(row.channels.map((channel) => channel.provider), (provider) => formatProviderDisplayName(provider, t))} + capability={props.capability?.[row.combo.id] ?? DEFAULT_CAPABILITY_SETTINGS} + saving={busy === row.combo.id || props.lockedId === row.combo.id} + onSave={(channels, settings) => void saveChannels(row.combo, channels, settings)} + onSaveModel={props.onSaveModel} + onProbeModel={props.onProbeModel} + onCancel={() => setExpanded(null)} + /> + + ))} +
    + ); +} diff --git a/gui/src/components/route-board/StrategyMenu.tsx b/gui/src/components/route-board/StrategyMenu.tsx new file mode 100644 index 00000000000..bd85ec34102 --- /dev/null +++ b/gui/src/components/route-board/StrategyMenu.tsx @@ -0,0 +1,47 @@ +import { COMBO_STRATEGY_LABEL_KEYS, type ComboStrategy } from "../../combo-workspace-data"; +import { useT, type TKey } from "../../i18n/shared"; +import { ROUTE_BOARD_STRATEGIES } from "../../route-board-model"; +import { Select } from "../../ui"; + +/** What picking each strategy does, in the user's terms (Magpie's GROUP_HINT style). */ +const STRATEGY_HINT_KEYS: Record = { + failover: "routeBoard.strategyHint.failover", + "round-robin": "routeBoard.strategyHint.roundRobin", + random: "routeBoard.strategyHint.random", + "least-used": "routeBoard.strategyHint.leastUsed", + "reset-window": "routeBoard.strategyHint.resetWindow", + jev: "routeBoard.strategyHint.jev", +}; + +/** Row strategy picker: every option carries its one-line explanation; the trigger shows the name. */ +export function StrategyMenu({ value, label, disabled, onChange }: { + value: ComboStrategy; + label: string; + disabled?: boolean; + onChange: (next: ComboStrategy) => void; +}) { + const t = useT(); + const options = ROUTE_BOARD_STRATEGIES.map((strategy) => ({ + value: strategy, + textValue: t(COMBO_STRATEGY_LABEL_KEYS[strategy]), + label: ( + + {t(COMBO_STRATEGY_LABEL_KEYS[strategy])} + {t(STRATEGY_HINT_KEYS[strategy])} + + ), + })); + return ( + void toggle(name, event.target.checked)} /> + + {label(name)} + + {on && ( + + )} + + ); + })} + + {failed &&

    {t("comboSuggest.exclude.saveFailed")}

    } + + )} + + ); +} diff --git a/gui/src/components/route-board/drag-rows.ts b/gui/src/components/route-board/drag-rows.ts new file mode 100644 index 00000000000..28b72724cae --- /dev/null +++ b/gui/src/components/route-board/drag-rows.ts @@ -0,0 +1,171 @@ +/* + * Pointer row sorter, adapted from Magpie's `dragRows`, `dragScroll`, `dragListen` and `tapLike` + * (internal/gui/assets/app.js in https://github.com/yetone/magpie). + * + * MIT License + * + * Copyright (c) 2026 yetone + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + * Changes from the original: TypeScript; the target slot goes through `dragSlot` (the row + * midpoints from layout, plus a few pixels of hysteresis at each boundary) instead of the plain + * midpoint walk, so a pointer resting on a boundary cannot make the rows flip back and forth. + */ +import { dragSlot } from "../../route-board-model"; + +/** The box a drag scrolls, and how fast a pointer at y scrolls it. */ +function dragScroll(list: HTMLElement) { + let scroll: HTMLElement | null = list.parentElement; + while (scroll && !/(auto|scroll)/.test(window.getComputedStyle(scroll).overflowY)) scroll = scroll.parentElement; + const box = scroll ?? (document.scrollingElement as HTMLElement | null) ?? document.documentElement; + const bounds = box.getBoundingClientRect(); + const edge = 36; + return { + scroll: box, + speedAt: (y: number) => y < bounds.top + edge ? -Math.min(1, (bounds.top + edge - y) / edge) + : y > bounds.bottom - edge ? Math.min(1, (y - bounds.bottom + edge) / edge) : 0, + }; +} + +/** A drag's listeners: letting go saves; Escape, blur, resize and a lost capture cancel. */ +function dragListen(handle: HTMLElement, move: (ev: PointerEvent) => void, finish: (save: boolean, ev?: PointerEvent) => void) { + const cancel = (ev: Event) => finish(false, ev as PointerEvent); + const on: Array<[EventTarget, string, EventListener, AddEventListenerOptions | boolean | undefined]> = [ + [document, "pointermove", move as EventListener, { passive: false }], + [document, "pointerup", ((ev: PointerEvent) => finish(true, ev)) as EventListener, undefined], + [document, "pointercancel", cancel, undefined], + [handle, "lostpointercapture", cancel, undefined], + [window, "blur", cancel, undefined], + [window, "resize", cancel, undefined], + [document, "keydown", ((ev: KeyboardEvent) => { + if (ev.key === "Escape") { ev.preventDefault(); ev.stopImmediatePropagation(); finish(false); } + }) as EventListener, true], + ]; + for (const [target, name, listener, options] of on) target.addEventListener(name, listener, options); + return () => { for (const [target, name, listener, options] of on) target.removeEventListener(name, listener, options); }; +} + +/** + * A tap on a trackpad can slide a few pixels between press and lift: let go within 300ms and + * under 12px from where it came down is a click, not a drag. + */ +const tapLike = (t0: number, x0: number, y0: number, ev?: PointerEvent) => + ev?.type === "pointerup" && performance.now() - t0 < 300 && Math.hypot(ev.clientX - x0, ev.clientY - y0) < 12; + +const frameRequest = (callback: FrameRequestCallback) => + typeof requestAnimationFrame === "function" ? requestAnimationFrame(callback) : setTimeout(() => callback(performance.now()), 16) as unknown as number; +const frameCancel = (id: number) => { + if (typeof cancelAnimationFrame === "function") cancelAnimationFrame(id); else clearTimeout(id); +}; + +/** + * The row itself follows the pointer (a transform, no copy and no placeholder); the rows it + * passes slide a row's height out of the way; one `commit(to)` on release. Returns false when the + * press does not start a drag. + */ +export function dragRows( + e: PointerEvent, + handle: HTMLElement, + row: HTMLElement, + list: HTMLElement, + rows: HTMLElement[], + commit: (to: number) => void, +): boolean { + if (e.button !== 0 || e.isPrimary === false || rows.length < 2) return false; + const from = rows.indexOf(row); + if (from < 0) return false; + const base = () => list.getBoundingClientRect().top - list.scrollTop - rows[0]!.offsetTop; + const lift = rows[0]!.getBoundingClientRect().top - base() - rows[0]!.offsetTop; + const grab = e.clientY - row.getBoundingClientRect().top; + const { scroll, speedAt } = dragScroll(list); + let dragging = false; + let ended = false; + let to = from; + let y = e.clientY; + let frame = 0; + let lastTime = 0; + const y0 = y; + const x0 = e.clientX; + const t0 = performance.now(); + const pointer = e.pointerId; + + const paint = (time: number) => { + frame = 0; + if (!rows.every((r) => r.isConnected)) { finish(false); return; } + if (!dragging) return; + const dt = Math.min(32, lastTime ? time - lastTime : 16); + lastTime = time; + const speed = speedAt(y); + if (speed) scroll.scrollTop += speed * dt * 0.6; + const b = base() + lift; + const tops = rows.map((r) => b + r.offsetTop); + const heights = rows.map((r) => r.offsetHeight); + const h = heights[from]!; + const lo = tops[0]! - tops[from]!; + const hi = tops.at(-1)! + heights.at(-1)! - h - tops[from]!; + const d = Math.max(lo, Math.min(hi, y - grab - tops[from]!)); + Object.assign(row.style, { transform: `translateY(${d}px)` }); + to = dragSlot(tops.map((top, i) => top + heights[i]! / 2), from, tops[from]! + d + h / 2, to); + // Held at the top or the foot, it goes there even if the end row's middle is out of reach. + if (d <= lo && from > 0) to = 0; + else if (d >= hi && from < rows.length - 1) to = rows.length - 1; + rows.forEach((r, i) => { + if (i === from) return; + const shift = i > from && i <= to ? -h : i < from && i >= to ? h : 0; + Object.assign(r.style, { transform: shift ? `translateY(${shift}px)` : "" }); + }); + frame = frameRequest(paint); + }; + const move = (ev: PointerEvent) => { + if (ev.pointerId !== pointer) return; + if (!row.isConnected || !handle.isConnected) { finish(false, ev); return; } + y = ev.clientY; + if (!dragging) { + if (Math.abs(y - y0) < 4) return; + dragging = true; + list.classList.add("sorting"); + row.classList.add("dragging"); + window.getSelection()?.removeAllRanges(); + handle.setPointerCapture?.(pointer); + } + ev.preventDefault(); + if (!frame) frame = frameRequest(paint); + }; + const finish = (save: boolean, ev?: PointerEvent) => { + if (ended || (ev?.pointerId != null && ev.pointerId !== pointer)) return; + if (save && dragging && tapLike(t0, x0, y0, ev)) save = false; + if (save && dragging && ev) { + y = ev.clientY; + frameCancel(frame); + paint(performance.now()); + } + if (ended) return; + ended = true; + frameCancel(frame); + off(); + if (handle.hasPointerCapture?.(pointer)) handle.releasePointerCapture(pointer); + list.classList.remove("sorting"); + row.classList.remove("dragging"); + rows.forEach((r) => { r.style.transform = ""; }); + if (save && dragging && to !== from) commit(to); + }; + const off = dragListen(handle, move, finish); + return true; +} diff --git a/gui/src/components/route-board/use-suggestion-exclusions.ts b/gui/src/components/route-board/use-suggestion-exclusions.ts new file mode 100644 index 00000000000..21a8df98655 --- /dev/null +++ b/gui/src/components/route-board/use-suggestion-exclusions.ts @@ -0,0 +1,53 @@ +/** + * The providers the suggested combos leave out, kept in config.json + * (`comboSuggestionExcludedProviders`, `GET|PUT /api/combo-suggestions`) so the choice follows + * the operator across browsers. + */ +import { useCallback, useEffect, useState } from "react"; + +export interface SuggestionExclusions { + excluded: readonly string[]; + /** Saves the whole list; resolves false when the proxy did not take it (the list stays as it was). */ + save: (next: readonly string[]) => Promise; +} + +function parse(body: unknown): string[] | null { + if (!body || typeof body !== "object" || !("excludedProviders" in body)) return null; + const list = (body as { excludedProviders: unknown }).excludedProviders; + return Array.isArray(list) ? list.filter((name): name is string => typeof name === "string") : null; +} + +export function useSuggestionExclusions(apiBase: string): SuggestionExclusions { + const [excluded, setExcluded] = useState([]); + + useEffect(() => { + const controller = new AbortController(); + void fetch(`${apiBase}/api/combo-suggestions`, { signal: controller.signal }) + .then((response) => (response.ok ? response.json() : null)) + .then((body) => { + const list = parse(body); + if (list) setExcluded(list); + }) + // An older proxy without the route: nothing is excluded. + .catch(() => {}); + return () => controller.abort(); + }, [apiBase]); + + const save = useCallback(async (next: readonly string[]) => { + try { + const response = await fetch(`${apiBase}/api/combo-suggestions`, { + method: "PUT", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ excludedProviders: next }), + }); + const list = response.ok ? parse(await response.json()) : null; + if (!list) return false; + setExcluded(list); + return true; + } catch { + return false; + } + }, [apiBase]); + + return { excluded, save }; +} diff --git a/gui/src/design/pages/route-board.css b/gui/src/design/pages/route-board.css new file mode 100644 index 00000000000..208384fb39c --- /dev/null +++ b/gui/src/design/pages/route-board.css @@ -0,0 +1,259 @@ +/* Combos overview (route board): one row per combo. Layout idea from Magpie's routing page + (MIT, Copyright (c) 2026 yetone); styles are OpenCodex's own tokens. */ + +.rb-viewbar { display: flex; align-items: center; gap: 12px; margin-bottom: 12px; } +.rb-lede { flex: 1 1 auto; margin: 0; color: var(--ocx-fg-subtle); font-size: 13px; } +.combos-workspace-shell .rb-viewbar { flex-shrink: 0; padding-inline: 36px; } +.combos-workspace-shell--overview { padding: 0 36px 28px; overflow-y: auto; } +.combos-workspace-shell--overview .rb-viewbar { padding-inline: 0; } +/* The workspace grid fills and clips; the overview grows with its rows and the shell scrolls. */ +.combos-workspace-shell--overview > .combos-workspace-shell-body { flex: none; min-height: auto; overflow: visible; } +.combos-workspace-shell--overview .rb-list { flex-shrink: 0; } +@media (max-width: 760px) { + .combos-workspace-shell .rb-viewbar { padding-inline: 18px; } + .combos-workspace-shell--overview { padding-inline: 18px; } +} + +.rb-list { + list-style: none; + margin: 0; + padding: 0; + border-radius: 12px; + background: var(--ocx-surface); + box-shadow: inset 0 0 0 1px var(--ocx-line); + overflow: hidden; +} +.rb-row + .rb-row { border-top: 1px solid var(--ocx-line); } +.rb-row--open { background: light-dark(var(--ocx-raised), var(--ocx-surface-2)); } +.rb-row-main { display: flex; align-items: center; gap: 12px; padding: 12px 16px; } +.rb-row-toggle { + display: flex; + flex: 1 1 auto; + min-width: 0; + align-items: flex-start; + gap: 12px; + padding: 0; + border: 0; + background: transparent; + color: inherit; + text-align: left; + font: inherit; + cursor: pointer; +} +.rb-row-toggle:focus-visible { outline: 2px solid var(--ocx-highlight); outline-offset: 4px; border-radius: 6px; } +.rb-row--off .rb-row-body, .rb-row--off .rb-icons { opacity: 0.5; } + +.rb-icons { display: inline-flex; flex: 0 0 72px; padding-top: 2px; } +.rb-icons .rb-icon { border-radius: 6px; box-shadow: 0 0 0 2px var(--ocx-surface); } +.rb-icons .rb-icon + .rb-icon { margin-left: -8px; } + +.rb-row-body { display: flex; flex-direction: column; gap: 3px; min-width: 0; } +.rb-row-title { display: flex; align-items: baseline; flex-wrap: wrap; gap: 8px; } +.rb-row-title strong { color: var(--ocx-fg); font-size: 15px; font-weight: 600; } +.rb-row-title code { + padding: 1px 6px; + border-radius: 6px; + background: var(--ocx-accent-soft); + color: var(--ocx-fg-muted); + font-family: var(--font-code); + font-size: 12px; +} +.rb-order { display: flex; flex-wrap: wrap; gap: 0 4px; color: var(--ocx-fg-muted); font-size: 13px; } +.rb-order-item { display: inline-flex; align-items: baseline; gap: 4px; } +.rb-order-item--off { text-decoration: line-through; color: var(--ocx-fg-subtle); } +.rb-order-sep { color: var(--ocx-fg-subtle); } +.rb-mark { + padding: 0 5px; + border-radius: 999px; + background: var(--ocx-warning-soft); + color: var(--ocx-warning); + font-size: 11px; +} + +.rb-quota { display: flex; flex-wrap: wrap; gap: 2px 12px; margin: 0; color: var(--ocx-fg-subtle); font-size: 12.5px; } +.rb-quota-item { display: inline-flex; flex-wrap: wrap; align-items: baseline; gap: 2px 6px; } +.rb-quota-provider { color: var(--ocx-fg-muted); } +.rb-tone-ok { color: var(--ocx-success); } +.rb-tone-warn { color: var(--ocx-warning); } +.rb-tone-low { color: var(--ocx-danger); } +.rb-quota-muted { color: var(--ocx-fg-subtle); } + +.rb-row-controls { display: flex; flex: 0 0 auto; align-items: center; gap: 8px; } +.rb-tag { + padding: 2px 8px; + border-radius: 6px; + background: var(--ocx-accent-soft); + color: var(--ocx-fg-muted); + font-size: 12px; + white-space: nowrap; +} +.rb-tag--warn { background: var(--ocx-warning-soft); color: var(--ocx-warning); } +.rb-strategy .select-trigger { min-width: 112px; } +.rb-strategy .select-trigger .rb-strategy-hint { display: none; } +.rb-strategy-option { display: flex; flex-direction: column; gap: 2px; white-space: normal; text-align: left; } +.rb-strategy-name { color: var(--ocx-fg); font-weight: 500; } +.rb-strategy-hint { color: var(--ocx-fg-subtle); font-size: 12px; line-height: 1.35; } +.rb-row-message { margin: 0; padding: 0 16px 10px 68px; color: var(--ocx-danger); font-size: 12.5px; } + +.rb-editor { margin: 0 16px 14px 56px; padding: 10px; border-radius: 10px; background: var(--ocx-surface); box-shadow: inset 0 0 0 1px var(--ocx-line); } +.rb-channels { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 6px; } +.rb-channel { + display: grid; + grid-template-columns: auto 20px auto minmax(160px, 1.1fr) minmax(160px, 1.4fr) auto; + align-items: center; + gap: 10px; + padding: 8px 10px; + border-radius: 8px; + background: var(--ocx-bg); + box-shadow: inset 0 0 0 1px var(--ocx-line); +} +.rb-channel-grip { color: var(--ocx-fg-subtle); cursor: grab; letter-spacing: -2px; } +.rb-channel-index { color: var(--ocx-fg-subtle); font-variant-numeric: tabular-nums; text-align: right; } +.rb-channel-name { display: flex; flex-direction: column; min-width: 0; } +.rb-channel-name strong { color: var(--ocx-fg); font-weight: 500; } +.rb-channel-name code { overflow: hidden; color: var(--ocx-fg-subtle); font-family: var(--font-code); font-size: 12px; text-overflow: ellipsis; white-space: nowrap; } +.rb-channel-quota .rb-quota-provider { display: none; } +.rb-channel-actions { display: flex; align-items: center; gap: 2px; } +.rb-last-resort.is-on { background: var(--ocx-warning-soft); color: var(--ocx-warning); } +.rb-add { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin-top: 10px; } +.rb-editor-hint { margin: 10px 0 0; color: var(--ocx-fg-subtle); font-size: 12.5px; } +.rb-editor-warn { color: var(--ocx-warning); } +.rb-editor-footer { display: flex; align-items: center; gap: 8px; margin-top: 10px; } +.rb-editor-spacer { flex: 1 1 auto; } +.rb-unsaved { color: var(--ocx-warning); font-size: 12.5px; } + +.rb-empty { padding: 32px 16px; border-radius: 12px; background: var(--ocx-surface); box-shadow: inset 0 0 0 1px var(--ocx-line); text-align: center; color: var(--ocx-fg-muted); } + +@media (max-width: 900px) { + .rb-row-main { flex-direction: column; align-items: stretch; } + .rb-row-controls { flex-wrap: wrap; justify-content: flex-end; } + .rb-editor { margin-left: 16px; } + .rb-channel { grid-template-columns: auto 20px auto 1fr; } + .rb-channel-quota, .rb-channel-actions { grid-column: 3 / -1; } +} +.rb-advanced:not([hidden]) { display: contents; } +.rb-mark--inert { background: var(--ocx-accent-soft); color: var(--ocx-fg-subtle); } +.rb-last-resort.is-inert { background: var(--ocx-accent-soft); color: var(--ocx-fg-subtle); text-decoration: line-through; } +.rb-tag--button { border: 0; font: inherit; font-size: 12px; cursor: pointer; } +.rb-tag--button:hover { color: var(--ocx-fg); box-shadow: inset 0 0 0 1px var(--ocx-line-strong); } +.rb-tag--button:focus-visible { outline: 2px solid var(--ocx-highlight); outline-offset: 1px; } +.rb-tag-basis { color: var(--ocx-fg-subtle); } +.rb-channel:active { cursor: grabbing; } + +.rb-more { margin-top: 10px; border-top: 1px solid var(--ocx-line); padding-top: 8px; } +.rb-more-toggle { + display: inline-flex; align-items: center; gap: 6px; padding: 4px 2px; border: 0; background: transparent; + color: var(--ocx-fg-muted); font: inherit; font-size: 13px; font-weight: 500; cursor: pointer; +} +.rb-more-toggle:hover { color: var(--ocx-fg); } +.rb-more-toggle:focus-visible { outline: 2px solid var(--ocx-highlight); outline-offset: 2px; border-radius: 4px; } +.rb-more-body { display: flex; flex-direction: column; gap: 2px; margin-top: 6px; } +.rb-pref { display: flex; align-items: center; justify-content: space-between; gap: 16px; padding: 8px 4px; border-bottom: 1px solid var(--ocx-line); } +.rb-pref-text { display: flex; flex-direction: column; gap: 2px; min-width: 0; } +.rb-pref-name { color: var(--ocx-fg); font-size: 13px; font-weight: 500; } +.rb-pref-hint { color: var(--ocx-fg-subtle); font-size: 12.5px; line-height: 1.4; } +.rb-members { width: 100%; margin-top: 10px; border-collapse: collapse; font-size: 12.5px; } +.rb-members caption { padding: 0 4px 6px; color: var(--ocx-fg-muted); font-weight: 500; text-align: left; } +.rb-members th, .rb-members td { padding: 5px 8px; border-bottom: 1px solid var(--ocx-line); text-align: left; color: var(--ocx-fg-muted); font-weight: 400; } +.rb-members thead th { color: var(--ocx-fg-subtle); font-size: 12px; } +.rb-members tbody th { color: var(--ocx-fg); } +.rb-members tfoot th, .rb-members tfoot td { color: var(--ocx-fg); font-weight: 600; border-bottom: 0; } +.rb-members-basis { color: var(--ocx-fg-subtle); font-weight: 400; } +.rb-members-model { display: block; font-size: 11.5px; color: var(--ocx-fg-subtle); font-weight: 400; } +.rb-members-actions { text-align: right; white-space: nowrap; } +.rb-src { display: inline-block; margin-left: 4px; padding: 0 5px; border-radius: 4px; font-size: 11px; line-height: 16px; color: var(--ocx-fg-subtle); background: var(--ocx-surface-2); } +.rb-src--manual { color: var(--ocx-accent); } +.rb-src--inferred { color: var(--ocx-warning); } +.rb-src--unknown { opacity: .7; } +.rb-members-editrow td { padding-top: 0; } +.rb-member-edit { display: flex; flex-direction: column; gap: 8px; padding: 10px 12px; border: 1px solid var(--ocx-line); border-radius: 8px; } +.rb-member-field { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; } +.rb-member-field > span:first-child { min-width: 84px; color: var(--ocx-fg-muted); font-size: 12.5px; } +.rb-member-field .input { max-width: 300px; } +.rb-chips { display: inline-flex; flex-wrap: wrap; gap: 6px; } +.rb-chip { padding: 2px 10px; border: 1px solid var(--ocx-line); border-radius: 999px; background: transparent; color: var(--ocx-fg-muted); font: inherit; font-size: 12.5px; cursor: pointer; } +.rb-chip[aria-pressed="true"] { border-color: var(--ocx-accent); color: var(--ocx-fg); background: var(--ocx-accent-soft); } +.rb-member-note { margin: 0; color: var(--ocx-fg-subtle); font-size: 12.5px; } +.rb-member-error { margin: 0; color: var(--ocx-danger); font-size: 12.5px; } +.rb-member-buttons { display: flex; align-items: center; gap: 8px; } +.rb-inferred { color: var(--ocx-warning); font-size: 12.5px; } +.rb-adopt { margin-left: 4px; } +.rb-probe { display: flex; flex-direction: column; gap: 6px; padding: 8px 12px; border: 1px dashed var(--ocx-line); border-radius: 8px; } +.rb-probe-confirm { display: flex; flex-direction: column; gap: 6px; } +.rb-probe-results { margin: 0; padding-left: 18px; font-size: 12.5px; } +/* Pointer sorting, after Magpie's routing page: the row itself is lifted, the others slide aside. */ +.rb-channels.sorting { user-select: none; -webkit-user-select: none; } +.rb-channels.sorting > .rb-channel { transition: transform .22s cubic-bezier(.22, 1, .36, 1); } +.rb-channels > .rb-channel.dragging { position: relative; z-index: 2; background: var(--ocx-surface-2); cursor: grabbing; transition: none; will-change: transform; + box-shadow: 0 6px 18px rgba(0, 0, 0, .28), 0 0 0 1px var(--ocx-line); } +.rb-channel-grip { touch-action: none; } +.rb-channel :is(button, input, [role=combobox]) { cursor: pointer; } +/* A press on the provider icon must start the row drag, not the browser's own image drag. */ +.rb-channel img, .rb-channel svg { pointer-events: none; -webkit-user-drag: none; user-select: none; } + +/* Suggested combos: same-name models across providers (T2c). Grey, above the combo list. */ +.rb-suggest { + margin-bottom: 16px; + padding: 12px 0 4px; + border-radius: 12px; + background: light-dark(var(--ocx-raised), var(--ocx-surface-2)); + box-shadow: inset 0 0 0 1px var(--ocx-line); +} +.rb-suggest-head { display: flex; flex-wrap: wrap; align-items: baseline; gap: 4px 10px; padding: 0 16px 6px; } +.rb-suggest-head strong { color: var(--ocx-fg); font-size: 14px; font-weight: 600; } +.rb-suggest-head span { color: var(--ocx-fg-subtle); font-size: 12.5px; } +.rb-suggest-exclude { display: contents; } +.rb-suggest-head .rb-suggest-exclude-toggle { margin-left: auto; color: var(--ocx-fg-subtle); font-size: 12.5px; } +.rb-suggest-exclude-panel { + flex-basis: 100%; + margin: 6px 0 4px; + padding: 8px 12px 10px; + border: 0; + border-radius: 10px; + box-shadow: inset 0 0 0 1px var(--ocx-line); +} +.rb-suggest-exclude-panel legend { float: left; width: 100%; padding: 0; color: var(--ocx-fg); font-size: 13px; font-weight: 600; } +.rb-suggest-exclude-panel ul { display: flex; flex-wrap: wrap; gap: 4px 14px; list-style: none; margin: 6px 0 0; padding: 0; } +.rb-suggest-exclude-panel li { display: inline-flex; align-items: center; gap: 4px; } +.rb-suggest-exclude-panel label { display: inline-flex; align-items: center; gap: 6px; cursor: pointer; } +.rb-suggest-head .rb-suggest-exclude-panel span { color: var(--ocx-fg); font-size: 13px; } +.rb-suggest-empty { padding: 0 16px 8px; } +.rb-suggest-list { list-style: none; margin: 0; padding: 0; } +.rb-suggest-card + .rb-suggest-card { border-top: 1px dashed var(--ocx-line); } +.rb-suggest-actions { display: inline-flex; flex: none; gap: 6px; } +.rb-suggest-note { color: var(--ocx-fg-subtle); font-size: 12.5px; } +.rb-suggest-tier { + padding: 0 5px; + border-radius: 999px; + background: var(--ocx-accent-soft); + color: var(--ocx-fg-subtle); + font-size: 11px; +} +.rb-suggest-tier--own-subscription { background: var(--ocx-success-soft); color: var(--ocx-success); } +.rb-suggest-tier--subscription { background: var(--ocx-highlight-soft); color: var(--ocx-highlight); } +.rb-suggest-more { margin: 2px 12px 6px; } +.rb-suggest-draft { display: flex; flex-direction: column; gap: 8px; padding: 0 16px 14px 100px; } +.rb-suggest-field { display: inline-flex; align-items: center; gap: 8px; color: var(--ocx-fg-muted); font-size: 13px; } +.rb-suggest-id { width: 260px; font-family: var(--font-code); } +.rb-suggest-hint { margin: 0; color: var(--ocx-fg-subtle); font-size: 12.5px; } +.rb-suggest-members { display: flex; flex-direction: column; gap: 4px; margin: 0; padding: 0; list-style: none; counter-reset: rb-member; } +.rb-suggest-members li { + display: flex; + align-items: center; + gap: 8px; + padding: 4px 8px; + border-radius: 8px; + background: var(--ocx-surface); + box-shadow: inset 0 0 0 1px var(--ocx-line); + font-size: 13px; + counter-increment: rb-member; +} +.rb-suggest-members li::before { content: counter(rb-member); width: 14px; color: var(--ocx-fg-subtle); font-size: 12px; text-align: right; } +.rb-suggest-member-name { color: var(--ocx-fg); } +.rb-suggest-members code { color: var(--ocx-fg-muted); font-family: var(--font-code); font-size: 12px; } +.rb-suggest-move { display: inline-flex; gap: 2px; margin-left: auto; } +.rb-suggest-icon-btn { min-width: 28px; padding-inline: 6px; } +.rb-suggest-draft-actions { display: flex; align-items: center; justify-content: flex-end; gap: 8px; } +.rb-suggest-draft-actions .rb-suggest-note { margin-right: auto; } +@media (max-width: 760px) { .rb-suggest-draft { padding-left: 16px; } } +.rb-suggest-card .rb-row-body { flex: 1 1 auto; } diff --git a/gui/src/design/theme.css b/gui/src/design/theme.css index 023bb717c16..70f678f355a 100644 --- a/gui/src/design/theme.css +++ b/gui/src/design/theme.css @@ -32,6 +32,7 @@ /* v1 classes repainted with v2 tokens while pages migrate (see bridge.css) */ @import "./bridge.css" layer(bridge); @import "./pages/models.css" layer(bridge); +@import "./pages/route-board.css" layer(bridge); @import "./pages/accounts.css" layer(bridge); @import "./pages/subagents.css" layer(bridge); @import "./pages/usage.css" layer(bridge); diff --git a/gui/src/i18n/de.ts b/gui/src/i18n/de.ts index 234541ce8ca..1e0ff031238 100644 --- a/gui/src/i18n/de.ts +++ b/gui/src/i18n/de.ts @@ -4506,4 +4506,152 @@ export const de: Record = { "remoteLink.error.policy_write_failed": "Die Child-Richtlinie konnte nicht gespeichert werden.", "remoteLink.error.runtime_role_client": "Dieser Computer ist ein Child; nur ein Home kann Children bedienen.", "remoteLink.error.link_not_home_initiated": "Dieser Child hat sich selbst verbunden; bedienen Sie ihn von seinem eigenen Computer aus.", + "routeBoard.lede": "Jede Combo, die Kanäle dahinter und die Reihenfolge, in der sie genutzt werden. Strategie und Ein/Aus direkt in der Zeile ändern; Zeile anklicken, um die Kanäle zu bearbeiten.", + "routeBoard.advanced": "Erweitert", + "routeBoard.advancedHint": "Vollständiger Combo-Editor: Aliasse, JEV-Entscheidungsdienst, Reasoning-Stufe, Bildeingabe, native Aliasse.", + "routeBoard.backToOverview": "Zurück zur Übersicht", + "routeBoard.empty": "Noch keine Combos. Eine Combo zeigt Clients einen Modellnamen und verteilt ihn auf mehrere Anbieter.", + "routeBoard.listAria": "Combos", + "routeBoard.window.weekly": "Woche", + "routeBoard.window.fiveHour": "5 Std.", + "routeBoard.window.monthly": "Monat", + "routeBoard.quota.left": "{window} {percent}% übrig", + "routeBoard.quota.accounts": "{provider} ({count} Konten)", + "routeBoard.quota.metered": "nutzungsbasiert", + "routeBoard.quota.unknown": "keine Kontingentdaten", + "routeBoard.lastResort": "nur als Reserve", + "routeBoard.tag.channelsOff": "{count} aus", + "routeBoard.tag.sticky": "haftend ×{count}", + "routeBoard.tag.noImages": "nur Text", + "routeBoard.context": "Kontext {size}", + "routeBoard.contextHint": "Anklicken, um zu sehen, wie diese Zahl zustande kommt.", + "routeBoard.strategyLabel": "Strategie für {model}", + "routeBoard.enabledLabel": "{model} für Clients anbieten", + "routeBoard.enabledHint": "Aus behält die Einstellungen der Combo, bietet sie Clients aber nicht mehr an.", + "routeBoard.notSaved": "Nicht gespeichert: {reason}", + "routeBoard.jevInAdvanced": "JEV braucht einen Entscheidungsdienst. Stellen Sie hier die Strategie auf JEV, prüfen Sie, welcher Dienst entscheidet, und speichern Sie dann.", + "routeBoard.edit.aria": "Kanäle für {model}", + "routeBoard.edit.drag": "Zum Sortieren ziehen", + "routeBoard.edit.lastResortHint": "Nur als Reserve: wird erst genutzt, wenn kein anderer Kanal verfügbar ist.", + "routeBoard.edit.lastResortInert": "Nicht wirksam: Schalten Sie unter „Weitere Einstellungen“ „Reservekanäle kommen zuletzt“ ein. Bis dahin wird dieser Kanal wie die anderen der Reihe nach genutzt.", + "routeBoard.edit.moveUp": "{name} nach oben", + "routeBoard.edit.moveDown": "{name} nach unten", + "routeBoard.edit.remove": "{name} entfernen", + "routeBoard.edit.provider": "Anbieter", + "routeBoard.edit.model": "Modell", + "routeBoard.edit.noModels": "Keine weiteren Modelle", + "routeBoard.edit.add": "Kanal hinzufügen", + "routeBoard.edit.more": "Weitere Einstellungen", + "routeBoard.edit.unsaved": "Nicht gespeichert", + "routeBoard.locked": "ungespeichert in Erweitert", + "routeBoard.lockedHint": "Diese Combo hat ungespeicherte Änderungen im erweiterten Editor. Speichern oder verwerfen Sie sie dort, bevor Sie sie hier ändern.", + "routeBoard.strategyHint.failover": "Der Reihe nach: Der erste funktionierende Kanal bleibt in Gebrauch; erst bei leerem Kontingent, Ratenlimit oder Fehler geht es zum nächsten, und nur bevor die Antwort beginnt.", + "routeBoard.strategyHint.roundRobin": "Abwechselnd: Jede Anfrage geht an den nächsten Kanal, das Kontingent verteilt sich.", + "routeBoard.strategyHint.random": "Zufällig: Jede Anfrage nimmt zufällig einen funktionierenden Kanal.", + "routeBoard.strategyHint.leastUsed": "Am wenigsten genutzt: Der zuletzt am seltensten genutzte Kanal kommt zuerst.", + "routeBoard.strategyHint.resetWindow": "Früheste Zurücksetzung zuerst: Konten, deren Kontingent bald zurückgesetzt wird, kommen zuerst dran, damit nichts verfällt.", + "routeBoard.strategyHint.jev": "Intelligent: Ein kleines Modell liest die Anfrage zuerst und wählt Kanal und Reasoning-Stufe.", + "routeBoard.quota.family": "{family} · {window}", + "routeBoard.quota.paused": "(+{count} pausiert)", + "routeBoard.cap.title": "Fähigkeiten", + "routeBoard.cap.intersection": "Schnittmenge", + "routeBoard.cap.intersectionHint": "Schnittmenge: Das Kontextfenster ist das des kleinsten Mitglieds; Bilder und Reasoning-Stufen zählen nur, wenn alle Mitglieder sie können.", + "routeBoard.cap.union": "Vereinigung", + "routeBoard.cap.unionHint": "Vereinigung: Das größte Mitglied wird angeboten; passt eine Anfrage nicht oder braucht sie Bilder oder eine höhere Stufe, werden ungeeignete Mitglieder übersprungen.", + "routeBoard.cap.unservable": "Wenn kein Kanal sie bedienen kann", + "routeBoard.cap.degrade": "Abschwächen", + "routeBoard.cap.degradeHint": "Den Teil weglassen, den kein Kanal unterstützt (etwa ein Bild), und trotzdem antworten.", + "routeBoard.cap.reject": "Ablehnen", + "routeBoard.cap.rejectHint": "Einen Fehler zurückgeben, statt ohne diesen Teil zu antworten.", + "routeBoard.more.fallbackOnly": "Reservekanäle kommen zuletzt", + "routeBoard.more.fallbackOnlyHint": "Ein: Als Reserve markierte Kanäle werden übersprungen, solange ein anderer Kanal funktioniert. Aus: Sie werden wie die anderen der Reihe nach genutzt.", + "routeBoard.members.title": "Woher die Zahlen der Combo kommen", + "routeBoard.members.channel": "Kanal", + "routeBoard.members.context": "Kontext", + "routeBoard.members.input": "Eingabe", + "routeBoard.members.efforts": "Reasoning-Stufen", + "routeBoard.members.text": "Text", + "routeBoard.members.image": "Bilder", + "routeBoard.members.unknown": "unbekannt", + "routeBoard.members.none": "keine", + "routeBoard.members.combo": "Diese Combo", + "routeBoard.contextBasis.min": "(kleinstes Mitglied)", + "routeBoard.contextBasis.max": "(größtes Mitglied)", + "routeBoard.source.reported": "Anbieterangabe", + "routeBoard.source.inferred": "von gleichnamigem Modell abgeleitet", + "routeBoard.source.manual": "manuell", + "routeBoard.source.unknown": "unbekannt", + "routeBoard.members.actions": "Aktionen", + "routeBoard.members.edit": "Bearbeiten", + "routeBoard.members.editAria": "Bearbeiten, was {name} annimmt", + "routeBoard.members.contextPlaceholder": "z. B. 200K oder 1M; leer behält den Anbieterwert", + "routeBoard.members.contextInvalid": "Gib eine Tokenzahl ein, etwa 200000, 200K oder 1M.", + "routeBoard.members.scopeNote": "Wird bei {name} selbst gespeichert: Jede Kombination mit diesem Modell ändert sich mit.", + "routeBoard.members.restore": "Anbieterwerte verwenden", + "routeBoard.probe.run": "Testen", + "routeBoard.source.probed": "getestet", + "routeBoard.basis.registry": "integrierte Tabelle von {provider}", + "routeBoard.basis.vendor": "Modelldaten von {provider}", + "routeBoard.basis.provider": "konfigurierter Anbieter {provider}", + "routeBoard.basis.aggregator": "Katalog von {provider}", + "routeBoard.inferred.cell": "abgeleitet {value} (laut {basis})", + "routeBoard.inferred.adopt": "Übernehmen", + "routeBoard.inferred.adoptAria": "Abgeleiteten Wert {value} für {name} als manuelle Einstellung speichern", + "routeBoard.members.includesInferred": "enthält abgeleitete Werte", + "routeBoard.probe.runAria": "Testen, was {name} annimmt", + "routeBoard.probe.running": "Test läuft…", + "routeBoard.probe.confirmTitle": "Kostenpflichtigen Test bestätigen", + "routeBoard.probe.confirm": "Dieser Anbieter rechnet nach Nutzung ab: Der Test sendet {count} sehr kleine Anfragen. Fortfahren?", + "routeBoard.probe.confirmGo": "Test starten", + "routeBoard.probe.reason.disabled": "Kein Test möglich: Dieser Anbieter ist ausgeschaltet.", + "routeBoard.probe.reason.forward_auth": "Kein Test möglich: Dieser Anbieter leitet die Anmeldung des Clients weiter.", + "routeBoard.probe.reason.oauth_auth": "Kein Test möglich: Abo-Anmeldungen werden nicht getestet.", + "routeBoard.probe.reason.unsupported_adapter": "Kein Test möglich: Nur OpenAI-kompatible Endpunkte lassen sich testen.", + "routeBoard.probe.reason.unsupported_transport": "Kein Test möglich: Die Verbindungsart dieses Anbieters wird nicht unterstützt.", + "routeBoard.probe.reason.other": "Dieser Anbieter lässt sich nicht testen.", + "routeBoard.probe.busy": "Dieser Anbieter wird gerade getestet.", + "routeBoard.probe.failed": "Der Test wurde nicht abgeschlossen. Nichts wurde geändert.", + "routeBoard.probe.uncertain": "Unklar: Die einfache Anfrage kam nicht durch, daher wurde nichts geändert.", + "routeBoard.probe.image": "Bilder: {status}", + "routeBoard.probe.accepted": "angenommen", + "routeBoard.probe.rejected": "abgelehnt", + "routeBoard.probe.inconclusive": "unklar", + "routeBoard.probe.efforts": "Stufen angenommen: {accepted}; abgelehnt: {rejected}; unklar: {inconclusive}", + "routeBoard.probe.appliedInput": "gespeicherte Eingabe: {value}", + "routeBoard.probe.appliedEfforts": "gespeicherte Stufen: {value}", + "routeBoard.probe.nothingApplied": "Nichts eindeutig, daher nichts gespeichert.", + "routeBoard.probe.contextNote": "Der Kontext wird aus dem Modellnamen abgeleitet, nicht gemessen.", + "routeBoard.probe.close": "Schließen", + "comboSuggest.title": "Vorgeschlagene Combos", + "comboSuggest.lede": "Modelle, die mehr als einer Ihrer Anbieter unter demselben Namen bereitstellt. Erstellen Sie eine Combo, um einen Modellnamen über alle diese Anbieter zu routen.", + "comboSuggest.servedBy": "bereitgestellt von {count} Anbietern", + "comboSuggest.canAdd": "kann auch {providers} nutzen", + "comboSuggest.generate": "Erstellen", + "comboSuggest.addTo": "Zur Combo hinzufügen", + "comboSuggest.dismiss": "Ausblenden", + "models.latestPerFamily": "Neuestes je Familie", + "models.latestPerFamilyHint": "Nur das neueste Modell jeder Familie zeigen", + "comboSuggest.exclude.button": "Anbieter ausnehmen…", + "comboSuggest.exclude.active": "Ausgenommen: {names}", + "comboSuggest.exclude.head": "Aus vorgeschlagenen Kombis ausnehmen", + "comboSuggest.exclude.hint": "Ihre Modelle kommen in keine vorgeschlagene Kombi; bestehende Kombis behalten sie.", + "comboSuggest.exclude.restore": "Wiederherstellen", + "comboSuggest.exclude.saveFailed": "Die ausgenommenen Anbieter konnten nicht gespeichert werden.", + "comboSuggest.exclude.none": "Ohne diese Anbieter bleiben keine Vorschläge.", + "comboSuggest.showAll": "Alle {count} anzeigen", + "comboSuggest.showFewer": "Weniger anzeigen", + "comboSuggest.tier.ownSubscription": "Abo des Herstellers", + "comboSuggest.tier.subscription": "Abo", + "comboSuggest.tier.vertex": "Vertex-Guthaben", + "comboSuggest.tier.metered": "nutzungsabhängig", + "comboSuggest.draft.id": "Combo-ID", + "comboSuggest.draft.orderHint": "Die Reihenfolge von oben nach unten: zuerst Abos, dann Vertex-Guthaben, zuletzt Keys mit nutzungsabhängiger Abrechnung und Relays. Vor dem Speichern umsortieren oder entfernen.", + "comboSuggest.draft.left": "{percent}% übrig", + "comboSuggest.draft.up": "Nach oben", + "comboSuggest.draft.down": "Nach unten", + "comboSuggest.draft.remove": "Entfernen", + "comboSuggest.draft.strategy": "Strategie: Failover. Nach dem Speichern in der Zeile ändern.", + "comboSuggest.draft.cancel": "Abbrechen", + "comboSuggest.draft.save": "Combo speichern", + "comboSuggest.draft.saving": "Wird gespeichert…", }; diff --git a/gui/src/i18n/en.ts b/gui/src/i18n/en.ts index 76381be2404..e289a3c55c9 100644 --- a/gui/src/i18n/en.ts +++ b/gui/src/i18n/en.ts @@ -4540,6 +4540,154 @@ export const en = { "remoteLink.error.policy_write_failed": "The Child policy could not be saved.", "remoteLink.error.runtime_role_client": "This computer is a Child; only a Home can operate Children.", "remoteLink.error.link_not_home_initiated": "This Child linked itself, so operate it from its own computer.", + "routeBoard.lede": "Every combo, the channels behind it and the order they are used in. Change the strategy or switch a combo off right in its row; click a row to edit its channels.", + "routeBoard.advanced": "Advanced", + "routeBoard.advancedHint": "Full combo editor: aliases, JEV decision service, effort, image input, native aliases.", + "routeBoard.backToOverview": "Back to overview", + "routeBoard.empty": "No combos yet. A combo lists one model name to clients and routes it across several providers.", + "routeBoard.listAria": "Combos", + "routeBoard.window.weekly": "weekly", + "routeBoard.window.fiveHour": "5h", + "routeBoard.window.monthly": "monthly", + "routeBoard.quota.left": "{window} {percent}% left", + "routeBoard.quota.accounts": "{provider} ({count} accounts)", + "routeBoard.quota.metered": "pay per use", + "routeBoard.quota.unknown": "no quota data", + "routeBoard.lastResort": "fallback only", + "routeBoard.tag.channelsOff": "{count} off", + "routeBoard.tag.sticky": "sticky ×{count}", + "routeBoard.tag.noImages": "text only", + "routeBoard.context": "ctx {size}", + "routeBoard.contextHint": "Click to see how this number is worked out.", + "routeBoard.strategyLabel": "Strategy for {model}", + "routeBoard.enabledLabel": "List {model} to clients", + "routeBoard.enabledHint": "Off keeps the combo's settings but stops listing it to clients.", + "routeBoard.notSaved": "Not saved: {reason}", + "routeBoard.jevInAdvanced": "JEV needs a decision service. Switch the strategy to JEV here, check which service decides, then save.", + "routeBoard.edit.aria": "Channels for {model}", + "routeBoard.edit.drag": "Drag to reorder", + "routeBoard.edit.lastResortHint": "Fallback only: used only when every other channel is unavailable.", + "routeBoard.edit.lastResortInert": "Not in effect: turn on “Fallback channels wait their turn” under More settings. Until then this channel is used in order like the others.", + "routeBoard.edit.moveUp": "Move {name} up", + "routeBoard.edit.moveDown": "Move {name} down", + "routeBoard.edit.remove": "Remove {name}", + "routeBoard.edit.provider": "Provider", + "routeBoard.edit.model": "Model", + "routeBoard.edit.noModels": "No other models", + "routeBoard.edit.add": "Add channel", + "routeBoard.edit.more": "More settings", + "routeBoard.edit.unsaved": "Unsaved", + "routeBoard.locked": "unsaved in Advanced", + "routeBoard.lockedHint": "This combo has unsaved changes in the Advanced editor. Save or discard them there before changing it here.", + "routeBoard.strategyHint.failover": "In order: keep using the first channel that works; when its quota runs out, it is rate-limited or errors, move to the next, only before the reply starts.", + "routeBoard.strategyHint.roundRobin": "Take turns: each request goes to the next channel, spreading the quota.", + "routeBoard.strategyHint.random": "Random: each request picks one working channel at random.", + "routeBoard.strategyHint.leastUsed": "Least used: the channel used least recently goes first.", + "routeBoard.strategyHint.resetWindow": "Soonest reset first: accounts whose quota resets soonest are used first, so nothing goes to waste at the reset.", + "routeBoard.strategyHint.jev": "Smart: a small model reads the request first, then picks the channel and how hard to think.", + "routeBoard.quota.family": "{family} · {window}", + "routeBoard.quota.paused": "(+{count} paused)", + "routeBoard.cap.title": "Capabilities", + "routeBoard.cap.intersection": "Intersection", + "routeBoard.cap.intersectionHint": "Intersection: the context window is the smallest member's, and images or effort levels count only if every member supports them.", + "routeBoard.cap.union": "Union", + "routeBoard.cap.unionHint": "Union: advertise the largest member; a request that does not fit, or needs images or a higher effort, skips the members that cannot take it.", + "routeBoard.cap.unservable": "When no channel can serve it", + "routeBoard.cap.degrade": "Degrade", + "routeBoard.cap.degradeHint": "Drop the part no channel supports (an image, say) and answer anyway.", + "routeBoard.cap.reject": "Reject", + "routeBoard.cap.rejectHint": "Return an error instead of answering without that part.", + "routeBoard.more.fallbackOnly": "Fallback channels wait their turn", + "routeBoard.more.fallbackOnlyHint": "On: channels marked fallback only are skipped while any other channel works. Off: they are used in order like the rest.", + "routeBoard.members.title": "Where the combo's numbers come from", + "routeBoard.members.channel": "Channel", + "routeBoard.members.context": "Context", + "routeBoard.members.input": "Input", + "routeBoard.members.efforts": "Effort levels", + "routeBoard.members.text": "text", + "routeBoard.members.image": "images", + "routeBoard.members.unknown": "unknown", + "routeBoard.members.none": "none", + "routeBoard.members.combo": "This combo", + "routeBoard.contextBasis.min": "(smallest member)", + "routeBoard.contextBasis.max": "(largest member)", + "routeBoard.source.reported": "provider report", + "routeBoard.source.inferred": "inferred from same-name model", + "routeBoard.source.manual": "manual", + "routeBoard.source.unknown": "unknown", + "routeBoard.members.actions": "Actions", + "routeBoard.members.edit": "Edit", + "routeBoard.members.editAria": "Edit what {name} can take", + "routeBoard.members.contextPlaceholder": "e.g. 200K or 1M; empty keeps the provider's value", + "routeBoard.members.contextInvalid": "Enter a token count such as 200000, 200K or 1M.", + "routeBoard.members.scopeNote": "Saved to {name} itself: every combo that uses this model changes too.", + "routeBoard.members.restore": "Use the provider's values", + "routeBoard.probe.run": "Test it", + "routeBoard.source.probed": "probed", + "routeBoard.basis.registry": "{provider} built-in table", + "routeBoard.basis.vendor": "{provider} model metadata", + "routeBoard.basis.provider": "configured {provider}", + "routeBoard.basis.aggregator": "{provider} catalog", + "routeBoard.inferred.cell": "inferred {value} (based on {basis})", + "routeBoard.inferred.adopt": "Adopt", + "routeBoard.inferred.adoptAria": "Save the inferred {value} for {name} as a manual setting", + "routeBoard.members.includesInferred": "includes inferred", + "routeBoard.probe.runAria": "Test what {name} accepts", + "routeBoard.probe.running": "Testing…", + "routeBoard.probe.confirmTitle": "Confirm a paid test", + "routeBoard.probe.confirm": "This provider bills per use: the test sends {count} very small requests. Go ahead?", + "routeBoard.probe.confirmGo": "Run the test", + "routeBoard.probe.reason.disabled": "Can't test: this provider is turned off.", + "routeBoard.probe.reason.forward_auth": "Can't test: this provider forwards the client's own login.", + "routeBoard.probe.reason.oauth_auth": "Can't test: subscription logins are not probed.", + "routeBoard.probe.reason.unsupported_adapter": "Can't test: only OpenAI-compatible endpoints can be probed.", + "routeBoard.probe.reason.unsupported_transport": "Can't test: this provider's connection type is not supported.", + "routeBoard.probe.reason.other": "Can't test this provider.", + "routeBoard.probe.busy": "This provider is already being tested.", + "routeBoard.probe.failed": "The test did not finish. Nothing was changed.", + "routeBoard.probe.uncertain": "Inconclusive: the plain request did not go through, so nothing was changed.", + "routeBoard.probe.image": "Images: {status}", + "routeBoard.probe.accepted": "accepted", + "routeBoard.probe.rejected": "refused", + "routeBoard.probe.inconclusive": "unclear", + "routeBoard.probe.efforts": "Effort levels accepted: {accepted}; refused: {rejected}; unclear: {inconclusive}", + "routeBoard.probe.appliedInput": "saved input: {value}", + "routeBoard.probe.appliedEfforts": "saved effort levels: {value}", + "routeBoard.probe.nothingApplied": "Nothing conclusive, so nothing was saved.", + "routeBoard.probe.contextNote": "Context is inferred from the model name, not measured.", + "routeBoard.probe.close": "Close", + "comboSuggest.title": "Suggested combos", + "comboSuggest.lede": "Models that more than one of your providers serve under the same name. Generate a combo to route one model name across all of them.", + "comboSuggest.servedBy": "served by {count} providers", + "comboSuggest.canAdd": "can also use {providers}", + "comboSuggest.generate": "Generate", + "comboSuggest.addTo": "Add to combo", + "comboSuggest.dismiss": "Dismiss", + "models.latestPerFamily": "Latest per family", + "models.latestPerFamilyHint": "Show only the newest model of each family", + "comboSuggest.exclude.button": "Exclude a provider…", + "comboSuggest.exclude.active": "Excluded: {names}", + "comboSuggest.exclude.head": "Leave out of suggested combos", + "comboSuggest.exclude.hint": "Their models join no suggested combo; combos you already made keep them.", + "comboSuggest.exclude.restore": "Restore", + "comboSuggest.exclude.saveFailed": "Could not save the excluded providers.", + "comboSuggest.exclude.none": "No suggestions left with these providers excluded.", + "comboSuggest.showAll": "Show all {count}", + "comboSuggest.showFewer": "Show fewer", + "comboSuggest.tier.ownSubscription": "maker's subscription", + "comboSuggest.tier.subscription": "subscription", + "comboSuggest.tier.vertex": "Vertex credit", + "comboSuggest.tier.metered": "pay per use", + "comboSuggest.draft.id": "Combo id", + "comboSuggest.draft.orderHint": "Tried top to bottom: subscriptions first, then Vertex credit, pay-per-use keys and relays last. Reorder or remove before saving.", + "comboSuggest.draft.left": "{percent}% left", + "comboSuggest.draft.up": "Move up", + "comboSuggest.draft.down": "Move down", + "comboSuggest.draft.remove": "Remove", + "comboSuggest.draft.strategy": "Strategy: failover. Change it in the row after saving.", + "comboSuggest.draft.cancel": "Cancel", + "comboSuggest.draft.save": "Save combo", + "comboSuggest.draft.saving": "Saving…", } as const; export type TKey = keyof typeof en; diff --git a/gui/src/i18n/fr.ts b/gui/src/i18n/fr.ts index f0314b0c16e..e30eaa8b5bd 100644 --- a/gui/src/i18n/fr.ts +++ b/gui/src/i18n/fr.ts @@ -4495,4 +4495,152 @@ export const fr: Record = { "remoteLink.error.policy_write_failed": "La politique de l’Enfant n’a pas pu être enregistrée.", "remoteLink.error.runtime_role_client": "Cet ordinateur est un Enfant ; seul un Home peut piloter des Enfants.", "remoteLink.error.link_not_home_initiated": "Cet Enfant s’est connecté lui-même ; pilotez-le depuis son propre ordinateur.", + "routeBoard.lede": "Chaque combo, les canaux qui la servent et l’ordre dans lequel ils sont utilisés. Changez la stratégie ou désactivez une combo directement dans sa ligne ; cliquez sur une ligne pour modifier ses canaux.", + "routeBoard.advanced": "Avancé", + "routeBoard.advancedHint": "Éditeur complet des combos : alias, service de décision JEV, niveau de raisonnement, entrée d’images, alias natifs.", + "routeBoard.backToOverview": "Retour à la vue d’ensemble", + "routeBoard.empty": "Aucune combo pour l’instant. Une combo présente un seul nom de modèle aux clients et le répartit entre plusieurs fournisseurs.", + "routeBoard.listAria": "Liste des combos", + "routeBoard.window.weekly": "semaine", + "routeBoard.window.fiveHour": "5 h", + "routeBoard.window.monthly": "mois", + "routeBoard.quota.left": "{window} : {percent} % restants", + "routeBoard.quota.accounts": "{provider} ({count} comptes)", + "routeBoard.quota.metered": "à l’usage", + "routeBoard.quota.unknown": "pas de données de quota", + "routeBoard.lastResort": "secours uniquement", + "routeBoard.tag.channelsOff": "{count} désactivés", + "routeBoard.tag.sticky": "collant ×{count}", + "routeBoard.tag.noImages": "texte seul", + "routeBoard.context": "contexte {size}", + "routeBoard.contextHint": "Cliquez pour voir comment ce nombre est calculé.", + "routeBoard.strategyLabel": "Stratégie de {model}", + "routeBoard.enabledLabel": "Proposer {model} aux clients", + "routeBoard.enabledHint": "Désactivée, la combo garde ses réglages mais n’est plus proposée aux clients.", + "routeBoard.notSaved": "Non enregistré : {reason}", + "routeBoard.jevInAdvanced": "JEV a besoin d’un service de décision. Passez ici la stratégie à JEV, vérifiez quel service décide, puis enregistrez.", + "routeBoard.edit.aria": "Canaux de {model}", + "routeBoard.edit.drag": "Glisser pour réordonner", + "routeBoard.edit.lastResortHint": "Secours uniquement : utilisé seulement quand aucun autre canal n’est disponible.", + "routeBoard.edit.lastResortInert": "Sans effet : activez « Les canaux de secours passent en dernier » dans Plus de réglages. D’ici là, ce canal est utilisé dans l’ordre comme les autres.", + "routeBoard.edit.moveUp": "Monter {name}", + "routeBoard.edit.moveDown": "Descendre {name}", + "routeBoard.edit.remove": "Retirer {name}", + "routeBoard.edit.provider": "Fournisseur", + "routeBoard.edit.model": "Modèle", + "routeBoard.edit.noModels": "Aucun autre modèle", + "routeBoard.edit.add": "Ajouter un canal", + "routeBoard.edit.more": "Plus de réglages", + "routeBoard.edit.unsaved": "Non enregistré", + "routeBoard.locked": "non enregistré dans Avancé", + "routeBoard.lockedHint": "Cette combo a des modifications non enregistrées dans l’éditeur avancé. Enregistrez-les ou abandonnez-les là-bas avant de la modifier ici.", + "routeBoard.strategyHint.failover": "Dans l’ordre : le premier canal qui fonctionne reste utilisé ; quand son quota est épuisé, qu’il est limité ou en erreur, on passe au suivant, et seulement avant le début de la réponse.", + "routeBoard.strategyHint.roundRobin": "À tour de rôle : chaque requête va au canal suivant, ce qui répartit le quota.", + "routeBoard.strategyHint.random": "Aléatoire : chaque requête prend un canal disponible au hasard.", + "routeBoard.strategyHint.leastUsed": "Le moins utilisé : le canal le moins utilisé récemment passe en premier.", + "routeBoard.strategyHint.resetWindow": "Réinitialisation la plus proche d’abord : les comptes dont le quota se réinitialise bientôt passent en premier, pour ne rien perdre.", + "routeBoard.strategyHint.jev": "Intelligent : un petit modèle lit d’abord la requête, puis choisit le canal et le niveau de raisonnement.", + "routeBoard.quota.family": "{family} · {window}", + "routeBoard.quota.paused": "(+{count} en pause)", + "routeBoard.cap.title": "Capacités", + "routeBoard.cap.intersection": "Intersection des capacités", + "routeBoard.cap.intersectionHint": "Intersection : la fenêtre de contexte est celle du plus petit membre ; images et niveaux de raisonnement ne comptent que si tous les membres les gèrent.", + "routeBoard.cap.union": "Réunion des capacités", + "routeBoard.cap.unionHint": "Réunion : on annonce le plus grand membre ; une requête trop longue, ou qui demande des images ou plus de raisonnement, saute les membres qui ne peuvent pas la prendre.", + "routeBoard.cap.unservable": "Quand aucun canal ne peut la servir", + "routeBoard.cap.degrade": "Dégrader", + "routeBoard.cap.degradeHint": "Retirer la partie qu’aucun canal ne gère (une image, par exemple) et répondre quand même.", + "routeBoard.cap.reject": "Refuser", + "routeBoard.cap.rejectHint": "Renvoyer une erreur plutôt que répondre sans cette partie.", + "routeBoard.more.fallbackOnly": "Les canaux de secours passent en dernier", + "routeBoard.more.fallbackOnlyHint": "Activé : les canaux marqués secours sont sautés tant qu’un autre canal fonctionne. Désactivé : ils sont utilisés dans l’ordre comme les autres.", + "routeBoard.members.title": "D’où viennent les chiffres de la combo", + "routeBoard.members.channel": "Canal", + "routeBoard.members.context": "Contexte", + "routeBoard.members.input": "Entrée", + "routeBoard.members.efforts": "Niveaux de raisonnement", + "routeBoard.members.text": "texte", + "routeBoard.members.image": "image", + "routeBoard.members.unknown": "inconnu", + "routeBoard.members.none": "aucun", + "routeBoard.members.combo": "Cette combo", + "routeBoard.contextBasis.min": "(plus petit membre)", + "routeBoard.contextBasis.max": "(plus grand membre)", + "routeBoard.source.reported": "déclaré par le fournisseur", + "routeBoard.source.inferred": "déduit d'un modèle homonyme", + "routeBoard.source.manual": "saisi à la main", + "routeBoard.source.unknown": "inconnu", + "routeBoard.members.actions": "Actions possibles", + "routeBoard.members.edit": "Modifier", + "routeBoard.members.editAria": "Modifier ce que {name} accepte", + "routeBoard.members.contextPlaceholder": "ex. 200K ou 1M ; vide garde la valeur du fournisseur", + "routeBoard.members.contextInvalid": "Saisissez un nombre de jetons, par exemple 200000, 200K ou 1M.", + "routeBoard.members.scopeNote": "Enregistré sur {name} lui-même : chaque combo qui utilise ce modèle change aussi.", + "routeBoard.members.restore": "Reprendre les valeurs du fournisseur", + "routeBoard.probe.run": "Tester", + "routeBoard.source.probed": "testé", + "routeBoard.basis.registry": "table intégrée de {provider}", + "routeBoard.basis.vendor": "métadonnées de {provider}", + "routeBoard.basis.provider": "fournisseur configuré {provider}", + "routeBoard.basis.aggregator": "catalogue de {provider}", + "routeBoard.inferred.cell": "déduit {value} (d'après {basis})", + "routeBoard.inferred.adopt": "Adopter", + "routeBoard.inferred.adoptAria": "Enregistrer la valeur déduite {value} pour {name} comme réglage manuel", + "routeBoard.members.includesInferred": "inclut des valeurs déduites", + "routeBoard.probe.runAria": "Tester ce que {name} accepte", + "routeBoard.probe.running": "Test en cours…", + "routeBoard.probe.confirmTitle": "Confirmer un test payant", + "routeBoard.probe.confirm": "Ce fournisseur facture à l'usage : le test envoie {count} toutes petites requêtes. Continuer ?", + "routeBoard.probe.confirmGo": "Lancer le test", + "routeBoard.probe.reason.disabled": "Test impossible : ce fournisseur est désactivé.", + "routeBoard.probe.reason.forward_auth": "Test impossible : ce fournisseur relaie la connexion du client.", + "routeBoard.probe.reason.oauth_auth": "Test impossible : les connexions par abonnement ne sont pas testées.", + "routeBoard.probe.reason.unsupported_adapter": "Test impossible : seuls les points d'accès compatibles OpenAI se testent.", + "routeBoard.probe.reason.unsupported_transport": "Test impossible : le type de connexion de ce fournisseur n'est pas pris en charge.", + "routeBoard.probe.reason.other": "Ce fournisseur ne peut pas être testé.", + "routeBoard.probe.busy": "Ce fournisseur est déjà en cours de test.", + "routeBoard.probe.failed": "Le test n'a pas abouti. Rien n'a été modifié.", + "routeBoard.probe.uncertain": "Résultat incertain : la requête simple n'est pas passée, rien n'a été modifié.", + "routeBoard.probe.image": "Images : {status}", + "routeBoard.probe.accepted": "acceptées", + "routeBoard.probe.rejected": "refusées", + "routeBoard.probe.inconclusive": "incertain", + "routeBoard.probe.efforts": "Niveaux acceptés : {accepted} ; refusés : {rejected} ; incertains : {inconclusive}", + "routeBoard.probe.appliedInput": "entrée enregistrée : {value}", + "routeBoard.probe.appliedEfforts": "niveaux enregistrés : {value}", + "routeBoard.probe.nothingApplied": "Rien de concluant, donc rien n'a été enregistré.", + "routeBoard.probe.contextNote": "Le contexte est déduit du nom du modèle, pas mesuré.", + "routeBoard.probe.close": "Fermer", + "comboSuggest.title": "Combinaisons suggérées", + "comboSuggest.lede": "Modèles que plusieurs de vos fournisseurs proposent sous le même nom. Générez une combinaison pour router un seul nom de modèle vers tous ces fournisseurs.", + "comboSuggest.servedBy": "proposé par {count} fournisseurs", + "comboSuggest.canAdd": "peut aussi utiliser {providers}", + "comboSuggest.generate": "Générer", + "comboSuggest.addTo": "Ajouter à la combinaison", + "comboSuggest.dismiss": "Ignorer", + "models.latestPerFamily": "Dernier par famille", + "models.latestPerFamilyHint": "N'afficher que le modèle le plus récent de chaque famille", + "comboSuggest.exclude.button": "Exclure un fournisseur…", + "comboSuggest.exclude.active": "Exclus : {names}", + "comboSuggest.exclude.head": "Exclure des combos suggérés", + "comboSuggest.exclude.hint": "Leurs modèles n'entrent dans aucun combo suggéré ; vos combos existants les gardent.", + "comboSuggest.exclude.restore": "Rétablir", + "comboSuggest.exclude.saveFailed": "Impossible d'enregistrer les fournisseurs exclus.", + "comboSuggest.exclude.none": "Aucune suggestion ne reste avec ces fournisseurs exclus.", + "comboSuggest.showAll": "Afficher les {count}", + "comboSuggest.showFewer": "Afficher moins", + "comboSuggest.tier.ownSubscription": "abonnement de l’éditeur", + "comboSuggest.tier.subscription": "abonnement", + "comboSuggest.tier.vertex": "crédit Vertex", + "comboSuggest.tier.metered": "paiement à l’usage", + "comboSuggest.draft.id": "Identifiant de la combinaison", + "comboSuggest.draft.orderHint": "Testés de haut en bas : les abonnements d’abord, puis le crédit Vertex, les clés à l’usage et les relais en dernier. Réordonnez ou retirez des éléments avant d’enregistrer.", + "comboSuggest.draft.left": "{percent} % restants", + "comboSuggest.draft.up": "Monter", + "comboSuggest.draft.down": "Descendre", + "comboSuggest.draft.remove": "Retirer", + "comboSuggest.draft.strategy": "Stratégie : basculement. Modifiez-la dans la ligne après l’enregistrement.", + "comboSuggest.draft.cancel": "Annuler", + "comboSuggest.draft.save": "Enregistrer la combinaison", + "comboSuggest.draft.saving": "Enregistrement…", }; diff --git a/gui/src/i18n/ja.ts b/gui/src/i18n/ja.ts index b71b131dd49..b3dd1cb6fb6 100644 --- a/gui/src/i18n/ja.ts +++ b/gui/src/i18n/ja.ts @@ -4528,4 +4528,152 @@ export const ja: Record = { "remoteLink.error.policy_write_failed": "Child ポリシーを保存できませんでした。", "remoteLink.error.runtime_role_client": "このコンピュータは Child です。Child を操作できるのは Home だけです。", "remoteLink.error.link_not_home_initiated": "この Child は自身で接続したため、そのコンピュータから操作してください。", + "routeBoard.lede": "各コンボの背後にあるチャネルと、その使用順をこのページで確認できます。戦略とオン/オフは行内で変更し、行をクリックするとチャネルを編集できます。", + "routeBoard.advanced": "詳細", + "routeBoard.advancedHint": "コンボの完全なエディター:エイリアス、JEV 判定サービス、推論強度、画像入力、ネイティブエイリアス。", + "routeBoard.backToOverview": "概要に戻る", + "routeBoard.empty": "コンボはまだありません。コンボはクライアントに 1 つのモデル名を見せ、複数のプロバイダーに振り分けます。", + "routeBoard.listAria": "コンボ", + "routeBoard.window.weekly": "週", + "routeBoard.window.fiveHour": "5 時間", + "routeBoard.window.monthly": "月", + "routeBoard.quota.left": "{window} 残り {percent}%", + "routeBoard.quota.accounts": "{provider}({count} アカウント)", + "routeBoard.quota.metered": "従量課金", + "routeBoard.quota.unknown": "クォータ情報なし", + "routeBoard.lastResort": "予備", + "routeBoard.tag.channelsOff": "{count} 件オフ", + "routeBoard.tag.sticky": "固定 ×{count}", + "routeBoard.tag.noImages": "テキストのみ", + "routeBoard.context": "コンテキスト {size}", + "routeBoard.contextHint": "クリックすると、この数値の求め方が見られます。", + "routeBoard.strategyLabel": "{model} の戦略", + "routeBoard.enabledLabel": "{model} をクライアントに提供", + "routeBoard.enabledHint": "オフにしても設定は残り、クライアントへの提供だけを止めます。", + "routeBoard.notSaved": "保存されていません:{reason}", + "routeBoard.jevInAdvanced": "JEV には判定サービスが必要です。ここで戦略を JEV に切り替え、判定するサービスを確認してから保存してください。", + "routeBoard.edit.aria": "{model} のチャネル", + "routeBoard.edit.drag": "ドラッグで並べ替え", + "routeBoard.edit.lastResortHint": "予備:他のチャネルがすべて使えないときだけ使います。", + "routeBoard.edit.lastResortInert": "無効です:「その他の設定」で「予備チャネルは最後に回す」をオンにしてください。それまでは他と同じく順番どおりに使われます。", + "routeBoard.edit.moveUp": "{name} を上へ", + "routeBoard.edit.moveDown": "{name} を下へ", + "routeBoard.edit.remove": "{name} を外す", + "routeBoard.edit.provider": "プロバイダー", + "routeBoard.edit.model": "モデル", + "routeBoard.edit.noModels": "他のモデルはありません", + "routeBoard.edit.add": "チャネルを追加", + "routeBoard.edit.more": "その他の設定", + "routeBoard.edit.unsaved": "未保存", + "routeBoard.locked": "詳細に未保存の変更", + "routeBoard.lockedHint": "このコンボには詳細エディターで未保存の変更があります。そこで保存または破棄してから、ここで変更してください。", + "routeBoard.strategyHint.failover": "順番どおり:使える最初のチャネルを使い続け、クォータ切れ・レート制限・エラーのときだけ次へ移ります。切り替えは応答開始前のみです。", + "routeBoard.strategyHint.roundRobin": "交代:リクエストごとに次のチャネルへ回し、クォータを分散します。", + "routeBoard.strategyHint.random": "ランダム:リクエストごとに使えるチャネルを 1 つ無作為に選びます。", + "routeBoard.strategyHint.leastUsed": "最少使用:最近いちばん使われていないチャネルから使います。", + "routeBoard.strategyHint.resetWindow": "リセットが近い順:クォータのリセットが近いアカウントから使い、リセットで無駄にしません。", + "routeBoard.strategyHint.jev": "スマート:小さなモデルが先にリクエストを読み、送り先と推論の強さを決めます。", + "routeBoard.quota.family": "{family} · {window}", + "routeBoard.quota.paused": "(他に一時停止 {count})", + "routeBoard.cap.title": "機能", + "routeBoard.cap.intersection": "共通部分", + "routeBoard.cap.intersectionHint": "共通部分:コンテキストは最小のメンバーに合わせ、画像や推論強度は全メンバーが対応するものだけを数えます。", + "routeBoard.cap.union": "和集合", + "routeBoard.cap.unionHint": "和集合:最大のメンバーで公開し、収まらない・画像や高い推論強度が必要なリクエストは、対応できないメンバーを飛ばします。", + "routeBoard.cap.unservable": "どのチャネルも対応できないとき", + "routeBoard.cap.degrade": "縮退", + "routeBoard.cap.degradeHint": "どのチャネルも対応しない部分(画像など)を外して、そのまま応答します。", + "routeBoard.cap.reject": "拒否", + "routeBoard.cap.rejectHint": "その部分を欠いたまま応答せず、エラーを返します。", + "routeBoard.more.fallbackOnly": "予備チャネルは最後に回す", + "routeBoard.more.fallbackOnlyHint": "オン:予備に指定したチャネルは、他に使えるチャネルがある限り飛ばします。オフ:他と同じく順番どおりに使います。", + "routeBoard.members.title": "コンボの数値の出どころ", + "routeBoard.members.channel": "チャネル", + "routeBoard.members.context": "コンテキスト", + "routeBoard.members.input": "入力", + "routeBoard.members.efforts": "推論強度", + "routeBoard.members.text": "テキスト", + "routeBoard.members.image": "画像", + "routeBoard.members.unknown": "不明", + "routeBoard.members.none": "なし", + "routeBoard.members.combo": "このコンボ", + "routeBoard.contextBasis.min": "(最小メンバー)", + "routeBoard.contextBasis.max": "(最大メンバー)", + "routeBoard.source.reported": "プロバイダー報告", + "routeBoard.source.inferred": "同名モデルから推定", + "routeBoard.source.manual": "手動", + "routeBoard.source.unknown": "不明", + "routeBoard.members.actions": "操作", + "routeBoard.members.edit": "編集", + "routeBoard.members.editAria": "{name} が受け付ける内容を編集", + "routeBoard.members.contextPlaceholder": "例: 200K、1M。空欄ならプロバイダーの値のまま", + "routeBoard.members.contextInvalid": "200000、200K、1M のようにトークン数を入力してください。", + "routeBoard.members.scopeNote": "{name} 自体に保存されます。このモデルを使うすべてのコンボが変わります。", + "routeBoard.members.restore": "プロバイダーの値に戻す", + "routeBoard.probe.run": "テストする", + "routeBoard.source.probed": "実測", + "routeBoard.basis.registry": "{provider} の内蔵表", + "routeBoard.basis.vendor": "{provider} のモデル情報", + "routeBoard.basis.provider": "設定済みの {provider}", + "routeBoard.basis.aggregator": "{provider} のカタログ", + "routeBoard.inferred.cell": "推定 {value}(根拠: {basis})", + "routeBoard.inferred.adopt": "採用", + "routeBoard.inferred.adoptAria": "{name} の推定値 {value} を手動設定として保存", + "routeBoard.members.includesInferred": "推定値を含む", + "routeBoard.probe.runAria": "{name} が受け付けるものをテスト", + "routeBoard.probe.running": "テスト中…", + "routeBoard.probe.confirmTitle": "有料テストの確認", + "routeBoard.probe.confirm": "このプロバイダーは従量課金です。テストではごく小さなリクエストを {count} 回送ります。続けますか?", + "routeBoard.probe.confirmGo": "テストする", + "routeBoard.probe.reason.disabled": "テストできません: このプロバイダーはオフです。", + "routeBoard.probe.reason.forward_auth": "テストできません: このプロバイダーはクライアントのログインを転送します。", + "routeBoard.probe.reason.oauth_auth": "テストできません: サブスクリプションのログインはテストしません。", + "routeBoard.probe.reason.unsupported_adapter": "テストできません: OpenAI 互換のエンドポイントだけがテストできます。", + "routeBoard.probe.reason.unsupported_transport": "テストできません: このプロバイダーの接続方式には対応していません。", + "routeBoard.probe.reason.other": "このプロバイダーはテストできません。", + "routeBoard.probe.busy": "このプロバイダーはテスト中です。", + "routeBoard.probe.failed": "テストが完了しませんでした。何も変更していません。", + "routeBoard.probe.uncertain": "判定できません: 通常のリクエストが通らなかったため、何も変更していません。", + "routeBoard.probe.image": "画像: {status}", + "routeBoard.probe.accepted": "受け付け", + "routeBoard.probe.rejected": "拒否", + "routeBoard.probe.inconclusive": "不明", + "routeBoard.probe.efforts": "推論レベル 受け付け: {accepted}、拒否: {rejected}、不明: {inconclusive}", + "routeBoard.probe.appliedInput": "入力を保存: {value}", + "routeBoard.probe.appliedEfforts": "推論レベルを保存: {value}", + "routeBoard.probe.nothingApplied": "確かな結果がないため、何も保存していません。", + "routeBoard.probe.contextNote": "コンテキストはモデル名から推定し、実測しません。", + "routeBoard.probe.close": "閉じる", + "comboSuggest.title": "おすすめのコンボ", + "comboSuggest.lede": "複数のプロバイダーが同じ名前で提供しているモデルです。コンボを生成すると、1 つのモデル名ですべてのプロバイダーにルーティングできます。", + "comboSuggest.servedBy": "{count} 社のプロバイダーが提供", + "comboSuggest.canAdd": "{providers} も利用可能", + "comboSuggest.generate": "生成", + "comboSuggest.addTo": "コンボに追加", + "comboSuggest.dismiss": "非表示", + "models.latestPerFamily": "系列の最新のみ", + "models.latestPerFamilyHint": "各系列の最新モデルだけを表示", + "comboSuggest.exclude.button": "プロバイダを除外…", + "comboSuggest.exclude.active": "除外中:{names}", + "comboSuggest.exclude.head": "おすすめの組み合わせから除外", + "comboSuggest.exclude.hint": "そのモデルはおすすめの組み合わせに入りません。作成済みの組み合わせはそのままです。", + "comboSuggest.exclude.restore": "元に戻す", + "comboSuggest.exclude.saveFailed": "除外したプロバイダを保存できませんでした。", + "comboSuggest.exclude.none": "これらのプロバイダを除外すると、おすすめはありません。", + "comboSuggest.showAll": "すべて表示({count} 件)", + "comboSuggest.showFewer": "折りたたむ", + "comboSuggest.tier.ownSubscription": "提供元のサブスクリプション", + "comboSuggest.tier.subscription": "サブスクリプション", + "comboSuggest.tier.vertex": "Vertex クレジット", + "comboSuggest.tier.metered": "従量課金", + "comboSuggest.draft.id": "コンボ ID", + "comboSuggest.draft.orderHint": "上から順に試行されます。サブスクリプションが先、次に Vertex クレジット、従量課金の API キーとリレーは最後です。保存前に並べ替えや削除ができます。", + "comboSuggest.draft.left": "残り {percent}%", + "comboSuggest.draft.up": "上へ", + "comboSuggest.draft.down": "下へ", + "comboSuggest.draft.remove": "削除", + "comboSuggest.draft.strategy": "戦略:フェイルオーバー。保存後に行内で変更できます。", + "comboSuggest.draft.cancel": "キャンセル", + "comboSuggest.draft.save": "コンボを保存", + "comboSuggest.draft.saving": "保存中…", }; diff --git a/gui/src/i18n/ko.ts b/gui/src/i18n/ko.ts index 399a227c363..4104f26250f 100644 --- a/gui/src/i18n/ko.ts +++ b/gui/src/i18n/ko.ts @@ -4528,4 +4528,152 @@ export const ko: Record = { "remoteLink.error.policy_write_failed": "Child 정책을 저장하지 못했습니다.", "remoteLink.error.runtime_role_client": "이 컴퓨터는 Child이므로 Home만 Child를 조작할 수 있습니다.", "remoteLink.error.link_not_home_initiated": "이 Child가 직접 연결했으므로 해당 Child 컴퓨터에서 조작하세요.", + "routeBoard.lede": "각 콤보 뒤에 어떤 채널이 있고 어떤 순서로 쓰이는지 이 페이지에서 볼 수 있습니다. 전략과 켜기/끄기는 행에서 바로 바꾸고, 행을 클릭하면 채널을 편집합니다.", + "routeBoard.advanced": "고급", + "routeBoard.advancedHint": "전체 콤보 편집기: 별칭, JEV 판정 서비스, 추론 강도, 이미지 입력, 네이티브 별칭.", + "routeBoard.backToOverview": "개요로 돌아가기", + "routeBoard.empty": "아직 콤보가 없습니다. 콤보는 클라이언트에 모델 이름 하나를 보여 주고 여러 공급자로 나눠 보냅니다.", + "routeBoard.listAria": "콤보", + "routeBoard.window.weekly": "주간", + "routeBoard.window.fiveHour": "5시간", + "routeBoard.window.monthly": "월간", + "routeBoard.quota.left": "{window} {percent}% 남음", + "routeBoard.quota.accounts": "{provider} (계정 {count}개)", + "routeBoard.quota.metered": "사용량 과금", + "routeBoard.quota.unknown": "할당량 정보 없음", + "routeBoard.lastResort": "예비", + "routeBoard.tag.channelsOff": "{count}개 꺼짐", + "routeBoard.tag.sticky": "고정 ×{count}", + "routeBoard.tag.noImages": "텍스트만", + "routeBoard.context": "컨텍스트 {size}", + "routeBoard.contextHint": "클릭하면 이 숫자가 어떻게 나왔는지 볼 수 있습니다.", + "routeBoard.strategyLabel": "{model} 전략", + "routeBoard.enabledLabel": "클라이언트에 {model} 제공", + "routeBoard.enabledHint": "끄면 콤보 설정은 그대로 두고 클라이언트 목록에서만 뺍니다.", + "routeBoard.notSaved": "저장되지 않음: {reason}", + "routeBoard.jevInAdvanced": "JEV에는 판정 서비스가 필요합니다. 여기서 전략을 JEV로 바꾸고 어떤 서비스가 판정하는지 확인한 뒤 저장하세요.", + "routeBoard.edit.aria": "{model} 채널", + "routeBoard.edit.drag": "드래그해서 순서 변경", + "routeBoard.edit.lastResortHint": "예비: 다른 채널을 모두 쓸 수 없을 때만 씁니다.", + "routeBoard.edit.lastResortInert": "적용 안 됨: '추가 설정'에서 '예비 채널은 마지막에'를 켜세요. 그 전에는 다른 채널처럼 순서대로 쓰입니다.", + "routeBoard.edit.moveUp": "{name} 위로", + "routeBoard.edit.moveDown": "{name} 아래로", + "routeBoard.edit.remove": "{name} 제거", + "routeBoard.edit.provider": "공급자", + "routeBoard.edit.model": "모델", + "routeBoard.edit.noModels": "다른 모델 없음", + "routeBoard.edit.add": "채널 추가", + "routeBoard.edit.more": "추가 설정", + "routeBoard.edit.unsaved": "저장 안 됨", + "routeBoard.locked": "고급에 저장 안 된 변경", + "routeBoard.lockedHint": "이 콤보는 고급 편집기에 저장되지 않은 변경이 있습니다. 거기서 저장하거나 버린 뒤 여기서 바꾸세요.", + "routeBoard.strategyHint.failover": "순서대로: 쓸 수 있는 첫 채널을 계속 쓰고, 할당량 소진·속도 제한·오류일 때만 다음으로 넘어갑니다. 전환은 응답이 시작되기 전에만 합니다.", + "routeBoard.strategyHint.roundRobin": "돌아가며: 요청마다 다음 채널로 보내 할당량을 나눕니다.", + "routeBoard.strategyHint.random": "무작위: 요청마다 쓸 수 있는 채널 하나를 무작위로 고릅니다.", + "routeBoard.strategyHint.leastUsed": "최소 사용: 최근 가장 적게 쓴 채널부터 씁니다.", + "routeBoard.strategyHint.resetWindow": "곧 초기화되는 것 먼저: 할당량이 곧 초기화되는 계정부터 써서 낭비를 막습니다.", + "routeBoard.strategyHint.jev": "스마트: 작은 모델이 먼저 요청을 읽고, 보낼 채널과 추론 강도를 정합니다.", + "routeBoard.quota.family": "{family} · {window}", + "routeBoard.quota.paused": "(일시 중지 {count}개 별도)", + "routeBoard.cap.title": "기능", + "routeBoard.cap.intersection": "교집합", + "routeBoard.cap.intersectionHint": "교집합: 컨텍스트는 가장 작은 멤버 기준이고, 이미지와 추론 강도는 모든 멤버가 지원하는 것만 셉니다.", + "routeBoard.cap.union": "합집합", + "routeBoard.cap.unionHint": "합집합: 가장 큰 멤버 기준으로 알리고, 맞지 않거나 이미지·높은 추론 강도가 필요한 요청은 처리할 수 없는 멤버를 건너뜁니다.", + "routeBoard.cap.unservable": "어떤 채널도 처리할 수 없을 때", + "routeBoard.cap.degrade": "기능 축소", + "routeBoard.cap.degradeHint": "어떤 채널도 지원하지 않는 부분(예: 이미지)을 빼고 그대로 답합니다.", + "routeBoard.cap.reject": "거부", + "routeBoard.cap.rejectHint": "그 부분 없이 답하지 않고 오류를 돌려줍니다.", + "routeBoard.more.fallbackOnly": "예비 채널은 마지막에", + "routeBoard.more.fallbackOnlyHint": "켜기: 예비로 표시한 채널은 다른 채널을 쓸 수 있는 동안 건너뜁니다. 끄기: 다른 채널처럼 순서대로 씁니다.", + "routeBoard.members.title": "콤보 숫자가 나온 방식", + "routeBoard.members.channel": "채널", + "routeBoard.members.context": "컨텍스트", + "routeBoard.members.input": "입력", + "routeBoard.members.efforts": "추론 강도", + "routeBoard.members.text": "텍스트", + "routeBoard.members.image": "이미지", + "routeBoard.members.unknown": "알 수 없음", + "routeBoard.members.none": "없음", + "routeBoard.members.combo": "이 콤보", + "routeBoard.contextBasis.min": "(가장 작은 멤버)", + "routeBoard.contextBasis.max": "(가장 큰 멤버)", + "routeBoard.source.reported": "제공자 보고", + "routeBoard.source.inferred": "같은 이름 모델에서 추정", + "routeBoard.source.manual": "수동", + "routeBoard.source.unknown": "알 수 없음", + "routeBoard.members.actions": "작업", + "routeBoard.members.edit": "편집", + "routeBoard.members.editAria": "{name}이(가) 받는 항목 편집", + "routeBoard.members.contextPlaceholder": "예: 200K, 1M. 비우면 제공자 값 유지", + "routeBoard.members.contextInvalid": "200000, 200K, 1M처럼 토큰 수를 입력하세요.", + "routeBoard.members.scopeNote": "{name} 자체에 저장됩니다. 이 모델을 쓰는 모든 콤보가 함께 바뀝니다.", + "routeBoard.members.restore": "제공자 값 사용", + "routeBoard.probe.run": "테스트", + "routeBoard.source.probed": "실측", + "routeBoard.basis.registry": "{provider} 내장 표", + "routeBoard.basis.vendor": "{provider} 모델 정보", + "routeBoard.basis.provider": "설정된 {provider}", + "routeBoard.basis.aggregator": "{provider} 카탈로그", + "routeBoard.inferred.cell": "추정 {value}(근거: {basis})", + "routeBoard.inferred.adopt": "채택", + "routeBoard.inferred.adoptAria": "{name}의 추정값 {value}을(를) 수동 설정으로 저장", + "routeBoard.members.includesInferred": "추정값 포함", + "routeBoard.probe.runAria": "{name}이(가) 받는 항목 테스트", + "routeBoard.probe.running": "테스트 중…", + "routeBoard.probe.confirmTitle": "유료 테스트 확인", + "routeBoard.probe.confirm": "이 제공자는 종량제입니다. 테스트는 아주 작은 요청을 {count}번 보냅니다. 계속할까요?", + "routeBoard.probe.confirmGo": "테스트 실행", + "routeBoard.probe.reason.disabled": "테스트 불가: 이 제공자는 꺼져 있습니다.", + "routeBoard.probe.reason.forward_auth": "테스트 불가: 이 제공자는 클라이언트 로그인을 그대로 전달합니다.", + "routeBoard.probe.reason.oauth_auth": "테스트 불가: 구독 로그인은 테스트하지 않습니다.", + "routeBoard.probe.reason.unsupported_adapter": "테스트 불가: OpenAI 호환 엔드포인트만 테스트할 수 있습니다.", + "routeBoard.probe.reason.unsupported_transport": "테스트 불가: 이 제공자의 연결 방식은 지원하지 않습니다.", + "routeBoard.probe.reason.other": "이 제공자는 테스트할 수 없습니다.", + "routeBoard.probe.busy": "이 제공자는 이미 테스트 중입니다.", + "routeBoard.probe.failed": "테스트가 끝나지 않았습니다. 아무것도 바꾸지 않았습니다.", + "routeBoard.probe.uncertain": "판단 불가: 기본 요청이 통과하지 못해 아무것도 바꾸지 않았습니다.", + "routeBoard.probe.image": "이미지: {status}", + "routeBoard.probe.accepted": "수락", + "routeBoard.probe.rejected": "거부", + "routeBoard.probe.inconclusive": "불확실", + "routeBoard.probe.efforts": "추론 단계 수락: {accepted}; 거부: {rejected}; 불확실: {inconclusive}", + "routeBoard.probe.appliedInput": "입력 저장: {value}", + "routeBoard.probe.appliedEfforts": "추론 단계 저장: {value}", + "routeBoard.probe.nothingApplied": "확실한 결과가 없어 아무것도 저장하지 않았습니다.", + "routeBoard.probe.contextNote": "컨텍스트는 모델 이름으로 추정하며 실측하지 않습니다.", + "routeBoard.probe.close": "닫기", + "comboSuggest.title": "추천 콤보", + "comboSuggest.lede": "둘 이상의 프로바이더가 같은 이름으로 제공하는 모델입니다. 콤보를 생성하면 하나의 모델 이름으로 이들 모두에 라우팅할 수 있습니다.", + "comboSuggest.servedBy": "{count}개 프로바이더가 제공", + "comboSuggest.canAdd": "{providers}도 사용할 수 있음", + "comboSuggest.generate": "생성", + "comboSuggest.addTo": "콤보에 추가", + "comboSuggest.dismiss": "무시", + "models.latestPerFamily": "계열별 최신", + "models.latestPerFamilyHint": "각 계열의 최신 모델만 표시", + "comboSuggest.exclude.button": "제공자 제외…", + "comboSuggest.exclude.active": "제외됨: {names}", + "comboSuggest.exclude.head": "추천 조합에서 제외", + "comboSuggest.exclude.hint": "해당 모델은 추천 조합에 들어가지 않습니다. 이미 만든 조합은 그대로입니다.", + "comboSuggest.exclude.restore": "복원", + "comboSuggest.exclude.saveFailed": "제외한 제공자를 저장하지 못했습니다.", + "comboSuggest.exclude.none": "이 제공자들을 제외하면 남은 추천이 없습니다.", + "comboSuggest.showAll": "전체 {count}개 보기", + "comboSuggest.showFewer": "접기", + "comboSuggest.tier.ownSubscription": "제작사 구독", + "comboSuggest.tier.subscription": "구독", + "comboSuggest.tier.vertex": "Vertex 크레딧", + "comboSuggest.tier.metered": "종량제", + "comboSuggest.draft.id": "콤보 ID", + "comboSuggest.draft.orderHint": "위에서 아래 순서로 시도합니다. 구독이 먼저, 그다음 Vertex 크레딧, 종량제 키와 릴레이는 마지막입니다. 저장하기 전에 순서를 바꾸거나 삭제할 수 있습니다.", + "comboSuggest.draft.left": "{percent}% 남음", + "comboSuggest.draft.up": "위로", + "comboSuggest.draft.down": "아래로", + "comboSuggest.draft.remove": "삭제", + "comboSuggest.draft.strategy": "전략: 장애 조치(failover). 저장 후 행에서 바꿀 수 있습니다.", + "comboSuggest.draft.cancel": "취소", + "comboSuggest.draft.save": "콤보 저장", + "comboSuggest.draft.saving": "저장 중…", }; diff --git a/gui/src/i18n/pt.ts b/gui/src/i18n/pt.ts index 1b5c4960b76..fb967b639b2 100644 --- a/gui/src/i18n/pt.ts +++ b/gui/src/i18n/pt.ts @@ -4501,4 +4501,152 @@ export const pt: Record = { "remoteLink.error.policy_write_failed": "Não foi possível salvar a política do Child.", "remoteLink.error.runtime_role_client": "Este computador é um Child; apenas um Home pode operar Children.", "remoteLink.error.link_not_home_initiated": "Este Child se conectou sozinho, então opere-o a partir do próprio computador dele.", + "routeBoard.lede": "Cada combo, os canais por trás dela e a ordem em que são usados. Mude a estratégia ou desligue uma combo na própria linha; clique numa linha para editar os canais.", + "routeBoard.advanced": "Avançado", + "routeBoard.advancedHint": "Editor completo de combos: aliases, serviço de decisão JEV, nível de raciocínio, entrada de imagens, aliases nativos.", + "routeBoard.backToOverview": "Voltar à visão geral", + "routeBoard.empty": "Ainda não há combos. Uma combo mostra um único nome de modelo aos clientes e o distribui entre vários provedores.", + "routeBoard.listAria": "Combos", + "routeBoard.window.weekly": "semanal", + "routeBoard.window.fiveHour": "5 h", + "routeBoard.window.monthly": "mensal", + "routeBoard.quota.left": "{window} {percent}% restante", + "routeBoard.quota.accounts": "{provider} ({count} contas)", + "routeBoard.quota.metered": "por uso", + "routeBoard.quota.unknown": "sem dados de cota", + "routeBoard.lastResort": "só reserva", + "routeBoard.tag.channelsOff": "{count} desligados", + "routeBoard.tag.sticky": "fixo ×{count}", + "routeBoard.tag.noImages": "só texto", + "routeBoard.context": "ctx {size}", + "routeBoard.contextHint": "Clique para ver como este número é calculado.", + "routeBoard.strategyLabel": "Estratégia de {model}", + "routeBoard.enabledLabel": "Oferecer {model} aos clientes", + "routeBoard.enabledHint": "Desligada, a combo mantém as configurações mas deixa de ser oferecida aos clientes.", + "routeBoard.notSaved": "Não salvo: {reason}", + "routeBoard.jevInAdvanced": "JEV precisa de um serviço de decisão. Mude aqui a estratégia para JEV, confira qual serviço decide e depois salve.", + "routeBoard.edit.aria": "Canais de {model}", + "routeBoard.edit.drag": "Arraste para reordenar", + "routeBoard.edit.lastResortHint": "Só reserva: usado apenas quando nenhum outro canal está disponível.", + "routeBoard.edit.lastResortInert": "Sem efeito: ative “Canais de reserva ficam por último” em Mais configurações. Até lá, este canal é usado em ordem como os outros.", + "routeBoard.edit.moveUp": "Mover {name} para cima", + "routeBoard.edit.moveDown": "Mover {name} para baixo", + "routeBoard.edit.remove": "Remover {name}", + "routeBoard.edit.provider": "Provedor", + "routeBoard.edit.model": "Modelo", + "routeBoard.edit.noModels": "Nenhum outro modelo", + "routeBoard.edit.add": "Adicionar canal", + "routeBoard.edit.more": "Mais configurações", + "routeBoard.edit.unsaved": "Não salvo", + "routeBoard.locked": "não salvo em Avançado", + "routeBoard.lockedHint": "Esta combo tem alterações não salvas no editor avançado. Salve ou descarte-as lá antes de mudá-la aqui.", + "routeBoard.strategyHint.failover": "Em ordem: o primeiro canal que funciona continua em uso; quando a cota acaba, há limite de taxa ou erro, passa ao próximo, só antes de a resposta começar.", + "routeBoard.strategyHint.roundRobin": "Revezamento: cada requisição vai para o próximo canal, dividindo a cota.", + "routeBoard.strategyHint.random": "Aleatório: cada requisição escolhe ao acaso um canal disponível.", + "routeBoard.strategyHint.leastUsed": "Menos usado: o canal menos usado recentemente vai primeiro.", + "routeBoard.strategyHint.resetWindow": "Reinício mais próximo primeiro: contas cuja cota reinicia antes são usadas primeiro, para nada se perder.", + "routeBoard.strategyHint.jev": "Inteligente: um modelo pequeno lê a requisição primeiro e escolhe o canal e o nível de raciocínio.", + "routeBoard.quota.family": "{family} · {window}", + "routeBoard.quota.paused": "(+{count} pausadas)", + "routeBoard.cap.title": "Capacidades", + "routeBoard.cap.intersection": "Interseção", + "routeBoard.cap.intersectionHint": "Interseção: a janela de contexto é a do menor membro; imagens e níveis de raciocínio só contam se todos os membros os suportarem.", + "routeBoard.cap.union": "União", + "routeBoard.cap.unionHint": "União: anuncia o maior membro; uma requisição que não cabe, ou que pede imagens ou mais raciocínio, pula os membros que não a aceitam.", + "routeBoard.cap.unservable": "Quando nenhum canal consegue atender", + "routeBoard.cap.degrade": "Degradar", + "routeBoard.cap.degradeHint": "Remover a parte que nenhum canal suporta (uma imagem, por exemplo) e responder mesmo assim.", + "routeBoard.cap.reject": "Rejeitar", + "routeBoard.cap.rejectHint": "Devolver um erro em vez de responder sem essa parte.", + "routeBoard.more.fallbackOnly": "Canais de reserva ficam por último", + "routeBoard.more.fallbackOnlyHint": "Ligado: canais marcados como reserva são pulados enquanto outro canal funcionar. Desligado: são usados em ordem como os demais.", + "routeBoard.members.title": "De onde vêm os números da combo", + "routeBoard.members.channel": "Canal", + "routeBoard.members.context": "Contexto", + "routeBoard.members.input": "Entrada", + "routeBoard.members.efforts": "Níveis de raciocínio", + "routeBoard.members.text": "texto", + "routeBoard.members.image": "imagens", + "routeBoard.members.unknown": "desconhecido", + "routeBoard.members.none": "nenhum", + "routeBoard.members.combo": "Esta combo", + "routeBoard.contextBasis.min": "(menor membro)", + "routeBoard.contextBasis.max": "(maior membro)", + "routeBoard.source.reported": "informado pelo provedor", + "routeBoard.source.inferred": "inferido de modelo homônimo", + "routeBoard.source.manual": "manual", + "routeBoard.source.unknown": "desconhecido", + "routeBoard.members.actions": "Ações", + "routeBoard.members.edit": "Editar", + "routeBoard.members.editAria": "Editar o que {name} aceita", + "routeBoard.members.contextPlaceholder": "ex.: 200K ou 1M; vazio mantém o valor do provedor", + "routeBoard.members.contextInvalid": "Informe uma contagem de tokens, como 200000, 200K ou 1M.", + "routeBoard.members.scopeNote": "Salvo no próprio {name}: todo combo que usa este modelo muda junto.", + "routeBoard.members.restore": "Usar os valores do provedor", + "routeBoard.probe.run": "Testar", + "routeBoard.source.probed": "testado", + "routeBoard.basis.registry": "tabela integrada de {provider}", + "routeBoard.basis.vendor": "metadados de {provider}", + "routeBoard.basis.provider": "provedor configurado {provider}", + "routeBoard.basis.aggregator": "catálogo de {provider}", + "routeBoard.inferred.cell": "inferido {value} (com base em {basis})", + "routeBoard.inferred.adopt": "Adotar", + "routeBoard.inferred.adoptAria": "Salvar o valor inferido {value} de {name} como configuração manual", + "routeBoard.members.includesInferred": "inclui valores inferidos", + "routeBoard.probe.runAria": "Testar o que {name} aceita", + "routeBoard.probe.running": "Testando…", + "routeBoard.probe.confirmTitle": "Confirmar um teste pago", + "routeBoard.probe.confirm": "Este provedor cobra por uso: o teste envia {count} solicitações bem pequenas. Continuar?", + "routeBoard.probe.confirmGo": "Executar o teste", + "routeBoard.probe.reason.disabled": "Não dá para testar: este provedor está desligado.", + "routeBoard.probe.reason.forward_auth": "Não dá para testar: este provedor repassa o login do cliente.", + "routeBoard.probe.reason.oauth_auth": "Não dá para testar: logins de assinatura não são testados.", + "routeBoard.probe.reason.unsupported_adapter": "Não dá para testar: só endpoints compatíveis com OpenAI podem ser testados.", + "routeBoard.probe.reason.unsupported_transport": "Não dá para testar: o tipo de conexão deste provedor não é suportado.", + "routeBoard.probe.reason.other": "Este provedor não pode ser testado.", + "routeBoard.probe.busy": "Este provedor já está sendo testado.", + "routeBoard.probe.failed": "O teste não terminou. Nada foi alterado.", + "routeBoard.probe.uncertain": "Inconclusivo: a solicitação simples não passou, então nada foi alterado.", + "routeBoard.probe.image": "Imagens: {status}", + "routeBoard.probe.accepted": "aceitas", + "routeBoard.probe.rejected": "recusadas", + "routeBoard.probe.inconclusive": "incerto", + "routeBoard.probe.efforts": "Níveis aceitos: {accepted}; recusados: {rejected}; incertos: {inconclusive}", + "routeBoard.probe.appliedInput": "entrada salva: {value}", + "routeBoard.probe.appliedEfforts": "níveis salvos: {value}", + "routeBoard.probe.nothingApplied": "Nada conclusivo, então nada foi salvo.", + "routeBoard.probe.contextNote": "O contexto é inferido do nome do modelo, não medido.", + "routeBoard.probe.close": "Fechar", + "comboSuggest.title": "Combos sugeridos", + "comboSuggest.lede": "Modelos que mais de um dos seus provedores oferece com o mesmo nome. Gere um combo para rotear um único nome de modelo entre todos eles.", + "comboSuggest.servedBy": "oferecido por {count} provedores", + "comboSuggest.canAdd": "também pode usar {providers}", + "comboSuggest.generate": "Gerar", + "comboSuggest.addTo": "Adicionar ao combo", + "comboSuggest.dismiss": "Dispensar", + "models.latestPerFamily": "Mais recente por família", + "models.latestPerFamilyHint": "Mostrar só o modelo mais recente de cada família", + "comboSuggest.exclude.button": "Excluir um provedor…", + "comboSuggest.exclude.active": "Excluídos: {names}", + "comboSuggest.exclude.head": "Deixar fora das combinações sugeridas", + "comboSuggest.exclude.hint": "Os modelos deles não entram em nenhuma combinação sugerida; as que você já criou continuam iguais.", + "comboSuggest.exclude.restore": "Restaurar", + "comboSuggest.exclude.saveFailed": "Não foi possível salvar os provedores excluídos.", + "comboSuggest.exclude.none": "Sem sugestões com esses provedores excluídos.", + "comboSuggest.showAll": "Mostrar todos ({count})", + "comboSuggest.showFewer": "Mostrar menos", + "comboSuggest.tier.ownSubscription": "assinatura do criador", + "comboSuggest.tier.subscription": "assinatura", + "comboSuggest.tier.vertex": "crédito Vertex", + "comboSuggest.tier.metered": "pago por uso", + "comboSuggest.draft.id": "ID do combo", + "comboSuggest.draft.orderHint": "Testados de cima para baixo: assinaturas primeiro, depois crédito Vertex; chaves de pagamento por uso e relays por último. Reordene ou remova antes de salvar.", + "comboSuggest.draft.left": "{percent}% restante", + "comboSuggest.draft.up": "Mover para cima", + "comboSuggest.draft.down": "Mover para baixo", + "comboSuggest.draft.remove": "Remover", + "comboSuggest.draft.strategy": "Estratégia: failover. Altere-a na linha depois de salvar.", + "comboSuggest.draft.cancel": "Cancelar", + "comboSuggest.draft.save": "Salvar combo", + "comboSuggest.draft.saving": "Salvando…", }; diff --git a/gui/src/i18n/ru.ts b/gui/src/i18n/ru.ts index 2771adadf00..53f736f5802 100644 --- a/gui/src/i18n/ru.ts +++ b/gui/src/i18n/ru.ts @@ -4529,4 +4529,152 @@ export const ru: Record = { "remoteLink.error.policy_write_failed": "Не удалось сохранить политику Child.", "remoteLink.error.runtime_role_client": "Этот компьютер — Child; управлять Children может только Home.", "remoteLink.error.link_not_home_initiated": "Этот Child подключился сам, поэтому управляйте им с его собственного компьютера.", + "routeBoard.lede": "Каждое комбо, каналы за ним и порядок их использования. Стратегию и включение меняйте прямо в строке; нажмите на строку, чтобы изменить каналы.", + "routeBoard.advanced": "Расширенно", + "routeBoard.advancedHint": "Полный редактор комбо: псевдонимы, сервис решений JEV, уровень рассуждений, ввод изображений, нативные псевдонимы.", + "routeBoard.backToOverview": "Назад к обзору", + "routeBoard.empty": "Комбо пока нет. Комбо показывает клиентам одно имя модели и распределяет запросы между несколькими провайдерами.", + "routeBoard.listAria": "Комбо", + "routeBoard.window.weekly": "неделя", + "routeBoard.window.fiveHour": "5 ч", + "routeBoard.window.monthly": "месяц", + "routeBoard.quota.left": "{window}: осталось {percent}%", + "routeBoard.quota.accounts": "{provider} ({count} акк.)", + "routeBoard.quota.metered": "оплата за использование", + "routeBoard.quota.unknown": "нет данных о квоте", + "routeBoard.lastResort": "только резерв", + "routeBoard.tag.channelsOff": "выкл.: {count}", + "routeBoard.tag.sticky": "закрепление ×{count}", + "routeBoard.tag.noImages": "только текст", + "routeBoard.context": "контекст {size}", + "routeBoard.contextHint": "Нажмите, чтобы увидеть, как получено это число.", + "routeBoard.strategyLabel": "Стратегия для {model}", + "routeBoard.enabledLabel": "Показывать {model} клиентам", + "routeBoard.enabledHint": "Выключенное комбо сохраняет настройки, но больше не показывается клиентам.", + "routeBoard.notSaved": "Не сохранено: {reason}", + "routeBoard.jevInAdvanced": "Для JEV нужен сервис решений. Переключите здесь стратегию на JEV, проверьте, какой сервис принимает решение, и сохраните.", + "routeBoard.edit.aria": "Каналы для {model}", + "routeBoard.edit.drag": "Перетащите, чтобы изменить порядок", + "routeBoard.edit.lastResortHint": "Только резерв: используется, лишь когда ни один другой канал недоступен.", + "routeBoard.edit.lastResortInert": "Не действует: включите «Резервные каналы — в последнюю очередь» в разделе «Другие настройки». До тех пор канал используется по порядку, как остальные.", + "routeBoard.edit.moveUp": "Переместить {name} выше", + "routeBoard.edit.moveDown": "Переместить {name} ниже", + "routeBoard.edit.remove": "Убрать {name}", + "routeBoard.edit.provider": "Провайдер", + "routeBoard.edit.model": "Модель", + "routeBoard.edit.noModels": "Других моделей нет", + "routeBoard.edit.add": "Добавить канал", + "routeBoard.edit.more": "Другие настройки", + "routeBoard.edit.unsaved": "Не сохранено", + "routeBoard.locked": "не сохранено в расширенном", + "routeBoard.lockedHint": "В расширенном редакторе есть несохранённые изменения этого комбо. Сохраните или отмените их там, прежде чем менять здесь.", + "routeBoard.strategyHint.failover": "По порядку: используется первый рабочий канал; при исчерпании квоты, лимите или ошибке — следующий, и только до начала ответа.", + "routeBoard.strategyHint.roundRobin": "По очереди: каждый запрос идёт на следующий канал, квота распределяется.", + "routeBoard.strategyHint.random": "Случайно: каждый запрос берёт случайный рабочий канал.", + "routeBoard.strategyHint.leastUsed": "Наименее используемый: первым идёт канал, которым реже всего пользовались в последнее время.", + "routeBoard.strategyHint.resetWindow": "Ближайший сброс первым: сначала аккаунты, чья квота скоро сбросится, чтобы ничего не пропало.", + "routeBoard.strategyHint.jev": "Умный выбор: маленькая модель сначала читает запрос, затем выбирает канал и уровень рассуждений.", + "routeBoard.quota.family": "{family} · {window}", + "routeBoard.quota.paused": "(+{count} на паузе)", + "routeBoard.cap.title": "Возможности", + "routeBoard.cap.intersection": "Пересечение", + "routeBoard.cap.intersectionHint": "Пересечение: окно контекста — как у самого маленького участника; изображения и уровни рассуждений учитываются, только если их поддерживают все.", + "routeBoard.cap.union": "Объединение", + "routeBoard.cap.unionHint": "Объединение: объявляется самый большой участник; запрос, который не помещается или требует изображений либо более высокого уровня, пропускает неподходящих участников.", + "routeBoard.cap.unservable": "Когда ни один канал не справится", + "routeBoard.cap.degrade": "Упростить", + "routeBoard.cap.degradeHint": "Убрать часть, которую не поддерживает ни один канал (например, изображение), и всё равно ответить.", + "routeBoard.cap.reject": "Отклонить", + "routeBoard.cap.rejectHint": "Вернуть ошибку вместо ответа без этой части.", + "routeBoard.more.fallbackOnly": "Резервные каналы — в последнюю очередь", + "routeBoard.more.fallbackOnlyHint": "Вкл.: каналы с пометкой «резерв» пропускаются, пока работает любой другой. Выкл.: они используются по порядку, как остальные.", + "routeBoard.members.title": "Откуда берутся числа комбо", + "routeBoard.members.channel": "Канал", + "routeBoard.members.context": "Контекст", + "routeBoard.members.input": "Ввод", + "routeBoard.members.efforts": "Уровни рассуждений", + "routeBoard.members.text": "текст", + "routeBoard.members.image": "изображения", + "routeBoard.members.unknown": "неизвестно", + "routeBoard.members.none": "нет", + "routeBoard.members.combo": "Это комбо", + "routeBoard.contextBasis.min": "(наименьший участник)", + "routeBoard.contextBasis.max": "(наибольший участник)", + "routeBoard.source.reported": "данные провайдера", + "routeBoard.source.inferred": "выведено из одноимённой модели", + "routeBoard.source.manual": "вручную", + "routeBoard.source.unknown": "неизвестно", + "routeBoard.members.actions": "Действия", + "routeBoard.members.edit": "Изменить", + "routeBoard.members.editAria": "Изменить, что принимает {name}", + "routeBoard.members.contextPlaceholder": "напр. 200K или 1M; пусто — значение провайдера", + "routeBoard.members.contextInvalid": "Введите число токенов, например 200000, 200K или 1M.", + "routeBoard.members.scopeNote": "Сохраняется в самой модели {name}: меняются все комбо, где она используется.", + "routeBoard.members.restore": "Вернуть значения провайдера", + "routeBoard.probe.run": "Проверить", + "routeBoard.source.probed": "проверено", + "routeBoard.basis.registry": "встроенная таблица {provider}", + "routeBoard.basis.vendor": "данные моделей {provider}", + "routeBoard.basis.provider": "настроенный провайдер {provider}", + "routeBoard.basis.aggregator": "каталог {provider}", + "routeBoard.inferred.cell": "предположительно {value} (по данным: {basis})", + "routeBoard.inferred.adopt": "Принять", + "routeBoard.inferred.adoptAria": "Сохранить предполагаемое значение {value} для {name} как ручную настройку", + "routeBoard.members.includesInferred": "с предполагаемыми значениями", + "routeBoard.probe.runAria": "Проверить, что принимает {name}", + "routeBoard.probe.running": "Проверка…", + "routeBoard.probe.confirmTitle": "Подтвердите платную проверку", + "routeBoard.probe.confirm": "Этот провайдер берёт плату за использование: проверка отправит {count} очень маленьких запросов. Продолжить?", + "routeBoard.probe.confirmGo": "Проверить", + "routeBoard.probe.reason.disabled": "Проверить нельзя: провайдер выключен.", + "routeBoard.probe.reason.forward_auth": "Проверить нельзя: провайдер передаёт вход клиента.", + "routeBoard.probe.reason.oauth_auth": "Проверить нельзя: входы по подписке не проверяются.", + "routeBoard.probe.reason.unsupported_adapter": "Проверить нельзя: проверяются только OpenAI-совместимые адреса.", + "routeBoard.probe.reason.unsupported_transport": "Проверить нельзя: тип подключения провайдера не поддерживается.", + "routeBoard.probe.reason.other": "Этот провайдер нельзя проверить.", + "routeBoard.probe.busy": "Этот провайдер уже проверяется.", + "routeBoard.probe.failed": "Проверка не завершилась. Ничего не изменено.", + "routeBoard.probe.uncertain": "Неясно: обычный запрос не прошёл, поэтому ничего не изменено.", + "routeBoard.probe.image": "Изображения: {status}", + "routeBoard.probe.accepted": "принимаются", + "routeBoard.probe.rejected": "отклоняются", + "routeBoard.probe.inconclusive": "неясно", + "routeBoard.probe.efforts": "Уровни приняты: {accepted}; отклонены: {rejected}; неясно: {inconclusive}", + "routeBoard.probe.appliedInput": "сохранён ввод: {value}", + "routeBoard.probe.appliedEfforts": "сохранены уровни: {value}", + "routeBoard.probe.nothingApplied": "Ничего определённого, поэтому ничего не сохранено.", + "routeBoard.probe.contextNote": "Контекст определяется по имени модели и не измеряется.", + "routeBoard.probe.close": "Закрыть", + "comboSuggest.title": "Рекомендуемые комбо", + "comboSuggest.lede": "Модели, которые несколько ваших провайдеров предлагают под одним именем. Создайте комбо, чтобы направлять одно имя модели на все они сразу.", + "comboSuggest.servedBy": "доступна у {count} провайдеров", + "comboSuggest.canAdd": "также может использовать {providers}", + "comboSuggest.generate": "Создать", + "comboSuggest.addTo": "Добавить в комбо", + "comboSuggest.dismiss": "Скрыть", + "models.latestPerFamily": "Новейшая в семействе", + "models.latestPerFamilyHint": "Показывать только новейшую модель каждого семейства", + "comboSuggest.exclude.button": "Исключить провайдера…", + "comboSuggest.exclude.active": "Исключены: {names}", + "comboSuggest.exclude.head": "Не предлагать в комбо", + "comboSuggest.exclude.hint": "Их модели не попадут в предлагаемые комбо; уже созданные комбо не меняются.", + "comboSuggest.exclude.restore": "Вернуть", + "comboSuggest.exclude.saveFailed": "Не удалось сохранить исключённых провайдеров.", + "comboSuggest.exclude.none": "С этими исключениями предложений не осталось.", + "comboSuggest.showAll": "Показать все ({count})", + "comboSuggest.showFewer": "Свернуть", + "comboSuggest.tier.ownSubscription": "подписка создателя модели", + "comboSuggest.tier.subscription": "подписка", + "comboSuggest.tier.vertex": "кредит Vertex", + "comboSuggest.tier.metered": "оплата по факту", + "comboSuggest.draft.id": "ID комбо", + "comboSuggest.draft.orderHint": "Пробуются сверху вниз: сначала подписки, затем кредит Vertex, а ключи с оплатой по факту и ретрансляторы — в конце. Измените порядок или удалите лишнее перед сохранением.", + "comboSuggest.draft.left": "осталось {percent}%", + "comboSuggest.draft.up": "Вверх", + "comboSuggest.draft.down": "Вниз", + "comboSuggest.draft.remove": "Удалить", + "comboSuggest.draft.strategy": "Стратегия: Failover. Изменить можно в строке после сохранения.", + "comboSuggest.draft.cancel": "Отмена", + "comboSuggest.draft.save": "Сохранить комбо", + "comboSuggest.draft.saving": "Сохранение…", }; diff --git a/gui/src/i18n/tr.ts b/gui/src/i18n/tr.ts index c27997fc8b4..4e7a7e46311 100644 --- a/gui/src/i18n/tr.ts +++ b/gui/src/i18n/tr.ts @@ -4529,4 +4529,152 @@ export const tr: Record = { "remoteLink.error.policy_write_failed": "Child ilkesi kaydedilemedi.", "remoteLink.error.runtime_role_client": "Bu bilgisayar bir Child; Child’ları yalnızca bir Home yönetebilir.", "remoteLink.error.link_not_home_initiated": "Bu Child kendini bağladı, bu yüzden onu kendi bilgisayarından yönetin.", + "routeBoard.lede": "Her kombo, arkasındaki kanallar ve kullanım sırası. Stratejiyi değiştirin veya komboyu satırdan kapatın; kanalları düzenlemek için satıra tıklayın.", + "routeBoard.advanced": "Gelişmiş", + "routeBoard.advancedHint": "Tam kombo düzenleyicisi: takma adlar, JEV karar hizmeti, akıl yürütme düzeyi, görsel girişi, yerel takma adlar.", + "routeBoard.backToOverview": "Genel bakışa dön", + "routeBoard.empty": "Henüz kombo yok. Kombo, istemcilere tek bir model adı gösterir ve onu birden çok sağlayıcıya dağıtır.", + "routeBoard.listAria": "Kombolar", + "routeBoard.window.weekly": "haftalık", + "routeBoard.window.fiveHour": "5 sa", + "routeBoard.window.monthly": "aylık", + "routeBoard.quota.left": "{window} %{percent} kaldı", + "routeBoard.quota.accounts": "{provider} ({count} hesap)", + "routeBoard.quota.metered": "kullanım başına", + "routeBoard.quota.unknown": "kota verisi yok", + "routeBoard.lastResort": "yalnızca yedek", + "routeBoard.tag.channelsOff": "{count} kapalı", + "routeBoard.tag.sticky": "yapışkan ×{count}", + "routeBoard.tag.noImages": "yalnızca metin", + "routeBoard.context": "bağlam {size}", + "routeBoard.contextHint": "Bu sayının nasıl hesaplandığını görmek için tıklayın.", + "routeBoard.strategyLabel": "{model} stratejisi", + "routeBoard.enabledLabel": "{model} istemcilere sunulsun", + "routeBoard.enabledHint": "Kapatıldığında kombonun ayarları korunur ama istemcilere artık sunulmaz.", + "routeBoard.notSaved": "Kaydedilmedi: {reason}", + "routeBoard.jevInAdvanced": "JEV bir karar hizmeti gerektirir. Stratejiyi burada JEV olarak değiştirin, hangi hizmetin karar verdiğini kontrol edin, sonra kaydedin.", + "routeBoard.edit.aria": "{model} kanalları", + "routeBoard.edit.drag": "Sıralamak için sürükleyin", + "routeBoard.edit.lastResortHint": "Yalnızca yedek: başka hiçbir kanal kullanılamadığında kullanılır.", + "routeBoard.edit.lastResortInert": "Etkin değil: Diğer ayarlar altında “Yedek kanallar en sona kalır” seçeneğini açın. O zamana kadar bu kanal diğerleri gibi sırayla kullanılır.", + "routeBoard.edit.moveUp": "{name} yukarı taşı", + "routeBoard.edit.moveDown": "{name} aşağı taşı", + "routeBoard.edit.remove": "{name} kaldır", + "routeBoard.edit.provider": "Sağlayıcı", + "routeBoard.edit.model": "Model", + "routeBoard.edit.noModels": "Başka model yok", + "routeBoard.edit.add": "Kanal ekle", + "routeBoard.edit.more": "Diğer ayarlar", + "routeBoard.edit.unsaved": "Kaydedilmedi", + "routeBoard.locked": "Gelişmiş'te kaydedilmemiş", + "routeBoard.lockedHint": "Bu komboda Gelişmiş düzenleyicide kaydedilmemiş değişiklikler var. Burada değiştirmeden önce orada kaydedin veya vazgeçin.", + "routeBoard.strategyHint.failover": "Sırayla: çalışan ilk kanal kullanılmaya devam eder; kotası bitince, hız sınırına takılınca veya hata verince sıradakine geçilir, yalnızca yanıt başlamadan önce.", + "routeBoard.strategyHint.roundRobin": "Sırayla dönüşümlü: her istek bir sonraki kanala gider, kota paylaşılır.", + "routeBoard.strategyHint.random": "Rastgele: her istek çalışan bir kanalı rastgele seçer.", + "routeBoard.strategyHint.leastUsed": "En az kullanılan: son zamanda en az kullanılan kanal önce gelir.", + "routeBoard.strategyHint.resetWindow": "En yakın sıfırlama önce: kotası en yakında sıfırlanan hesaplar önce kullanılır, böylece boşa gitmez.", + "routeBoard.strategyHint.jev": "Akıllı: küçük bir model isteği önce okur, sonra kanalı ve akıl yürütme düzeyini seçer.", + "routeBoard.quota.family": "{family} · {window}", + "routeBoard.quota.paused": "(+{count} duraklatıldı)", + "routeBoard.cap.title": "Yetenekler", + "routeBoard.cap.intersection": "Kesişim", + "routeBoard.cap.intersectionHint": "Kesişim: bağlam penceresi en küçük üyeninkidir; görseller ve akıl yürütme düzeyleri yalnızca tüm üyeler destekliyorsa sayılır.", + "routeBoard.cap.union": "Birleşim", + "routeBoard.cap.unionHint": "Birleşim: en büyük üye duyurulur; sığmayan ya da görsel veya daha yüksek düzey isteyen istekler, alamayan üyeleri atlar.", + "routeBoard.cap.unservable": "Hiçbir kanal karşılayamadığında", + "routeBoard.cap.degrade": "Düşür", + "routeBoard.cap.degradeHint": "Hiçbir kanalın desteklemediği kısmı (örneğin görseli) çıkar ve yine de yanıtla.", + "routeBoard.cap.reject": "Reddet", + "routeBoard.cap.rejectHint": "O kısım olmadan yanıtlamak yerine hata döndür.", + "routeBoard.more.fallbackOnly": "Yedek kanallar en sona kalır", + "routeBoard.more.fallbackOnlyHint": "Açık: yedek olarak işaretli kanallar, başka bir kanal çalıştığı sürece atlanır. Kapalı: diğerleri gibi sırayla kullanılır.", + "routeBoard.members.title": "Kombonun sayıları nereden geliyor", + "routeBoard.members.channel": "Kanal", + "routeBoard.members.context": "Bağlam", + "routeBoard.members.input": "Girdi", + "routeBoard.members.efforts": "Akıl yürütme düzeyleri", + "routeBoard.members.text": "metin", + "routeBoard.members.image": "görsel", + "routeBoard.members.unknown": "bilinmiyor", + "routeBoard.members.none": "yok", + "routeBoard.members.combo": "Bu kombo", + "routeBoard.contextBasis.min": "(en küçük üye)", + "routeBoard.contextBasis.max": "(en büyük üye)", + "routeBoard.source.reported": "sağlayıcı bildirdi", + "routeBoard.source.inferred": "aynı adlı modelden çıkarıldı", + "routeBoard.source.manual": "elle", + "routeBoard.source.unknown": "bilinmiyor", + "routeBoard.members.actions": "İşlemler", + "routeBoard.members.edit": "Düzenle", + "routeBoard.members.editAria": "{name} modelinin kabul ettiklerini düzenle", + "routeBoard.members.contextPlaceholder": "örn. 200K veya 1M; boş bırakılırsa sağlayıcı değeri kalır", + "routeBoard.members.contextInvalid": "200000, 200K veya 1M gibi bir token sayısı girin.", + "routeBoard.members.scopeNote": "{name} modelinin kendisine kaydedilir: bu modeli kullanan her kombo da değişir.", + "routeBoard.members.restore": "Sağlayıcı değerlerini kullan", + "routeBoard.probe.run": "Test et", + "routeBoard.source.probed": "test edildi", + "routeBoard.basis.registry": "{provider} yerleşik tablosu", + "routeBoard.basis.vendor": "{provider} model bilgileri", + "routeBoard.basis.provider": "yapılandırılmış {provider}", + "routeBoard.basis.aggregator": "{provider} kataloğu", + "routeBoard.inferred.cell": "tahmini {value} (dayanak: {basis})", + "routeBoard.inferred.adopt": "Benimse", + "routeBoard.inferred.adoptAria": "{name} için tahmini {value} değerini elle ayar olarak kaydet", + "routeBoard.members.includesInferred": "tahmini değerler içerir", + "routeBoard.probe.runAria": "{name} modelinin kabul ettiklerini test et", + "routeBoard.probe.running": "Test ediliyor…", + "routeBoard.probe.confirmTitle": "Ücretli testi onayla", + "routeBoard.probe.confirm": "Bu sağlayıcı kullanıma göre ücretlendirir: test {count} çok küçük istek gönderir. Devam edilsin mi?", + "routeBoard.probe.confirmGo": "Testi çalıştır", + "routeBoard.probe.reason.disabled": "Test edilemez: bu sağlayıcı kapalı.", + "routeBoard.probe.reason.forward_auth": "Test edilemez: bu sağlayıcı istemcinin oturumunu iletir.", + "routeBoard.probe.reason.oauth_auth": "Test edilemez: abonelik oturumları test edilmez.", + "routeBoard.probe.reason.unsupported_adapter": "Test edilemez: yalnızca OpenAI uyumlu uç noktalar test edilebilir.", + "routeBoard.probe.reason.unsupported_transport": "Test edilemez: bu sağlayıcının bağlantı türü desteklenmiyor.", + "routeBoard.probe.reason.other": "Bu sağlayıcı test edilemez.", + "routeBoard.probe.busy": "Bu sağlayıcı zaten test ediliyor.", + "routeBoard.probe.failed": "Test tamamlanmadı. Hiçbir şey değiştirilmedi.", + "routeBoard.probe.uncertain": "Belirsiz: düz istek geçmedi, bu yüzden hiçbir şey değiştirilmedi.", + "routeBoard.probe.image": "Görseller: {status}", + "routeBoard.probe.accepted": "kabul edildi", + "routeBoard.probe.rejected": "reddedildi", + "routeBoard.probe.inconclusive": "belirsiz", + "routeBoard.probe.efforts": "Düzeyler kabul: {accepted}; ret: {rejected}; belirsiz: {inconclusive}", + "routeBoard.probe.appliedInput": "kaydedilen giriş: {value}", + "routeBoard.probe.appliedEfforts": "kaydedilen düzeyler: {value}", + "routeBoard.probe.nothingApplied": "Kesin sonuç yok, bu yüzden hiçbir şey kaydedilmedi.", + "routeBoard.probe.contextNote": "Bağlam model adından tahmin edilir, ölçülmez.", + "routeBoard.probe.close": "Kapat", + "comboSuggest.title": "Önerilen kombolar", + "comboSuggest.lede": "Birden fazla sağlayıcınızın aynı adla sunduğu modeller. Tüm bu sağlayıcılar üzerinde tek bir model adını yönlendirmek için kombo oluşturun.", + "comboSuggest.servedBy": "{count} sağlayıcı sunuyor", + "comboSuggest.canAdd": "{providers} da kullanabilir", + "comboSuggest.generate": "Oluştur", + "comboSuggest.addTo": "Komboya ekle", + "comboSuggest.dismiss": "Kapat", + "models.latestPerFamily": "Aile başına en yeni", + "models.latestPerFamilyHint": "Her ailenin yalnızca en yeni modelini göster", + "comboSuggest.exclude.button": "Sağlayıcı hariç tut…", + "comboSuggest.exclude.active": "Hariç: {names}", + "comboSuggest.exclude.head": "Önerilen kombolardan hariç tut", + "comboSuggest.exclude.hint": "Modelleri hiçbir önerilen komboya girmez; oluşturduğunuz kombolar aynı kalır.", + "comboSuggest.exclude.restore": "Geri al", + "comboSuggest.exclude.saveFailed": "Hariç tutulan sağlayıcılar kaydedilemedi.", + "comboSuggest.exclude.none": "Bu sağlayıcılar hariç tutulunca öneri kalmadı.", + "comboSuggest.showAll": "Tümünü göster ({count})", + "comboSuggest.showFewer": "Daha azını göster", + "comboSuggest.tier.ownSubscription": "üreticinin aboneliği", + "comboSuggest.tier.subscription": "abonelik", + "comboSuggest.tier.vertex": "Vertex kredisi", + "comboSuggest.tier.metered": "kullandıkça öde", + "comboSuggest.draft.id": "Kombo kimliği", + "comboSuggest.draft.orderHint": "Yukarıdan aşağıya denenir: önce abonelikler, sonra Vertex kredisi, kullandıkça ödemeli anahtarlar ve röleler en sonda. Kaydetmeden önce sırayı değiştirin ya da kaldırın.", + "comboSuggest.draft.left": "%{percent} kaldı", + "comboSuggest.draft.up": "Yukarı taşı", + "comboSuggest.draft.down": "Aşağı taşı", + "comboSuggest.draft.remove": "Kaldır", + "comboSuggest.draft.strategy": "Strateji: failover. Kaydettikten sonra satırda değiştirin.", + "comboSuggest.draft.cancel": "İptal", + "comboSuggest.draft.save": "Komboyu kaydet", + "comboSuggest.draft.saving": "Kaydediliyor…", }; diff --git a/gui/src/i18n/vi.ts b/gui/src/i18n/vi.ts index 930028388dc..d2936e85494 100644 --- a/gui/src/i18n/vi.ts +++ b/gui/src/i18n/vi.ts @@ -4498,4 +4498,152 @@ export const vi: Record = { "remoteLink.error.policy_write_failed": "Không lưu được chính sách máy con.", "remoteLink.error.runtime_role_client": "Máy này là máy con; chỉ Home mới điều khiển được máy con.", "remoteLink.error.link_not_home_initiated": "Máy con này tự kết nối nên hãy điều khiển nó từ chính máy đó.", + "routeBoard.lede": "Mỗi combo, các kênh phía sau và thứ tự sử dụng. Đổi chiến lược hoặc tắt combo ngay trên hàng; bấm vào hàng để sửa kênh.", + "routeBoard.advanced": "Nâng cao", + "routeBoard.advancedHint": "Trình sửa combo đầy đủ: bí danh, dịch vụ quyết định JEV, mức suy luận, đầu vào hình ảnh, bí danh gốc.", + "routeBoard.backToOverview": "Quay lại tổng quan", + "routeBoard.empty": "Chưa có combo. Combo hiển thị một tên mô hình cho máy khách và chia nó cho nhiều nhà cung cấp.", + "routeBoard.listAria": "Combo", + "routeBoard.window.weekly": "tuần", + "routeBoard.window.fiveHour": "5 giờ", + "routeBoard.window.monthly": "tháng", + "routeBoard.quota.left": "{window} còn {percent}%", + "routeBoard.quota.accounts": "{provider} ({count} tài khoản)", + "routeBoard.quota.metered": "trả theo lượng dùng", + "routeBoard.quota.unknown": "không có dữ liệu hạn mức", + "routeBoard.lastResort": "chỉ dự phòng", + "routeBoard.tag.channelsOff": "{count} đã tắt", + "routeBoard.tag.sticky": "giữ ×{count}", + "routeBoard.tag.noImages": "chỉ văn bản", + "routeBoard.context": "ngữ cảnh {size}", + "routeBoard.contextHint": "Bấm để xem con số này được tính thế nào.", + "routeBoard.strategyLabel": "Chiến lược cho {model}", + "routeBoard.enabledLabel": "Cung cấp {model} cho máy khách", + "routeBoard.enabledHint": "Tắt thì giữ nguyên cài đặt của combo nhưng không còn cung cấp cho máy khách.", + "routeBoard.notSaved": "Chưa lưu: {reason}", + "routeBoard.jevInAdvanced": "JEV cần một dịch vụ quyết định. Hãy đổi chiến lược sang JEV tại đây, kiểm tra dịch vụ nào quyết định, rồi lưu.", + "routeBoard.edit.aria": "Kênh của {model}", + "routeBoard.edit.drag": "Kéo để sắp xếp", + "routeBoard.edit.lastResortHint": "Chỉ dự phòng: chỉ dùng khi không còn kênh nào khác dùng được.", + "routeBoard.edit.lastResortInert": "Chưa có hiệu lực: bật “Kênh dự phòng xếp sau cùng” trong Cài đặt khác. Trước đó kênh này vẫn được dùng theo thứ tự như các kênh khác.", + "routeBoard.edit.moveUp": "Đưa {name} lên", + "routeBoard.edit.moveDown": "Đưa {name} xuống", + "routeBoard.edit.remove": "Bỏ {name}", + "routeBoard.edit.provider": "Nhà cung cấp", + "routeBoard.edit.model": "Mô hình", + "routeBoard.edit.noModels": "Không còn mô hình khác", + "routeBoard.edit.add": "Thêm kênh", + "routeBoard.edit.more": "Cài đặt khác", + "routeBoard.edit.unsaved": "Chưa lưu", + "routeBoard.locked": "chưa lưu trong Nâng cao", + "routeBoard.lockedHint": "Combo này có thay đổi chưa lưu trong trình sửa Nâng cao. Hãy lưu hoặc bỏ chúng ở đó trước khi sửa ở đây.", + "routeBoard.strategyHint.failover": "Theo thứ tự: kênh đầu tiên dùng được sẽ được dùng tiếp; khi hết hạn mức, bị giới hạn tốc độ hoặc lỗi thì chuyển sang kênh kế, chỉ trước khi phản hồi bắt đầu.", + "routeBoard.strategyHint.roundRobin": "Luân phiên: mỗi yêu cầu sang kênh kế tiếp, chia đều hạn mức.", + "routeBoard.strategyHint.random": "Ngẫu nhiên: mỗi yêu cầu chọn ngẫu nhiên một kênh dùng được.", + "routeBoard.strategyHint.leastUsed": "Ít dùng nhất: kênh ít được dùng gần đây nhất đi trước.", + "routeBoard.strategyHint.resetWindow": "Sắp đặt lại trước: tài khoản có hạn mức sắp đặt lại được dùng trước, để không lãng phí.", + "routeBoard.strategyHint.jev": "Thông minh: một mô hình nhỏ đọc yêu cầu trước, rồi chọn kênh và mức suy luận.", + "routeBoard.quota.family": "{family} · {window}", + "routeBoard.quota.paused": "(+{count} tạm dừng)", + "routeBoard.cap.title": "Khả năng", + "routeBoard.cap.intersection": "Giao", + "routeBoard.cap.intersectionHint": "Giao: cửa sổ ngữ cảnh lấy theo thành viên nhỏ nhất; hình ảnh và mức suy luận chỉ tính khi mọi thành viên đều hỗ trợ.", + "routeBoard.cap.union": "Hợp", + "routeBoard.cap.unionHint": "Hợp: công bố theo thành viên lớn nhất; yêu cầu không vừa, hoặc cần hình ảnh hay mức suy luận cao hơn, sẽ bỏ qua thành viên không nhận được.", + "routeBoard.cap.unservable": "Khi không kênh nào xử lý được", + "routeBoard.cap.degrade": "Giảm bớt", + "routeBoard.cap.degradeHint": "Bỏ phần không kênh nào hỗ trợ (ví dụ hình ảnh) và vẫn trả lời.", + "routeBoard.cap.reject": "Từ chối", + "routeBoard.cap.rejectHint": "Trả về lỗi thay vì trả lời khi thiếu phần đó.", + "routeBoard.more.fallbackOnly": "Kênh dự phòng xếp sau cùng", + "routeBoard.more.fallbackOnlyHint": "Bật: kênh đánh dấu dự phòng sẽ bị bỏ qua khi vẫn còn kênh khác dùng được. Tắt: chúng được dùng theo thứ tự như các kênh khác.", + "routeBoard.members.title": "Các con số của combo đến từ đâu", + "routeBoard.members.channel": "Kênh", + "routeBoard.members.context": "Ngữ cảnh", + "routeBoard.members.input": "Đầu vào", + "routeBoard.members.efforts": "Mức suy luận", + "routeBoard.members.text": "văn bản", + "routeBoard.members.image": "hình ảnh", + "routeBoard.members.unknown": "không rõ", + "routeBoard.members.none": "không có", + "routeBoard.members.combo": "Combo này", + "routeBoard.contextBasis.min": "(thành viên nhỏ nhất)", + "routeBoard.contextBasis.max": "(thành viên lớn nhất)", + "routeBoard.source.reported": "nhà cung cấp báo", + "routeBoard.source.inferred": "suy ra từ mô hình cùng tên", + "routeBoard.source.manual": "thủ công", + "routeBoard.source.unknown": "không rõ", + "routeBoard.members.actions": "Thao tác", + "routeBoard.members.edit": "Sửa", + "routeBoard.members.editAria": "Sửa những gì {name} nhận", + "routeBoard.members.contextPlaceholder": "vd. 200K hoặc 1M; để trống giữ giá trị của nhà cung cấp", + "routeBoard.members.contextInvalid": "Nhập số token, ví dụ 200000, 200K hoặc 1M.", + "routeBoard.members.scopeNote": "Lưu vào chính {name}: mọi combo dùng mô hình này đều thay đổi theo.", + "routeBoard.members.restore": "Dùng giá trị của nhà cung cấp", + "routeBoard.probe.run": "Kiểm tra", + "routeBoard.source.probed": "đã đo", + "routeBoard.basis.registry": "bảng tích hợp của {provider}", + "routeBoard.basis.vendor": "dữ liệu mô hình của {provider}", + "routeBoard.basis.provider": "{provider} đã cấu hình", + "routeBoard.basis.aggregator": "danh mục của {provider}", + "routeBoard.inferred.cell": "suy ra {value} (dựa trên {basis})", + "routeBoard.inferred.adopt": "Áp dụng", + "routeBoard.inferred.adoptAria": "Lưu giá trị suy ra {value} của {name} thành thiết lập thủ công", + "routeBoard.members.includesInferred": "có giá trị suy ra", + "routeBoard.probe.runAria": "Kiểm tra những gì {name} nhận", + "routeBoard.probe.running": "Đang kiểm tra…", + "routeBoard.probe.confirmTitle": "Xác nhận kiểm tra có tính phí", + "routeBoard.probe.confirm": "Nhà cung cấp này tính phí theo lượt: phép kiểm tra gửi {count} yêu cầu rất nhỏ. Tiếp tục?", + "routeBoard.probe.confirmGo": "Chạy kiểm tra", + "routeBoard.probe.reason.disabled": "Không kiểm tra được: nhà cung cấp này đang tắt.", + "routeBoard.probe.reason.forward_auth": "Không kiểm tra được: nhà cung cấp này chuyển tiếp đăng nhập của máy khách.", + "routeBoard.probe.reason.oauth_auth": "Không kiểm tra được: đăng nhập theo gói thuê bao không được kiểm tra.", + "routeBoard.probe.reason.unsupported_adapter": "Không kiểm tra được: chỉ kiểm tra được điểm cuối tương thích OpenAI.", + "routeBoard.probe.reason.unsupported_transport": "Không kiểm tra được: kiểu kết nối của nhà cung cấp này chưa được hỗ trợ.", + "routeBoard.probe.reason.other": "Không kiểm tra được nhà cung cấp này.", + "routeBoard.probe.busy": "Nhà cung cấp này đang được kiểm tra.", + "routeBoard.probe.failed": "Phép kiểm tra chưa xong. Không có gì thay đổi.", + "routeBoard.probe.uncertain": "Không chắc chắn: yêu cầu thường không qua được nên không có gì thay đổi.", + "routeBoard.probe.image": "Hình ảnh: {status}", + "routeBoard.probe.accepted": "chấp nhận", + "routeBoard.probe.rejected": "từ chối", + "routeBoard.probe.inconclusive": "không rõ", + "routeBoard.probe.efforts": "Mức suy luận chấp nhận: {accepted}; từ chối: {rejected}; không rõ: {inconclusive}", + "routeBoard.probe.appliedInput": "đã lưu đầu vào: {value}", + "routeBoard.probe.appliedEfforts": "đã lưu mức suy luận: {value}", + "routeBoard.probe.nothingApplied": "Không có kết quả chắc chắn nên không lưu gì.", + "routeBoard.probe.contextNote": "Ngữ cảnh được suy ra từ tên mô hình, không đo thực tế.", + "routeBoard.probe.close": "Đóng", + "comboSuggest.title": "Combo gợi ý", + "comboSuggest.lede": "Các model mà nhiều provider của bạn cùng phục vụ dưới một tên. Tạo combo để định tuyến một tên model qua tất cả chúng.", + "comboSuggest.servedBy": "được {count} provider phục vụ", + "comboSuggest.canAdd": "cũng có thể dùng {providers}", + "comboSuggest.generate": "Tạo", + "comboSuggest.addTo": "Thêm vào combo", + "comboSuggest.dismiss": "Bỏ qua", + "models.latestPerFamily": "Mới nhất mỗi dòng", + "models.latestPerFamilyHint": "Chỉ hiện mẫu mới nhất của mỗi dòng", + "comboSuggest.exclude.button": "Loại trừ nhà cung cấp…", + "comboSuggest.exclude.active": "Đã loại trừ: {names}", + "comboSuggest.exclude.head": "Không đưa vào combo gợi ý", + "comboSuggest.exclude.hint": "Mô hình của họ không vào combo gợi ý nào; combo bạn đã tạo vẫn giữ nguyên.", + "comboSuggest.exclude.restore": "Khôi phục", + "comboSuggest.exclude.saveFailed": "Không lưu được danh sách nhà cung cấp bị loại trừ.", + "comboSuggest.exclude.none": "Không còn gợi ý nào khi loại trừ các nhà cung cấp này.", + "comboSuggest.showAll": "Hiện tất cả {count}", + "comboSuggest.showFewer": "Thu gọn", + "comboSuggest.tier.ownSubscription": "gói đăng ký của nhà phát triển", + "comboSuggest.tier.subscription": "gói đăng ký", + "comboSuggest.tier.vertex": "credit Vertex", + "comboSuggest.tier.metered": "trả theo lượt dùng", + "comboSuggest.draft.id": "ID combo", + "comboSuggest.draft.orderHint": "Thử từ trên xuống: gói đăng ký trước, rồi credit Vertex, key trả theo lượt dùng và relay ở cuối. Sắp xếp lại hoặc xóa trước khi lưu.", + "comboSuggest.draft.left": "còn {percent}%", + "comboSuggest.draft.up": "Lên", + "comboSuggest.draft.down": "Xuống", + "comboSuggest.draft.remove": "Xóa", + "comboSuggest.draft.strategy": "Chiến lược: failover. Đổi trong hàng sau khi lưu.", + "comboSuggest.draft.cancel": "Hủy", + "comboSuggest.draft.save": "Lưu combo", + "comboSuggest.draft.saving": "Đang lưu…", }; diff --git a/gui/src/i18n/zh-TW.ts b/gui/src/i18n/zh-TW.ts index 33da090ccc0..b699b43c719 100644 --- a/gui/src/i18n/zh-TW.ts +++ b/gui/src/i18n/zh-TW.ts @@ -4492,4 +4492,152 @@ export const zhTW: Record = { "remoteLink.error.policy_write_failed": "無法儲存子裝置原則。", "remoteLink.error.runtime_role_client": "此電腦是子裝置;只有 Home 能操作子裝置。", "remoteLink.error.link_not_home_initiated": "此子裝置是自行連線的,請在其自己的電腦上操作。", + "routeBoard.lede": "每個組合背後掛了哪些通道、按什麼順序使用,都在這一頁。策略和開關在列中直接改;點一列編輯通道。", + "routeBoard.advanced": "進階", + "routeBoard.advancedHint": "完整的組合編輯器:別名、JEV 判定服務、推理強度、圖片輸入、原生別名。", + "routeBoard.backToOverview": "返回總覽", + "routeBoard.empty": "還沒有組合。組合對用戶端只顯示一個模型名稱,背後分給多個供應商。", + "routeBoard.listAria": "組合", + "routeBoard.window.weekly": "週", + "routeBoard.window.fiveHour": "5 小時", + "routeBoard.window.monthly": "月", + "routeBoard.quota.left": "{window} 剩 {percent}%", + "routeBoard.quota.accounts": "{provider}({count} 個帳號)", + "routeBoard.quota.metered": "按量計費", + "routeBoard.quota.unknown": "無額度資料", + "routeBoard.lastResort": "兜底", + "routeBoard.tag.channelsOff": "{count} 個已關閉", + "routeBoard.tag.sticky": "黏住 ×{count}", + "routeBoard.tag.noImages": "僅文字", + "routeBoard.context": "上下文 {size}", + "routeBoard.contextHint": "點一下,看這個數字是怎麼算出來的。", + "routeBoard.strategyLabel": "{model} 的策略", + "routeBoard.enabledLabel": "向用戶端提供 {model}", + "routeBoard.enabledHint": "關閉後保留組合設定,只是不再提供給用戶端。", + "routeBoard.notSaved": "未儲存:{reason}", + "routeBoard.jevInAdvanced": "JEV 需要判定服務。請在這裡把策略改成 JEV,確認由哪個服務判定,再儲存。", + "routeBoard.edit.aria": "{model} 的通道", + "routeBoard.edit.drag": "拖曳調整順序", + "routeBoard.edit.lastResortHint": "兜底:前面的通道都不可用時才使用。", + "routeBoard.edit.lastResortInert": "未生效:在「更多設定」裡開啟「兜底通道排在最後」。在此之前,它和其他通道一樣依序使用。", + "routeBoard.edit.moveUp": "上移 {name}", + "routeBoard.edit.moveDown": "下移 {name}", + "routeBoard.edit.remove": "移出 {name}", + "routeBoard.edit.provider": "供應商", + "routeBoard.edit.model": "模型", + "routeBoard.edit.noModels": "沒有其他模型", + "routeBoard.edit.add": "新增通道", + "routeBoard.edit.more": "更多設定", + "routeBoard.edit.unsaved": "未儲存", + "routeBoard.locked": "進階中有未儲存的修改", + "routeBoard.lockedHint": "此組合在「進階」編輯器中有未儲存的修改。請先在那裡儲存或捨棄,再在這裡修改。", + "routeBoard.strategyHint.failover": "按順序:第一條能用就一直用它;額度用完、被限流或報錯時換下一條,只在回覆開始之前換。", + "routeBoard.strategyHint.roundRobin": "輪流:每次請求換下一條通道,分攤額度。", + "routeBoard.strategyHint.random": "隨機:每次隨機挑一條能用的。", + "routeBoard.strategyHint.leastUsed": "最少使用:最近用得最少的通道先上。", + "routeBoard.strategyHint.resetWindow": "先用快重置的:額度快重置的帳號先用,免得重置時白白浪費。", + "routeBoard.strategyHint.jev": "智慧判斷:先讓一個小模型看請求,再決定發給哪條、用多大的推理強度。", + "routeBoard.quota.family": "{family} · {window}", + "routeBoard.quota.paused": "(另有 {count} 個已暫停)", + "routeBoard.cap.title": "能力", + "routeBoard.cap.intersection": "取交集", + "routeBoard.cap.intersectionHint": "取交集:上下文按最小成員計算,圖片和推理檔位只算所有成員都支援的。", + "routeBoard.cap.union": "取聯集", + "routeBoard.cap.unionHint": "取聯集:按最大成員宣稱;放不下、要圖片或要高檔位的請求,自動跳過接不了的成員。", + "routeBoard.cap.unservable": "都接不了時", + "routeBoard.cap.degrade": "降級", + "routeBoard.cap.degradeHint": "去掉沒有通道支援的部分(例如圖片),照常回答。", + "routeBoard.cap.reject": "拒絕", + "routeBoard.cap.rejectHint": "直接回傳錯誤,不在缺了這部分的情況下回答。", + "routeBoard.more.fallbackOnly": "兜底通道排在最後", + "routeBoard.more.fallbackOnlyHint": "開:標了兜底的通道,只要還有別的通道能用就跳過。關:它們和其他通道一樣依序使用。", + "routeBoard.members.title": "組合的數字是怎麼來的", + "routeBoard.members.channel": "通道", + "routeBoard.members.context": "上下文", + "routeBoard.members.input": "輸入", + "routeBoard.members.efforts": "推理檔位", + "routeBoard.members.text": "文字", + "routeBoard.members.image": "圖片", + "routeBoard.members.unknown": "未知", + "routeBoard.members.none": "無", + "routeBoard.members.combo": "這個組合", + "routeBoard.contextBasis.min": "(最小成員)", + "routeBoard.contextBasis.max": "(最大成員)", + "routeBoard.source.reported": "提供方回報", + "routeBoard.source.inferred": "同名模型推斷", + "routeBoard.source.manual": "手動", + "routeBoard.source.unknown": "未知", + "routeBoard.members.actions": "操作", + "routeBoard.members.edit": "修改", + "routeBoard.members.editAria": "修改 {name} 能接收的內容", + "routeBoard.members.contextPlaceholder": "例如 200K、1M;留空則用提供方的值", + "routeBoard.members.contextInvalid": "請輸入 token 數,例如 200000、200K 或 1M。", + "routeBoard.members.scopeNote": "改的是 {name} 這個模型本身:所有用到它的組合都會跟著變。", + "routeBoard.members.restore": "恢復提供方的值", + "routeBoard.probe.run": "測一下", + "routeBoard.source.probed": "實測", + "routeBoard.basis.registry": "{provider} 內建表", + "routeBoard.basis.vendor": "{provider} 模型資料", + "routeBoard.basis.provider": "已設定的 {provider}", + "routeBoard.basis.aggregator": "{provider} 目錄", + "routeBoard.inferred.cell": "推斷 {value}(依據 {basis})", + "routeBoard.inferred.adopt": "採用", + "routeBoard.inferred.adoptAria": "把 {name} 的推斷值 {value} 存成手動設定", + "routeBoard.members.includesInferred": "含推斷", + "routeBoard.probe.runAria": "測一下 {name} 能接收什麼", + "routeBoard.probe.running": "正在測…", + "routeBoard.probe.confirmTitle": "確認付費測試", + "routeBoard.probe.confirm": "這家按量計費,會發 {count} 個很小的請求。繼續嗎?", + "routeBoard.probe.confirmGo": "繼續測", + "routeBoard.probe.reason.disabled": "測不了:這家提供方已關閉。", + "routeBoard.probe.reason.forward_auth": "測不了:這家提供方轉發的是用戶端自己的登入。", + "routeBoard.probe.reason.oauth_auth": "測不了:訂閱登入的提供方不做探測。", + "routeBoard.probe.reason.unsupported_adapter": "測不了:只能探測 OpenAI 相容的介面。", + "routeBoard.probe.reason.unsupported_transport": "測不了:不支援這家提供方的連線方式。", + "routeBoard.probe.reason.other": "這家提供方測不了。", + "routeBoard.probe.busy": "這家正在探測。", + "routeBoard.probe.failed": "測試沒跑完,沒有改任何值。", + "routeBoard.probe.uncertain": "探測不確定:一般請求沒通過,沒有改任何值。", + "routeBoard.probe.image": "圖片:{status}", + "routeBoard.probe.accepted": "接受", + "routeBoard.probe.rejected": "拒絕", + "routeBoard.probe.inconclusive": "不確定", + "routeBoard.probe.efforts": "推理檔位 接受:{accepted};拒絕:{rejected};不確定:{inconclusive}", + "routeBoard.probe.appliedInput": "已寫入輸入:{value}", + "routeBoard.probe.appliedEfforts": "已寫入檔位:{value}", + "routeBoard.probe.nothingApplied": "沒有確定的結果,沒有寫入任何值。", + "routeBoard.probe.contextNote": "上下文從名字推斷,不實測。", + "routeBoard.probe.close": "關閉", + "comboSuggest.title": "推薦組合", + "comboSuggest.lede": "多家供應商都以同一名稱提供的模型。生成一個組合,就能用一個模型名在這幾家之間路由。", + "comboSuggest.servedBy": "{count} 家供應商都有", + "comboSuggest.canAdd": "還可以加進 {providers}", + "comboSuggest.generate": "生成", + "comboSuggest.addTo": "加進組合", + "comboSuggest.dismiss": "忽略", + "models.latestPerFamily": "每系最新", + "models.latestPerFamilyHint": "只顯示每個系列最新的模型", + "comboSuggest.exclude.button": "排除供應商…", + "comboSuggest.exclude.active": "已排除:{names}", + "comboSuggest.exclude.head": "不參與推薦組合", + "comboSuggest.exclude.hint": "它們的模型不會出現在推薦組合裡;你已建好的組合不受影響。", + "comboSuggest.exclude.restore": "恢復", + "comboSuggest.exclude.saveFailed": "排除的供應商沒能儲存。", + "comboSuggest.exclude.none": "排除這些供應商後,沒有可推薦的組合了。", + "comboSuggest.showAll": "顯示全部 {count} 條", + "comboSuggest.showFewer": "收起", + "comboSuggest.tier.ownSubscription": "原廠訂閱", + "comboSuggest.tier.subscription": "訂閱", + "comboSuggest.tier.vertex": "Vertex 贈金", + "comboSuggest.tier.metered": "按量計費", + "comboSuggest.draft.id": "組合 ID", + "comboSuggest.draft.orderHint": "從上往下依次嘗試:訂閱在前,其次 Vertex 贈金,按量 API key 和中轉站最後。儲存前可以調整順序或刪掉某一家。", + "comboSuggest.draft.left": "剩 {percent}%", + "comboSuggest.draft.up": "上移", + "comboSuggest.draft.down": "下移", + "comboSuggest.draft.remove": "刪掉", + "comboSuggest.draft.strategy": "策略:容錯移轉。儲存後可以在列中改。", + "comboSuggest.draft.cancel": "取消", + "comboSuggest.draft.save": "儲存組合", + "comboSuggest.draft.saving": "正在儲存…", }; diff --git a/gui/src/i18n/zh.ts b/gui/src/i18n/zh.ts index fe8f2d4c4d9..a28a6361876 100644 --- a/gui/src/i18n/zh.ts +++ b/gui/src/i18n/zh.ts @@ -4527,4 +4527,152 @@ export const zh: Record = { "remoteLink.error.policy_write_failed": "无法保存子设备策略。", "remoteLink.error.runtime_role_client": "此计算机是子设备;只有 Home 才能操作子设备。", "remoteLink.error.link_not_home_initiated": "此子设备是自行连接的,请在其自己的计算机上操作。", + "routeBoard.lede": "每个组合背后挂了哪些通道、按什么顺序用,都在这一页。策略和开关在行里直接改;点一行编辑通道。", + "routeBoard.advanced": "高级", + "routeBoard.advancedHint": "完整的组合编辑器:别名、JEV 判定服务、推理强度、图片输入、原生别名。", + "routeBoard.backToOverview": "返回总览", + "routeBoard.empty": "还没有组合。组合对客户端只显示一个模型名,背后分给多个供应商。", + "routeBoard.listAria": "组合", + "routeBoard.window.weekly": "周", + "routeBoard.window.fiveHour": "5 小时", + "routeBoard.window.monthly": "月", + "routeBoard.quota.left": "{window} {percent}% 剩", + "routeBoard.quota.accounts": "{provider}({count} 个账号)", + "routeBoard.quota.metered": "按量", + "routeBoard.quota.unknown": "无额度数据", + "routeBoard.lastResort": "兜底", + "routeBoard.tag.channelsOff": "{count} 个已关闭", + "routeBoard.tag.sticky": "粘住 ×{count}", + "routeBoard.tag.noImages": "仅文字", + "routeBoard.context": "上下文 {size}", + "routeBoard.contextHint": "点一下,看这个数是怎么算出来的。", + "routeBoard.strategyLabel": "{model} 的策略", + "routeBoard.enabledLabel": "向客户端提供 {model}", + "routeBoard.enabledHint": "关掉后保留组合设置,只是不再提供给客户端。", + "routeBoard.notSaved": "没有保存:{reason}", + "routeBoard.jevInAdvanced": "JEV 需要判定服务。请在这里把策略改成 JEV,看清由哪个服务判定,再保存。", + "routeBoard.edit.aria": "{model} 的通道", + "routeBoard.edit.drag": "拖动调整顺序", + "routeBoard.edit.lastResortHint": "兜底:前面的通道都不可用时才用它。", + "routeBoard.edit.lastResortInert": "没生效:在「更多设置」里打开「兜底通道排在最后」。在那之前,它和其他通道一样按顺序用。", + "routeBoard.edit.moveUp": "上移 {name}", + "routeBoard.edit.moveDown": "下移 {name}", + "routeBoard.edit.remove": "移出 {name}", + "routeBoard.edit.provider": "供应商", + "routeBoard.edit.model": "模型", + "routeBoard.edit.noModels": "没有其他模型", + "routeBoard.edit.add": "加通道", + "routeBoard.edit.more": "更多设置", + "routeBoard.edit.unsaved": "未保存", + "routeBoard.locked": "高级里有未保存的修改", + "routeBoard.lockedHint": "这个组合在「高级」编辑器里有未保存的修改。先在那里保存或放弃,再在这里改。", + "routeBoard.strategyHint.failover": "按顺序:第一条能用就一直用它;额度用完、被限流或报错时换下一条,只在回复开始之前换。", + "routeBoard.strategyHint.roundRobin": "轮流:每次请求换下一条通道,分摊额度。", + "routeBoard.strategyHint.random": "随机:每次随机挑一条能用的。", + "routeBoard.strategyHint.leastUsed": "最少使用:最近用得最少的通道先上。", + "routeBoard.strategyHint.resetWindow": "先用快重置的:额度快重置的账号先用,免得重置时白白浪费。", + "routeBoard.strategyHint.jev": "智能判断:先让一个小模型看请求,再决定发给哪条、用多大的推理强度。", + "routeBoard.quota.family": "{family} · {window}", + "routeBoard.quota.paused": "(另有 {count} 个已暂停)", + "routeBoard.cap.title": "能力", + "routeBoard.cap.intersection": "取交集", + "routeBoard.cap.intersectionHint": "取交集:上下文按最小成员算,图片和推理档位只算所有成员都支持的。", + "routeBoard.cap.union": "取并集", + "routeBoard.cap.unionHint": "取并集:按最大成员宣称;放不下、要图片或要高档位的请求,自动跳过接不了的成员。", + "routeBoard.cap.unservable": "都接不了时", + "routeBoard.cap.degrade": "降级", + "routeBoard.cap.degradeHint": "去掉没有通道支持的部分(比如图片),照常回答。", + "routeBoard.cap.reject": "拒绝", + "routeBoard.cap.rejectHint": "直接报错,不在缺了这部分的情况下回答。", + "routeBoard.more.fallbackOnly": "兜底通道排在最后", + "routeBoard.more.fallbackOnlyHint": "开:标了兜底的通道,只要还有别的通道能用就跳过。关:它们和其他通道一样按顺序用。", + "routeBoard.members.title": "组合的数字是怎么来的", + "routeBoard.members.channel": "通道", + "routeBoard.members.context": "上下文", + "routeBoard.members.input": "输入", + "routeBoard.members.efforts": "推理档位", + "routeBoard.members.text": "文字", + "routeBoard.members.image": "图片", + "routeBoard.members.unknown": "未知", + "routeBoard.members.none": "无", + "routeBoard.members.combo": "这个组合", + "routeBoard.contextBasis.min": "(最小成员)", + "routeBoard.contextBasis.max": "(最大成员)", + "routeBoard.source.reported": "提供方报告", + "routeBoard.source.inferred": "同名模型推断", + "routeBoard.source.manual": "手动", + "routeBoard.source.unknown": "未知", + "routeBoard.members.actions": "操作", + "routeBoard.members.edit": "修改", + "routeBoard.members.editAria": "修改 {name} 能接收的内容", + "routeBoard.members.contextPlaceholder": "例如 200K、1M;留空则用提供方的值", + "routeBoard.members.contextInvalid": "请输入 token 数,例如 200000、200K 或 1M。", + "routeBoard.members.scopeNote": "改的是 {name} 这个模型本身:所有用到它的组合都会跟着变。", + "routeBoard.members.restore": "恢复提供方的值", + "routeBoard.probe.run": "测一下", + "routeBoard.source.probed": "实测", + "routeBoard.basis.registry": "{provider} 内置表", + "routeBoard.basis.vendor": "{provider} 模型资料", + "routeBoard.basis.provider": "已配置的 {provider}", + "routeBoard.basis.aggregator": "{provider} 目录", + "routeBoard.inferred.cell": "推断 {value}(依据 {basis})", + "routeBoard.inferred.adopt": "采用", + "routeBoard.inferred.adoptAria": "把 {name} 的推断值 {value} 存成手动设置", + "routeBoard.members.includesInferred": "含推断", + "routeBoard.probe.runAria": "测一下 {name} 能接收什么", + "routeBoard.probe.running": "正在测…", + "routeBoard.probe.confirmTitle": "确认付费测试", + "routeBoard.probe.confirm": "这家按量计费,会发 {count} 个很小的请求。继续吗?", + "routeBoard.probe.confirmGo": "继续测", + "routeBoard.probe.reason.disabled": "测不了:这家提供方已关闭。", + "routeBoard.probe.reason.forward_auth": "测不了:这家提供方转发的是客户端自己的登录。", + "routeBoard.probe.reason.oauth_auth": "测不了:订阅登录的提供方不做探测。", + "routeBoard.probe.reason.unsupported_adapter": "测不了:只能探测 OpenAI 兼容的接口。", + "routeBoard.probe.reason.unsupported_transport": "测不了:不支持这家提供方的连接方式。", + "routeBoard.probe.reason.other": "这家提供方测不了。", + "routeBoard.probe.busy": "这家正在探测。", + "routeBoard.probe.failed": "测试没跑完,没有改任何值。", + "routeBoard.probe.uncertain": "探测不确定:普通请求没通过,没有改任何值。", + "routeBoard.probe.image": "图片:{status}", + "routeBoard.probe.accepted": "接受", + "routeBoard.probe.rejected": "拒绝", + "routeBoard.probe.inconclusive": "不确定", + "routeBoard.probe.efforts": "推理档位 接受:{accepted};拒绝:{rejected};不确定:{inconclusive}", + "routeBoard.probe.appliedInput": "已写入输入:{value}", + "routeBoard.probe.appliedEfforts": "已写入档位:{value}", + "routeBoard.probe.nothingApplied": "没有确定的结果,没有写入任何值。", + "routeBoard.probe.contextNote": "上下文从名字推断,不实测。", + "routeBoard.probe.close": "关闭", + "comboSuggest.title": "推荐组合", + "comboSuggest.lede": "你有两家以上提供方都提供同名的模型。生成一个组合,就能用一个模型名在这几家之间路由。", + "comboSuggest.servedBy": "{count} 家提供方都有", + "comboSuggest.canAdd": "还可以加进 {providers}", + "comboSuggest.generate": "生成", + "comboSuggest.addTo": "加进组合", + "comboSuggest.dismiss": "忽略", + "models.latestPerFamily": "每系最新", + "models.latestPerFamilyHint": "只显示每个系列最新的模型", + "comboSuggest.exclude.button": "排除供应商…", + "comboSuggest.exclude.active": "已排除:{names}", + "comboSuggest.exclude.head": "不参与推荐组合", + "comboSuggest.exclude.hint": "它们的模型不会出现在推荐组合里;你已建好的组合不受影响。", + "comboSuggest.exclude.restore": "恢复", + "comboSuggest.exclude.saveFailed": "排除的供应商没能保存。", + "comboSuggest.exclude.none": "排除这些供应商后,没有可推荐的组合了。", + "comboSuggest.showAll": "显示全部 {count} 条", + "comboSuggest.showFewer": "收起", + "comboSuggest.tier.ownSubscription": "原厂订阅", + "comboSuggest.tier.subscription": "订阅", + "comboSuggest.tier.vertex": "Vertex 赠金", + "comboSuggest.tier.metered": "按量计费", + "comboSuggest.draft.id": "组合 ID", + "comboSuggest.draft.orderHint": "从上往下依次尝试:订阅在前,其次 Vertex 赠金,按量 API key 和中转站最后。保存前可以调整顺序或删掉某一家。", + "comboSuggest.draft.left": "剩 {percent}%", + "comboSuggest.draft.up": "上移", + "comboSuggest.draft.down": "下移", + "comboSuggest.draft.remove": "删掉", + "comboSuggest.draft.strategy": "策略:故障转移。保存后可以在行里改。", + "comboSuggest.draft.cancel": "取消", + "comboSuggest.draft.save": "保存组合", + "comboSuggest.draft.saving": "正在保存…", }; diff --git a/gui/src/lib/latest-per-family-pref.ts b/gui/src/lib/latest-per-family-pref.ts new file mode 100644 index 00000000000..6f6d510b0a9 --- /dev/null +++ b/gui/src/lib/latest-per-family-pref.ts @@ -0,0 +1,29 @@ +/** + * The "latest per family" view switch on model pickers (a provider's model list, the combo + * member picker). View state of this browser only, default off; it never changes what a + * provider serves or what a combo routes to. + */ +import { useState } from "react"; + +const KEY = "ocx.models.latestPerFamily.v1"; + +export function readLatestPerFamilyPref(): boolean { + try { + return window.localStorage.getItem(KEY) === "1"; + } catch { + return false; + } +} + +export function writeLatestPerFamilyPref(on: boolean): void { + try { + window.localStorage.setItem(KEY, on ? "1" : "0"); + } catch { + // Storage disabled: the switch still works for this page view. + } +} + +export function useLatestPerFamilyPref(): [boolean, (on: boolean) => void] { + const [on, setOn] = useState(readLatestPerFamilyPref); + return [on, (next: boolean) => { writeLatestPerFamilyPref(next); setOn(next); }]; +} diff --git a/gui/src/lib/model-family.ts b/gui/src/lib/model-family.ts new file mode 100644 index 00000000000..6451488dcaa --- /dev/null +++ b/gui/src/lib/model-family.ts @@ -0,0 +1,156 @@ +/* + * Model families and "latest per family", adapted from Magpie (https://github.com/yetone/magpie), + * MIT License, Copyright (c) yetone: `FamilyOf`, `newerInFamily` and `BestInFamily` in + * internal/catalog/family.go. + * + * MIT License + * + * Copyright (c) 2026 yetone + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + * Changes from the original: TypeScript; ids only (OpenCodex's pickers carry no release date, so + * the release-date tie-break is gone and the later snapshot decides directly). Pure: no React, + * no storage. + * + * A model's family is its id with the version numbers taken out, so claude-opus-4-8 and + * claude-opus-5-5 are claude-opus, o3 and o1 are o, and o4-mini is o-mini. Read off the id alone: + * + * - a version: a number (4, 4.5), the digits a word ends in (qwen3, o4, k2), a v and its digits + * (v3, v1:0), or the digits a word starts with that aren't a size (gpt-4o is gpt-o); + * - a size, which stays in the name: 8b, 70b, 1.5b, a22b, 8x7b, 128e, 32k; + * - a snapshot: a date or revision (20251101, 0528, 2507, 2024-08-06, 05-20, 001); + * - a preview (preview, exp, beta): the same model before its release; + * - latest, an alias of the newest. + * + * Every other word stays in the name: -mini, -pro, -flash-lite, -codex, :free, a provider prefix. + */ + +export interface ModelFamily { + /** The id, lowercased, without its version, snapshot or preview. */ + name: string; + /** Every version number, in the order the id has them. */ + version: number[]; + /** Its dates or revision, "" for an alias. */ + snapshot: string; + preview: boolean; +} + +const SEP = /[-_/:@[\]\s]+/; +const SEP_ALL = /[-_/:@[\]\s]+/g; +const NUM = /^\d+(?:\.\d+)*$/; +const TAIL = /^([a-z][a-z.]*?[a-z])(\d+(?:\.\d+)*)$|^([a-z])(\d+(?:\.\d+)*)$/; +const HEAD = /^(\d+(?:\.\d+)*)([a-z]+)$/; +const SIZE = /^(?:[a-z]?\d+(?:\.\d+)?|\d+x\d+(?:\.\d+)?)[bmkte]$/; +const YEAR = /^(?:19|20)\d\d$/; +const PREVIEW = new Set(["preview", "exp", "experimental", "beta", "alpha"]); + +/** What an id's name says about it: the family it belongs to and where it stands in it. */ +export function familyOf(id: string): ModelFamily { + const s = id.trim().toLowerCase(); + const words = s.split(SEP); + const seps = s.match(SEP_ALL) ?? []; + // which purely numeric words are a snapshot rather than a version + const snap = words.map((w) => NUM.test(w) && !w.includes(".") && (w.length >= 4 || (w.length >= 2 && w[0] === "0"))); + words.forEach((w, i) => { + if (snap[i] || !NUM.test(w) || w.length !== 2) return; + // the day after a month (05-20), the month before a year (12-2024) + if ((i > 0 && snap[i - 1]) || (i + 1 < words.length && YEAR.test(words[i + 1]!))) snap[i] = true; + }); + const version: number[] = []; + let name = ""; + const snaps: string[] = []; + let preview = false; + const keep = (i: number, w: string) => { + if (name.length > 0 && i > 0) name += seps[i - 1] ?? ""; + name += w; + }; + const addVersion = (v: string) => { + for (const n of v.split(".")) { + const x = Number.parseInt(n, 10); + version.push(Number.isFinite(x) ? x : 0); + } + }; + words.forEach((w, i) => { + if (w === "") return; + if (snap[i]) { snaps.push(w); return; } + if (PREVIEW.has(w)) { preview = true; return; } + if (w === "latest") return; + if (NUM.test(w)) { addVersion(w); return; } + if (SIZE.test(w)) { keep(i, w); return; } + const tail = TAIL.exec(w); + if (tail) { + const word = tail[1] ?? tail[3]!; + const v = tail[2] ?? tail[4]!; + if (word !== "v") keep(i, word); // v3, v1: the version alone + addVersion(v); + return; + } + const head = HEAD.exec(w); + if (head) { + addVersion(head[1]!); + keep(i, head[2]!); + return; + } + keep(i, w); + }); + // all numbers: a family of its own + return { name: name || s, version, snapshot: snaps.join("-"), preview }; +} + +/** The family an id belongs to: two ids with the same key are versions of one model. */ +export function modelFamilyKey(id: string): string { + return familyOf(id).name; +} + +function compareVersions(a: readonly number[], b: readonly number[]): number { + for (let i = 0; i < Math.min(a.length, b.length); i++) { + if (a[i] !== b[i]) return a[i]! - b[i]!; + } + return a.length - b.length; +} + +/** + * `a`, of the same family as `b`, is the one to show over it: the higher version; at the same + * version a release over a preview, then the alias over a dated snapshot (the alias names the + * vendor's current one), then the later snapshot. + */ +function newerInFamily(a: ModelFamily, b: ModelFamily): boolean { + const c = compareVersions(a.version, b.version); + if (c !== 0) return c > 0; + if (a.preview !== b.preview) return b.preview; + if ((a.snapshot === "") !== (b.snapshot === "")) return a.snapshot === ""; + return a.snapshot > b.snapshot; +} + +/** `items` with only the newest of each family left, in their order. A family's first listed wins a tie. */ +export function latestPerFamilyBy(items: readonly T[], idOf: (item: T) => string): T[] { + const families = items.map((item) => familyOf(idOf(item))); + const best = new Map(); + families.forEach((family, i) => { + const j = best.get(family.name); + if (j === undefined || newerInFamily(family, families[j]!)) best.set(family.name, i); + }); + return items.filter((_, i) => best.get(families[i]!.name) === i); +} + +/** `ids` with only the newest model of each family left, in their order. */ +export function latestPerFamily(ids: readonly string[]): string[] { + return latestPerFamilyBy(ids, (id) => id); +} diff --git a/gui/src/pages/Combos.tsx b/gui/src/pages/Combos.tsx index 616de085480..a9d0c194bc0 100644 --- a/gui/src/pages/Combos.tsx +++ b/gui/src/pages/Combos.tsx @@ -8,6 +8,7 @@ import { providerQuotaStatesFromReports, nextProviderQuotaStateExpiration, toPutBody, + validateComboDraft, } from "../combo-workspace-data"; import { hostDocumentHidden, onHostVisibilityChange } from "../host-visibility"; import { hideRedundantChatGptForwardProviders } from "../provider-workspace/catalog"; @@ -16,9 +17,37 @@ import { Notice } from "../ui"; import { useT } from "../i18n/shared"; import { useDataSurface } from "../data-surface"; import { DataSurfaceSkeleton } from "../components/data-surface"; -import { replaceHash } from "../hash-routing"; +import { navigateHash, replaceHash } from "../hash-routing"; import { jevAutoCreateDecisionProvider } from "../app-routing"; +import { COMBOS_ADVANCED_HASH } from "./combos-advanced-hash"; import type { ComboAddIntent } from "../components/combo-workspace-types"; +import { RouteBoard } from "../components/route-board/RouteBoard"; +import { ComboSuggestions } from "../components/route-board/ComboSuggestions"; +import { useSuggestionExclusions } from "../components/route-board/use-suggestion-exclusions"; +import type { EditableChannel } from "../components/route-board/ChannelEditor"; +import { comboDraftErrorText } from "../components/combo-workspace-utils"; +import { putModelVisibility } from "../model-visibility"; +import { + accountCountFromList, + channelKey, + channelQuota, + quotaWindowsByProvider, + channelTargetsForPut, + capabilitySource, + parseCapabilitySources, + parseInferredCapabilities, + parseProbeResponse, + type MemberInferred, + type ProbeOutcome, + configuredMemberModels, + parseCapabilitySettings, + type AccountCount, + type ComboCapabilitySettings, + type ComboCatalogMeta, + type MemberSources, + type ComboSettingsPatch, +} from "../route-board-model"; +import { readCombosView, type CombosView } from "./combos-view"; type ProviderOption = { name: string; @@ -38,6 +67,9 @@ type ModelOption = { inputModalities?: string[]; inputModalitiesDeclared?: string[]; visionSidecarConsumer?: boolean; + contextWindow?: number; + sources?: MemberSources; + inferred?: MemberInferred; }; type ProviderDto = { adapter: string; @@ -54,6 +86,15 @@ type CachedCombosPage = { models: ModelOption[]; capabilityModels?: ModelOption[]; cataloguedComboIds: string[]; + /** Route board extras; absent in a session cache written before they existed. */ + comboCatalog?: Record; + lastResort?: Record; + lastResortActive?: string[]; + capability?: Record; + /** Catalog models plus configured-only members, for the route board's member table. */ + memberModels?: ModelOption[]; + /** `provider/model` rows hidden from the catalog; suggestions rank combos with a listed member first. */ + hiddenModels?: string[]; }; type ProviderQuotasDto = { reports?: unknown }; @@ -94,6 +135,7 @@ export default function Combos({ const t = useT(); const cacheKey = `ocx.combos.workspace.v2:${apiBase}`; const cached = useMemo(() => seedCombos(cacheKey), [cacheKey]); + const suggestionExclusions = useSuggestionExclusions(apiBase); /* * The last coherent payload, kept so a hidden panel can keep rendering. @@ -118,11 +160,31 @@ export default function Combos({ () => jevAutoCreateDecisionProvider(window.location.hash) ?? null, ); + /* + * Overview by default; the full workspace behind "Advanced" (and the JEV Auto deep link). + * The workspace stays mounted once opened, so an unsaved editor draft survives a trip to the + * overview the same way it survives a tab hop. + */ + const [view, setView] = useState(() => readCombosView()); + const [workspaceMounted, setWorkspaceMounted] = useState(() => readCombosView() === "advanced"); + const [selectRequest, setSelectRequest] = useState<{ id: string; seq: number } | undefined>(); + // An overview save on this combo would replace the workspace's baseline and drop its draft. + const [draftComboId, setDraftComboId] = useState(null); + useEffect(() => { + const sync = () => { + const next = readCombosView(); + setView(next); + if (next === "advanced") setWorkspaceMounted(true); + }; + window.addEventListener("hashchange", sync); + return () => window.removeEventListener("hashchange", sync); + }, []); + const closeAdd = useCallback(() => { setAddIntent(null); setAddDecisionProvider(null); if (jevAutoCreateDecisionProvider(window.location.hash) !== undefined) { - replaceHash("models/combos"); + replaceHash(COMBOS_ADVANCED_HASH); } }, []); @@ -131,6 +193,18 @@ export default function Combos({ setStatusOk(ok); }; + const openAdvanced = (id?: string, reason?: "jev") => { + if (id) setSelectRequest((current) => ({ id, seq: (current?.seq ?? 0) + 1 })); + if (reason === "jev") notify(t("routeBoard.jevInAdvanced"), true); + setWorkspaceMounted(true); + setView("advanced"); + navigateHash(COMBOS_ADVANCED_HASH); + }; + const openOverview = () => { + setView("overview"); + navigateHash("models/combos"); + }; + // Success banners are transient; errors stay until the next notify. useEffect(() => { if (!status || !statusOk) return; @@ -163,6 +237,24 @@ export default function Combos({ : []; const combos = parseComboList(combosJson); + // parseComboList keeps only what the workspace edits; the overview also shows last-resort marks. + const lastResort: Record = {}; + const lastResortActive: string[] = []; + const capability: Record = {}; + const rawCombos = (combosJson as { combos?: unknown } | null)?.combos; + for (const raw of Array.isArray(rawCombos) ? rawCombos : []) { + if (!raw || typeof raw !== "object") continue; + const { id, targets, cooldownWaitPolicy, capabilityPolicy, onUnservable } = raw as { + id?: unknown; targets?: unknown; cooldownWaitPolicy?: unknown; capabilityPolicy?: unknown; onUnservable?: unknown; + }; + if (typeof id !== "string" || !Array.isArray(targets)) continue; + capability[id.trim()] = parseCapabilitySettings({ capabilityPolicy, onUnservable }); + lastResort[id.trim()] = targets.flatMap((target: { provider?: unknown; model?: unknown; lastResort?: unknown } | null) => + target?.lastResort === true && typeof target.provider === "string" && typeof target.model === "string" + ? [channelKey(target.provider.trim(), target.model.trim())] + : []); + if (cooldownWaitPolicy === "before-last-resort") lastResortActive.push(id.trim()); + } const allProviders = configJson.providers ?? {}; // Collapse canonical forward aliases only in the new-member picker. Validation keeps // every configured provider id, including legacy chatgpt members already in a combo. @@ -179,8 +271,13 @@ export default function Combos({ })); const models: ModelOption[] = []; + /** Where each catalog member's capability values come from; only the route board reads it. */ + const sourcesByKey = new Map(); + const inferredByKey = new Map(); const capabilityModels: ModelOption[] = []; const catalogued = new Set(); + const comboCatalog: Record = {}; + const hiddenModels: string[] = []; const parseModalities = (raw: unknown): string[] | undefined => Array.isArray(raw) ? raw.flatMap((modality) => { @@ -195,10 +292,17 @@ export default function Combos({ id?: unknown; namespaced?: unknown; disabled?: unknown; + displayName?: unknown; + displayNameSource?: unknown; + contextWindow?: unknown; reasoningEfforts?: unknown; inputModalities?: unknown; inputModalitiesDeclared?: unknown; visionSidecarConsumer?: unknown; + contextWindowDeclared?: unknown; + reasoningOverridden?: unknown; + capabilitySources?: unknown; + inferredCapabilities?: unknown; }; if (typeof model.provider !== "string" || typeof model.id !== "string") continue; const provider = model.provider.trim(); @@ -206,6 +310,15 @@ export default function Combos({ if (!provider || !id) continue; if (provider === "combo") { catalogued.add(id); + comboCatalog[id] = { + disabled: model.disabled === true, + ...(typeof model.displayName === "string" && model.displayNameSource !== "fallback" + ? { displayName: model.displayName } + : {}), + ...(typeof model.contextWindow === "number" && model.contextWindow > 0 + ? { contextWindow: model.contextWindow } + : {}), + }; continue; // combos cannot nest other combos as targets } const reasoningEfforts = Array.isArray(model.reasoningEfforts) @@ -221,7 +334,18 @@ export default function Combos({ ...(inputModalities && inputModalities.length > 0 ? { inputModalities } : {}), ...(inputModalitiesDeclared && inputModalitiesDeclared.length > 0 ? { inputModalitiesDeclared } : {}), visionSidecarConsumer: model.visionSidecarConsumer === true, + ...(typeof model.contextWindow === "number" && model.contextWindow > 0 ? { contextWindow: model.contextWindow } : {}), }; + // The server labels each axis (`capabilitySources`); an older server does not, so fall back + // to the manual flags it does send. + sourcesByKey.set(channelKey(provider, id), parseCapabilitySources(model.capabilitySources) ?? { + context: capabilitySource(typeof model.contextWindow === "number", typeof model.contextWindowDeclared === "number"), + input: capabilitySource(Boolean(inputModalities?.length), Boolean(inputModalitiesDeclared?.length)), + efforts: capabilitySource(reasoningEfforts !== undefined, model.reasoningOverridden === true), + }); + if (model.disabled === true) hiddenModels.push(`${provider}/${id}`); + const inferred = parseInferredCapabilities(model.inferredCapabilities); + if (inferred) inferredByKey.set(channelKey(provider, id), inferred); capabilityModels.push(option); models.push(option); // Catalog visibility does not restrict internal Combo selection. } @@ -235,7 +359,27 @@ export default function Combos({ } } - const next = { combos, providers, models, capabilityModels, cataloguedComboIds: [...catalogued] } satisfies CachedCombosPage; + const catalogKeys = new Set(models.map((model) => channelKey(model.provider, model.id))); + const memberModels = [ + ...models.map((model) => { + const key = channelKey(model.provider, model.id); + const sources = sourcesByKey.get(key); + const inferred = inferredByKey.get(key); + return { ...model, ...(sources ? { sources } : {}), ...(inferred ? { inferred } : {}) }; + }), + ...configuredMemberModels(allProviders) + .filter((member) => !catalogKeys.has(channelKey(member.provider, member.id))) + .map((member): ModelOption => ({ + provider: member.provider, + id: member.id, + namespaced: `${member.provider}/${member.id}`, + ...(member.contextWindow ? { contextWindow: member.contextWindow } : {}), + ...(member.inputModalities ? { inputModalities: [...member.inputModalities] } : {}), + ...(member.reasoningEfforts ? { reasoningEfforts: [...member.reasoningEfforts] } : {}), + ...(member.sources ? { sources: member.sources } : {}), + })), + ]; + const next = { combos, providers, models, capabilityModels, cataloguedComboIds: [...catalogued], comboCatalog, lastResort, lastResortActive, capability, memberModels, hiddenModels } satisfies CachedCombosPage; writeSessionListCacheEntry(cacheKey, next); // Retain the coherent payload here — one place, on the success path, never during // render. See the `retainedData` note below. @@ -325,6 +469,30 @@ export default function Combos({ }, [active, apiBase, quotaResource.data, quotaResource.lastAttemptOk, quotaExpiry]); const data = state.data ?? retainedData ?? undefined; + + /* + * Account counts for OAuth providers whose quota report carries no aggregate (Antigravity + * pools, Anthropic). One list read per provider while the tab is active; a failure shows no count. + */ + const oauthProviders = (data?.providers ?? []).filter((provider) => provider.authMode === "oauth" && !provider.disabled) + .map((provider) => provider.name).sort().join(","); + const [accountCounts, setAccountCounts] = useState>({}); + useEffect(() => { + if (!active || !oauthProviders) return; + let cancelled = false; + void Promise.all(oauthProviders.split(",").map(async (provider) => { + try { + const res = await fetch(`${apiBase}/api/oauth/accounts?provider=${encodeURIComponent(provider)}`); + const count = res.ok ? accountCountFromList(await res.json()) : null; + return count ? [[provider, count] as const] : []; + } catch { + return []; + } + })).then((entries) => { + if (!cancelled) setAccountCounts(Object.fromEntries(entries.flat())); + }); + return () => { cancelled = true; }; + }, [active, apiBase, oauthProviders]); const combos = data?.combos ?? []; /* @@ -340,19 +508,32 @@ export default function Combos({ const capabilityModels = data?.capabilityModels ?? models; const cataloguedComboIds = new Set(data?.cataloguedComboIds ?? []); - const saveCombo = async (item: ComboItem, isCreate: boolean, renameFrom?: string) => { + /** `overview` saves report failures in their own row, so they skip the page banner. */ + const saveCombo = async ( + item: ComboItem, + isCreate: boolean, + renameFrom?: string, + overview?: { channels?: readonly EditableChannel[]; capability?: ComboSettingsPatch }, + ) => { + const channels = overview?.channels; try { + const body = toPutBody(item, { + ...(renameFrom ? { renameFrom } : {}), + // Enabling images declares text-only members for the Vision Sidecar so the + // operator never has to hand-edit provider config for a multimodal combo. + ...(item.imageInput !== "disabled" + ? { visionSidecarTargets: comboVisionSidecarTargets(item.targets, capabilityModels) } + : {}), + }); + // Only the channel editor sends `lastResort`; every other save omits it and the server keeps it. + // Capability fields (T4c) go out only when the operator changed them in the channel editor. + const wire = channels + ? { ...body, combo: { ...body.combo, targets: channelTargetsForPut(body.combo.targets, channels), ...overview?.capability } } + : body; const res = await fetch(`${apiBase}/api/combos`, { method: "PUT", headers: { "content-type": "application/json" }, - body: JSON.stringify(toPutBody(item, { - ...(renameFrom ? { renameFrom } : {}), - // Enabling images declares text-only members for the Vision Sidecar so the - // operator never has to hand-edit provider config for a multimodal combo. - ...(item.imageInput !== "disabled" - ? { visionSidecarTargets: comboVisionSidecarTargets(item.targets, capabilityModels) } - : {}), - })), + body: JSON.stringify(wire), }); const data = res.ok ? await res.json() as unknown @@ -360,7 +541,7 @@ export default function Combos({ const serverError = responseError(data); if (!res.ok || serverError || !responseSucceeded(data)) { const err = serverError || t("cws.saveFailed"); - notify(err, false); + if (!overview) notify(err, false); return { ok: false as const, error: err }; } resource.refresh(); @@ -373,11 +554,99 @@ export default function Combos({ return { ok: true as const }; } catch { const err = t("cws.saveFailed"); - notify(err, false); + if (!overview) notify(err, false); return { ok: false as const, error: err }; } }; + /** + * One member model's per-provider settings (context, input, effort levels), the same write the + * Models page's settings dialog makes. Every combo using that model sees the change. + */ + const saveModelSettings = async (provider: string, modelId: string, patch: Record) => { + try { + const res = await fetch(`${apiBase}/api/model-settings`, { + method: "PUT", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ provider, modelId, ...patch }), + }); + const body = await res.json().catch(() => null) as unknown; + const receipt = body && typeof body === "object" ? body as { ok?: unknown; provider?: unknown; modelId?: unknown } : {}; + if (!res.ok || receipt.ok !== true || receipt.provider !== provider || receipt.modelId !== modelId) { + return responseError(body) || t("cws.saveFailed"); + } + resource.refresh(); + return null; + } catch { + return t("cws.saveFailed"); + } + }; + + /** + * `POST /api/providers/probe-capabilities` for one member, applying conclusive results. A metered + * provider answers `requiresConfirmation` first; the repeat carries the operator's consent. + */ + const probeModel = async (provider: string, modelId: string, confirmed: boolean): Promise => { + try { + const res = await fetch(`${apiBase}/api/providers/probe-capabilities`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ name: provider, model: modelId, apply: true, ...(confirmed ? { confirmMetered: true } : {}) }), + }); + const outcome = parseProbeResponse(res.status, await res.json().catch(() => null)); + if (outcome.kind === "done" && Object.keys(outcome.applied).length > 0) resource.refresh(); + return outcome; + } catch { + return { kind: "failed" }; + } + }; + + const setComboEnabled = async (id: string, enabled: boolean) => { + try { + const res = await putModelVisibility(apiBase, "models", "combo", [{ id }], enabled); + const body = await res.json().catch(() => null) as unknown; + if (!res.ok) { + const err = responseError(body) || t("cws.saveFailed"); + return { ok: false as const, error: err }; + } + resource.refresh(); + return { ok: true as const }; + } catch { + return { ok: false as const, error: t("cws.saveFailed") }; + } + }; + + const providerRows = Object.fromEntries(providers.map((provider) => [provider.name, { + disabled: provider.disabled, + adapter: provider.adapter, + baseUrl: provider.baseUrl, + defaultModel: provider.defaultModel, + models: provider.models, + }])); + const validateOverviewEdit = (item: ComboItem) => validateComboDraft(item, { + existingIds: combos.flatMap((combo) => combo.id === item.id ? [] : [combo.id]), + existingAliases: combos.flatMap((combo) => combo.id !== item.id && combo.alias ? [combo.alias] : []), + combos: combos.filter((combo) => combo.id !== item.id), + isCreate: false, + providers: providerRows, + }); + + const validateSuggested = (item: ComboItem, isCreate: boolean) => isCreate + ? validateComboDraft(item, { + existingIds: combos.map((combo) => combo.id), + existingAliases: combos.flatMap((combo) => combo.alias ? [combo.alias] : []), + combos, + isCreate: true, + providers: providerRows, + }) + : validateOverviewEdit(item); + const quotaByProvider = quotaWindowsByProvider(quotaReports); + const providerByName = new Map(providers.map((provider) => [provider.name, provider])); + const remainingPercent = (provider: string, model: string) => { + const quota = channelQuota(providerByName.get(provider), quotaByProvider.get(provider), [model]); + return quota.kind === "windows" ? Math.min(...quota.windows.map((window) => window.remainingPercent)) : undefined; + }; + const removeCombo = async (id: string) => { try { const res = await fetch(`${apiBase}/api/combos?id=${encodeURIComponent(id)}`, { method: "DELETE" }); @@ -423,7 +692,7 @@ export default function Combos({ } return ( -
    +
    {status && (
    {status} @@ -436,10 +705,60 @@ export default function Combos({ )} {/* Revalidation is silent by design: existing combos stay visible, and the shell announces the in-flight refresh to assistive tech only. */} +
    + {view === "overview" ? ( + <> +

    {t("routeBoard.lede")}

    + + + ) : ( + + )} +
    {state.refreshing ? t("common.loading") : ""} + {view === "overview" && ( + comboDraftErrorText(t, code, item, providerRows)} + onCreate={(item) => saveCombo(item, true, undefined, {})} + onExtend={(item) => saveCombo(item, false, undefined, {})} + excludedProviders={suggestionExclusions.excluded} + onExcludedChange={suggestionExclusions.save} + /> + )} + {view === "overview" && ( + comboDraftErrorText(t, code, item, providerRows)} + onSave={(item, channels, capability) => saveCombo(item, false, undefined, { channels, capability })} + accountCounts={accountCounts} + capability={data?.capability ?? {}} + onSetEnabled={setComboEnabled} + onOpenAdvanced={openAdvanced} + lockedId={draftComboId} + onSaveModel={saveModelSettings} + onProbeModel={probeModel} + /> + )} + {workspaceMounted && ( + + )}
    ); diff --git a/gui/src/pages/combos-advanced-hash.ts b/gui/src/pages/combos-advanced-hash.ts new file mode 100644 index 00000000000..f287660cc0f --- /dev/null +++ b/gui/src/pages/combos-advanced-hash.ts @@ -0,0 +1,2 @@ +/** The full combo workspace, behind the Combos overview's "Advanced" entry. */ +export const COMBOS_ADVANCED_HASH = "models/combos/advanced"; diff --git a/gui/src/pages/combos-view.ts b/gui/src/pages/combos-view.ts new file mode 100644 index 00000000000..06c7660cd6c --- /dev/null +++ b/gui/src/pages/combos-view.ts @@ -0,0 +1,15 @@ +/** + * Which Combos view the hash asks for: the overview (route board) at `#models/combos`, or the + * full combo workspace at `#models/combos/advanced` and the JEV Auto deep link, which opens the + * workspace's add flow. + */ +import { JEV_AUTO_CREATE_HASH } from "../app-routing"; +import { COMBOS_ADVANCED_HASH } from "./combos-advanced-hash"; +import { normalizeHashPath, splitHashQuery } from "../hash-routing"; + +export type CombosView = "overview" | "advanced"; + +export function readCombosView(hash = window.location.hash): CombosView { + const path = splitHashQuery(normalizeHashPath(hash)).path; + return path === COMBOS_ADVANCED_HASH || path === JEV_AUTO_CREATE_HASH ? "advanced" : "overview"; +} diff --git a/gui/src/pages/models-tab.ts b/gui/src/pages/models-tab.ts index 4afe3f87d26..ae9bf0431c3 100644 --- a/gui/src/pages/models-tab.ts +++ b/gui/src/pages/models-tab.ts @@ -8,6 +8,7 @@ import { navigateHash, normalizeHashPath, splitHashQuery } from "../hash-routing"; import { JEV_AUTO_CREATE_HASH } from "../app-routing"; +import { COMBOS_ADVANCED_HASH } from "./combos-advanced-hash"; /** * `catalog` rather than `models` for the first tab: the page is Models and its first @@ -34,7 +35,7 @@ export function modelsTabHash(tab: ModelsTab): string { export function readModelsTab(hash = window.location.hash): ModelsTab { // A compatibility prefilter rides in `?query` (protocol-deep-links.ts); the tab is the path. const raw = splitHashQuery(normalizeHashPath(hash)).path; - if (raw === "models/combos" || raw === JEV_AUTO_CREATE_HASH || raw === "combos" || raw.startsWith("combos/")) return "combos"; + if (raw === "models/combos" || raw === JEV_AUTO_CREATE_HASH || raw === COMBOS_ADVANCED_HASH || raw === "combos" || raw.startsWith("combos/")) return "combos"; if (raw === "models/routing" || raw === "routing" || raw.startsWith("routing/")) return "routing"; if (raw === "models/compatibility" || raw === "lab" || raw.startsWith("lab/")) return "compatibility"; return "catalog"; diff --git a/gui/src/route-board-model.ts b/gui/src/route-board-model.ts new file mode 100644 index 00000000000..13b39dc6c82 --- /dev/null +++ b/gui/src/route-board-model.ts @@ -0,0 +1,641 @@ +/** + * Pure view model for the Combos overview (route board): one row per combo, its channels in + * routing order, and what each channel's provider has left. No React, no fetch. + * + * The layout follows the "one row per model group" idea of Magpie's routing page + * (MIT, Copyright (c) 2026 yetone). No code is taken from it. + */ +import { + COMBO_STRATEGIES, + type ComboDraftError, + type ComboItem, + type ComboStrategy, + comboPublicModelId, +} from "./combo-workspace-data"; +import type { TKey } from "./i18n/shared"; +import { freshQuotaReportsFromResponse } from "./provider-workspace/report"; +import { buildQuotaSummary, type QuotaSummaryWindow } from "./quota-summary"; + +/** What `/api/models` says about one combo row (`provider === "combo"`). */ +export interface ComboCatalogMeta { + displayName?: string; + contextWindow?: number; + disabled: boolean; +} + +export interface RouteBoardProvider { + name: string; + disabled?: boolean; + authMode?: string; +} + +export type QuotaTone = "ok" | "warn" | "low"; + +export interface QuotaWindowView { + id: string; + /** Fixed window name; otherwise `label` is the provider's own window name. */ + labelKey?: TKey; + label?: string; + remainingPercent: number; + tone: QuotaTone; +} + +/** Subscription windows, a pay-per-use key, or nothing reported. */ +export type ChannelQuota = + | { kind: "windows"; windows: QuotaWindowView[] } + | { kind: "metered" } + | { kind: "unknown" }; + +/** Accounts behind one provider; paused accounts take no traffic. */ +export interface AccountCount { + active: number; + paused: number; +} + +export interface RouteChannel { + key: string; + provider: string; + model: string; + lastResort: boolean; + providerDisabled: boolean; +} + +export interface ProviderQuotaLine { + provider: string; + quota: ChannelQuota; + accounts?: AccountCount; +} + +/** What the catalog says one member can take. */ +/** + * Where a member capability value comes from, as `/api/models` labels it per axis + * (`capabilitySources`): the operator's declaration, a declaration a capability probe wrote, the + * provider's own report, a same-name estimate, or nowhere. + */ +export type CapabilitySource = "manual" | "probed" | "reported" | "inferred" | "unknown"; +const CAPABILITY_SOURCES: ReadonlySet = new Set(["manual", "probed", "reported", "inferred", "unknown"]); + +/** A same-name estimate and what it rests on. Display data only: it never routes. */ +export interface InferredValue { + value: T; + basis: { source: "registry" | "vendor" | "provider" | "aggregator"; provider: string; modelId: string }; +} + +export interface MemberInferred { + context?: InferredValue; + input?: InferredValue; + efforts?: InferredValue; +} + +/** `capabilitySources` from a `/api/models` row; undefined from a backend that does not send it. */ +export function parseCapabilitySources(raw: unknown): MemberSources | undefined { + if (!raw || typeof raw !== "object") return undefined; + const axes = raw as { contextWindow?: unknown; inputModalities?: unknown; reasoningEfforts?: unknown }; + const read = (value: unknown): CapabilitySource => typeof value === "string" && CAPABILITY_SOURCES.has(value) ? value as CapabilitySource : "unknown"; + return { context: read(axes.contextWindow), input: read(axes.inputModalities), efforts: read(axes.reasoningEfforts) }; +} + +/** `inferredCapabilities` from a `/api/models` row: only well-formed axes survive. */ +export function parseInferredCapabilities(raw: unknown): MemberInferred | undefined { + if (!raw || typeof raw !== "object") return undefined; + const basisOf = (value: unknown): InferredValue["basis"] | undefined => { + if (!value || typeof value !== "object") return undefined; + const basis = value as { source?: unknown; provider?: unknown; modelId?: unknown }; + return ["registry", "vendor", "provider", "aggregator"].includes(String(basis.source)) + && typeof basis.provider === "string" && typeof basis.modelId === "string" + ? { source: basis.source as InferredValue["basis"]["source"], provider: basis.provider, modelId: basis.modelId } + : undefined; + }; + const axis = (value: unknown, valid: (candidate: unknown) => candidate is T): InferredValue | undefined => { + if (!value || typeof value !== "object") return undefined; + const entry = value as { value?: unknown; basis?: unknown }; + const basis = basisOf(entry.basis); + return basis && valid(entry.value) ? { value: entry.value, basis } : undefined; + }; + const isTokens = (value: unknown): value is number => typeof value === "number" && Number.isSafeInteger(value) && value > 0; + const isList = (value: unknown): value is string[] => Array.isArray(value) && value.length > 0 && value.every((item) => typeof item === "string"); + const axes = raw as { contextWindow?: unknown; inputModalities?: unknown; reasoningEfforts?: unknown }; + const out: MemberInferred = { + ...(axis(axes.contextWindow, isTokens) ? { context: axis(axes.contextWindow, isTokens)! } : {}), + ...(axis(axes.inputModalities, isList) ? { input: axis(axes.inputModalities, isList)! } : {}), + ...(axis(axes.reasoningEfforts, isList) ? { efforts: axis(axes.reasoningEfforts, isList)! } : {}), + }; + return Object.keys(out).length > 0 ? out : undefined; +} + +/** + * Members with estimates filled into the gaps, for the combo's combined row only. `used` says + * whether any estimate went in, so the combined values can be labelled as including one. + */ +export function withInferredGaps(members: readonly MemberFacts[]): { members: MemberFacts[]; used: boolean } { + let used = false; + const filled = members.map((member) => { + const next: MemberFacts = { ...member }; + if (next.contextWindow === undefined && member.inferred?.context) { next.contextWindow = member.inferred.context.value; used = true; } + if (next.inputModalities === undefined && member.inferred?.input) { next.inputModalities = member.inferred.input.value; used = true; } + if (next.reasoningEfforts === undefined && member.inferred?.efforts) { next.reasoningEfforts = member.inferred.efforts.value; used = true; } + return next; + }); + return { members: filled, used }; +} + +/** What `POST /api/providers/probe-capabilities` answered, reduced to what the table shows. */ +export type ProbeOutcome = + | { kind: "confirm"; planned: number } + | { kind: "inapplicable"; reason: string } + | { kind: "busy" } + | { kind: "failed" } + | { + kind: "done"; + baselineOk: boolean; + image?: "accepted" | "rejected" | "inconclusive"; + accepted: string[]; + rejected: string[]; + inconclusive: string[]; + applied: { inputModalities?: string[]; reasoningEfforts?: string[] }; + }; + +export function parseProbeResponse(status: number, body: unknown): ProbeOutcome { + if (status === 409) return { kind: "busy" }; + if (status < 200 || status >= 300 || !body || typeof body !== "object") return { kind: "failed" }; + const raw = body as Record; + if (raw.applicable === false) return { kind: "inapplicable", reason: typeof raw.reason === "string" ? raw.reason : "unknown" }; + if (raw.requiresConfirmation === true) { + return { kind: "confirm", planned: typeof raw.plannedRequests === "number" && raw.plannedRequests > 0 ? raw.plannedRequests : 1 }; + } + if (raw.sent !== true || !raw.baseline || typeof raw.baseline !== "object") return { kind: "failed" }; + const list = (value: unknown) => Array.isArray(value) ? value.filter((item): item is string => typeof item === "string") : []; + const reasoning = (raw.reasoning ?? {}) as Record; + const imageStatus = (raw.image as { status?: unknown } | undefined)?.status; + const applied = (raw.applied ?? {}) as Record; + return { + kind: "done", + baselineOk: (raw.baseline as { status?: unknown }).status === "accepted", + ...(imageStatus === "accepted" || imageStatus === "rejected" || imageStatus === "inconclusive" ? { image: imageStatus } : {}), + accepted: list(reasoning.accepted), + rejected: list(reasoning.rejected), + inconclusive: list(reasoning.inconclusive), + applied: { + ...(Array.isArray(applied.inputModalities) ? { inputModalities: list(applied.inputModalities) } : {}), + ...(Array.isArray(applied.reasoningEfforts) ? { reasoningEfforts: list(applied.reasoningEfforts) } : {}), + }, + }; +} + +export interface MemberSources { + context: CapabilitySource; + input: CapabilitySource; + efforts: CapabilitySource; +} + +export interface MemberFacts { + contextWindow?: number; + inputModalities?: readonly string[]; + reasoningEfforts?: readonly string[]; + sources?: MemberSources; + inferred?: MemberInferred; +} + +/** + * Source of one capability field on a `/api/models` row. A manual flag wins; an explicit + * `inferred` source (the T4c backend names it) comes next; any other present value is the + * provider's report. + */ +export function capabilitySource(hasValue: boolean, manual: boolean, declaredSource?: unknown): CapabilitySource { + if (manual) return "manual"; + if (declaredSource === "inferred") return "inferred"; + return hasValue ? "reported" : "unknown"; +} + +/** + * Members the catalog has no row for (a provider whose model list was never fetched) still have + * whatever the operator set per model in config. Those values are manual by definition. + */ +export function configuredMemberModels(providers: Readonly>): MemberModel[] { + const out = new Map(); + const strings = (value: unknown) => Array.isArray(value) ? value.filter((v): v is string => typeof v === "string") : undefined; + const entry = (provider: string, id: string) => { + const key = channelKey(provider, id); + const found = out.get(key) ?? { provider, id, sources: { context: "unknown", input: "unknown", efforts: "unknown" } }; + out.set(key, found); + return found as MemberModel & { sources: MemberSources }; + }; + for (const [provider, raw] of Object.entries(providers)) { + if (!raw || typeof raw !== "object") continue; + const config = raw as { modelContextWindows?: unknown; modelReasoningEfforts?: unknown; modelCapabilities?: unknown }; + for (const [id, tokens] of Object.entries((config.modelContextWindows ?? {}) as Record)) { + if (typeof tokens !== "number" || tokens <= 0) continue; + const member = entry(provider, id); + member.contextWindow = tokens; + member.sources.context = "manual"; + } + for (const [id, ladder] of Object.entries((config.modelReasoningEfforts ?? {}) as Record)) { + const list = strings(ladder); + if (!list) continue; + const member = entry(provider, id); + member.reasoningEfforts = list; + member.sources.efforts = "manual"; + } + for (const [id, capabilities] of Object.entries((config.modelCapabilities ?? {}) as Record)) { + const list = strings((capabilities as { inputModalities?: unknown } | null)?.inputModalities); + if (!list) continue; + const member = entry(provider, id); + member.inputModalities = list; + member.sources.input = "manual"; + } + } + return [...out.values()]; +} + +/** Context typed by an operator: "200000", "200K", "1M", "1.5m". Undefined when it is not a positive whole token count. */ +export function parseContextInput(text: string): number | undefined { + const match = /^\s*(\d+(?:\.\d+)?)\s*([km]?)\s*$/i.exec(text.replace(/[,_]/g, "")); + if (!match) return undefined; + const unit = match[2]!.toLowerCase(); + const tokens = Math.round(Number(match[1]) * (unit === "m" ? 1_000_000 : unit === "k" ? 1_000 : 1)); + return Number.isSafeInteger(tokens) && tokens > 0 ? tokens : undefined; +} + +export interface MemberDraft { + context: string; + input: readonly string[]; + efforts: readonly string[]; +} + +/** Only the fields the operator changed, in the shape `PUT /api/model-settings` takes. */ +export function memberSettingsPatch(current: MemberFacts, draft: MemberDraft, order: readonly string[]): + { patch: Record; invalid?: "context" } { + const patch: Record = {}; + const contextText = draft.context.trim(); + if (contextText) { + const tokens = parseContextInput(contextText); + if (tokens === undefined) return { patch, invalid: "context" }; + if (tokens !== current.contextWindow) patch.contextWindow = tokens; + } + const same = (a: readonly string[] | undefined, b: readonly string[]) => + (a ?? []).length === b.length && b.every((value) => (a ?? []).includes(value)); + if (!same(current.inputModalities, draft.input)) patch.inputModalities = [...draft.input]; + if (!same(current.reasoningEfforts, draft.efforts)) { + patch.reasoningEfforts = order.filter((level) => draft.efforts.includes(level)); + } + return { patch }; +} + +/** Clears every per-model setting the operator made, so the provider's own values apply again. */ +export function memberRestorePatch(sources: MemberSources | undefined): Record { + const declared = (source: CapabilitySource | undefined) => source === "manual" || source === "probed"; + return { + ...(declared(sources?.context) ? { contextWindow: null } : {}), + ...(declared(sources?.input) ? { inputModalities: null } : {}), + ...(declared(sources?.efforts) ? { reasoningEfforts: null } : {}), + }; +} + +export interface MemberModel extends MemberFacts { + provider: string; + id: string; +} + +export type ContextBasis = "min" | "max" | "catalog"; + +/** + * The combo's context window as the policy advertises it. Intersection is the server's own catalog + * number (it already takes the smallest member and applies context caps the member rows do not + * show); only without one does it fall back to the smallest member here. Union takes the largest + * member (union over context lands with the T4c backend). + */ +export function comboContextWindow( + members: readonly MemberFacts[], + policy: CapabilityPolicy, + catalog: number | undefined, +): { tokens?: number; basis: ContextBasis } { + const known = members.flatMap((member) => typeof member.contextWindow === "number" && member.contextWindow > 0 ? [member.contextWindow] : []); + if (policy === "union" && known.length > 0) return { tokens: Math.max(...known, catalog ?? 0), basis: "max" }; + if (policy === "intersection" && catalog !== undefined) return { tokens: catalog, basis: "min" }; + if (known.length > 0) return { tokens: Math.min(...known), basis: "min" }; + return catalog !== undefined ? { tokens: catalog, basis: "catalog" } : { basis: "catalog" }; +} + +/** Combined list under the policy: every member's (intersection) or any member's (union); undefined when no member reports one. */ +export function combineLists(lists: ReadonlyArray, policy: CapabilityPolicy, order: readonly string[] = []): string[] | undefined { + const known = lists.filter((list): list is readonly string[] => list !== undefined); + if (known.length === 0) return undefined; + const merged = policy === "union" + ? [...new Set(known.flat())] + : known.reduce((common, list) => common.filter((value) => list.includes(value)), [...known[0]!]); + const rank = (value: string) => { const index = order.indexOf(value); return index < 0 ? order.length : index; }; + return merged.sort((a, b) => rank(a) - rank(b)); +} + +export function memberFacts(models: readonly MemberModel[], provider: string, model: string): MemberFacts { + return models.find((candidate) => candidate.provider === provider && candidate.id === model) ?? {}; +} + +export interface RouteRow { + combo: ComboItem; + publicId: string; + displayName: string; + channels: RouteChannel[]; + /** One entry per distinct provider, in first-use order. */ + quotas: ProviderQuotaLine[]; + contextWindow?: number; + contextBasis: ContextBasis; + enabled: boolean; + lastResortCount: number; +} + +/** Combo capability policy (T4c). Absent on the wire means the default. */ +export type CapabilityPolicy = "intersection" | "union"; +export type UnservablePolicy = "degrade" | "reject"; +export interface ComboCapabilitySettings { + capabilityPolicy: CapabilityPolicy; + onUnservable: UnservablePolicy; +} +export const DEFAULT_CAPABILITY_SETTINGS: ComboCapabilitySettings = { capabilityPolicy: "intersection", onUnservable: "degrade" }; + +export function parseCapabilitySettings(raw: { capabilityPolicy?: unknown; onUnservable?: unknown }): ComboCapabilitySettings { + return { + capabilityPolicy: raw.capabilityPolicy === "union" ? "union" : "intersection", + onUnservable: raw.onUnservable === "reject" ? "reject" : "degrade", + }; +} + +/** Fields the inline editor writes besides the targets; each is sent only when changed. */ +export type ComboSettingsPatch = Partial & { cooldownWaitPolicy?: "before-last-resort" | null }; + +/** Only the fields that changed, so a server without them never sees them unless the operator asked. */ +export function capabilityPatch(before: ComboCapabilitySettings, after: ComboCapabilitySettings): Partial { + return { + ...(after.capabilityPolicy !== before.capabilityPolicy ? { capabilityPolicy: after.capabilityPolicy } : {}), + ...(after.onUnservable !== before.onUnservable ? { onUnservable: after.onUnservable } : {}), + }; +} + +/** Antigravity names its quota pools by family; spell them out like the provider does. */ +const QUOTA_FAMILY_NAMES: Readonly> = { + gem: "Gemini", + cla: "Claude & GPT", + argon: "Gemini 4 Argon", +}; + +/** `Cla (Weekly)` → family "Claude & GPT", weekly window; anything else is left alone. */ +export function quotaFamilyWindow(label: string): { family: string; weekly: boolean } | null { + const match = /^([A-Za-z]+)( \(Weekly\))?$/.exec(label.trim()); + const family = match ? QUOTA_FAMILY_NAMES[match[1]!.toLowerCase()] : undefined; + return family ? { family, weekly: match![2] !== undefined } : null; +} + +export const ROUTE_BOARD_STRATEGIES: readonly ComboStrategy[] = COMBO_STRATEGIES; + +export function channelKey(provider: string, model: string): string { + return `${provider}\u0000${model}`; +} + +/** Remaining-percent colour: green above 50%, amber from 20% to 50%, red below 20%. */ +export function quotaTone(remainingPercent: number): QuotaTone { + if (remainingPercent > 50) return "ok"; + if (remainingPercent >= 20) return "warn"; + return "low"; +} + +const WINDOW_ORDER: TKey[] = ["quota.weeklyLimit", "quota.fiveHourLimit", "quota.monthlyLimit"]; + +function windowFamily(window: QuotaSummaryWindow): string { + return (window.label ?? "").toLowerCase().split(/[\s(]/)[0] ?? ""; +} + +/** + * The windows that matter for this provider's models in this combo, at most two. + * + * A provider such as Antigravity reports one window per model family ("Gem", "Cla (Weekly)"). + * A Claude channel must not show the Gemini window, so a window that names a family or a model + * is kept only when a channel's model belongs to it. + */ +function pickWindows(windows: QuotaSummaryWindow[], models: readonly string[]): QuotaSummaryWindow[] { + const measured = windows.filter((window) => window.percent !== undefined); + const lowered = models.map((model) => model.toLowerCase()); + const relevant = measured.filter((window) => { + if (window.modelId !== undefined) return lowered.includes(window.modelId.toLowerCase()); + if (window.labelKey !== undefined) return true; + const family = windowFamily(window); + return family.length >= 3 && lowered.some((model) => model.startsWith(family)); + }); + const generic = measured.filter((window) => window.labelKey !== undefined || window.modelId === undefined); + const pool = relevant.length > 0 ? relevant : generic; + const rank = (window: QuotaSummaryWindow) => { + if (window.modelId !== undefined) return -1; + const fixed = window.labelKey ? WINDOW_ORDER.indexOf(window.labelKey) : -1; + if (fixed >= 0) return fixed; + return /week/i.test(window.label ?? "") ? 0.5 : WINDOW_ORDER.length; + }; + return [...pool].sort((a, b) => rank(a) - rank(b)).slice(0, 2); +} + +function accountCount(aggregation: unknown): AccountCount | undefined { + if (!aggregation || typeof aggregation !== "object") return undefined; + const { includedAccounts, excludedAccounts, pausedAccounts } = aggregation as Record; + if (typeof includedAccounts !== "number") return undefined; + const total = includedAccounts + (typeof excludedAccounts === "number" ? excludedAccounts : 0); + const paused = typeof pausedAccounts === "number" ? Math.min(pausedAccounts, total) : 0; + return { active: total - paused, paused }; +} + +/** `GET /api/oauth/accounts` → active and paused counts; null when the body is not an account list. */ +export function accountCountFromList(body: unknown): AccountCount | null { + const accounts = body && typeof body === "object" ? (body as { accounts?: unknown }).accounts : undefined; + if (!Array.isArray(accounts)) return null; + const paused = accounts.filter((account) => (account as { paused?: unknown } | null)?.paused === true).length; + return { active: accounts.length - paused, paused }; +} + +/** Parse `/api/provider-quotas` `reports` once per render into provider → windows. */ +export function quotaWindowsByProvider( + reports: unknown, + now = Date.now(), +): Map { + const fresh = freshQuotaReportsFromResponse(reports, now); + const out = new Map(); + for (const row of buildQuotaSummary(fresh, (provider) => provider)) { + if (row.passive) continue; + const accounts = accountCount(fresh[row.provider]?.aggregation); + out.set(row.provider, { windows: row.windows, ...(accounts !== undefined ? { accounts } : {}) }); + } + return out; +} + +export function channelQuota( + provider: RouteBoardProvider | undefined, + reported: { windows: QuotaSummaryWindow[]; accounts?: AccountCount } | undefined, + models: readonly string[], +): ChannelQuota { + const windows = reported ? pickWindows(reported.windows, models) : []; + if (windows.length > 0) { + return { + kind: "windows", + windows: windows.map((window) => { + const remainingPercent = Math.max(0, Math.min(100, 100 - (window.percent ?? 0))); + return { + id: window.id, + ...(window.labelKey ? { labelKey: window.labelKey } : { label: window.label ?? window.id }), + remainingPercent, + tone: quotaTone(remainingPercent), + }; + }), + }; + } + if (provider?.authMode === "key") return { kind: "metered" }; + return { kind: "unknown" }; +} + +export function buildRouteRows(input: { + combos: readonly ComboItem[]; + catalog: Readonly>; + lastResort: Readonly>; + providers: readonly RouteBoardProvider[]; + quotaReports: unknown; + /** Per-provider account counts read from the account list, for providers whose quota has no aggregate. */ + accountCounts?: Readonly>; + models?: readonly MemberModel[]; + capability?: Readonly>; + now?: number; +}): RouteRow[] { + const providers = new Map(input.providers.map((provider) => [provider.name, provider])); + const reported = quotaWindowsByProvider(input.quotaReports, input.now); + const rows = input.combos.map((combo) => { + const lastResort = new Set(input.lastResort[combo.id] ?? []); + const channels = combo.targets.map((target) => { + const key = channelKey(target.provider, target.model); + return { + key, + provider: target.provider, + model: target.model, + lastResort: lastResort.has(key), + providerDisabled: providers.get(target.provider)?.disabled === true, + }; + }); + const quotas: ProviderQuotaLine[] = []; + for (const channel of channels) { + if (quotas.some((line) => line.provider === channel.provider)) continue; + const models = channels.filter((c) => c.provider === channel.provider).map((c) => c.model); + const accounts = reported.get(channel.provider)?.accounts ?? input.accountCounts?.[channel.provider]; + quotas.push({ + provider: channel.provider, + quota: channelQuota(providers.get(channel.provider), reported.get(channel.provider), models), + ...(accounts !== undefined ? { accounts } : {}), + }); + } + const meta = input.catalog[combo.id]; + const policy = input.capability?.[combo.id]?.capabilityPolicy ?? "intersection"; + const context = comboContextWindow( + channels.map((channel) => memberFacts(input.models ?? [], channel.provider, channel.model)), + policy, + meta?.contextWindow, + ); + const publicId = comboPublicModelId(combo.id, combo.alias); + return { + combo, + publicId, + displayName: combo.displayName?.trim() || meta?.displayName?.trim() || combo.id, + channels, + quotas, + ...(context.tokens !== undefined ? { contextWindow: context.tokens } : {}), + contextBasis: context.basis, + enabled: meta ? !meta.disabled : true, + lastResortCount: channels.filter((channel) => channel.lastResort).length, + }; + }); + // Switched-off combos go last so the live ones lead; the sort is stable within each group. + return [...rows.filter((row) => row.enabled), ...rows.filter((row) => !row.enabled)]; +} + +/** + * Provider labels for one row. Two providers can share a display name (`anthropic` and + * `anthropic-apikey` are both "Anthropic Claude"); the later one gets its id appended. + */ +export function distinctProviderLabels( + providers: readonly string[], + display: (provider: string) => string, +): Map { + const labels = new Map(); + const taken = new Set(); + for (const provider of providers) { + if (labels.has(provider)) continue; + const name = display(provider); + labels.set(provider, taken.has(name) ? `${name} (${provider})` : name); + taken.add(name); + } + return labels; +} + +/** `1M`, `200K`, `128K`. */ +export function formatContextWindow(tokens: number): string { + if (tokens >= 1_000_000) { + const millions = tokens / 1_000_000; + return `${Number(millions.toFixed(1))}M`; + } + return `${Math.round(tokens / 1000)}K`; +} + +/** + * What picking a strategy in the row menu does. + * + * JEV never saves from the row: with no decision service chosen it hands requests to the + * hosted TypeSafe JEV service, so the operator picks it in the full editor where that is shown. + */ +export type StrategyChange = + | { kind: "unchanged" } + | { kind: "open-advanced" } + | { kind: "invalid"; error: ComboDraftError; item: ComboItem } + | { kind: "save"; item: ComboItem }; + +export function planStrategyChange( + combo: ComboItem, + next: ComboStrategy, + validate: (item: ComboItem) => ComboDraftError | null, +): StrategyChange { + if (next === combo.strategy) return { kind: "unchanged" }; + if (next === "jev") return { kind: "open-advanced" }; + const item = { ...combo, strategy: next }; + const error = validate(item); + return error ? { kind: "invalid", error, item } : { kind: "save", item }; +} + +/** Move one channel; out-of-range moves leave the list as it was. */ +export function moveChannel(list: readonly T[], from: number, to: number): T[] { + if (from === to || from < 0 || to < 0 || from >= list.length || to >= list.length) return [...list]; + const next = [...list]; + const [moved] = next.splice(from, 1); + next.splice(to, 0, moved!); + return next; +} + +/** Pointer must pass a row's midpoint by this much before the drop slot changes. */ +export const DRAG_HYSTERESIS_PX = 8; + +/** + * Drop slot for a dragged row, from the pointer's Y against the rows' midpoints as they were when + * the drag started. The rows that make room move on screen, but these midpoints do not, so the + * slot cannot flip back and forth as rows slide under a still pointer. `current` adds hysteresis: + * the slot changes only once the pointer is clearly past the midpoint that separates the two. + */ +export function dragSlot(startMids: readonly number[], from: number, y: number, current: number): number { + const others = startMids.filter((_, index) => index !== from); + const slotAt = (pointer: number) => others.filter((mid) => mid < pointer).length; + const next = slotAt(y); + if (next === current) return current; + // Moving down past others[current], or up past others[current - 1]: require the margin. + const boundary = next > current ? others[current] : others[current - 1]; + if (boundary === undefined) return next; + return Math.abs(y - boundary) >= DRAG_HYSTERESIS_PX ? next : current; +} + +/** `PUT /api/combos` target list for an edited channel list: `lastResort` sent explicitly. */ +export function channelTargetsForPut( + putTargets: readonly T[], + channels: readonly Pick[], +): Array { + return putTargets.map((target) => { + const channel = channels.find((c) => c.provider === target.provider && c.model === target.model); + return { ...target, lastResort: channel?.lastResort === true }; + }); +} diff --git a/gui/tests/combo-capability-hidden-targets.test.tsx b/gui/tests/combo-capability-hidden-targets.test.tsx index 940e28b33e6..79149395079 100644 --- a/gui/tests/combo-capability-hidden-targets.test.tsx +++ b/gui/tests/combo-capability-hidden-targets.test.tsx @@ -45,7 +45,7 @@ const combo = (targets: Target[], extra: Record = {}) => ({ beforeEach(() => { clearClientResourceStoresForTests(); previousGlobals = Object.fromEntries(globals.map(key => [key, Reflect.get(globalThis, key)])) as typeof previousGlobals; - testWindow = new Window({ url: `${API_BASE}/#models/combos` }); + testWindow = new Window({ url: `${API_BASE}/#models/combos/advanced` }); Object.defineProperty(testWindow.navigator, "language", { configurable: true, value: "en-US" }); Object.defineProperties(globalThis, { document: { configurable: true, value: testWindow.document }, diff --git a/gui/tests/combo-suggestions.test.tsx b/gui/tests/combo-suggestions.test.tsx new file mode 100644 index 00000000000..5cc8c69983a --- /dev/null +++ b/gui/tests/combo-suggestions.test.tsx @@ -0,0 +1,327 @@ +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { Window } from "happy-dom"; +import { act } from "react"; +import type { Root } from "react-dom/client"; +import { + buildComboSuggestions, + channelTier, + extendedCombo, + freeComboId, + normalizeModelName, + orderMembers, + suggestionDraft, + type ChannelTier, + type SuggestionInput, + type SuggestionProvider, +} from "../src/combo-suggestions"; +import type { ComboItem } from "../src/combo-workspace-data"; +import { ComboSuggestions } from "../src/components/route-board/ComboSuggestions"; +import { LanguageProvider } from "../src/i18n/provider"; + +const combo = (id: string, targets: Array<[string, string]>, extra: Partial = {}): ComboItem => ({ + id, + model: `combo/${id}`, + alias: null, + nativeAlias: false, + displayName: null, + strategy: "failover", + stickyLimit: 1, + defaultEffort: null, + imageInput: "auto", + reasoningEffortMode: "strict", + targets: targets.map(([provider, model]) => ({ provider, model })), + ...extra, +}); + +const PROVIDERS: SuggestionProvider[] = [ + { name: "anthropic-apikey", authMode: "key", baseUrl: "https://api.anthropic.com" }, + { name: "cursor", authMode: "oauth", baseUrl: "https://api2.cursor.sh" }, + { name: "anthropic", authMode: "oauth", baseUrl: "https://api.anthropic.com" }, + { name: "google-vertex", baseUrl: "https://aiplatform.googleapis.com" }, + { name: "google-antigravity", authMode: "oauth", baseUrl: "https://daily-cloudcode-pa.googleapis.com" }, + { name: "openai", authMode: "forward", baseUrl: "https://chatgpt.com/backend-api/codex" }, + { name: "zayu-claude", authMode: "key", baseUrl: "https://relay.example" }, + { name: "qoder", authMode: "key", disabled: true }, + { name: "jev", authMode: "key", hiddenFromPicker: true }, +]; + +const models = (rows: Array<[string, string]>) => rows.map(([provider, id]) => ({ provider, id })); +const suggest = (input: Partial & Pick) => + buildComboSuggestions({ combos: [], providers: PROVIDERS, ...input }); +const summary = (input: Partial & Pick) => + suggest(input).map((s) => `${s.kind} ${s.comboId}: ${s.members.map((m) => m.provider).join(" > ")}`); + +describe("normalizeModelName", () => { + test("folds case, provider prefix, version dots, gaps and a trailing effort suffix", () => { + expect(normalizeModelName("Claude-Opus-5.5")).toBe("claude-opus-5-5"); + expect(normalizeModelName("anthropic/claude-opus-5-5")).toBe("claude-opus-5-5"); + expect(normalizeModelName("deepseek-ai/DeepSeek-V4.1-Flash")).toBe("deepseek-v4-1-flash"); + expect(normalizeModelName("GPT 6.1 Sol")).toBe("gpt-6-1-sol"); + expect(normalizeModelName("gpt-6.1-sol-xhigh")).toBe("gpt-6-1-sol"); + expect(normalizeModelName("gemini_3.8__flash-low")).toBe("gemini-3-8-flash"); + }); + + test("keeps snapshot dates and other variants apart", () => { + expect(normalizeModelName("claude-opus-5-5-20260801")).not.toBe(normalizeModelName("claude-opus-5-5")); + expect(normalizeModelName("gemini-3.8-flash-thinking")).toBe("gemini-3-8-flash-thinking"); + }); +}); + +describe("buildComboSuggestions", () => { + test("suggests a model two providers serve under different spellings, once per provider", () => { + expect(summary({ + models: models([ + ["cursor", "Gemini-3.8-Flash"], + ["google-antigravity", "gemini-3.8-flash"], + ["google-antigravity", "gemini-3.8-flash-high"], + ["openai", "gpt-6-luna"], + ]), + })).toEqual(["create gemini-3.8-flash: google-antigravity > cursor"]); + }); + + test("a model only one provider serves is no suggestion", () => { + expect(suggest({ models: models([["openai", "gpt-6-luna"], ["openai", "gpt-6-luna-high"]]) })).toEqual([]); + }); + + test("disabled and picker-hidden providers do not count", () => { + expect(suggest({ models: models([["anthropic", "claude-x"], ["qoder", "claude-x"], ["jev", "claude-x"]]) })).toEqual([]); + }); + + test("models hidden from the catalog still count, but suggestions with a listed member come first", () => { + const hiddenModels = new Set(["openai/gpt-5.5", "cursor/gpt-5.5", "cursor/gpt-5.6-luna"]); + const result = suggest({ + models: models([["openai", "gpt-5.5"], ["cursor", "gpt-5.5"], ["openai", "gpt-5.6-luna"], ["cursor", "gpt-5.6-luna"]]), + hiddenModels, + }); + expect(result.map((s) => [s.comboId, s.kind === "create" && s.listed])).toEqual([["gpt-5.6-luna", true], ["gpt-5.5", false]]); + }); + + test("orders members: maker's subscription, other subscriptions, Vertex, then keys and relays", () => { + expect(summary({ + models: models([ + ["zayu-claude", "claude-opus-5-5"], + ["anthropic-apikey", "claude-opus-5-5"], + ["google-vertex", "claude-opus-5-5"], + ["cursor", "claude-opus-5.5"], + ["anthropic", "claude-opus-5-5"], + ]), + })).toEqual(["create claude-opus-5-5: anthropic > cursor > google-vertex > zayu-claude > anthropic-apikey"]); + }); + + test("within a tier, more quota left goes first and unknown quota last", () => { + const remaining: Record = { anthropic: 10, "google-antigravity": 80 }; + const result = suggest({ + models: models([["cursor", "claude-sonnet-5-5"], ["anthropic", "claude-sonnet-5-5"], ["google-antigravity", "claude-sonnet-5-5"]]), + remainingPercent: (provider) => remaining[provider], + }); + // anthropic is the maker's own subscription, so it leads despite its lower quota. + expect(result[0]!.members.map((m) => [m.provider, m.remainingPercent])).toEqual([ + ["anthropic", 10], ["google-antigravity", 80], ["cursor", undefined], + ]); + }); + + test("a combo already about the model is not suggested again; a missing provider becomes an extend hint", () => { + const combos = [combo("claude-opus-5-5", [["anthropic", "claude-opus-5-5"], ["zayu-claude", "claude-opus-5-5"]])]; + const rows = models([["anthropic", "claude-opus-5-5"], ["zayu-claude", "claude-opus-5-5"], ["cursor", "claude-opus-5.5"]]); + expect(summary({ combos, models: rows })).toEqual(["extend claude-opus-5-5: cursor"]); + expect(summary({ combos, models: rows.slice(0, 2) })).toEqual([]); + }); + + test("hints for existing combos come before suggestions whose members are all hidden", () => { + const combos = [combo("gemini", [["google-antigravity", "gemini-3.8-flash"]])]; + const result = suggest({ + combos, + models: models([["google-antigravity", "gemini-3.8-flash"], ["cursor", "gemini-3.8-flash"], ["openai", "gpt-5.5"], ["cursor", "gpt-5.5"], ["openai", "gpt-6-luna"], ["cursor", "gpt-6-luna"]]), + hiddenModels: new Set(["openai/gpt-5.5", "cursor/gpt-5.5"]), + }); + expect(result.map((s) => `${s.kind} ${s.comboId}`)).toEqual(["create gpt-6-luna", "extend gemini", "create gpt-5.5"]); + }); + + test("a combo whose members all serve the model covers it whatever its id", () => { + const combos = [combo("opus", [["anthropic", "claude-opus-5-5"], ["cursor", "claude-opus-5.5"]])]; + expect(suggest({ combos, models: models([["anthropic", "claude-opus-5-5"], ["cursor", "claude-opus-5.5"]]) })).toEqual([]); + }); + + test("a mixed combo that does not name the model does not cover it", () => { + const combos = [combo("Reviewer", [["anthropic", "claude-sonnet-5-5"], ["google-antigravity", "gemini-3.8-flash"]])]; + expect(summary({ combos, models: models([["google-antigravity", "gemini-3.8-flash"], ["cursor", "gemini-3.8-flash"]]) })) + .toEqual(["create gemini-3.8-flash: google-antigravity > cursor"]); + }); + + test("a taken combo id or alias gets -2, -3", () => { + const combos = [combo("gpt-5.5", [["openai", "gpt-6-luna"], ["anthropic", "claude-x"]]), combo("other", [["openai", "x"]], { alias: "gpt-5.5-2" })]; + expect(freeComboId("gpt-5.5", combos)).toBe("gpt-5.5-3"); + expect(freeComboId("GPT-5.5", [])).toBe("GPT-5.5"); + expect(suggest({ combos, models: models([["openai", "gpt-5.5"], ["cursor", "gpt-5.5"]]) })[0]!.comboId).toBe("gpt-5.5-3"); + }); + + test("dismissed suggestions stay out, other ones stay in", () => { + const rows = models([["openai", "gpt-5.5"], ["cursor", "gpt-5.5"], ["openai", "gpt-5.6-sol"], ["cursor", "gpt-5.6-sol"]]); + const all = suggest({ models: rows }); + expect(all.map((s) => s.key)).toEqual(["create:gpt-5-5", "create:gpt-5-6-sol"]); + expect(suggest({ models: rows, dismissed: new Set(["create:gpt-5-5"]) }).map((s) => s.comboId)).toEqual(["gpt-5.6-sol"]); + }); + + test("an excluded provider joins no suggested combo, new or existing", () => { + const rows = models([["openai", "gpt-5.5"], ["cursor", "gpt-5.5"], ["anthropic", "claude-x"], ["cursor", "claude-x"], ["zayu-claude", "claude-x"]]); + const excludedProviders = new Set(["cursor"]); + expect(summary({ models: rows, excludedProviders })).toEqual(["create claude-x: anthropic > zayu-claude"]); + const combos = [combo("claude-x", [["anthropic", "claude-x"]])]; + expect(summary({ combos, models: rows, excludedProviders })).toEqual(["extend claude-x: zayu-claude"]); + }); +}); + +describe("drafts", () => { + test("a create draft is a failover combo with the members in the order given", () => { + const members = orderMembers([ + { provider: "cursor", model: "gpt-5.5", tier: "subscription" }, + { provider: "openai", model: "gpt-5.5", tier: "own-subscription" }, + ]); + const draft = suggestionDraft("gpt-5.5", members); + expect([draft.id, draft.model, draft.strategy]).toEqual(["gpt-5.5", "combo/gpt-5.5", "failover"]); + expect(draft.targets.map((t) => `${t.provider}/${t.model}`)).toEqual(["openai/gpt-5.5", "cursor/gpt-5.5"]); + }); + + test("extending puts a member ahead of the first lower-tier one and keeps the combo's own order", () => { + const tiers: Record = { anthropic: "own-subscription", "anthropic-apikey": "metered", "zayu-claude": "metered" }; + const tierOf = (provider: string) => tiers[provider]!; + const base = combo("opus", [["anthropic", "claude-opus-5-5"], ["zayu-claude", "claude-opus-5-5"], ["anthropic-apikey", "claude-opus-5-5"]]); + const next = extendedCombo(base, [ + { provider: "cursor", model: "claude-opus-5.5", tier: "subscription" }, + { provider: "relay-2", model: "claude-opus-5-5", tier: "metered" }, + ], tierOf); + expect(next.targets.map((t) => t.provider)).toEqual(["anthropic", "cursor", "zayu-claude", "anthropic-apikey", "relay-2"]); + const relayFirst = combo("opus", [["zayu-claude", "claude-opus-5-5"], ["anthropic", "claude-opus-5-5"]]); + expect(extendedCombo(relayFirst, [{ provider: "cursor", model: "claude-opus-5.5", tier: "subscription" }], tierOf).targets.map((t) => t.provider)) + .toEqual(["cursor", "zayu-claude", "anthropic"]); + }); + + test("tiers read the provider, not its name", () => { + expect(channelTier({ name: "my-vertex-2", baseUrl: "https://x.example" }, "gemini-4-argon")).toBe("vertex"); + expect(channelTier({ name: "anything", authMode: "forward", baseUrl: "https://chatgpt.com" }, "gpt-6-luna")).toBe("own-subscription"); + expect(channelTier({ name: "xai", authMode: "oauth", baseUrl: "https://api.x.ai/v1" }, "grok-4.7")).toBe("own-subscription"); + expect(channelTier({ name: "zed", authMode: "oauth", baseUrl: "https://cloud.zed.dev" }, "grok-4.7")).toBe("subscription"); + expect(channelTier({ name: "ollama", baseUrl: "http://localhost:11434" }, "llama")).toBe("metered"); + }); +}); + +describe("ComboSuggestions card", () => { + let testWindow: Window; + let root: Root | null = null; + let host: HTMLElement; + const globals = ["document", "window", "navigator", "localStorage"] as const; + let previous: Record<(typeof globals)[number], unknown>; + + beforeEach(() => { + previous = Object.fromEntries(globals.map((key) => [key, Reflect.get(globalThis, key)])) as typeof previous; + testWindow = new Window({ url: "http://localhost/#models/combos" }); + Object.defineProperty(testWindow.navigator, "language", { configurable: true, value: "en-US" }); + Object.defineProperties(globalThis, { + document: { configurable: true, value: testWindow.document }, + window: { configurable: true, value: testWindow }, + navigator: { configurable: true, value: testWindow.navigator }, + localStorage: { configurable: true, value: testWindow.localStorage }, + }); + (globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + }); + + afterEach(async () => { + if (root) await act(async () => { root?.unmount(); }); + root = null; + testWindow.close(); + for (const key of globals) Object.defineProperty(globalThis, key, { configurable: true, value: previous[key] }); + }); + + const saved: Array<{ kind: string; item: ComboItem }> = []; + const exclusionWrites: string[][] = []; + async function render(combos: ComboItem[] = [], excluded?: string[]) { + saved.length = 0; + const { createRoot } = await import("react-dom/client"); + host = document.createElement("div"); + document.body.append(host); + root = createRoot(host); + await act(async () => { + root!.render( + + undefined} + validate={() => null} + errorText={() => "bad"} + onCreate={async (item) => { saved.push({ kind: "create", item }); return { ok: true }; }} + onExtend={async (item) => { saved.push({ kind: "extend", item }); return { ok: true }; }} + {...(excluded ? { + excludedProviders: excluded, + onExcludedChange: async (next: readonly string[]) => { exclusionWrites.push([...next]); return true; }, + } : {})} + /> + , + ); + }); + } + const button = (scope: ParentNode, name: string) => { + const found = [...scope.querySelectorAll("button")] + .find((item) => item.textContent?.trim() === name || item.getAttribute("aria-label") === name); + if (!found) throw new Error(`button not found: ${name}`); + return found; + }; + const card = (title: string) => { + const found = [...host.querySelectorAll(".rb-suggest-card")].find((item) => item.querySelector("strong")?.textContent === title); + if (!found) throw new Error(`card not found: ${title}`); + return found; + }; + + test("generate opens a draft; reordering and saving sends that order", async () => { + await render(); + expect(host.querySelector(".rb-suggest-head strong")?.textContent).toBe("Suggested combos"); + const gemini = card("gemini-3.8-flash"); + expect(gemini.querySelector(".rb-order")?.textContent).toContain("→"); + await act(async () => { button(gemini, "Generate").click(); }); + const draft = gemini.querySelector(".rb-suggest-draft")!; + await act(async () => { button(draft.querySelectorAll("li")[0]!, "Move down").click(); }); + await act(async () => { button(draft, "Save combo").click(); }); + expect(saved.map(({ kind, item }) => [kind, item.id, item.strategy, item.targets.map((t) => t.provider)])).toEqual([ + ["create", "gemini-3.8-flash", "failover", ["cursor", "google-antigravity"]], + ]); + }); + + test("dismiss hides the card and the choice survives a remount", async () => { + await render(); + await act(async () => { button(card("claude-opus-5-5"), "Dismiss").click(); }); + expect(() => card("claude-opus-5-5")).toThrow(); + await act(async () => { root?.unmount(); }); + await render(); + expect(() => card("claude-opus-5-5")).toThrow(); + expect(card("gemini-3.8-flash")).toBeTruthy(); + }); + + test("an existing combo missing a provider offers to add it", async () => { + await render([combo("gemini", [["google-antigravity", "gemini-3.8-flash"]])]); + const extend = card("gemini"); + expect(extend.textContent).toContain("can also use"); + await act(async () => { button(extend, "Add to combo").click(); }); + expect(saved.map(({ kind, item }) => [kind, item.id, item.targets.map((t) => t.provider)])).toEqual([ + ["extend", "gemini", ["google-antigravity", "cursor"]], + ]); + }); + + test("excluding a provider is offered under the title and restoring unticks it", async () => { + exclusionWrites.length = 0; + await render([], ["cursor"]); + // Every suggestion here needs cursor, so only the exclusion control and the empty note show. + expect(host.querySelectorAll(".rb-suggest-card")).toHaveLength(0); + const toggle = button(host, "Excluded: Cursor"); + await act(async () => { toggle.click(); }); + const panel = host.querySelector(".rb-suggest-exclude-panel")!; + await act(async () => { button(panel, "Restore").click(); }); + expect(exclusionWrites).toEqual([[]]); + }); + + test("without an exclusion handler there is no exclude control", async () => { + await render(); + expect(host.querySelector(".rb-suggest-exclude")).toBeNull(); + }); +}); diff --git a/gui/tests/jev-session-pin.test.tsx b/gui/tests/jev-session-pin.test.tsx index 555169b037c..f85f1b0f1cd 100644 --- a/gui/tests/jev-session-pin.test.tsx +++ b/gui/tests/jev-session-pin.test.tsx @@ -20,7 +20,7 @@ const row = { id: "pin", model: "combo/pin", strategy: "jev", targets: [{ provid beforeEach(() => { previous = Object.fromEntries(globals.map(key => [key, Reflect.get(globalThis, key)])); originalFetch = globalThis.fetch; - testWindow = new Window({ url: "http://localhost/#models/combos" }); + testWindow = new Window({ url: "http://localhost/#models/combos/advanced" }); Object.defineProperty(testWindow.navigator, "language", { configurable: true, value: "en-US" }); for (const [key, value] of Object.entries({ document: testWindow.document, window: testWindow, navigator: testWindow.navigator, localStorage: testWindow.localStorage, IS_REACT_ACT_ENVIRONMENT: true })) { diff --git a/gui/tests/model-family.test.ts b/gui/tests/model-family.test.ts new file mode 100644 index 00000000000..16471886ab9 --- /dev/null +++ b/gui/tests/model-family.test.ts @@ -0,0 +1,112 @@ +// Cases ported from Magpie's internal/catalog/family_test.go (MIT, Copyright (c) 2026 yetone). +import { describe, expect, test } from "bun:test"; +import { familyOf, latestPerFamily, latestPerFamilyBy, modelFamilyKey } from "../src/lib/model-family"; + +describe("familyOf", () => { + const cases: Array<[string, string, number[], string, boolean]> = [ + ["claude-opus-4-8", "claude-opus", [4, 8], "", false], + ["claude-opus-5-5", "claude-opus", [5, 5], "", false], + ["claude-opus-5", "claude-opus", [5], "", false], + // a dated snapshot is its alias + ["claude-opus-4-5-20251101", "claude-opus", [4, 5], "20251101", false], + ["claude-haiku-4-5-20251001", "claude-haiku", [4, 5], "20251001", false], + ["gpt-4o-2024-08-06", "gpt-o", [4], "2024-08-06", false], + ["deepseek-r1-0528", "deepseek-r", [1], "0528", false], + ["qwen3-235b-a22b-instruct-2507", "qwen-235b-a22b-instruct", [3], "2507", false], + ["gemini-2.5-flash-preview-05-20", "gemini-flash", [2, 5], "05-20", true], + ["gemini-embedding-001", "gemini-embedding", [], "001", false], + ["command-r7b-12-2024", "command-r7b", [], "12-2024", false], + // the version mid-name + ["claude-3-5-sonnet-20241022", "claude-sonnet", [3, 5], "20241022", false], + ["meta-llama/llama-3.3-70b-instruct", "meta-llama/llama-70b-instruct", [3, 3], "", false], + // sizes and suffixes stay in the name + ["gpt-5.4-mini", "gpt-mini", [5, 4], "", false], + ["gpt-5.5-pro", "gpt-pro", [5, 5], "", false], + ["gpt-4.1-nano", "gpt-nano", [4, 1], "", false], + ["gpt-5.3-codex-spark", "gpt-codex-spark", [5, 3], "", false], + ["qwen3.6-27b", "qwen-27b", [3, 6], "", false], + ["qwen3.6-35b-a3b", "qwen-35b-a3b", [3, 6], "", false], + ["mistralai/mixtral-8x7b-instruct", "mistralai/mixtral-8x7b-instruct", [], "", false], + ["gemma-3n-e4b-it", "gemma-n-e4b-it", [3], "", false], + // gemini: flash, flash-lite and pro are three + ["gemini-3.5-flash", "gemini-flash", [3, 5], "", false], + ["gemini-3.5-flash-lite", "gemini-flash-lite", [3, 5], "", false], + ["gemini-3.1-pro-preview", "gemini-pro", [3, 1], "", true], + ["gemini-pro-latest", "gemini-pro", [], "", false], + // the o-series + ["o3", "o", [3], "", false], + ["o4-mini", "o-mini", [4], "", false], + ["o1-pro", "o-pro", [1], "", false], + // a word that ends in its version + ["kimi-k2.6", "kimi-k", [2, 6], "", false], + ["glm-4.6v", "glm-v", [4, 6], "", false], + ["deepseek-v4-flash", "deepseek-flash", [4], "", false], + // a provider prefix stays + ["anthropic/claude-opus-4.5", "anthropic/claude-opus", [4, 5], "", false], + ["us.anthropic.claude-sonnet-4-5-20250929-v1:0", "us.anthropic.claude-sonnet", [4, 5, 1, 0], "20250929", false], + ["Qwen/Qwen3.8-27B", "qwen/qwen-27b", [3, 8], "", false], + ["claude-sonnet-4-5[1m]", "claude-sonnet[1m", [4, 5], "", false], + ]; + for (const [id, name, version, snapshot, preview] of cases) { + test(id, () => { + expect(familyOf(id)).toEqual({ name, version, snapshot, preview }); + }); + } +}); + +test("different models never share a family", () => { + const pairs: Array<[string, string]> = [ + ["gpt-5.4", "gpt-5.4-mini"], + ["gpt-5.4-mini", "gpt-5.4-nano"], + ["gpt-5.5", "gpt-5.5-pro"], + ["gpt-4", "gpt-4o"], + ["o3", "o3-mini"], + ["o3", "o3-pro"], + ["gemini-3.5-flash", "gemini-3.1-pro-preview"], + ["gemini-3.5-flash", "gemini-3.5-flash-lite"], + ["qwen3-8b", "qwen3-32b"], + ["llama-3.1-8b-instruct", "llama-3.1-70b-instruct"], + ["gpt-6.1-sol", "gpt-6.1-terra"], + ["claude-opus-5-5", "claude-sonnet-5-5"], + ["kimi-k2-thinking", "kimi-k2"], + ["openai/gpt-5", "azure/gpt-5"], + ["deepseek/deepseek-r1:free", "deepseek/deepseek-r1"], + ]; + for (const [a, b] of pairs) expect(modelFamilyKey(a)).not.toBe(modelFamilyKey(b)); +}); + +describe("latestPerFamily", () => { + const cases: Array<[string, string[], string[]]> = [ + ["codex", ["gpt-6.1-sol", "gpt-6-astra", "gpt-6-sol", "gpt-6-luna", "gpt-5.6-sol", "gpt-5.6-terra", "gpt-5.6-luna"], + ["gpt-6.1-sol", "gpt-6-astra", "gpt-6-luna", "gpt-5.6-terra"]], + // a newer one listed takes the old one's place by itself + ["opus 5.6", ["claude-opus-5-6", "claude-opus-5-5", "claude-sonnet-5-5"], ["claude-opus-5-6", "claude-sonnet-5-5"]], + ["openai sizes", ["gpt-5.6", "gpt-5.5", "gpt-5.4-mini", "gpt-5-mini", "gpt-4.1-nano", "gpt-5.4-nano", "gpt-5.5-pro", "gpt-5-pro"], + ["gpt-5.6", "gpt-5.4-mini", "gpt-5.4-nano", "gpt-5.5-pro"]], + ["o-series", ["o1", "o3", "o3-mini", "o4-mini", "o1-pro", "o3-pro"], ["o3", "o4-mini", "o3-pro"]], + ["gemini", ["gemini-2.5-flash", "gemini-3.5-flash", "gemini-2.5-pro", "gemini-3.1-pro-preview", "gemini-3.1-flash-lite-preview", "gemini-3.1-flash-lite", "gemini-pro-latest"], + ["gemini-3.5-flash", "gemini-3.1-pro-preview", "gemini-3.1-flash-lite"]], + // at one version, a release over its preview + ["preview", ["gemini-3-pro-image-preview", "gemini-3-pro-image"], ["gemini-3-pro-image"]], + // the alias over its dated snapshots + ["snapshots", ["gpt-4o", "gpt-4o-2024-08-06", "gpt-4o-2024-11-20"], ["gpt-4o"]], + ["snapshots alone", ["mistral-medium-2505", "mistral-medium-2508"], ["mistral-medium-2508"]], + ["qwen sizes", ["Qwen/Qwen3.5-27B", "Qwen/Qwen3.6-27B", "Qwen/Qwen3.8-27B", "Qwen/Qwen3.6-35B-A3B", "Qwen/Qwen3.5-35B-A3B"], + ["Qwen/Qwen3.8-27B", "Qwen/Qwen3.6-35B-A3B"]], + ["mid-name version", ["claude-3-5-sonnet-20241022", "claude-sonnet-4-5"], ["claude-sonnet-4-5"]], + ["bedrock", ["us.anthropic.claude-sonnet-4-5-20250929-v1:0", "us.anthropic.claude-sonnet-5-5", "us.meta.llama3-1-70b-instruct-v1:0", "us.meta.llama3-3-70b-instruct-v1:0"], + ["us.anthropic.claude-sonnet-5-5", "us.meta.llama3-3-70b-instruct-v1:0"]], + ["provider prefix", ["openai/gpt-5.5", "openai/gpt-5.6", "azure/gpt-5.5"], ["openai/gpt-5.6", "azure/gpt-5.5"]], + ["none", [], []], + ]; + for (const [name, input, want] of cases) { + test(name, () => { + expect(latestPerFamily(input)).toEqual(want); + }); + } + + test("keeps rows by their id, in order", () => { + const rows = [{ id: "claude-sonnet-4-5", n: 1 }, { id: "gpt-5", n: 2 }, { id: "claude-sonnet-4-6", n: 3 }, { id: "gpt-5.1", n: 4 }]; + expect(latestPerFamilyBy(rows, (row) => row.id).map((row) => row.n)).toEqual([3, 4]); + }); +}); diff --git a/gui/tests/models-workspace-panels.test.tsx b/gui/tests/models-workspace-panels.test.tsx index 5cb9098e488..5fb44c1c70a 100644 --- a/gui/tests/models-workspace-panels.test.tsx +++ b/gui/tests/models-workspace-panels.test.tsx @@ -333,8 +333,13 @@ test("an unsaved combo draft survives a tab switch", async () => { (container.querySelector("#models-tab-combos") as HTMLButtonElement).click(); }); await act(async () => { await Promise.resolve(); }); + await act(async () => { + [...panel(container, "combos")!.querySelectorAll("button")] + .find(button => button.textContent?.trim() === "Advanced")!.click(); + }); + await act(async () => { await Promise.resolve(); }); - const field = () => panel(container, "combos")?.querySelector("input") as HTMLInputElement | null; + const field = () => panel(container, "combos")?.querySelector(".combos-workspace-root input") as HTMLInputElement | null; const input = field(); expect(input).toBeTruthy(); @@ -387,6 +392,11 @@ test("a failed combos reload keeps the workspace instead of replacing it", async (container.querySelector("#models-tab-combos") as HTMLButtonElement).click(); }); await act(async () => { await Promise.resolve(); }); + await act(async () => { + [...panel(container, "combos")!.querySelectorAll("button")] + .find(button => button.textContent?.trim() === "Advanced")!.click(); + }); + await act(async () => { await Promise.resolve(); }); expect(panel(container, "combos")?.querySelector(".combos-workspace-root")).toBeTruthy(); failNext = true; diff --git a/gui/tests/page-loading-contract.test.tsx b/gui/tests/page-loading-contract.test.tsx index 9c5d46e57d8..61f339ee7f0 100644 --- a/gui/tests/page-loading-contract.test.tsx +++ b/gui/tests/page-loading-contract.test.tsx @@ -135,7 +135,7 @@ const CACHED_PAGE = { beforeEach(() => { clearClientResourceStoresForTests(); previousGlobals = Object.fromEntries(globals.map(key => [key, Reflect.get(globalThis, key)])) as typeof previousGlobals; - testWindow = new Window({ url: "http://localhost/#models/combos" }); + testWindow = new Window({ url: "http://localhost/#models/combos/advanced" }); Object.defineProperties(globalThis, { document: { configurable: true, value: testWindow.document }, window: { configurable: true, value: testWindow.window }, diff --git a/gui/tests/route-board.test.tsx b/gui/tests/route-board.test.tsx new file mode 100644 index 00000000000..56e3248c2f8 --- /dev/null +++ b/gui/tests/route-board.test.tsx @@ -0,0 +1,768 @@ +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { Window } from "happy-dom"; +import { act } from "react"; +import type { Root } from "react-dom/client"; +import { resolveAppHashChange } from "../src/app-routing"; +import { toPutBody, type ComboItem } from "../src/combo-workspace-data"; +import { LanguageProvider } from "../src/i18n/provider"; +import Combos from "../src/pages/Combos"; +import { readCombosView } from "../src/pages/combos-view"; +import { readModelsTab } from "../src/pages/models-tab"; +import { + accountCountFromList, + buildRouteRows, + capabilityPatch, + capabilitySource, + combineLists, + parseCapabilitySources, + parseInferredCapabilities, + parseProbeResponse, + withInferredGaps, + configuredMemberModels, + dragSlot, + memberRestorePatch, + memberSettingsPatch, + parseContextInput, + comboContextWindow, + parseCapabilitySettings, + quotaFamilyWindow, + channelKey, + channelTargetsForPut, + distinctProviderLabels, + formatContextWindow, + moveChannel, + planStrategyChange, + quotaTone, +} from "../src/route-board-model"; +import { chooseOption } from "./helpers/custom-select"; + +const combo = (id: string, targets: Array<[string, string]>, extra: Partial = {}): ComboItem => ({ + id, + model: `combo/${id}`, + alias: null, + nativeAlias: false, + displayName: null, + strategy: "failover", + stickyLimit: 1, + defaultEffort: null, + imageInput: "auto", + reasoningEffortMode: "strict", + targets: targets.map(([provider, model]) => ({ provider, model })), + ...extra, +}); + +const NOW = 1_800_000_000_000; + +describe("route board model", () => { + test("quota colour follows the remaining-percent thresholds", () => { + expect([quotaTone(51), quotaTone(50), quotaTone(20), quotaTone(19.9)]).toEqual(["ok", "warn", "warn", "low"]); + }); + + test("rows carry channel order, per-provider quota, last resort, catalog name, context and on/off", () => { + const [row] = buildRouteRows({ + combos: [combo("opus", [["google-antigravity", "claude-opus-5-5"], ["anthropic", "claude-opus-5-5"], ["anthropic-apikey", "claude-opus-5-5"], ["zed", "claude-opus-5-5"]])], + catalog: { opus: { displayName: "Claude Opus 5.5", contextWindow: 200_000, disabled: true } }, + lastResort: { opus: [channelKey("zed", "claude-opus-5-5")] }, + providers: [ + { name: "google-antigravity", authMode: "oauth" }, + { name: "anthropic", authMode: "oauth" }, + { name: "anthropic-apikey", authMode: "key" }, + { name: "zed", authMode: "oauth", disabled: true }, + ], + quotaReports: [ + { + provider: "google-antigravity", + updatedAt: NOW, + quota: { + customWindows: [ + { label: "Gem", percent: 10, resetAt: NOW + 3_600_000 }, + { label: "Cla (Weekly)", percent: 72, resetAt: NOW + 86_400_000 }, + { label: "Cla", percent: 85, resetAt: NOW + 3_600_000 }, + ], + updatedAt: NOW, + }, + }, + { + provider: "anthropic", + updatedAt: NOW, + quota: { fiveHourPercent: 17, weeklyPercent: 49, updatedAt: NOW }, + aggregation: { includedAccounts: 2, excludedAccounts: 1 }, + }, + ], + now: NOW, + }); + expect(row!.displayName).toBe("Claude Opus 5.5"); + expect(row!.publicId).toBe("combo/opus"); + expect(row!.contextWindow).toBe(200_000); + expect(row!.enabled).toBe(false); + expect(row!.channels.map(channel => [channel.provider, channel.lastResort, channel.providerDisabled])).toEqual([ + ["google-antigravity", false, false], + ["anthropic", false, false], + ["anthropic-apikey", false, false], + ["zed", true, true], + ]); + const quota = Object.fromEntries(row!.quotas.map(line => [line.provider, line.quota])); + expect(row!.quotas.find(line => line.provider === "anthropic")?.accounts).toEqual({ active: 3, paused: 0 }); + // A Claude channel shows the Claude windows, never Antigravity's Gemini window. + expect(quota["google-antigravity"]).toEqual({ + kind: "windows", + windows: [ + expect.objectContaining({ label: "Cla (Weekly)", remainingPercent: 28, tone: "warn" }), + expect.objectContaining({ label: "Cla", remainingPercent: 15, tone: "low" }), + ], + }); + expect(quota.anthropic).toEqual({ + kind: "windows", + windows: [ + expect.objectContaining({ labelKey: "quota.weeklyLimit", remainingPercent: 51, tone: "ok" }), + expect.objectContaining({ labelKey: "quota.fiveHourLimit", remainingPercent: 83, tone: "ok" }), + ], + }); + expect(quota["anthropic-apikey"]).toEqual({ kind: "metered" }); + expect(quota.zed).toEqual({ kind: "unknown" }); + }); + + test("a combo missing from the catalog falls back to its id and counts as on", () => { + const [row] = buildRouteRows({ combos: [combo("x", [["a", "m"]])], catalog: {}, lastResort: {}, providers: [], quotaReports: undefined }); + expect([row!.displayName, row!.enabled, row!.contextWindow]).toEqual(["x", true, undefined]); + }); + + test("switched-off combos sort after the live ones and listed accounts fill in missing aggregates", () => { + const rows = buildRouteRows({ + combos: [combo("a-off", [["p", "m"]]), combo("b-on", [["p", "m"]]), combo("c-on", [["p", "m"]])], + catalog: { "a-off": { disabled: true }, "b-on": { disabled: false }, "c-on": { disabled: false } }, + lastResort: {}, + providers: [{ name: "p", authMode: "oauth" }], + quotaReports: undefined, + accountCounts: { p: { active: 7, paused: 1 } }, + }); + expect(rows.map(row => row.combo.id)).toEqual(["b-on", "c-on", "a-off"]); + expect(rows[0]!.quotas[0]!.accounts).toEqual({ active: 7, paused: 1 }); + expect(accountCountFromList({ accounts: [{ id: "1" }, { id: "2", paused: true }, { id: "3" }] })).toEqual({ active: 2, paused: 1 }); + expect(accountCountFromList({ error: "unknown oauth provider" })).toBeNull(); + }); + + test("Antigravity pool windows read as full family names", () => { + expect(quotaFamilyWindow("Cla (Weekly)")).toEqual({ family: "Claude & GPT", weekly: true }); + expect(quotaFamilyWindow("Gem")).toEqual({ family: "Gemini", weekly: false }); + expect(quotaFamilyWindow("Argon (Weekly)")).toEqual({ family: "Gemini 4 Argon", weekly: true }); + expect(quotaFamilyWindow("First-party models")).toBeNull(); + }); + + test("capability settings default when absent and only changed fields are sent", () => { + expect(parseCapabilitySettings({})).toEqual({ capabilityPolicy: "intersection", onUnservable: "degrade" }); + const before = parseCapabilitySettings({ capabilityPolicy: "union" }); + expect(capabilityPatch(before, before)).toEqual({}); + expect(capabilityPatch(before, { ...before, onUnservable: "reject" })).toEqual({ onUnservable: "reject" }); + }); + + test("context follows the policy: smallest member under intersection, largest under union", () => { + const members = [{ contextWindow: 200_000 }, { contextWindow: 1_000_000 }, {}]; + // Intersection trusts the server's advertised number (it applies caps the member rows do not show). + expect(comboContextWindow(members, "intersection", 128_000)).toEqual({ tokens: 128_000, basis: "min" }); + expect(comboContextWindow(members, "intersection", undefined)).toEqual({ tokens: 200_000, basis: "min" }); + expect(comboContextWindow(members, "union", 64_000)).toEqual({ tokens: 1_000_000, basis: "max" }); + expect(comboContextWindow([{}], "union", 64_000)).toEqual({ tokens: 64_000, basis: "catalog" }); + expect(combineLists([["text", "image"], ["text"], undefined], "intersection", ["text", "image"])).toEqual(["text"]); + expect(combineLists([["high", "low"], ["medium"]], "union", ["low", "medium", "high"])).toEqual(["low", "medium", "high"]); + expect(combineLists([undefined], "union")).toBeUndefined(); + }); + + test("providers sharing a display name stay distinguishable in one row", () => { + const labels = distinctProviderLabels(["anthropic", "zed", "anthropic-apikey"], provider => provider.startsWith("anthropic") ? "Anthropic Claude" : "Zed"); + expect([...labels.values()]).toEqual(["Anthropic Claude", "Zed", "Anthropic Claude (anthropic-apikey)"]); + }); + + test("strategy picks: save after validation, JEV opens the advanced editor, invalid never saves", () => { + const item = combo("a", [["p", "m"]]); + expect(planStrategyChange(item, "failover", () => null)).toEqual({ kind: "unchanged" }); + expect(planStrategyChange(item, "jev", () => null)).toEqual({ kind: "open-advanced" }); + expect(planStrategyChange(item, "random", () => "noEnabledTarget")).toEqual({ kind: "invalid", error: "noEnabledTarget", item: { ...item, strategy: "random" } }); + expect(planStrategyChange(item, "random", () => null)).toEqual({ kind: "save", item: { ...item, strategy: "random" } }); + }); + + test("channel moves stay in range and the PUT carries lastResort explicitly", () => { + expect(moveChannel(["a", "b", "c"], 0, 2)).toEqual(["b", "c", "a"]); + expect(moveChannel(["a", "b"], 1, 2)).toEqual(["a", "b"]); + expect(channelTargetsForPut( + [{ provider: "p", model: "1", weight: 2 }, { provider: "q", model: "2" }], + [{ provider: "q", model: "2", lastResort: true }, { provider: "p", model: "1", lastResort: false }], + )).toEqual([{ provider: "p", model: "1", weight: 2, lastResort: false }, { provider: "q", model: "2", lastResort: true }]); + }); + + test("context windows read as tokens", () => { + expect([formatContextWindow(1_000_000), formatContextWindow(1_048_576), formatContextWindow(1_500_000), formatContextWindow(128_000)]).toEqual(["1M", "1M", "1.5M", "128K"]); + }); +}); + +describe("combos view routing", () => { + test("the overview is the default and the workspace lives at models/combos/advanced", () => { + expect(readCombosView("#models/combos")).toBe("overview"); + expect(readCombosView("#combos")).toBe("overview"); + expect(readCombosView("#models/combos/advanced")).toBe("advanced"); + expect(readModelsTab("#models/combos/advanced")).toBe("combos"); + expect(resolveAppHashChange("models/combos/advanced")).toEqual({ page: "models", replaceTo: null }); + }); + + test("the JEV Auto deep link still opens the workspace and keeps its query", () => { + expect(readCombosView("#models/combos/jev-auto?decisionProvider=local")).toBe("advanced"); + expect(resolveAppHashChange("models/combos/jev-auto?decisionProvider=local")).toEqual({ page: "models", replaceTo: null }); + }); +}); + +const globals = ["document", "window", "navigator", "localStorage", "sessionStorage", "IS_REACT_ACT_ENVIRONMENT"] as const; +let previousGlobals: Record<(typeof globals)[number], unknown>; +let originalFetch: typeof globalThis.fetch; +let testWindow: Window; +let root: Root | null; +let host: HTMLElement; + +type Call = { url: string; method: string; body: unknown }; +let calls: Call[]; +let probeReply: "ok" | "baseline" | "busy" | "blocked" = "ok"; +let combosPayload: unknown; + +const alpha = combo("alpha", [["openai", "gpt-5"], ["anthropic", "claude"]]); +const offOnly = combo("offline", [["dead", "m"]]); + +function installFetch() { + calls = []; + combosPayload = { + combos: [ + { + ...toPutBody(alpha).combo, + id: "alpha", + model: "combo/alpha", + displayName: "Alpha", + targets: [{ provider: "openai", model: "gpt-5", modelProfile: "subscription first" }, { provider: "anthropic", model: "claude", lastResort: true }], + }, + { ...toPutBody(offOnly).combo, id: "offline", model: "combo/offline" }, + ], + }; + Object.defineProperty(globalThis, "fetch", { + configurable: true, + value: async (input: RequestInfo | URL, init?: RequestInit) => { + const url = String(input); + const method = init?.method ?? "GET"; + if (method !== "GET") { + calls.push({ url, method, body: init?.body ? JSON.parse(String(init.body)) : undefined }); + if (url.endsWith("/api/providers/probe-capabilities")) { + const sent = JSON.parse(String(init!.body)) as { confirmMetered?: boolean }; + if (probeReply === "busy") return Response.json({ error: "busy" }, { status: 409 }); + if (probeReply === "blocked") return Response.json({ applicable: false, reason: "unsupported_adapter", sent: false }); + if (!sent.confirmMetered) return Response.json({ applicable: true, sent: false, requiresConfirmation: true, metered: true, plannedRequests: 4 }); + if (probeReply === "baseline") { + return Response.json({ applicable: true, sent: true, baseline: { status: "inconclusive" }, reasoning: { accepted: [], rejected: [], inconclusive: ["low"] }, applied: {} }); + } + return Response.json({ + applicable: true, sent: true, baseline: { status: "accepted" }, image: { status: "accepted" }, + reasoning: { accepted: ["low", "high"], rejected: ["max"], inconclusive: [] }, + applied: { inputModalities: ["text", "image"], reasoningEfforts: ["low", "high"] }, + }); + } + if (url.endsWith("/api/model-settings")) { + const sent = JSON.parse(String(init!.body)) as { provider: string; modelId: string }; + return Response.json({ ok: true, provider: sent.provider, modelId: sent.modelId, changed: true, hasOverrides: true, saved: true, catalogRefresh: { status: "skipped" } }); + } + return Response.json(url.endsWith("/api/combos") ? { success: true } : { ok: true }); + } + if (url.endsWith("/api/combos")) return Response.json(combosPayload); + if (url.endsWith("/api/config")) { + return Response.json({ + providers: { + openai: { adapter: "openai-responses", baseUrl: "https://api.openai.com/v1" }, + anthropic: { adapter: "anthropic", baseUrl: "https://api.anthropic.com", authMode: "key" }, + dead: { adapter: "openai-chat", baseUrl: "https://example.invalid", disabled: true }, + }, + }); + } + if (url.endsWith("/api/models")) { + return Response.json([ + { provider: "openai", id: "gpt-5", contextWindow: 400000, reasoningEfforts: ["low", "high"], reasoningOverridden: true }, + { + provider: "anthropic", id: "claude", + capabilitySources: { contextWindow: "unknown", inputModalities: "probed", reasoningEfforts: "unknown" }, + inputModalities: ["text"], + inferredCapabilities: { contextWindow: { value: 1000000, basis: { source: "registry", provider: "anthropic", modelId: "claude" } } }, + }, + { provider: "dead", id: "m" }, + { provider: "combo", id: "alpha", displayName: "Alpha", displayNameSource: "provider", contextWindow: 200000, disabled: false }, + { provider: "combo", id: "offline", disabled: false }, + ]); + } + if (url.endsWith("/api/provider-quotas")) return Response.json({ reports: [] }); + if (url.endsWith("/api/sidecar-settings")) return Response.json({}); + throw new Error(`unexpected request: ${url}`); + }, + }); +} + +beforeEach(() => { + previousGlobals = Object.fromEntries(globals.map(key => [key, Reflect.get(globalThis, key)])) as typeof previousGlobals; + originalFetch = globalThis.fetch; + testWindow = new Window({ url: "http://localhost/#models/combos" }); + Object.defineProperty(testWindow.navigator, "language", { configurable: true, value: "en-US" }); + Object.defineProperties(globalThis, { + document: { configurable: true, value: testWindow.document }, + window: { configurable: true, value: testWindow }, + navigator: { configurable: true, value: testWindow.navigator }, + localStorage: { configurable: true, value: testWindow.localStorage }, + sessionStorage: { configurable: true, value: testWindow.sessionStorage }, + }); + (globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + root = null; + probeReply = "ok"; + installFetch(); +}); + +afterEach(async () => { + if (root) await act(async () => { root?.unmount(); }); + Object.defineProperty(globalThis, "fetch", { configurable: true, value: originalFetch }); + testWindow.close(); + for (const key of globals) { + Object.defineProperty(globalThis, key, { configurable: true, value: previousGlobals[key] }); + } +}); + +async function flush(rounds = 6) { + await act(async () => { + for (let index = 0; index < rounds; index += 1) await new Promise(resolve => setTimeout(resolve, 0)); + }); +} + +async function renderPage() { + const { createRoot } = await import("react-dom/client"); + host = document.createElement("div"); + document.body.append(host); + root = createRoot(host); + await act(async () => { root!.render(); }); + await flush(); +} + +function row(id: string): HTMLElement { + const found = [...host.querySelectorAll(".rb-row")].find(item => item.querySelector("code")?.textContent === `combo/${id}`); + if (!found) throw new Error(`row not found: ${id}`); + return found; +} + +function strategyTrigger(id: string): HTMLButtonElement { + return row(id).querySelector(`[role=combobox][aria-label="Strategy for combo/${id}"]`)!; +} + +function button(scope: ParentNode, name: string): HTMLButtonElement { + const found = [...scope.querySelectorAll("button")] + .find(item => item.textContent?.trim() === name || item.getAttribute("aria-label") === name); + if (!found) throw new Error(`button not found: ${name}`); + return found; +} + +describe("Combos overview page", () => { + test("opens on the overview: one row per combo with order, last resort, metered quota and context", async () => { + await renderPage(); + expect(host.querySelector(".combos-workspace-root")).toBeNull(); + const alphaRow = row("alpha"); + expect(alphaRow.querySelector("strong")?.textContent).toBe("Alpha"); + expect(alphaRow.querySelector(".rb-order")?.textContent).toContain("→"); + expect(alphaRow.querySelector(".rb-mark")?.textContent).toBe("fallback only"); + // The page's combos set no cooldownWaitPolicy, so the mark is shown as not in effect. + expect(alphaRow.querySelector(".rb-mark")?.classList.contains("rb-mark--inert")).toBe(true); + expect(alphaRow.querySelector(".rb-quota")?.textContent).toContain("pay per use"); + expect(alphaRow.textContent).toContain("ctx 200K"); + }); + + test("picking a strategy saves the normal PUT body and leaves lastResort to the server", async () => { + await renderPage(); + await chooseOption(strategyTrigger("alpha"), "round-robin"); + await flush(); + const saved = { ...alpha, displayName: "Alpha", targets: [{ provider: "openai", model: "gpt-5", modelProfile: "subscription first" }, { provider: "anthropic", model: "claude" }] }; + expect(calls).toEqual([{ url: "/api/combos", method: "PUT", body: toPutBody({ ...saved, strategy: "round-robin" }) }]); + expect(JSON.stringify(calls[0]!.body)).not.toContain("lastResort"); + }); + + test("picking JEV saves nothing and opens the advanced editor on that combo", async () => { + await renderPage(); + await chooseOption(strategyTrigger("alpha"), "jev"); + await flush(); + expect(calls).toEqual([]); + expect(window.location.hash).toBe("#models/combos/advanced"); + const workspace = host.querySelector(".rb-advanced"); + expect(workspace?.hidden).toBe(false); + expect(host.querySelector(".combos-workspace-detail-title")?.textContent).toBe("combo/alpha"); + }); + + test("a strategy that fails validation sends nothing and says why in the row", async () => { + await renderPage(); + await chooseOption(strategyTrigger("offline"), "random"); + await flush(); + expect(calls).toEqual([]); + expect(row("offline").querySelector("[role=alert]")?.textContent).toContain("Not saved"); + }); + + test("the switch writes the combo's model-visibility selector", async () => { + await renderPage(); + await act(async () => { button(row("alpha"), "List combo/alpha to clients").click(); }); + await flush(); + expect(calls).toEqual([{ + url: "/api/model-visibility", + method: "PUT", + body: { scope: "models", provider: "combo", targets: [{ id: "alpha" }], enabled: false }, + }]); + }); + + test("the channel editor reorders, marks last resort and saves explicit flags", async () => { + await renderPage(); + await act(async () => { row("alpha").querySelector(".rb-row-toggle")!.click(); }); + const editor = row("alpha").querySelector(".rb-editor")!; + await act(async () => { editor.querySelector('button[aria-label$="gpt-5 down"]')!.click(); }); + const lastResortButtons = editor.querySelectorAll(".rb-last-resort"); + await act(async () => { lastResortButtons[0]!.click(); }); + expect(editor.textContent).toContain("Unsaved"); + await act(async () => { button(editor, "Save").click(); }); + await flush(); + const body = calls[0]!.body as ReturnType; + expect(body.combo.displayName).toBe("Alpha"); + expect(Object.hasOwn(body.combo, "capabilityPolicy")).toBe(false); + expect(Object.hasOwn(body.combo, "onUnservable")).toBe(false); + expect(Object.hasOwn(body.combo, "cooldownWaitPolicy")).toBe(false); + expect(body.combo.targets).toEqual([ + { provider: "anthropic", model: "claude", lastResort: false }, + { provider: "openai", model: "gpt-5", modelProfile: "subscription first", lastResort: false }, + ]); + }); + + test("pointer drag: the row itself follows, the others slide aside, one commit on release", async () => { + await renderPage(); + await act(async () => { row("alpha").querySelector(".rb-row-toggle")!.click(); }); + const editor = row("alpha").querySelector(".rb-editor")!; + const list = editor.querySelector(".rb-channels")!; + const names = () => [...editor.querySelectorAll(".rb-channel code")].map(node => node.textContent); + const items = () => [...editor.querySelectorAll(".rb-channel")]; + // Rows 40px tall at 0 and 40 in a list at 0 (happy-dom has no layout). + items().forEach((item, index) => { + Object.defineProperty(item, "offsetTop", { configurable: true, value: index * 40 }); + Object.defineProperty(item, "offsetHeight", { configurable: true, value: 40 }); + item.getBoundingClientRect = () => ({ top: index * 40, height: 40, bottom: index * 40 + 40, left: 0, right: 0, width: 0, x: 0, y: index * 40, toJSON: () => ({}) }) as DOMRect; + }); + const pointer = (target: EventTarget, type: string, clientY: number) => { + const event = new testWindow.Event(type, { bubbles: true, cancelable: true }) as unknown as Event; + Object.defineProperties(event, { clientY: { value: clientY }, clientX: { value: 0 }, pointerId: { value: 1 }, button: { value: 0 }, isPrimary: { value: true }, pointerType: { value: "mouse" } }); + target.dispatchEvent(event); + }; + const first = items()[0]!; + await act(async () => { pointer(first, "pointerdown", 20); }); + await act(async () => { pointer(document, "pointermove", 30); }); + expect(list.classList.contains("sorting")).toBe(true); + expect(first.classList.contains("dragging")).toBe(true); + expect(editor.querySelectorAll(".rb-channel").length).toBe(2); // no copy of the dragged row + expect(names()).toEqual(["gpt-5", "claude"]); // nothing reorders before the release + await new Promise(resolve => setTimeout(resolve, 400)); // past the tap window + await act(async () => { pointer(document, "pointerup", 75); }); + expect(names()).toEqual(["claude", "gpt-5"]); + expect(list.classList.contains("sorting")).toBe(false); + expect(items().every(item => item.style.transform === "")).toBe(true); + expect(editor.textContent).toContain("Unsaved"); + }); + + test("pointer drag: a press on a row's button stays a click, and Escape cancels a drag", async () => { + await renderPage(); + await act(async () => { row("alpha").querySelector(".rb-row-toggle")!.click(); }); + const editor = row("alpha").querySelector(".rb-editor")!; + const list = editor.querySelector(".rb-channels")!; + const names = () => [...editor.querySelectorAll(".rb-channel code")].map(node => node.textContent); + const pointer = (target: EventTarget, type: string, clientY: number) => { + const event = new testWindow.Event(type, { bubbles: true, cancelable: true }) as unknown as Event; + Object.defineProperties(event, { clientY: { value: clientY }, clientX: { value: 0 }, pointerId: { value: 1 }, button: { value: 0 }, isPrimary: { value: true }, pointerType: { value: "mouse" } }); + target.dispatchEvent(event); + }; + await act(async () => { pointer(editor.querySelector(".rb-remove")!, "pointerdown", 20); }); + await act(async () => { pointer(document, "pointermove", 60); }); + expect(list.classList.contains("sorting")).toBe(false); + await act(async () => { pointer(document, "pointerup", 60); }); + await act(async () => { pointer(editor.querySelector(".rb-channel")!, "pointerdown", 20); }); + await act(async () => { pointer(document, "pointermove", 60); }); + expect(list.classList.contains("sorting")).toBe(true); + await act(async () => { document.dispatchEvent(new testWindow.KeyboardEvent("keydown", { key: "Escape", bubbles: true, cancelable: true }) as unknown as Event); }); + expect(list.classList.contains("sorting")).toBe(false); + await act(async () => { pointer(document, "pointerup", 75); }); + expect(names()).toEqual(["gpt-5", "claude"]); + }); + + test("member table: source tags per cell, and an in-place edit writes the provider's model settings", async () => { + await renderPage(); + await act(async () => { row("alpha").querySelector(".rb-tag--button")!.click(); }); + const editor = row("alpha").querySelector(".rb-editor")!; + const gpt = [...editor.querySelectorAll(".rb-members tbody tr")].find(tr => tr.textContent?.includes("gpt-5"))!; + expect([...gpt.querySelectorAll(".rb-src")].map(tag => tag.textContent)).toEqual(["provider report", "unknown", "manual"]); + expect(gpt.textContent).not.toContain("unknown unknown"); + await act(async () => { button(gpt, "Edit what OpenAI (Codex login) gpt-5 can take").click(); }); + const form = editor.querySelector(".rb-member-edit")!; + expect(form.textContent).toContain("every combo that uses this model changes too"); + const input = form.querySelector("input")!; + const setValue = Object.getOwnPropertyDescriptor(testWindow.HTMLInputElement.prototype, "value")!.set!; + await act(async () => { + setValue.call(input, "nonsense"); + input.dispatchEvent(new testWindow.Event("input", { bubbles: true }) as unknown as Event); + }); + await act(async () => { button(form, "Save").click(); }); + expect(form.querySelector("[role=alert]")?.textContent).toContain("200K"); + expect(calls).toEqual([]); + await act(async () => { + setValue.call(input, "1M"); + input.dispatchEvent(new testWindow.Event("input", { bubbles: true }) as unknown as Event); + }); + await act(async () => { button(form, "images").click(); }); + await act(async () => { button(form, "Save").click(); }); + await flush(); + expect(calls).toEqual([{ url: "/api/model-settings", method: "PUT", body: { provider: "openai", modelId: "gpt-5", contextWindow: 1000000, inputModalities: ["image"] } }]); + expect(editor.querySelector(".rb-member-edit")).toBeNull(); + }); + + test("a gap with a same-name estimate shows it, and Adopt saves it as a manual setting", async () => { + await renderPage(); + await act(async () => { row("alpha").querySelector(".rb-tag--button")!.click(); }); + const editor = row("alpha").querySelector(".rb-editor")!; + const claude = [...editor.querySelectorAll(".rb-members tbody tr")].find(tr => tr.textContent?.includes("claude"))!; + expect(claude.textContent).toContain("inferred 1M (based on anthropic built-in table)"); + expect(claude.textContent).toContain("probed"); + expect(editor.querySelector(".rb-members tfoot")?.textContent).toContain("includes inferred"); + await act(async () => { claude.querySelector(".rb-adopt")!.click(); }); + await flush(); + expect(calls).toEqual([{ url: "/api/model-settings", method: "PUT", body: { provider: "anthropic", modelId: "claude", contextWindow: 1000000 } }]); + }); + + test("Test it asks before a metered probe, then repeats with consent and lists the results", async () => { + await renderPage(); + await act(async () => { row("alpha").querySelector(".rb-tag--button")!.click(); }); + const editor = row("alpha").querySelector(".rb-editor")!; + const gpt = () => [...editor.querySelectorAll(".rb-members tbody tr")].find(tr => tr.querySelector("th")?.textContent?.includes("gpt-5"))!; + await act(async () => { button(gpt(), "Test what OpenAI (Codex login) gpt-5 accepts").click(); }); + await flush(); + const dialog = editor.querySelector("[role=alertdialog]")!; + expect(dialog.textContent).toContain("sends 4 very small requests"); + expect(editor.textContent).toContain("Context is inferred from the model name, not measured."); + await act(async () => { button(dialog, "Run the test").click(); }); + await flush(); + expect(calls.map(call => call.body)).toEqual([ + { name: "openai", model: "gpt-5", apply: true }, + { name: "openai", model: "gpt-5", apply: true, confirmMetered: true }, + ]); + const results = editor.querySelector(".rb-probe")!.textContent!; + expect(results).toContain("Images: accepted"); + expect(results).toContain("accepted: low · high; refused: max"); + expect(results).toContain("saved effort levels: low · high"); + }); + + test("Test it: a failed baseline changes nothing, a busy provider says so, an inapplicable one greys the button", async () => { + await renderPage(); + await act(async () => { row("alpha").querySelector(".rb-tag--button")!.click(); }); + const editor = row("alpha").querySelector(".rb-editor")!; + const gpt = () => [...editor.querySelectorAll(".rb-members tbody tr")].find(tr => tr.querySelector("th")?.textContent?.includes("gpt-5"))!; + const test = () => button(gpt(), "Test what OpenAI (Codex login) gpt-5 accepts"); + probeReply = "baseline"; + await act(async () => { test().click(); }); + await flush(); + await act(async () => { button(editor.querySelector("[role=alertdialog]")!, "Run the test").click(); }); + await flush(); + expect(editor.querySelector(".rb-probe")!.textContent).toContain("Inconclusive"); + probeReply = "busy"; + await act(async () => { test().click(); }); + await flush(); + expect(editor.querySelector(".rb-probe")!.textContent).toContain("already being tested"); + probeReply = "blocked"; + await act(async () => { test().click(); }); + await flush(); + expect(editor.querySelector(".rb-probe")!.textContent).toContain("only OpenAI-compatible endpoints"); + expect(test().disabled).toBe(true); + }); + + test("restoring a member sends null only for the fields set by hand", async () => { + await renderPage(); + await act(async () => { row("alpha").querySelector(".rb-tag--button")!.click(); }); + const editor = row("alpha").querySelector(".rb-editor")!; + const gpt = [...editor.querySelectorAll(".rb-members tbody tr")].find(tr => tr.textContent?.includes("gpt-5"))!; + await act(async () => { button(gpt, "Edit what OpenAI (Codex login) gpt-5 can take").click(); }); + await act(async () => { button(editor.querySelector(".rb-member-edit")!, "Use the provider's values").click(); }); + await flush(); + expect(calls[0]!.body).toEqual({ provider: "openai", modelId: "gpt-5", reasoningEfforts: null }); + }); + + test("the context tag opens More settings in place, with the members' numbers", async () => { + await renderPage(); + await act(async () => { row("alpha").querySelector(".rb-tag--button")!.click(); }); + const editor = row("alpha").querySelector(".rb-editor")!; + expect(editor.querySelector(".rb-more-toggle")?.getAttribute("aria-expanded")).toBe("true"); + expect(editor.querySelector(".rb-members")).not.toBeNull(); + expect(window.location.hash).toBe("#models/combos"); + }); + + test("the fallback-only switch writes cooldownWaitPolicy", async () => { + await renderPage(); + await act(async () => { row("alpha").querySelector(".rb-row-toggle")!.click(); }); + const editor = row("alpha").querySelector(".rb-editor")!; + await act(async () => { editor.querySelector(".rb-more-toggle")!.click(); }); + await act(async () => { editor.querySelector('[role=switch][aria-label="Fallback channels wait their turn"]')!.click(); }); + await act(async () => { button(editor, "Save").click(); }); + await flush(); + expect((calls[0]!.body as { combo: Record }).combo.cooldownWaitPolicy).toBe("before-last-resort"); + }); + + test("capability policy: union reveals the unservable choice and only changed fields are sent", async () => { + await renderPage(); + await act(async () => { row("alpha").querySelector(".rb-row-toggle")!.click(); }); + const editor = row("alpha").querySelector(".rb-editor")!; + await act(async () => { editor.querySelector(".rb-more-toggle")!.click(); }); + expect(editor.querySelector('[role=combobox][aria-label="When no channel can serve it"]')).toBeNull(); + await chooseOption(editor.querySelector('[role=combobox][aria-label="Capabilities"]')!, "union"); + await chooseOption(editor.querySelector('[role=combobox][aria-label="When no channel can serve it"]')!, "reject"); + await act(async () => { button(editor, "Save").click(); }); + await flush(); + const body = calls[0]!.body as { combo: Record }; + expect([body.combo.capabilityPolicy, body.combo.onUnservable]).toEqual(["union", "reject"]); + }); + + test("an unsaved advanced draft survives the overview, locks its own row, and outlives a refresh", async () => { + window.location.hash = "#models/combos/advanced"; + await renderPage(); + const railRow = [...host.querySelectorAll(".combos-workspace-rail-row")] + .find(item => item.querySelector(".combos-workspace-rail-name")?.textContent === "combo/alpha")!; + await act(async () => { railRow.click(); }); + await flush(); + const alias = host.querySelector("#cwi-edit-alias")!; + await act(async () => { + Object.getOwnPropertyDescriptor(testWindow.HTMLInputElement.prototype, "value")!.set!.call(alias, "draft-alias"); + alias.dispatchEvent(new testWindow.Event("input", { bubbles: true })); + }); + + await act(async () => { button(host, "Back to overview").click(); }); + await flush(); + expect(host.querySelector(".rb-advanced")?.hidden).toBe(true); + expect(strategyTrigger("alpha").disabled).toBe(true); + expect(row("alpha").textContent).toContain("unsaved in Advanced"); + expect(strategyTrigger("offline").disabled).toBe(false); + await act(async () => { button(row("alpha"), "List combo/alpha to clients").click(); }); + await flush(); + expect(calls.map(call => call.url)).toEqual(["/api/model-visibility"]); + + await act(async () => { button(host, "Advanced").click(); }); + await flush(); + expect(host.querySelector("#cwi-edit-alias")?.value).toBe("draft-alias"); + }); +}); + +describe("drag slot", () => { + const mids = (count: number) => Array.from({ length: count }, (_, index) => index * 40 + 20); + /** Runs a pointer path and returns every slot change, like dragover events would. */ + const sweep = (count: number, from: number, path: number[]) => { + const start = mids(count); + let slot = from; + const changes: number[] = []; + for (const y of path) { + const next = dragSlot(start, from, y, slot); + if (next !== slot) { changes.push(next); slot = next; } + } + return { slot, changes }; + }; + const range = (from: number, to: number, step: number) => { + const out: number[] = []; + for (let y = from; step > 0 ? y <= to : y >= to; y += step) out.push(y); + return out; + }; + + for (const count of [4, 6]) { + test(`${count} rows: a slow drag to the last place passes each slot once`, () => { + const result = sweep(count, 0, range(20, count * 40, 1)); + expect(result.slot).toBe(count - 1); + expect(result.changes).toEqual(Array.from({ length: count - 1 }, (_, index) => index + 1)); + }); + test(`${count} rows: a slow drag back to the first place passes each slot once`, () => { + const result = sweep(count, count - 1, range(count * 40 - 20, 0, -1)); + expect(result.slot).toBe(0); + expect(result.changes).toEqual(Array.from({ length: count - 1 }, (_, index) => count - 2 - index)); + }); + test(`${count} rows: a fast drag lands on the first and the last place`, () => { + expect(sweep(count, count - 1, [count * 40 - 20, -10]).slot).toBe(0); + expect(sweep(count, 0, [20, count * 40 + 30]).slot).toBe(count - 1); + }); + test(`${count} rows: a pointer jittering on a boundary changes the slot at most once`, () => { + const boundary = mids(count)[2]!; + const jitter = Array.from({ length: 40 }, (_, index) => boundary + (index % 2 === 0 ? 3 : -3)); + expect(sweep(count, 0, [20, boundary - 10, ...jitter]).changes.length).toBeLessThanOrEqual(2); + }); + } + + test("moving back past the start returns the row to its own place", () => { + expect(sweep(4, 1, [60, 140, 60]).slot).toBe(1); + }); +}); + +describe("member capability edits", () => { + test("context input accepts plain numbers and K/M suffixes", () => { + expect(parseContextInput("200000")).toBe(200000); + expect(parseContextInput("200K")).toBe(200000); + expect(parseContextInput("1m")).toBe(1000000); + expect(parseContextInput("1.5M")).toBe(1500000); + expect(parseContextInput("1,000,000")).toBe(1000000); + expect(parseContextInput("big")).toBeUndefined(); + expect(parseContextInput("0")).toBeUndefined(); + }); + + test("only changed fields are patched; unknown lists left empty stay unknown", () => { + const order = ["none", "minimal", "low", "medium", "high", "xhigh", "max"]; + expect(memberSettingsPatch({ contextWindow: 200000 }, { context: "200K", input: [], efforts: [] }, order)).toEqual({ patch: {} }); + expect(memberSettingsPatch({ reasoningEfforts: ["high"] }, { context: "", input: ["text"], efforts: ["high", "low"] }, order)) + .toEqual({ patch: { inputModalities: ["text"], reasoningEfforts: ["low", "high"] } }); + expect(memberSettingsPatch({}, { context: "lots", input: [], efforts: [] }, order).invalid).toBe("context"); + }); + + test("a member with no catalog row still shows its per-model config, tagged manual", () => { + expect(configuredMemberModels({ + zed: { modelContextWindows: { m: 400000 }, modelCapabilities: { m: { inputModalities: ["text"] } } }, + other: { modelReasoningEfforts: { n: ["low"] } }, + })).toEqual([ + { provider: "zed", id: "m", contextWindow: 400000, inputModalities: ["text"], sources: { context: "manual", input: "manual", efforts: "unknown" } }, + { provider: "other", id: "n", reasoningEfforts: ["low"], sources: { context: "unknown", input: "unknown", efforts: "manual" } }, + ]); + }); + + test("sources: manual wins, an explicit inferred source next, else the provider's report", () => { + expect(capabilitySource(true, true, "inferred")).toBe("manual"); + expect(capabilitySource(true, false, "inferred")).toBe("inferred"); + expect(capabilitySource(true, false)).toBe("reported"); + expect(capabilitySource(false, false)).toBe("unknown"); + expect(memberRestorePatch({ context: "manual", input: "reported", efforts: "manual" })).toEqual({ contextWindow: null, reasoningEfforts: null }); + }); +}); + +describe("capability sources, estimates and probe replies", () => { + test("sources come from the server's per-axis labels; junk reads as unknown", () => { + expect(parseCapabilitySources({ contextWindow: "probed", inputModalities: "inferred", reasoningEfforts: "nonsense" })) + .toEqual({ context: "probed", input: "inferred", efforts: "unknown" }); + expect(parseCapabilitySources(undefined)).toBeUndefined(); + }); + + test("estimates keep only well-formed axes, and fill gaps only in the combined row", () => { + const inferred = parseInferredCapabilities({ + contextWindow: { value: 1000000, basis: { source: "registry", provider: "anthropic", modelId: "m" } }, + inputModalities: { value: [], basis: { source: "vendor", provider: "x", modelId: "m" } }, + reasoningEfforts: { value: ["low"], basis: { source: "nowhere", provider: "x", modelId: "m" } }, + }); + expect(inferred).toEqual({ context: { value: 1000000, basis: { source: "registry", provider: "anthropic", modelId: "m" } } }); + expect(withInferredGaps([{ contextWindow: 200000, inferred }, { inferred }])).toEqual({ + members: [{ contextWindow: 200000, inferred }, { contextWindow: 1000000, inferred }], + used: true, + }); + expect(withInferredGaps([{ contextWindow: 200000 }]).used).toBe(false); + }); + + test("probe replies map to confirm, inapplicable, busy, done and failed", () => { + expect(parseProbeResponse(200, { requiresConfirmation: true, plannedRequests: 5 })).toEqual({ kind: "confirm", planned: 5 }); + expect(parseProbeResponse(200, { applicable: false, reason: "oauth_auth" })).toEqual({ kind: "inapplicable", reason: "oauth_auth" }); + expect(parseProbeResponse(409, { error: "busy" })).toEqual({ kind: "busy" }); + expect(parseProbeResponse(500, { error: "x" })).toEqual({ kind: "failed" }); + expect(parseProbeResponse(200, { sent: true, baseline: { status: "inconclusive" } })).toMatchObject({ kind: "done", baselineOk: false }); + }); + + test("restore clears probed declarations too", () => { + expect(memberRestorePatch({ context: "reported", input: "probed", efforts: "manual" })).toEqual({ inputModalities: null, reasoningEfforts: null }); + }); +}); diff --git a/scripts/test-layout/layout.json b/scripts/test-layout/layout.json index 05605249cbe..188f94506d0 100644 --- a/scripts/test-layout/layout.json +++ b/scripts/test-layout/layout.json @@ -241,7 +241,7 @@ "antigravity-refusal.test.ts": "adapters/google", "antigravity-static-catalog.test.ts": "adapters/google", "api-access-endpoints.test.ts": "server", - "api-catalog-route.test.ts": "server", + "api-catalog-route.test.ts": "server", "combo-suggestion-routes.test.ts": "server", "api-codex-log-guard-compact.test.ts": "server", "api-codex-log-guard-protection.test.ts": "server", "api-codex-log-guard.test.ts": "server", diff --git a/src/config/schema/config-schema.ts b/src/config/schema/config-schema.ts index ceeeafb6a7a..d8f0a5f2894 100644 --- a/src/config/schema/config-schema.ts +++ b/src/config/schema/config-schema.ts @@ -408,6 +408,8 @@ export const configSchema = z.object({ }).optional().catch(undefined), // Model ids excluded from the Grok Build managed block (dashboard switches). grokExcludedModels: z.array(z.string()).optional(), + // Providers the dashboard's suggested combos leave out (Combos page). + comboSuggestionExcludedProviders: z.array(z.string().min(1)).optional().catch(undefined), // Invalid values degrade to undefined ("auto") instead of failing the whole // parse: a hand-edited typo must never trip the backup-and-defaults repair // path below and wipe providers/pool accounts. Warning emitted in loadConfig. diff --git a/src/server/management-api.ts b/src/server/management-api.ts index 2c77513135b..cddd415a471 100644 --- a/src/server/management-api.ts +++ b/src/server/management-api.ts @@ -176,6 +176,13 @@ async function handleFallbackRoutesOnDemand(ctx: ManagementContext): Promise { + if (!pathInManagementNamespace(ctx.url.pathname, "/api/combo-suggestions", false)) return null; + const { handleComboSuggestionRoutes } = await import("./management/combo-suggestion-routes"); + return handleComboSuggestionRoutes(ctx); +} + async function handleRouteToRoutesOnDemand(ctx: ManagementContext): Promise { if (!pathInManagementNamespace(ctx.url.pathname, "/api/route-to")) return null; const { handleRouteToRoutes } = await import("./management/route-to-routes"); @@ -382,6 +389,7 @@ export async function handleManagementAPI( ?? (await handleLowQuotaRoutesOnDemand(ctx)) ?? (await handleQuotaPoolRoutesOnDemand(ctx)) ?? (await handleFallbackRoutesOnDemand(ctx)) + ?? (await handleComboSuggestionRoutesOnDemand(ctx)) ?? (await handleRouteToRoutesOnDemand(ctx)) ?? (await handleWorkflowBudgetRoutesOnDemand(ctx)) ?? (await handleCodexAgentRoleRoutesOnDemand(ctx)) diff --git a/src/server/management/combo-suggestion-routes.ts b/src/server/management/combo-suggestion-routes.ts new file mode 100644 index 00000000000..2942f284994 --- /dev/null +++ b/src/server/management/combo-suggestion-routes.ts @@ -0,0 +1,69 @@ +/** + * `GET|PUT /api/combo-suggestions`: the providers left out of the Combos page's suggested + * combos (`comboSuggestionExcludedProviders`). Suggestions are computed in the dashboard; this + * only persists the exclusion list in config.json so it follows the operator across browsers. + * It never touches routing: a combo that already names an excluded provider keeps it. + */ +import type { ManagementContext } from "./context"; +import { jsonResponse } from "../auth-cors"; +import { mutatePersistedConfig } from "../../config"; +import { managementBodyTooLargeResponse, readManagementJsonBody } from "./body"; +import { isPlainRecord } from "./shared"; + +const MAX_PROVIDERS = 256; +const MAX_NAME_LENGTH = 256; + +/** Trimmed, deduplicated, in the order given; null when the value is not a list of names. */ +export function parseExcludedProviders(value: unknown): string[] | null { + if (!Array.isArray(value) || value.length > MAX_PROVIDERS) return null; + const out: string[] = []; + for (const entry of value) { + if (typeof entry !== "string") return null; + const name = entry.trim(); + if (!name || name.length > MAX_NAME_LENGTH) return null; + if (!out.includes(name)) out.push(name); + } + return out; +} + +function view(ctx: ManagementContext): Response { + const response = jsonResponse({ excludedProviders: ctx.config.comboSuggestionExcludedProviders ?? [] }, 200, ctx.req, ctx.config); + response.headers.set("cache-control", "no-store"); + return response; +} + +export async function handleComboSuggestionRoutes(ctx: ManagementContext): Promise { + const { req, url } = ctx; + if (url.pathname === "/api/combo-suggestions" && req.method === "GET") return view(ctx); + if (url.pathname === "/api/combo-suggestions" && req.method === "PUT") return await writeExcluded(ctx); + return null; +} + +async function writeExcluded(ctx: ManagementContext): Promise { + const { req, config } = ctx; + let body: unknown; + try { + body = await readManagementJsonBody(req); + } catch (error) { + return managementBodyTooLargeResponse(error, req, config) + ?? jsonResponse({ error: "invalid JSON body", code: "invalid_request" }, 400, req, config); + } + const excluded = isPlainRecord(body) && Object.keys(body).every(key => key === "excludedProviders") + ? parseExcludedProviders(body.excludedProviders) + : null; + if (!excluded) { + return jsonResponse({ error: "excludedProviders must be a list of provider names", code: "invalid_request" }, 400, req, config); + } + const outcome = mutatePersistedConfig(persisted => { + const before = JSON.stringify(persisted.comboSuggestionExcludedProviders ?? []); + if (excluded.length === 0) delete persisted.comboSuggestionExcludedProviders; + else persisted.comboSuggestionExcludedProviders = excluded; + return { changed: before !== JSON.stringify(excluded), value: excluded }; + }); + if (outcome.status === "unavailable") { + return jsonResponse({ error: `config.json is ${outcome.reason}; excluded providers were not saved`, code: "config_unavailable" }, 409, req, config); + } + if (excluded.length === 0) delete config.comboSuggestionExcludedProviders; + else config.comboSuggestionExcludedProviders = excluded; + return view(ctx); +} diff --git a/src/server/management/route-registry.ts b/src/server/management/route-registry.ts index 789d947e632..64afa6b4d43 100644 --- a/src/server/management/route-registry.ts +++ b/src/server/management/route-registry.ts @@ -226,6 +226,9 @@ export const MANAGEMENT_ROUTES: readonly ManagementRoute[] = [ { method: "DELETE", path: "/api/combos", module: "server/management/combo-routes", mutates: true }, { method: "GET", path: "/api/combos", module: "server/management/combo-routes", mutates: false }, { method: "PUT", path: "/api/combos", module: "server/management/combo-routes", mutates: true }, + // server/management/combo-suggestion-routes + { method: "GET", path: "/api/combo-suggestions", module: "server/management/combo-suggestion-routes", mutates: false, exempt: { reason: "gui-only", why: "Combo suggestions exist only on the dashboard's Combos page; the CLI has no suggestion view to filter." } }, + { method: "PUT", path: "/api/combo-suggestions", module: "server/management/combo-suggestion-routes", mutates: true, exempt: { reason: "gui-only", why: "Combo suggestions exist only on the dashboard's Combos page; the CLI has no suggestion view to filter." } }, // server/management/decision-routes { method: "GET", path: "/api/combos/decision-discovery", module: "server/management/decision-routes", mutates: false }, { method: "POST", path: "/api/combos/decision-test", module: "server/management/decision-routes", mutates: true }, diff --git a/src/types/config.ts b/src/types/config.ts index 286c92d5089..3bc53f80166 100644 --- a/src/types/config.ts +++ b/src/types/config.ts @@ -789,6 +789,11 @@ export interface OcxConfig extends OcxLinkHomeConfig { * would silently hide every future model behind a switch nobody knew to flip. */ grokExcludedModels?: string[]; + /** + * Provider names the dashboard's suggested combos leave out (Combos page). View-only: + * existing combos that name one keep routing to it. + */ + comboSuggestionExcludedProviders?: string[]; /** * When true, OpenAI-routed requests include `service_tier: "priority"` (fast inference). * When false, service_tier is stripped so requests use default speed. diff --git a/structure/dashboard-and-usage.md b/structure/dashboard-and-usage.md index 9c27768c993..4338061ae18 100644 --- a/structure/dashboard-and-usage.md +++ b/structure/dashboard-and-usage.md @@ -126,7 +126,7 @@ The sidebar exposes eight rows (`gui/src/nav-groups.ts` `NAV_GROUPS`), in order: | API keys | Key table plus per-key detail (`gui/src/components/apikeys-workspace/`). The list payload carries masked prefixes only; each row deletes in place behind a two-step confirm, and clicking a key fetches the full value from `POST /api/keys/reveal`, which requires a current pairing or trusted Tailscale-identity session and answers `no-store`; automatic loopback sessions and raw admin tokens cannot reveal stored values, and a refusal there answers with the pairing surface — on the same-origin standalone transport the local pairing form, elsewhere the explanation alone — and requires a fresh reveal click after pairing. Displayed secrets and copy feedback are cleared on shared-session loss, pairing, inactive/hidden views, or a target change; stale asynchronous completions cannot restore them. | | Storage | Rail plus cleanup and trash detail (`gui/src/components/storage-workspace/`). | | Subagents | Featured-roster selection workspace (`gui/src/components/subagents-workspace/`). | -| Combos | Rail, detail panel, and an add flow (`gui/src/components/ComboWorkspace.tsx`). | +| Combos | `#models/combos` opens the overview (`gui/src/components/route-board/RouteBoard.tsx`, view model `gui/src/route-board-model.ts`): one row per combo with stacked provider icons, display name and public id, the channel order (`→` for failover, `·` otherwise, last-resort members marked), one quota line per provider from `/api/provider-quotas` (remaining percent, green above 50%, amber 20–50%, red below 20%; `key` providers read as pay per use), the catalog context window, an inline strategy menu and an on/off switch. Switched-off combos sort after the live ones. Antigravity pool windows read as family names (`Cla (Weekly)` → "Claude & GPT · weekly"). Account counts come from the report's `aggregation`, otherwise from `GET /api/oauth/accounts?provider=` for enabled OAuth providers (paused accounts listed separately). A strategy pick runs `validateComboDraft` and then the normal `PUT /api/combos`; JEV never saves from the row and opens the workspace on that combo instead, because an empty decision service means the hosted TypeSafe service. The switch writes the combo selector through `PUT /api/model-visibility` (`provider: "combo"`). Clicking a row opens the channel editor (reorder by pointer drag or by move buttons (which slide with FLIP); mark fallback only, i.e. `lastResort`; remove; add). Its "More settings" section opens in place: the capability policy, a "fallback channels wait their turn" switch that writes `cooldownWaitPolicy` (`"before-last-resort"` or `null`), and a member table (`gui/src/components/route-board/MemberTable.tsx`) of each member's context window, input modalities and effort levels with the combined row. Every cell carries its source from the row's `capabilitySources` (`parseCapabilitySources`; an older server without it falls back to the `*Declared` / `reasoningOverridden` flags via `capabilitySource`); members with no `/api/models` row fall back to their per-model config (`configuredMemberModels`). A gap with an `inferredCapabilities` estimate shows the value and its basis with an Adopt button that writes it through `PUT /api/model-settings`; estimates fill gaps only in the combined row, labelled (`withInferredGaps`), never in routing. A member edit sends only the changed fields to `PUT /api/model-settings` (`memberSettingsPatch`; restore sends `null` for the manual fields), validates the receipt, and refreshes the page; "Test it" (`gui/src/components/route-board/MemberProbe.tsx`) posts `POST /api/providers/probe-capabilities` with `apply: true`, repeats with `confirmMetered: true` after an inline confirmation naming `plannedRequests`, and shows `applicable: false` reasons (button greyed), a 409 as already running, and a failed baseline as inconclusive (`parseProbeResponse`). Pointer drag is Magpie's row sorter (`gui/src/components/route-board/drag-rows.ts`, MIT, © yetone): the row itself follows the pointer by a transform with no copy or placeholder, the rows it passes slide a row's height aside, Escape cancels, and the order changes once on release; the slot comes from the layout midpoints with 8 px hysteresis (`dragSlot`), and presses on the row's own controls (or anywhere but the grip on touch) stay clicks. The row's context tag opens that section and shows the smallest member under intersection and the largest under union (`comboContextWindow`); fallback-only marks render greyed with the reason while the combo has no `cooldownWaitPolicy`; only its save sends `lastResort` explicitly, every other save omits it so the server carries it over. Capability fields (`capabilityPolicy`, `onUnservable`) and `cooldownWaitPolicy` read absent as the defaults and are sent only when changed. "Advanced" opens the rail, detail panel and add flow (`gui/src/components/ComboWorkspace.tsx`) at `#models/combos/advanced`; `#models/combos/jev-auto` still lands there (`gui/src/pages/combos-view.ts`). The workspace stays mounted once opened, so an unsaved draft survives the overview, and the overview locks the strategy and channel save of the combo being drafted until the draft is saved or discarded. Above the rows, suggested combos (`gui/src/components/route-board/ComboSuggestions.tsx`, pure model `gui/src/combo-suggestions.ts`) group catalog models of enabled, picker-visible providers by a normalized name (prefix, case, gaps, version dots and a trailing effort suffix folded; snapshot dates kept). Hidden catalog rows count, because hiding only affects external lists, but a suggestion with a listed member ranks first. A name served by two or more providers and not yet covered by a combo (one whose id names it or whose members all serve it) becomes a draft: members ordered maker's subscription, other subscriptions, Vertex, then keys and relays, by remaining quota within a tier; the operator can rename, reorder or drop members before the normal create `PUT /api/combos` (strategy failover, id made free with `-2`, `-3`). A covered name whose combo lacks a serving provider becomes an add hint that inserts the member ahead of the combo's first lower-tier member. Dismissals live in `localStorage` (`ocx.combos.suggestions.dismissed.v1`), never in config. Providers the operator excludes from suggestions ("Exclude a provider…" under the title, `gui/src/components/route-board/SuggestionExcludeProviders.tsx`, after Magpie's found-group skip) do live in config: `comboSuggestionExcludedProviders`, read and written whole through `GET|PUT /api/combo-suggestions` (`src/server/management/combo-suggestion-routes.ts`, dashboard-only); an excluded provider joins no create or add hint, and existing combos keep routing to it. The channel editor's add row and a provider's model list (`gui/src/components/provider-workspace/ProviderModels.tsx`) share a "Latest per family" switch (`localStorage` `ocx.models.latestPerFamily.v1`, default off) that shows only the newest model of each family (`gui/src/lib/model-family.ts`, ported from Magpie's `internal/catalog/family.go`, MIT, © yetone; `gui/tests/model-family.test.ts`); it is view state only. `gui/tests/combo-suggestions.test.tsx` covers normalization, coverage, ordering, id collisions, dismissal, provider exclusion and the draft save; `tests/server/combo-suggestion-routes.test.ts` covers the config round trip. `gui/tests/route-board.test.tsx` covers the rows, PUT bodies, the JEV hand-off, validation, the switch selector, the channel save, drag sweeps over 4 and 6 rows, the member edit and restore bodies, and the draft lock. | | Add provider | Catalog browser plus form and OAuth panes (`gui/src/components/provider-catalog/`, `gui/src/components/AddProviderModal.tsx`). The catalog browses four tabs — Accounts, Free, Local, Paid — where Local is a catalog-only bucket peeled out of `bucketPresets` after `presetTier` has classified; the workspace `providerTier` stays three-way, so the rail, the free-paid sort and the Free count still treat a local runtime as free. Search sits above the tabs and reaches every tab at once: while a query is live the list renders all four groups with headings and the strip becomes jump chips with counts rather than a tablist, because moving the selected tab would change the row kind under the user (a preset-select button becomes a login row). ArrowDown from the search input focuses the first enabled result action; if none is available, focus stays in the input. The tab strip wraps within narrow modals. Every nonempty note has a full-text button so narrow rows never hide content permanently; the native note dialog closes during teardown and restores focus to its trigger. Provider notes clamp to two lines and open in full in a stacked native `` owned by `AddProviderModal`, which also owns the search text so its `window` Escape handler can unwind popup, then query, then dialog. | | Codex accounts | Account pool cards, add-account flow, switch and reset modals (`gui/src/components/CodexAccountPool.tsx`, `gui/src/components/AddCodexAccountModal.tsx`), plus the generic account-targeting picker opt-in on `gui/src/pages/codex-set-multiauth.tsx`. Add/delete/login completion is projected to one boolean before presentation; pending catalog work is a warning, not a failed account mutation. The main card's native-main device reauth (#3898) is owned by `gui/src/components/use-main-device-reauth.ts`: the dedicated `/api/codex-auth/main/reauth-device` namespace only — never the pool login route — with flowId-owned polling, an allowlisted verification URL, and no token fields accepted from payloads. The main-device reauth hook retains flow ownership from the Cancel click, while DELETE is unresolved and after retryable failure; polling normally continues. A concurrent GET HTTP error cannot expose a replacement login POST before DELETE settles. If a retryable DELETE failure races with a non-2xx GET while the flow is pending or committing, either response order preserves same-flow Cancel retry, restores the last server-provided device code, verification URL, and phase when needed, and keeps the existing poll cadence so a later terminal result remains observable. Outside same-flow cancellation ownership, a GET HTTP failure still stops polling without starting a second login POST. The cancellation-failure indication survives pending status updates until a trusted terminal result releases ownership. A successful DELETE with a terminal `failed` DTO releases it and uses the same closed failure-code mapping as polling; only `succeeded` notifies login completion. Unrecognized or nonterminal DTO status values remain retryable. A DELETE response with HTTP 404 and code `unknown_flow` releases the expired flow and shows the existing generic failure state so device re-login is available again; it claims neither login success nor confirmed cancellation. Confirmed cancellation also makes device re-login available. Start, polling and cancellation completions verify their controller or flow ownership after asynchronous response reads; replaced flows and unmounted hooks cannot update a newer flow or notify completion. Effect setup restores mounted state after the StrictMode development cleanup cycle. | | Dashboard overview | Overview, Providers, and Models tabs at the page level (`gui/src/pages/Dashboard.tsx`), the 30-day token and coverage stats in the overview head (`gui/src/pages/dashboard-overview-head.tsx`), and the effort-cap, injection, maintenance, sidecar, reasoning-retention, and memory panels below it (`gui/src/pages/dashboard-overview-panels.tsx`). The Reasoning retention controls (`gui/src/components/ReasoningRetentionPanel.tsx`) live in a collapsed Advanced settings disclosure at the end of Overview. They read and save `reasoningRetention` via GET/PUT `/api/settings` in `src/server/management/config-routes.ts`: only explicit `enabled: true` activates retention; absent, disabled, and legacy threshold-only settings remain off. The enable switch exposes numeric controls with defaults of 20% and 100000 tokens; disabling saves `enabled: false`, and null reset removes the setting and turns it off. Omission preserves it, validation precedes mutation, and save failure restores value and key presence. Copy warns that opt-in can preserve plaintext reasoning in local history/archive and that completed archives have no aggregate quota or expiry and require manual deletion. Loading disables writes, failures permit retry without losing edits, and stale responses cannot update a new API target. Its scope is the [routed v1/v2 compaction contract](transports/responses-failover.md#compaction-routing-overrides); opaque output stays unchanged. `tests/config/settings-reasoning-retention.test.ts` and `gui/tests/reasoning-retention-panel.test.tsx` cover the API and controls. Inputs expose invalid state and reference the validation alert only for the failing field. | diff --git a/tests/fixtures/test-layout-expected.json b/tests/fixtures/test-layout-expected.json index ebfabf37355..81f23b6a02e 100644 --- a/tests/fixtures/test-layout-expected.json +++ b/tests/fixtures/test-layout-expected.json @@ -389,7 +389,7 @@ "anthropic-tool-declaration-constraints.test.ts": "adapters/anthropic", "anthropic-tool-schema.test.ts": "adapters/anthropic", "antigravity-baseurl-override.test.ts": "adapters/google", "antigravity-refusal.test.ts": "adapters/google", "antigravity-static-catalog.test.ts": "adapters/google", - "api-access-endpoints.test.ts": "server", "api-catalog-route.test.ts": "server", + "api-access-endpoints.test.ts": "server", "api-catalog-route.test.ts": "server", "combo-suggestion-routes.test.ts": "server", "api-codex-log-guard-compact.test.ts": "server", "api-codex-log-guard-protection.test.ts": "server", "api-codex-log-guard.test.ts": "server", "api-debug.test.ts": "server", "api-key-attribution.test.ts": "server", "api-key-catalog-authority.test.ts": "providers", diff --git a/tests/server/combo-suggestion-routes.test.ts b/tests/server/combo-suggestion-routes.test.ts new file mode 100644 index 00000000000..612bdc250e9 --- /dev/null +++ b/tests/server/combo-suggestion-routes.test.ts @@ -0,0 +1,68 @@ +import { afterEach, beforeEach, expect, test } from "bun:test"; +import { mkdtempSync, readFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { handleManagementAPI } from "../../src/server/management-api"; +import { loadConfig, saveConfig } from "../../src/config"; +import { ManagementRequest, managementHeaders } from "../helpers/management-auth"; +import { removeTreeWithRetry } from "../helpers/remove-tree"; +import { parseExcludedProviders } from "../../src/server/management/combo-suggestion-routes"; +import type { OcxConfig } from "../../src/types"; + +const previousHome = process.env.OPENCODEX_HOME; +let home = ""; + +beforeEach(() => { + home = mkdtempSync(join(tmpdir(), "ocx-combo-suggestion-routes-")); + process.env.OPENCODEX_HOME = home; + saveConfig({ + port: 10100, + hostname: "127.0.0.1", + defaultProvider: "mock", + providers: { mock: { adapter: "openai-chat", baseUrl: "http://127.0.0.1:1/v1", apiKey: "k", allowPrivateNetwork: true, models: ["m"] } }, + } as OcxConfig); +}); + +afterEach(() => { + if (previousHome === undefined) delete process.env.OPENCODEX_HOME; + else process.env.OPENCODEX_HOME = previousHome; + removeTreeWithRetry(home); +}); + +async function call(config: OcxConfig, method: "GET" | "PUT", body?: unknown) { + const url = new URL("http://localhost/api/combo-suggestions"); + const init: RequestInit = { method, headers: { ...managementHeaders(), "content-type": "application/json" } }; + if (body !== undefined) init.body = JSON.stringify(body); + const response = await handleManagementAPI(new ManagementRequest(url, init), url, config); + return { status: response!.status, body: await response!.json() as Record }; +} + +const onDisk = () => JSON.parse(readFileSync(join(home, "config.json"), "utf8")) as Record; + +test("excluded providers round-trip through config.json, and an empty list removes the key", async () => { + const live = loadConfig(); + expect(await call(live, "GET")).toEqual({ status: 200, body: { excludedProviders: [] } }); + + expect(await call(live, "PUT", { excludedProviders: [" cursor ", "cursor", "trae"] })) + .toEqual({ status: 200, body: { excludedProviders: ["cursor", "trae"] } }); + expect(onDisk().comboSuggestionExcludedProviders).toEqual(["cursor", "trae"]); + expect(loadConfig().comboSuggestionExcludedProviders).toEqual(["cursor", "trae"]); + expect(await call(loadConfig(), "GET")).toEqual({ status: 200, body: { excludedProviders: ["cursor", "trae"] } }); + + expect(await call(live, "PUT", { excludedProviders: [] })).toEqual({ status: 200, body: { excludedProviders: [] } }); + expect("comboSuggestionExcludedProviders" in onDisk()).toBe(false); + expect(live.comboSuggestionExcludedProviders).toBeUndefined(); +}); + +test("a malformed write is refused and changes nothing", async () => { + const live = loadConfig(); + for (const body of [{ excludedProviders: "cursor" }, { excludedProviders: [1] }, { excludedProviders: [""] }, { other: [] }]) { + expect((await call(live, "PUT", body)).status).toBe(400); + } + expect("comboSuggestionExcludedProviders" in onDisk()).toBe(false); +}); + +test("parseExcludedProviders trims, dedupes and keeps order", () => { + expect(parseExcludedProviders(["b", " a", "b "])).toEqual(["b", "a"]); + expect(parseExcludedProviders(null)).toBeNull(); +});