From 51d7ad1a49a6ed9656c9c238841be28db3c1b097 Mon Sep 17 00:00:00 2001 From: "Andrew (agent)" Date: Fri, 13 Nov 2026 20:11:55 -0500 Subject: [PATCH 01/21] feat(gui): Combos overview, one row per combo with inline strategy, switch and channel editor Original PR: #8656 --- .../src/content/docs/es/guides/combos.md | 2 + .../src/content/docs/fr/guides/combos.md | 2 + docs-site/src/content/docs/guides/combos.md | 24 +- .../src/content/docs/ja/guides/combos.md | 2 + .../src/content/docs/ko/guides/combos.md | 2 + .../src/content/docs/ru/guides/combos.md | 2 + .../src/content/docs/tr/guides/combos.md | 2 + .../src/content/docs/zh-cn/guides/combos.md | 2 + .../src/content/docs/zh-tw/guides/combos.md | 2 + gui/classic/src/pages/Combos.tsx | 466 +++++++++++ gui/src/app-routing.ts | 2 + gui/src/components/ComboWorkspace.tsx | 14 +- gui/src/components/combo-workspace-types.ts | 6 + .../components/route-board/ChannelEditor.tsx | 321 ++++++++ .../components/route-board/MemberProbe.tsx | 93 +++ .../components/route-board/MemberTable.tsx | 294 +++++++ .../components/route-board/ModelRouteRow.tsx | 116 +++ gui/src/components/route-board/QuotaLine.tsx | 52 ++ gui/src/components/route-board/RouteBoard.tsx | 164 ++++ .../components/route-board/StrategyMenu.tsx | 47 ++ gui/src/components/route-board/drag-rows.ts | 171 ++++ gui/src/design/pages/route-board.css | 192 +++++ gui/src/design/theme.css | 1 + gui/src/i18n/de.ts | 116 +++ gui/src/i18n/en.ts | 116 +++ gui/src/i18n/fr.ts | 116 +++ gui/src/i18n/ja.ts | 116 +++ gui/src/i18n/ko.ts | 116 +++ gui/src/i18n/pt.ts | 116 +++ gui/src/i18n/ru.ts | 116 +++ gui/src/i18n/tr.ts | 116 +++ gui/src/i18n/vi.ts | 116 +++ gui/src/i18n/zh-TW.ts | 116 +++ gui/src/i18n/zh.ts | 116 +++ gui/src/pages/Combos.tsx | 313 ++++++- gui/src/pages/combos-advanced-hash.ts | 2 + gui/src/pages/combos-view.ts | 15 + gui/src/pages/models-tab.ts | 3 +- gui/src/route-board-model.ts | 641 +++++++++++++++ .../combo-capability-hidden-targets.test.tsx | 2 +- gui/tests/jev-session-pin.test.tsx | 2 +- gui/tests/models-workspace-panels.test.tsx | 12 +- gui/tests/page-loading-contract.test.tsx | 2 +- gui/tests/route-board.test.tsx | 768 ++++++++++++++++++ structure/dashboard-and-usage.md | 2 +- 45 files changed, 4993 insertions(+), 24 deletions(-) create mode 100644 gui/classic/src/pages/Combos.tsx create mode 100644 gui/src/components/route-board/ChannelEditor.tsx create mode 100644 gui/src/components/route-board/MemberProbe.tsx create mode 100644 gui/src/components/route-board/MemberTable.tsx create mode 100644 gui/src/components/route-board/ModelRouteRow.tsx create mode 100644 gui/src/components/route-board/QuotaLine.tsx create mode 100644 gui/src/components/route-board/RouteBoard.tsx create mode 100644 gui/src/components/route-board/StrategyMenu.tsx create mode 100644 gui/src/components/route-board/drag-rows.ts create mode 100644 gui/src/design/pages/route-board.css create mode 100644 gui/src/pages/combos-advanced-hash.ts create mode 100644 gui/src/pages/combos-view.ts create mode 100644 gui/src/route-board-model.ts create mode 100644 gui/tests/route-board.test.tsx 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..d0b12332cce 100644 --- a/docs-site/src/content/docs/guides/combos.md +++ b/docs-site/src/content/docs/guides/combos.md @@ -982,8 +982,28 @@ 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. + +**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..ad51add3845 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 +**模型 → 组合** 默认先打开总览:每个组合一行,显示通道顺序、各供应商剩余额度、上下文窗口、策略下拉和开关。点 **高级** 打开下面介绍的完整工作区。 + 打开本地 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/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/route-board/ChannelEditor.tsx b/gui/src/components/route-board/ChannelEditor.tsx new file mode 100644 index 00000000000..e00ccd1f47a --- /dev/null +++ b/gui/src/components/route-board/ChannelEditor.tsx @@ -0,0 +1,321 @@ +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 { 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 addModels = models.filter((model) => model.provider === addProvider && !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} + /> + +
+

{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/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 ( + setComboId(event.target.value)} aria-invalid={!idOk} /> + +

    {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/design/pages/route-board.css b/gui/src/design/pages/route-board.css index 915a808edad..a3bedb8698f 100644 --- a/gui/src/design/pages/route-board.css +++ b/gui/src/design/pages/route-board.css @@ -190,3 +190,54 @@ .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-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/i18n/de.ts b/gui/src/i18n/de.ts index 91bc2c3bc16..8bfec431a7d 100644 --- a/gui/src/i18n/de.ts +++ b/gui/src/i18n/de.ts @@ -4622,4 +4622,27 @@ export const de: Record = { "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", + "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 45d985c4e9a..d7cbb332e88 100644 --- a/gui/src/i18n/en.ts +++ b/gui/src/i18n/en.ts @@ -4656,6 +4656,29 @@ export const en = { "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", + "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 53b695e341e..72db0d0d8f6 100644 --- a/gui/src/i18n/fr.ts +++ b/gui/src/i18n/fr.ts @@ -4611,4 +4611,27 @@ export const fr: Record = { "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", + "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 82b2ffb0b81..9220d4304c0 100644 --- a/gui/src/i18n/ja.ts +++ b/gui/src/i18n/ja.ts @@ -4644,4 +4644,27 @@ export const ja: Record = { "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": "非表示", + "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 c2fd35e42cc..cb020f8e8b2 100644 --- a/gui/src/i18n/ko.ts +++ b/gui/src/i18n/ko.ts @@ -4644,4 +4644,27 @@ export const ko: Record = { "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": "무시", + "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 b11e565091d..5fd4edcf56d 100644 --- a/gui/src/i18n/pt.ts +++ b/gui/src/i18n/pt.ts @@ -4617,4 +4617,27 @@ export const pt: Record = { "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", + "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 4171e8b8ce6..ca98437a55f 100644 --- a/gui/src/i18n/ru.ts +++ b/gui/src/i18n/ru.ts @@ -4645,4 +4645,27 @@ export const ru: Record = { "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": "Скрыть", + "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 7fcc74f566d..b0ef847d7c8 100644 --- a/gui/src/i18n/tr.ts +++ b/gui/src/i18n/tr.ts @@ -4645,4 +4645,27 @@ export const tr: Record = { "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", + "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 9c9d7b79941..262b4c2955f 100644 --- a/gui/src/i18n/vi.ts +++ b/gui/src/i18n/vi.ts @@ -4614,4 +4614,27 @@ export const vi: Record = { "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", + "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 3f860f149af..dc8f9b42761 100644 --- a/gui/src/i18n/zh-TW.ts +++ b/gui/src/i18n/zh-TW.ts @@ -4608,4 +4608,27 @@ export const zhTW: Record = { "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": "忽略", + "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 2e706828f35..0d5d79fa41c 100644 --- a/gui/src/i18n/zh.ts +++ b/gui/src/i18n/zh.ts @@ -4643,4 +4643,27 @@ export const zh: Record = { "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": "忽略", + "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/pages/Combos.tsx b/gui/src/pages/Combos.tsx index 785ddf14b12..79b57c7f23b 100644 --- a/gui/src/pages/Combos.tsx +++ b/gui/src/pages/Combos.tsx @@ -22,12 +22,15 @@ 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 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, @@ -89,6 +92,8 @@ type CachedCombosPage = { 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 }; @@ -270,6 +275,7 @@ export default function Combos({ 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) => { @@ -335,6 +341,7 @@ export default function Combos({ 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); @@ -370,7 +377,7 @@ export default function Combos({ ...(member.sources ? { sources: member.sources } : {}), })), ]; - const next = { combos, providers, models, capabilityModels, cataloguedComboIds: [...catalogued], comboCatalog, lastResort, lastResortActive, capability, memberModels } satisfies CachedCombosPage; + 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. @@ -622,6 +629,22 @@ export default function Combos({ 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" }); @@ -696,6 +719,19 @@ export default function Combos({ {state.refreshing ? t("common.loading") : ""} + {view === "overview" && ( + comboDraftErrorText(t, code, item, providerRows)} + onCreate={(item) => saveCombo(item, true, undefined, {})} + onExtend={(item) => saveCombo(item, false, undefined, {})} + /> + )} {view === "overview" && ( , 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"]); + }); +}); + +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 }> = []; + async function render(combos: ComboItem[] = []) { + 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 }; }} + /> + , + ); + }); + } + 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"]], + ]); + }); +}); diff --git a/structure/dashboard-and-usage.md b/structure/dashboard-and-usage.md index 76bbfe8c027..9665eed3834 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 | `#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. `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. | +| 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. `gui/tests/combo-suggestions.test.tsx` covers normalization, coverage, ordering, id collisions, dismissal and the draft save. `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. | From aa482094391abb7984047b1b4efb03ad7a6c795f Mon Sep 17 00:00:00 2001 From: "Andrew (agent)" Date: Fri, 13 Nov 2026 20:15:56 -0500 Subject: [PATCH 03/21] feat(gui): latest-per-family model filter and provider exclusion for suggested combos Original PR: #8729 --- gui/src/combo-suggestions.ts | 4 +- .../provider-workspace/ProviderModels.tsx | 14 +- .../components/route-board/ChannelEditor.tsx | 9 +- .../route-board/ComboSuggestions.tsx | 17 +- .../SuggestionExcludeProviders.tsx | 78 +++++++++ .../route-board/use-suggestion-exclusions.ts | 53 ++++++ gui/src/design/pages/route-board.css | 16 ++ gui/src/i18n/de.ts | 9 + gui/src/i18n/en.ts | 9 + gui/src/i18n/fr.ts | 9 + gui/src/i18n/ja.ts | 9 + gui/src/i18n/ko.ts | 9 + gui/src/i18n/pt.ts | 9 + gui/src/i18n/ru.ts | 9 + gui/src/i18n/tr.ts | 9 + gui/src/i18n/vi.ts | 9 + gui/src/i18n/zh-TW.ts | 9 + gui/src/i18n/zh.ts | 9 + gui/src/lib/latest-per-family-pref.ts | 29 ++++ gui/src/lib/model-family.ts | 156 ++++++++++++++++++ gui/src/pages/Combos.tsx | 4 + gui/tests/combo-suggestions.test.tsx | 32 +++- gui/tests/model-family.test.ts | 112 +++++++++++++ scripts/test-layout/layout.json | 2 +- src/config/schema/config-schema.ts | 2 + src/server/management-api.ts | 8 + .../management/combo-suggestion-routes.ts | 69 ++++++++ src/server/management/route-registry.ts | 3 + src/types/config.ts | 5 + structure/dashboard-and-usage.md | 2 +- tests/fixtures/test-layout-expected.json | 2 +- tests/server/combo-suggestion-routes.test.ts | 68 ++++++++ 32 files changed, 772 insertions(+), 12 deletions(-) create mode 100644 gui/src/components/route-board/SuggestionExcludeProviders.tsx create mode 100644 gui/src/components/route-board/use-suggestion-exclusions.ts create mode 100644 gui/src/lib/latest-per-family-pref.ts create mode 100644 gui/src/lib/model-family.ts create mode 100644 gui/tests/model-family.test.ts create mode 100644 src/server/management/combo-suggestion-routes.ts create mode 100644 tests/server/combo-suggestion-routes.test.ts diff --git a/gui/src/combo-suggestions.ts b/gui/src/combo-suggestions.ts index d635cbcf76a..9ebc7727599 100644 --- a/gui/src/combo-suggestions.ts +++ b/gui/src/combo-suggestions.ts @@ -157,6 +157,8 @@ export interface SuggestionInput { 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 { @@ -169,7 +171,7 @@ export function buildComboSuggestions(input: SuggestionInput): ComboSuggestion[] const byModel = new Map>(); for (const row of input.models) { const provider = providers.get(row.provider); - if (!provider || provider.disabled || provider.hiddenFromPicker) continue; + 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(); 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 index e00ccd1f47a..c2520785ba9 100644 --- a/gui/src/components/route-board/ChannelEditor.tsx +++ b/gui/src/components/route-board/ChannelEditor.tsx @@ -20,6 +20,8 @@ import { 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"; @@ -120,7 +122,10 @@ export function ChannelEditor({ const pickable = providers.filter((provider) => !provider.hiddenFromPicker); const [addProvider, setAddProvider] = useState(() => pickable[0]?.name ?? ""); const used = new Set(channels.map((channel) => channel.key)); - const addModels = models.filter((model) => model.provider === addProvider && !used.has(channelKey(model.provider, model.id))); + 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); @@ -236,6 +241,8 @@ export function ChannelEditor({ : [{ value: "", label: t("routeBoard.edit.noModels"), disabled: true }]} onChange={setAddModel} /> + setLatestOnly(!latestOnly)} label={t("models.latestPerFamily")} + title={t("models.latestPerFamilyHint")} showLabel /> diff --git a/gui/src/components/route-board/ComboSuggestions.tsx b/gui/src/components/route-board/ComboSuggestions.tsx index e76fa42e170..d16ca8028e8 100644 --- a/gui/src/components/route-board/ComboSuggestions.tsx +++ b/gui/src/components/route-board/ComboSuggestions.tsx @@ -16,6 +16,7 @@ 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 }; @@ -39,6 +40,9 @@ export interface ComboSuggestionsProps { 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. */ @@ -47,8 +51,9 @@ export function ComboSuggestions(props: ComboSuggestionsProps) { const [dismissed, setDismissed] = useState>(() => dismissedStore.read() ?? new Set()); const [showAll, setShowAll] = useState(false); const [draftKey, setDraftKey] = useState(null); - const suggestions = buildComboSuggestions({ ...props, dismissed }); - if (suggestions.length === 0) return 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); @@ -68,7 +73,15 @@ export function ComboSuggestions(props: ComboSuggestionsProps) {
    {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) => ( Promise; +}) { + const t = useT(); + const [open, setOpen] = useState(false); + const [busy, setBusy] = useState(false); + const [failed, setFailed] = useState(false); + // An excluded provider that was since removed still lists, so it can be restored. + const names = [...providers, ...excluded.filter((name) => !providers.includes(name))]; + const label = (name: string) => formatProviderDisplayName(name, t); + + const toggle = async (name: string, exclude: boolean) => { + setBusy(true); + setFailed(false); + const next = exclude ? [...excluded, name] : excluded.filter((entry) => entry !== name); + const ok = await onChange(next); + setBusy(false); + if (!ok) setFailed(true); + }; + + return ( +
      + + {open && ( +
      + {t("comboSuggest.exclude.head")} +

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

      +
        + {names.map((name) => { + const on = excluded.includes(name); + return ( +
      • + + {on && ( + + )} +
      • + ); + })} +
      + {failed &&

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

      } +
      + )} +
      + ); +} 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 index a3bedb8698f..208384fb39c 100644 --- a/gui/src/design/pages/route-board.css +++ b/gui/src/design/pages/route-board.css @@ -202,6 +202,22 @@ .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; } diff --git a/gui/src/i18n/de.ts b/gui/src/i18n/de.ts index 8bfec431a7d..1e0ff031238 100644 --- a/gui/src/i18n/de.ts +++ b/gui/src/i18n/de.ts @@ -4629,6 +4629,15 @@ export const de: Record = { "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", diff --git a/gui/src/i18n/en.ts b/gui/src/i18n/en.ts index d7cbb332e88..e289a3c55c9 100644 --- a/gui/src/i18n/en.ts +++ b/gui/src/i18n/en.ts @@ -4663,6 +4663,15 @@ export const en = { "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", diff --git a/gui/src/i18n/fr.ts b/gui/src/i18n/fr.ts index 72db0d0d8f6..e30eaa8b5bd 100644 --- a/gui/src/i18n/fr.ts +++ b/gui/src/i18n/fr.ts @@ -4618,6 +4618,15 @@ export const fr: Record = { "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", diff --git a/gui/src/i18n/ja.ts b/gui/src/i18n/ja.ts index 9220d4304c0..b3dd1cb6fb6 100644 --- a/gui/src/i18n/ja.ts +++ b/gui/src/i18n/ja.ts @@ -4651,6 +4651,15 @@ export const ja: Record = { "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": "提供元のサブスクリプション", diff --git a/gui/src/i18n/ko.ts b/gui/src/i18n/ko.ts index cb020f8e8b2..4104f26250f 100644 --- a/gui/src/i18n/ko.ts +++ b/gui/src/i18n/ko.ts @@ -4651,6 +4651,15 @@ export const ko: Record = { "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": "제작사 구독", diff --git a/gui/src/i18n/pt.ts b/gui/src/i18n/pt.ts index 5fd4edcf56d..fb967b639b2 100644 --- a/gui/src/i18n/pt.ts +++ b/gui/src/i18n/pt.ts @@ -4624,6 +4624,15 @@ export const pt: Record = { "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", diff --git a/gui/src/i18n/ru.ts b/gui/src/i18n/ru.ts index ca98437a55f..53f736f5802 100644 --- a/gui/src/i18n/ru.ts +++ b/gui/src/i18n/ru.ts @@ -4652,6 +4652,15 @@ export const ru: Record = { "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": "подписка создателя модели", diff --git a/gui/src/i18n/tr.ts b/gui/src/i18n/tr.ts index b0ef847d7c8..4e7a7e46311 100644 --- a/gui/src/i18n/tr.ts +++ b/gui/src/i18n/tr.ts @@ -4652,6 +4652,15 @@ export const tr: Record = { "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", diff --git a/gui/src/i18n/vi.ts b/gui/src/i18n/vi.ts index 262b4c2955f..d2936e85494 100644 --- a/gui/src/i18n/vi.ts +++ b/gui/src/i18n/vi.ts @@ -4621,6 +4621,15 @@ export const vi: Record = { "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", diff --git a/gui/src/i18n/zh-TW.ts b/gui/src/i18n/zh-TW.ts index dc8f9b42761..b699b43c719 100644 --- a/gui/src/i18n/zh-TW.ts +++ b/gui/src/i18n/zh-TW.ts @@ -4615,6 +4615,15 @@ export const zhTW: Record = { "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": "原廠訂閱", diff --git a/gui/src/i18n/zh.ts b/gui/src/i18n/zh.ts index 0d5d79fa41c..a28a6361876 100644 --- a/gui/src/i18n/zh.ts +++ b/gui/src/i18n/zh.ts @@ -4650,6 +4650,15 @@ export const zh: Record = { "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": "原厂订阅", 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 79b57c7f23b..a9d0c194bc0 100644 --- a/gui/src/pages/Combos.tsx +++ b/gui/src/pages/Combos.tsx @@ -23,6 +23,7 @@ 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"; @@ -134,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. @@ -730,6 +732,8 @@ export default function Combos({ errorText={(code, item) => 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" && ( diff --git a/gui/tests/combo-suggestions.test.tsx b/gui/tests/combo-suggestions.test.tsx index aa7910e6970..5cc8c69983a 100644 --- a/gui/tests/combo-suggestions.test.tsx +++ b/gui/tests/combo-suggestions.test.tsx @@ -161,6 +161,14 @@ describe("buildComboSuggestions", () => { 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", () => { @@ -225,7 +233,8 @@ describe("ComboSuggestions card", () => { }); const saved: Array<{ kind: string; item: ComboItem }> = []; - async function render(combos: 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"); @@ -244,6 +253,10 @@ describe("ComboSuggestions card", () => { 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; }, + } : {})} /> , ); @@ -294,4 +307,21 @@ describe("ComboSuggestions card", () => { ["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/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/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 9665eed3834..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 | `#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. `gui/tests/combo-suggestions.test.tsx` covers normalization, coverage, ordering, id collisions, dismissal and the draft save. `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. | +| 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(); +}); From ff17a01ae4a6fc630c774551d5b6ef6113af003a Mon Sep 17 00:00:00 2001 From: "Andrew (agent)" Date: Fri, 13 Nov 2026 20:18:56 -0500 Subject: [PATCH 04/21] refactor(server): dispatch /api/combo-suggestions from the combo routes The suggestion-exclusion route was mounted from management-api.ts, a sponsored surface. combo-routes.ts already owns the combo namespace, so the lazy import moves there and management-api.ts is unchanged from dev. --- src/server/management-api.ts | 8 -------- src/server/management/combo-routes.ts | 6 ++++++ 2 files changed, 6 insertions(+), 8 deletions(-) diff --git a/src/server/management-api.ts b/src/server/management-api.ts index cddd415a471..2c77513135b 100644 --- a/src/server/management-api.ts +++ b/src/server/management-api.ts @@ -176,13 +176,6 @@ 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"); @@ -389,7 +382,6 @@ 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-routes.ts b/src/server/management/combo-routes.ts index 47fcb237cde..6cdec5369c9 100644 --- a/src/server/management/combo-routes.ts +++ b/src/server/management/combo-routes.ts @@ -170,6 +170,12 @@ function parseVisionSidecarTargets( export async function handleComboRoutes(ctx: ManagementContext): Promise { const { req, url, config, deps, convergeCodexCatalog, syncClaudeAgentDefsBestEffort } = ctx; + // Only the Combos page reads the suggested combos' excluded-provider list; load it on demand. + if (url.pathname === "/api/combo-suggestions") { + const { handleComboSuggestionRoutes } = await import("./combo-suggestion-routes"); + return handleComboSuggestionRoutes(ctx); + } + if (url.pathname === "/api/combos" && req.method === "GET") { const { comboPublicModelId, getCombo, listComboIds } = await import("../../combos"); return jsonResponse({ combos: listComboIds(config).map(id => { From 0cf50efb80eece486d295ba7fce6821e5b97a49a Mon Sep 17 00:00:00 2001 From: "Andrew (agent)" Date: Fri, 13 Nov 2026 20:38:12 -0500 Subject: [PATCH 05/21] fix(gui): tidy the Combos overview and suggested combos - the quota line inside a row's toggle button is a span, not a paragraph - the exclude-provider list drops its Restore button; unticking already restores - draft member buttons name their member, reusing the channel editor's labels - a capability test notes that context is not probed only once it has finished - "ctx" reads "context"; unused locale keys removed --- .../route-board/ComboSuggestions.tsx | 43 ++++++++----------- .../components/route-board/MemberProbe.tsx | 8 ++-- gui/src/components/route-board/QuotaLine.tsx | 4 +- .../SuggestionExcludeProviders.tsx | 7 +-- gui/src/design/pages/route-board.css | 2 +- gui/src/i18n/de.ts | 6 --- gui/src/i18n/en.ts | 8 +--- gui/src/i18n/fr.ts | 6 --- gui/src/i18n/ja.ts | 6 --- gui/src/i18n/ko.ts | 6 --- gui/src/i18n/pt.ts | 8 +--- gui/src/i18n/ru.ts | 6 --- gui/src/i18n/tr.ts | 6 --- gui/src/i18n/vi.ts | 6 --- gui/src/i18n/zh-TW.ts | 6 --- gui/src/i18n/zh.ts | 6 --- gui/src/pages/Combos.tsx | 2 +- gui/tests/combo-suggestions.test.tsx | 7 +-- gui/tests/route-board.test.tsx | 5 ++- 19 files changed, 36 insertions(+), 112 deletions(-) diff --git a/gui/src/components/route-board/ComboSuggestions.tsx b/gui/src/components/route-board/ComboSuggestions.tsx index d16ca8028e8..31e14a0132f 100644 --- a/gui/src/components/route-board/ComboSuggestions.tsx +++ b/gui/src/components/route-board/ComboSuggestions.tsx @@ -175,25 +175,15 @@ function SuggestionCard({ ))} - {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.comboId} + + {suggestion.kind === "create" + ? t("comboSuggest.servedBy", { count: suggestion.members.length }) + : t("comboSuggest.canAdd", { providers: providers.map((provider) => formatProviderDisplayName(provider, t)).join(", ") })} + + + {suggestion.kind === "create" ? ( @@ -249,7 +239,9 @@ function SuggestionDraft({

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

        - {members.map((member, index) => ( + {members.map((member, index) => { + const name = `${formatProviderDisplayName(member.provider, t)} ${member.model}`; + return (
      1. {formatProviderDisplayName(member.provider, t)} @@ -259,19 +251,20 @@ function SuggestionDraft({ {t("comboSuggest.draft.left", { percent: Math.round(member.remainingPercent) })} )} - - -
      2. - ))} + ); + })}
      {t("comboSuggest.draft.strategy")} - + +
      )} diff --git a/gui/src/components/route-board/QuotaLine.tsx b/gui/src/components/route-board/QuotaLine.tsx index 58352027cd0..821f02b5ebc 100644 --- a/gui/src/components/route-board/QuotaLine.tsx +++ b/gui/src/components/route-board/QuotaLine.tsx @@ -20,7 +20,7 @@ function windowName(window: QuotaWindowView, t: TFn): string { 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; @@ -47,6 +47,6 @@ export function QuotaLine({ quotas, labels }: { quotas: readonly ProviderQuotaLi ); })} -

      +
      ); } diff --git a/gui/src/components/route-board/SuggestionExcludeProviders.tsx b/gui/src/components/route-board/SuggestionExcludeProviders.tsx index 519a71993a6..d6941b69757 100644 --- a/gui/src/components/route-board/SuggestionExcludeProviders.tsx +++ b/gui/src/components/route-board/SuggestionExcludeProviders.tsx @@ -6,7 +6,7 @@ import { ProviderIcon } from "../provider-workspace/ProviderRail"; /** * "Exclude a provider…" under the suggestions' title, after Magpie's 排除供应商 on its found * groups: a text button naming who is left out opens a list of providers, each ticked or not. - * A ticked provider joins no suggested combo; unticking restores it. Saved to config.json. + * A ticked provider joins no suggested combo; unticking brings it back. Saved to config.json. */ export function SuggestionExcludeProviders({ providers, @@ -61,11 +61,6 @@ export function SuggestionExcludeProviders({ {label(name)} - {on && ( - - )} ); })} diff --git a/gui/src/design/pages/route-board.css b/gui/src/design/pages/route-board.css index 208384fb39c..87c5c67c000 100644 --- a/gui/src/design/pages/route-board.css +++ b/gui/src/design/pages/route-board.css @@ -191,7 +191,7 @@ /* 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. */ +/* Suggested combos: same-name models across providers. Grey, above the combo list. */ .rb-suggest { margin-bottom: 16px; padding: 12px 0 4px; diff --git a/gui/src/i18n/de.ts b/gui/src/i18n/de.ts index 1e0ff031238..f3cfc584ac7 100644 --- a/gui/src/i18n/de.ts +++ b/gui/src/i18n/de.ts @@ -4621,7 +4621,6 @@ export const de: Record = { "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", @@ -4635,7 +4634,6 @@ export const de: Record = { "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", @@ -4647,11 +4645,7 @@ export const de: Record = { "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 e289a3c55c9..5c1f2610a89 100644 --- a/gui/src/i18n/en.ts +++ b/gui/src/i18n/en.ts @@ -4557,7 +4557,7 @@ export const en = { "routeBoard.tag.channelsOff": "{count} off", "routeBoard.tag.sticky": "sticky ×{count}", "routeBoard.tag.noImages": "text only", - "routeBoard.context": "ctx {size}", + "routeBoard.context": "context {size}", "routeBoard.contextHint": "Click to see how this number is worked out.", "routeBoard.strategyLabel": "Strategy for {model}", "routeBoard.enabledLabel": "List {model} to clients", @@ -4655,7 +4655,6 @@ export const en = { "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", @@ -4669,7 +4668,6 @@ export const en = { "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}", @@ -4681,11 +4679,7 @@ export const en = { "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; diff --git a/gui/src/i18n/fr.ts b/gui/src/i18n/fr.ts index e30eaa8b5bd..0ceeaf7d14c 100644 --- a/gui/src/i18n/fr.ts +++ b/gui/src/i18n/fr.ts @@ -4610,7 +4610,6 @@ export const fr: Record = { "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", @@ -4624,7 +4623,6 @@ export const fr: Record = { "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}", @@ -4636,11 +4634,7 @@ export const fr: Record = { "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 b3dd1cb6fb6..4457488f068 100644 --- a/gui/src/i18n/ja.ts +++ b/gui/src/i18n/ja.ts @@ -4643,7 +4643,6 @@ export const ja: Record = { "routeBoard.probe.appliedEfforts": "推論レベルを保存: {value}", "routeBoard.probe.nothingApplied": "確かな結果がないため、何も保存していません。", "routeBoard.probe.contextNote": "コンテキストはモデル名から推定し、実測しません。", - "routeBoard.probe.close": "閉じる", "comboSuggest.title": "おすすめのコンボ", "comboSuggest.lede": "複数のプロバイダーが同じ名前で提供しているモデルです。コンボを生成すると、1 つのモデル名ですべてのプロバイダーにルーティングできます。", "comboSuggest.servedBy": "{count} 社のプロバイダーが提供", @@ -4657,7 +4656,6 @@ export const ja: Record = { "comboSuggest.exclude.active": "除外中:{names}", "comboSuggest.exclude.head": "おすすめの組み合わせから除外", "comboSuggest.exclude.hint": "そのモデルはおすすめの組み合わせに入りません。作成済みの組み合わせはそのままです。", - "comboSuggest.exclude.restore": "元に戻す", "comboSuggest.exclude.saveFailed": "除外したプロバイダを保存できませんでした。", "comboSuggest.exclude.none": "これらのプロバイダを除外すると、おすすめはありません。", "comboSuggest.showAll": "すべて表示({count} 件)", @@ -4669,11 +4667,7 @@ export const ja: Record = { "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 4104f26250f..3da00fc49b8 100644 --- a/gui/src/i18n/ko.ts +++ b/gui/src/i18n/ko.ts @@ -4643,7 +4643,6 @@ export const ko: Record = { "routeBoard.probe.appliedEfforts": "추론 단계 저장: {value}", "routeBoard.probe.nothingApplied": "확실한 결과가 없어 아무것도 저장하지 않았습니다.", "routeBoard.probe.contextNote": "컨텍스트는 모델 이름으로 추정하며 실측하지 않습니다.", - "routeBoard.probe.close": "닫기", "comboSuggest.title": "추천 콤보", "comboSuggest.lede": "둘 이상의 프로바이더가 같은 이름으로 제공하는 모델입니다. 콤보를 생성하면 하나의 모델 이름으로 이들 모두에 라우팅할 수 있습니다.", "comboSuggest.servedBy": "{count}개 프로바이더가 제공", @@ -4657,7 +4656,6 @@ export const ko: Record = { "comboSuggest.exclude.active": "제외됨: {names}", "comboSuggest.exclude.head": "추천 조합에서 제외", "comboSuggest.exclude.hint": "해당 모델은 추천 조합에 들어가지 않습니다. 이미 만든 조합은 그대로입니다.", - "comboSuggest.exclude.restore": "복원", "comboSuggest.exclude.saveFailed": "제외한 제공자를 저장하지 못했습니다.", "comboSuggest.exclude.none": "이 제공자들을 제외하면 남은 추천이 없습니다.", "comboSuggest.showAll": "전체 {count}개 보기", @@ -4669,11 +4667,7 @@ export const ko: Record = { "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 fb967b639b2..ffafd8c6977 100644 --- a/gui/src/i18n/pt.ts +++ b/gui/src/i18n/pt.ts @@ -4518,7 +4518,7 @@ export const pt: Record = { "routeBoard.tag.channelsOff": "{count} desligados", "routeBoard.tag.sticky": "fixo ×{count}", "routeBoard.tag.noImages": "só texto", - "routeBoard.context": "ctx {size}", + "routeBoard.context": "contexto {size}", "routeBoard.contextHint": "Clique para ver como este número é calculado.", "routeBoard.strategyLabel": "Estratégia de {model}", "routeBoard.enabledLabel": "Oferecer {model} aos clientes", @@ -4616,7 +4616,6 @@ export const pt: Record = { "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", @@ -4630,7 +4629,6 @@ export const pt: Record = { "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})", @@ -4642,11 +4640,7 @@ export const pt: Record = { "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 53f736f5802..c56beded639 100644 --- a/gui/src/i18n/ru.ts +++ b/gui/src/i18n/ru.ts @@ -4644,7 +4644,6 @@ export const ru: Record = { "routeBoard.probe.appliedEfforts": "сохранены уровни: {value}", "routeBoard.probe.nothingApplied": "Ничего определённого, поэтому ничего не сохранено.", "routeBoard.probe.contextNote": "Контекст определяется по имени модели и не измеряется.", - "routeBoard.probe.close": "Закрыть", "comboSuggest.title": "Рекомендуемые комбо", "comboSuggest.lede": "Модели, которые несколько ваших провайдеров предлагают под одним именем. Создайте комбо, чтобы направлять одно имя модели на все они сразу.", "comboSuggest.servedBy": "доступна у {count} провайдеров", @@ -4658,7 +4657,6 @@ export const ru: Record = { "comboSuggest.exclude.active": "Исключены: {names}", "comboSuggest.exclude.head": "Не предлагать в комбо", "comboSuggest.exclude.hint": "Их модели не попадут в предлагаемые комбо; уже созданные комбо не меняются.", - "comboSuggest.exclude.restore": "Вернуть", "comboSuggest.exclude.saveFailed": "Не удалось сохранить исключённых провайдеров.", "comboSuggest.exclude.none": "С этими исключениями предложений не осталось.", "comboSuggest.showAll": "Показать все ({count})", @@ -4670,11 +4668,7 @@ export const ru: Record = { "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 4e7a7e46311..7bc97354f39 100644 --- a/gui/src/i18n/tr.ts +++ b/gui/src/i18n/tr.ts @@ -4644,7 +4644,6 @@ export const tr: Record = { "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", @@ -4658,7 +4657,6 @@ export const tr: Record = { "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})", @@ -4670,11 +4668,7 @@ export const tr: Record = { "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 d2936e85494..e07b72c5f02 100644 --- a/gui/src/i18n/vi.ts +++ b/gui/src/i18n/vi.ts @@ -4613,7 +4613,6 @@ export const vi: Record = { "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ụ", @@ -4627,7 +4626,6 @@ export const vi: Record = { "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}", @@ -4639,11 +4637,7 @@ export const vi: Record = { "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 b699b43c719..539d3ec4668 100644 --- a/gui/src/i18n/zh-TW.ts +++ b/gui/src/i18n/zh-TW.ts @@ -4607,7 +4607,6 @@ export const zhTW: Record = { "routeBoard.probe.appliedEfforts": "已寫入檔位:{value}", "routeBoard.probe.nothingApplied": "沒有確定的結果,沒有寫入任何值。", "routeBoard.probe.contextNote": "上下文從名字推斷,不實測。", - "routeBoard.probe.close": "關閉", "comboSuggest.title": "推薦組合", "comboSuggest.lede": "多家供應商都以同一名稱提供的模型。生成一個組合,就能用一個模型名在這幾家之間路由。", "comboSuggest.servedBy": "{count} 家供應商都有", @@ -4621,7 +4620,6 @@ export const zhTW: Record = { "comboSuggest.exclude.active": "已排除:{names}", "comboSuggest.exclude.head": "不參與推薦組合", "comboSuggest.exclude.hint": "它們的模型不會出現在推薦組合裡;你已建好的組合不受影響。", - "comboSuggest.exclude.restore": "恢復", "comboSuggest.exclude.saveFailed": "排除的供應商沒能儲存。", "comboSuggest.exclude.none": "排除這些供應商後,沒有可推薦的組合了。", "comboSuggest.showAll": "顯示全部 {count} 條", @@ -4633,11 +4631,7 @@ export const zhTW: Record = { "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 a28a6361876..202e32e470a 100644 --- a/gui/src/i18n/zh.ts +++ b/gui/src/i18n/zh.ts @@ -4642,7 +4642,6 @@ export const zh: Record = { "routeBoard.probe.appliedEfforts": "已写入档位:{value}", "routeBoard.probe.nothingApplied": "没有确定的结果,没有写入任何值。", "routeBoard.probe.contextNote": "上下文从名字推断,不实测。", - "routeBoard.probe.close": "关闭", "comboSuggest.title": "推荐组合", "comboSuggest.lede": "你有两家以上提供方都提供同名的模型。生成一个组合,就能用一个模型名在这几家之间路由。", "comboSuggest.servedBy": "{count} 家提供方都有", @@ -4656,7 +4655,6 @@ export const zh: Record = { "comboSuggest.exclude.active": "已排除:{names}", "comboSuggest.exclude.head": "不参与推荐组合", "comboSuggest.exclude.hint": "它们的模型不会出现在推荐组合里;你已建好的组合不受影响。", - "comboSuggest.exclude.restore": "恢复", "comboSuggest.exclude.saveFailed": "排除的供应商没能保存。", "comboSuggest.exclude.none": "排除这些供应商后,没有可推荐的组合了。", "comboSuggest.showAll": "显示全部 {count} 条", @@ -4668,11 +4666,7 @@ export const zh: Record = { "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/pages/Combos.tsx b/gui/src/pages/Combos.tsx index a9d0c194bc0..10c01c80ae5 100644 --- a/gui/src/pages/Combos.tsx +++ b/gui/src/pages/Combos.tsx @@ -526,7 +526,7 @@ export default function Combos({ : {}), }); // 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. + // Capability fields 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; diff --git a/gui/tests/combo-suggestions.test.tsx b/gui/tests/combo-suggestions.test.tsx index 5cc8c69983a..4a579849ed1 100644 --- a/gui/tests/combo-suggestions.test.tsx +++ b/gui/tests/combo-suggestions.test.tsx @@ -281,7 +281,7 @@ describe("ComboSuggestions card", () => { 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.querySelectorAll("li")[0]!, "Move Google Antigravity gemini-3.8-flash 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"]], @@ -308,7 +308,7 @@ describe("ComboSuggestions card", () => { ]); }); - test("excluding a provider is offered under the title and restoring unticks it", async () => { + test("excluding a provider is offered under the title and unticking restores it", async () => { exclusionWrites.length = 0; await render([], ["cursor"]); // Every suggestion here needs cursor, so only the exclusion control and the empty note show. @@ -316,7 +316,8 @@ describe("ComboSuggestions card", () => { 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(); }); + const cursor = panel.querySelector("input[type=checkbox]:checked")!; + await act(async () => { cursor.click(); }); expect(exclusionWrites).toEqual([[]]); }); diff --git a/gui/tests/route-board.test.tsx b/gui/tests/route-board.test.tsx index 56e3248c2f8..79131f11253 100644 --- a/gui/tests/route-board.test.tsx +++ b/gui/tests/route-board.test.tsx @@ -367,7 +367,7 @@ describe("Combos overview page", () => { // 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"); + expect(alphaRow.textContent).toContain("context 200K"); }); test("picking a strategy saves the normal PUT body and leaves lastResort to the server", async () => { @@ -539,7 +539,7 @@ describe("Combos overview page", () => { 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."); + expect(editor.textContent).not.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([ @@ -550,6 +550,7 @@ describe("Combos overview page", () => { expect(results).toContain("Images: accepted"); expect(results).toContain("accepted: low · high; refused: max"); expect(results).toContain("saved effort levels: low · high"); + expect(results).toContain("Context is inferred from the model name, not measured."); }); test("Test it: a failed baseline changes nothing, a busy provider says so, an inapplicable one greys the button", async () => { From 4b2fc79139fa9d0086ccf03cff1001e6b1600bd0 Mon Sep 17 00:00:00 2001 From: "Andrew (agent)" Date: Fri, 13 Nov 2026 20:43:40 -0500 Subject: [PATCH 06/21] fix(gui): drop the Combos overview lede and the one-account count The page subtitle and the rows already say what a combo is, so the overview keeps only its Advanced switch. A provider with a single account no longer reads "(1 accounts)"; counts show from two accounts up. --- gui/src/components/route-board/QuotaLine.tsx | 2 +- gui/src/design/pages/route-board.css | 3 +-- gui/src/i18n/de.ts | 1 - gui/src/i18n/en.ts | 1 - gui/src/i18n/fr.ts | 1 - gui/src/i18n/ja.ts | 1 - gui/src/i18n/ko.ts | 1 - gui/src/i18n/pt.ts | 1 - gui/src/i18n/ru.ts | 1 - gui/src/i18n/tr.ts | 1 - gui/src/i18n/vi.ts | 1 - gui/src/i18n/zh-TW.ts | 1 - gui/src/i18n/zh.ts | 1 - gui/src/pages/Combos.tsx | 1 - 14 files changed, 2 insertions(+), 15 deletions(-) diff --git a/gui/src/components/route-board/QuotaLine.tsx b/gui/src/components/route-board/QuotaLine.tsx index 821f02b5ebc..8a63f3ee408 100644 --- a/gui/src/components/route-board/QuotaLine.tsx +++ b/gui/src/components/route-board/QuotaLine.tsx @@ -27,7 +27,7 @@ export function QuotaLine({ quotas, labels }: { quotas: readonly ProviderQuotaLi return ( - {line.accounts !== undefined && line.accounts.active > 0 + {line.accounts !== undefined && line.accounts.active > 1 ? t("routeBoard.quota.accounts", { provider: name, count: line.accounts.active }) : name} {line.accounts !== undefined && line.accounts.paused > 0 && ( diff --git a/gui/src/design/pages/route-board.css b/gui/src/design/pages/route-board.css index 87c5c67c000..4f5ae7aab27 100644 --- a/gui/src/design/pages/route-board.css +++ b/gui/src/design/pages/route-board.css @@ -1,8 +1,7 @@ /* 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; } +.rb-viewbar { display: flex; align-items: center; justify-content: flex-end; gap: 12px; margin-bottom: 12px; } .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; } diff --git a/gui/src/i18n/de.ts b/gui/src/i18n/de.ts index f3cfc584ac7..8af6b59de7b 100644 --- a/gui/src/i18n/de.ts +++ b/gui/src/i18n/de.ts @@ -4506,7 +4506,6 @@ 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", diff --git a/gui/src/i18n/en.ts b/gui/src/i18n/en.ts index 5c1f2610a89..33ba6550853 100644 --- a/gui/src/i18n/en.ts +++ b/gui/src/i18n/en.ts @@ -4540,7 +4540,6 @@ 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", diff --git a/gui/src/i18n/fr.ts b/gui/src/i18n/fr.ts index 0ceeaf7d14c..39242f77542 100644 --- a/gui/src/i18n/fr.ts +++ b/gui/src/i18n/fr.ts @@ -4495,7 +4495,6 @@ 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", diff --git a/gui/src/i18n/ja.ts b/gui/src/i18n/ja.ts index 4457488f068..3b5efafab72 100644 --- a/gui/src/i18n/ja.ts +++ b/gui/src/i18n/ja.ts @@ -4528,7 +4528,6 @@ 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": "概要に戻る", diff --git a/gui/src/i18n/ko.ts b/gui/src/i18n/ko.ts index 3da00fc49b8..77647f68f9a 100644 --- a/gui/src/i18n/ko.ts +++ b/gui/src/i18n/ko.ts @@ -4528,7 +4528,6 @@ 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": "개요로 돌아가기", diff --git a/gui/src/i18n/pt.ts b/gui/src/i18n/pt.ts index ffafd8c6977..592bf973131 100644 --- a/gui/src/i18n/pt.ts +++ b/gui/src/i18n/pt.ts @@ -4501,7 +4501,6 @@ 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", diff --git a/gui/src/i18n/ru.ts b/gui/src/i18n/ru.ts index c56beded639..f679388a0b0 100644 --- a/gui/src/i18n/ru.ts +++ b/gui/src/i18n/ru.ts @@ -4529,7 +4529,6 @@ 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": "Назад к обзору", diff --git a/gui/src/i18n/tr.ts b/gui/src/i18n/tr.ts index 7bc97354f39..21b02bb7b79 100644 --- a/gui/src/i18n/tr.ts +++ b/gui/src/i18n/tr.ts @@ -4529,7 +4529,6 @@ 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", diff --git a/gui/src/i18n/vi.ts b/gui/src/i18n/vi.ts index e07b72c5f02..3bf61898f5b 100644 --- a/gui/src/i18n/vi.ts +++ b/gui/src/i18n/vi.ts @@ -4498,7 +4498,6 @@ 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", diff --git a/gui/src/i18n/zh-TW.ts b/gui/src/i18n/zh-TW.ts index 539d3ec4668..938f5ad57b2 100644 --- a/gui/src/i18n/zh-TW.ts +++ b/gui/src/i18n/zh-TW.ts @@ -4492,7 +4492,6 @@ 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": "返回總覽", diff --git a/gui/src/i18n/zh.ts b/gui/src/i18n/zh.ts index 202e32e470a..a35f96630c0 100644 --- a/gui/src/i18n/zh.ts +++ b/gui/src/i18n/zh.ts @@ -4527,7 +4527,6 @@ 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": "返回总览", diff --git a/gui/src/pages/Combos.tsx b/gui/src/pages/Combos.tsx index 10c01c80ae5..05dd674a56b 100644 --- a/gui/src/pages/Combos.tsx +++ b/gui/src/pages/Combos.tsx @@ -708,7 +708,6 @@ export default function Combos({
      {view === "overview" ? ( <> -

      {t("routeBoard.lede")}

      From 76c940bd7caba1c949fdef57474a4f3b0e571b30 Mon Sep 17 00:00:00 2001 From: "Andrew (agent)" Date: Fri, 13 Nov 2026 20:56:54 -0500 Subject: [PATCH 07/21] fix(gui): restart an open suggested-combo draft when its members change Excluding a provider while its draft was open updated the card but left the provider in the draft, so Save combo still included it. --- .../route-board/ComboSuggestions.tsx | 2 ++ gui/tests/combo-suggestions.test.tsx | 31 +++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/gui/src/components/route-board/ComboSuggestions.tsx b/gui/src/components/route-board/ComboSuggestions.tsx index 31e14a0132f..084d6c1b833 100644 --- a/gui/src/components/route-board/ComboSuggestions.tsx +++ b/gui/src/components/route-board/ComboSuggestions.tsx @@ -206,6 +206,8 @@ function SuggestionCard({ {message &&

      {message}

      } {drafting && suggestion.kind === "create" && ( `${member.provider}/${member.model}`).join("|")} suggestion={suggestion} busy={busy} onSave={(item) => void save(item, true)} diff --git a/gui/tests/combo-suggestions.test.tsx b/gui/tests/combo-suggestions.test.tsx index 4a579849ed1..ea5bae124d3 100644 --- a/gui/tests/combo-suggestions.test.tsx +++ b/gui/tests/combo-suggestions.test.tsx @@ -321,6 +321,37 @@ describe("ComboSuggestions card", () => { expect(exclusionWrites).toEqual([[]]); }); + test("excluding a provider while its draft is open drops it from the draft", async () => { + const { createRoot } = await import("react-dom/client"); + host = document.createElement("div"); + document.body.append(host); + root = createRoot(host); + const view = (excluded: string[]) => ( + + undefined} + validate={() => null} + errorText={() => "bad"} + onCreate={async () => ({ ok: true })} + onExtend={async () => ({ ok: true })} + excludedProviders={excluded} + onExcludedChange={async () => true} + /> + + ); + await act(async () => { root!.render(view([])); }); + await act(async () => { button(card("gemini-3.8-flash"), "Generate").click(); }); + const draftProviders = () => [...card("gemini-3.8-flash").querySelectorAll(".rb-suggest-draft li")].map((row) => row.textContent ?? ""); + expect(draftProviders().some((row) => row.includes("Cursor"))).toBe(true); + await act(async () => { root!.render(view(["cursor"])); }); + expect(draftProviders().length).toBe(2); + expect(draftProviders().some((row) => row.includes("Cursor"))).toBe(false); + }); + test("without an exclusion handler there is no exclude control", async () => { await render(); expect(host.querySelector(".rb-suggest-exclude")).toBeNull(); From 876008632652721d111510298c52e3bf1a99a302 Mon Sep 17 00:00:00 2001 From: "Andrew (agent)" Date: Sat, 14 Nov 2026 01:17:32 -0500 Subject: [PATCH 08/21] fix(gui): offer an existing combo the one eligible provider left after exclusions --- gui/src/combo-suggestions.ts | 4 +++- gui/tests/combo-suggestions.test.tsx | 8 ++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/gui/src/combo-suggestions.ts b/gui/src/combo-suggestions.ts index 9ebc7727599..6e5b6b2e29d 100644 --- a/gui/src/combo-suggestions.ts +++ b/gui/src/combo-suggestions.ts @@ -199,8 +199,9 @@ export function buildComboSuggestions(input: SuggestionInput): ComboSuggestion[] const creates: Array = []; const extends_: Array = []; for (const [name, served] of byModel) { - if (served.size < 2) continue; const combo = covering.get(name); + // An existing combo takes any eligible provider it is missing, even the only one left once + // its own members are excluded; a new combo needs two providers to fail over between. if (combo) { const routed = new Set(combo.targets.map((target) => target.provider)); const missing = [...served].filter(([provider]) => !routed.has(provider)); @@ -209,6 +210,7 @@ export function buildComboSuggestions(input: SuggestionInput): ComboSuggestion[] extends_.push({ kind: "extend", key, model: name, comboId: combo.id, members: orderMembers(missing.map(([p, m]) => member(p, m))) }); continue; } + if (served.size < 2) continue; const key = suggestionKey("create", name); if (input.dismissed?.has(key)) continue; const spellings = [...served.values()].map(spelling); diff --git a/gui/tests/combo-suggestions.test.tsx b/gui/tests/combo-suggestions.test.tsx index ea5bae124d3..359563f4906 100644 --- a/gui/tests/combo-suggestions.test.tsx +++ b/gui/tests/combo-suggestions.test.tsx @@ -169,6 +169,14 @@ describe("buildComboSuggestions", () => { const combos = [combo("claude-x", [["anthropic", "claude-x"]])]; expect(summary({ combos, models: rows, excludedProviders })).toEqual(["extend claude-x: zayu-claude"]); }); + + test("an existing combo whose own provider is excluded still offers the one eligible provider left", () => { + const combos = [combo("claude-x", [["anthropic", "claude-x"]])]; + const rows = models([["anthropic", "claude-x"], ["zayu-claude", "claude-x"]]); + expect(summary({ combos, models: rows, excludedProviders: new Set(["anthropic"]) })).toEqual(["extend claude-x: zayu-claude"]); + expect(summary({ combos, models: rows.slice(0, 1) })).toEqual([]); + expect(summary({ models: rows, excludedProviders: new Set(["anthropic"]) })).toEqual([]); + }); }); describe("drafts", () => { From ac6623e0f593c7936c188b64309875cd0c85c365 Mon Sep 17 00:00:00 2001 From: "Andrew (agent)" Date: Sat, 14 Nov 2026 01:18:27 -0500 Subject: [PATCH 09/21] fix(gui): latest-per-family keeps every row with the newest id and compares snapshot dates by digits --- gui/src/lib/model-family.ts | 13 +++++++++---- gui/tests/model-family.test.ts | 10 ++++++++++ 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/gui/src/lib/model-family.ts b/gui/src/lib/model-family.ts index 6451488dcaa..692406d796f 100644 --- a/gui/src/lib/model-family.ts +++ b/gui/src/lib/model-family.ts @@ -136,18 +136,23 @@ function newerInFamily(a: ModelFamily, b: ModelFamily): boolean { 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; + // 2025-12-01 and 20251101 are both dates: compare the digits, not where the dashes fall + return a.snapshot.replace(/-/g, "") > b.snapshot.replace(/-/g, ""); } -/** `items` with only the newest of each family left, in their order. A family's first listed wins a tie. */ +/** + * `items` with only the newest of each family left, in their order. A family's first listed wins a + * tie; every item carrying the winning id stays (two providers' rows can share one id). + */ export function latestPerFamilyBy(items: readonly T[], idOf: (item: T) => string): T[] { - const families = items.map((item) => familyOf(idOf(item))); + const ids = items.map(idOf); + const families = ids.map((id) => familyOf(id)); 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); + return items.filter((_, i) => ids[best.get(families[i]!.name)!] === ids[i]); } /** `ids` with only the newest model of each family left, in their order. */ diff --git a/gui/tests/model-family.test.ts b/gui/tests/model-family.test.ts index 16471886ab9..d56ebf0058b 100644 --- a/gui/tests/model-family.test.ts +++ b/gui/tests/model-family.test.ts @@ -109,4 +109,14 @@ describe("latestPerFamily", () => { 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]); }); + + test("keeps every row that carries the newest id, such as a native and a custom row", () => { + const rows = [{ id: "gpt-5", n: 1 }, { id: "gpt-5.1", n: 2 }, { id: "gpt-5.1", n: 3 }]; + expect(latestPerFamilyBy(rows, (row) => row.id).map((row) => row.n)).toEqual([2, 3]); + }); + + test("compares dated snapshots by date whatever their separators", () => { + expect(latestPerFamily(["claude-sonnet-4-5-20251101", "claude-sonnet-4-5-2025-12-01"])).toEqual(["claude-sonnet-4-5-2025-12-01"]); + expect(latestPerFamily(["claude-sonnet-4-5-2025-12-01", "claude-sonnet-4-5-20251101"])).toEqual(["claude-sonnet-4-5-2025-12-01"]); + }); }); From 784873f3e4083c55044def8dbe8a7b168773e1d1 Mon Sep 17 00:00:00 2001 From: "Andrew (agent)" Date: Sat, 14 Nov 2026 01:24:22 -0500 Subject: [PATCH 10/21] fix(gui): route board saves track each combo, editors hold still while saving, context preview follows the draft, placeholders keep configured values --- .../components/route-board/ChannelEditor.tsx | 30 +++++++++++++------ .../components/route-board/MemberTable.tsx | 5 ++-- gui/src/components/route-board/RouteBoard.tsx | 18 +++++++---- gui/src/pages/Combos.tsx | 14 +++++---- gui/src/route-board-model.ts | 23 ++++++++++++++ gui/tests/route-board.test.tsx | 28 +++++++++++++++++ 6 files changed, 95 insertions(+), 23 deletions(-) diff --git a/gui/src/components/route-board/ChannelEditor.tsx b/gui/src/components/route-board/ChannelEditor.tsx index c2520785ba9..bfbc6adfb0e 100644 --- a/gui/src/components/route-board/ChannelEditor.tsx +++ b/gui/src/components/route-board/ChannelEditor.tsx @@ -85,6 +85,7 @@ export function ChannelEditor({ catalogContext, moreOpen: moreOpenInitially = false, saving, + locked = false, onSave, onSaveModel, onProbeModel, @@ -105,7 +106,10 @@ export function ChannelEditor({ catalogContext?: number; /** Open "More settings" and bring it into view (the row's context tag asks for this). */ moreOpen?: boolean; + /** This editor's save is in flight: its channels and settings hold still until it settles. */ saving: boolean; + /** The combo has an unsaved draft in the advanced editor, so this one cannot save. */ + locked?: boolean; onSave: (channels: EditableChannel[], settings: ComboSettingsPatch) => void; /** Writes one member model's per-provider settings (shared by every combo using it). */ onSaveModel?: SaveMemberModel; @@ -144,7 +148,9 @@ export function ChannelEditor({ }); useEffect(() => { - if (moreOpenInitially) moreRef.current?.scrollIntoView?.({ block: "nearest", behavior: "smooth" }); + if (!moreOpenInitially) return; + setMoreOpen(true); + moreRef.current?.scrollIntoView?.({ block: "nearest", behavior: "smooth" }); }, [moreOpenInitially]); const move = (from: number, to: number) => setChannels((list) => moveChannel(list, from, to)); @@ -155,7 +161,7 @@ export function ChannelEditor({ 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; + if (!list || saving || 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[]; @@ -173,7 +179,10 @@ export function ChannelEditor({ 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); + // The server's number describes the saved combo: once members or policy change, the draft's own members decide. + const asSaved = policy === initialCapability.capabilityPolicy && channels.length === initial.length + && channels.every((channel, index) => channel.key === initial[index]?.key); + const context = comboContextWindow(combined.members, policy, asSaved ? catalogContext : undefined); const modalities = combineLists(combined.members.map((fact) => fact.inputModalities), policy, MODALITY_ORDER); const efforts = combineLists(combined.members.map((fact) => fact.reasoningEfforts), policy, COMBO_EFFORTS); @@ -208,14 +217,15 @@ export function ChannelEditor({ type="button" className={`btn btn-ghost btn-sm rb-last-resort${channel.lastResort ? (fallbackOnly ? " is-on" : " is-inert") : ""}`} aria-pressed={channel.lastResort} + disabled={saving} title={channel.lastResort && !fallbackOnly ? t("routeBoard.edit.lastResortInert") : t("routeBoard.edit.lastResortHint")} onClick={() => setChannels((list) => list.map((c, i) => i === index ? { ...c, lastResort: !c.lastResort } : c))} >{t("routeBoard.lastResort")} - - - @@ -243,7 +253,7 @@ export function ChannelEditor({ /> setLatestOnly(!latestOnly)} label={t("models.latestPerFamily")} title={t("models.latestPerFamilyHint")} showLabel /> -
      @@ -264,6 +274,7 @@ export function ChannelEditor({ size="sm" className="rb-strategy" value={policy} + disabled={saving} label={t("routeBoard.cap.title")} align="right" dropdownStyle={{ width: 360 }} @@ -284,6 +295,7 @@ export function ChannelEditor({ size="sm" className="rb-strategy" value={capability.onUnservable} + disabled={saving} label={t("routeBoard.cap.unservable")} align="right" dropdownStyle={{ width: 360 }} @@ -300,7 +312,7 @@ export function ChannelEditor({ {t("routeBoard.more.fallbackOnly")} {t("routeBoard.more.fallbackOnlyHint")} - setFallbackOnly((on) => !on)} /> + setFallbackOnly((on) => !on)} /> {dirty && {t("routeBoard.edit.unsaved")}} - diff --git a/gui/src/components/route-board/MemberTable.tsx b/gui/src/components/route-board/MemberTable.tsx index 3d1b897523d..66704704e74 100644 --- a/gui/src/components/route-board/MemberTable.tsx +++ b/gui/src/components/route-board/MemberTable.tsx @@ -230,6 +230,7 @@ export function MemberTable({ set({ context: event.target.value })} /> @@ -238,7 +239,7 @@ export function MemberTable({ {t("routeBoard.members.input")} {MODALITIES.map((modality) => ( - ))} @@ -247,7 +248,7 @@ export function MemberTable({ {t("routeBoard.members.efforts")} {REASONING_EFFORT_LEVELS.map((level) => ( - ))} diff --git a/gui/src/components/route-board/RouteBoard.tsx b/gui/src/components/route-board/RouteBoard.tsx index 7a8a22b656d..6d898b6701c 100644 --- a/gui/src/components/route-board/RouteBoard.tsx +++ b/gui/src/components/route-board/RouteBoard.tsx @@ -57,7 +57,8 @@ export function RouteBoard(props: RouteBoardProps) { 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); + /** Combos with a save in flight; each run clears only its own id. */ + const [busy, setBusy] = useState>(() => new Set()); const [messages, setMessages] = useState>({}); const rows = buildRouteRows({ combos: props.combos, @@ -79,14 +80,18 @@ export function RouteBoard(props: RouteBoardProps) { }); const run = async (id: string, work: () => Promise): Promise => { - setBusy(id); + setBusy((current) => new Set(current).add(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); + setBusy((current) => { + const next = new Set(current); + next.delete(id); + return next; + }); } }; @@ -127,7 +132,7 @@ export function RouteBoard(props: RouteBoardProps) { expanded={expanded === row.combo.id} lastResortActive={props.lastResortActive.has(row.combo.id)} onOpenContext={() => { setMoreFor(row.combo.id); setExpanded(row.combo.id); }} - busy={busy === row.combo.id} + busy={busy.has(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); }} @@ -135,7 +140,7 @@ export function RouteBoard(props: RouteBoardProps) { onEnabled={(next) => void run(row.combo.id, () => props.onSetEnabled(row.combo.id, next))} > 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} + saving={busy.has(row.combo.id)} + locked={props.lockedId === row.combo.id} onSave={(channels, settings) => void saveChannels(row.combo, channels, settings)} onSaveModel={props.onSaveModel} onProbeModel={props.onProbeModel} diff --git a/gui/src/pages/Combos.tsx b/gui/src/pages/Combos.tsx index 05dd674a56b..1c1c44d59da 100644 --- a/gui/src/pages/Combos.tsx +++ b/gui/src/pages/Combos.tsx @@ -40,6 +40,7 @@ import { type MemberInferred, type ProbeOutcome, configuredMemberModels, + withConfiguredMembers, parseCapabilitySettings, type AccountCount, type ComboCapabilitySettings, @@ -359,16 +360,17 @@ export default function Combos({ } } - const catalogKeys = new Set(models.map((model) => channelKey(model.provider, model.id))); - const memberModels = [ - ...models.map((model) => { + // Only real catalog rows shadow the per-model config; a default-model placeholder takes it. + const catalogKeys = new Set(capabilityModels.map((model) => channelKey(model.provider, model.id))); + const memberModels = withConfiguredMembers( + models.map((model): ModelOption => { 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))) + catalogKeys, + configuredMemberModels(allProviders) .map((member): ModelOption => ({ provider: member.provider, id: member.id, @@ -378,7 +380,7 @@ export default function Combos({ ...(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 diff --git a/gui/src/route-board-model.ts b/gui/src/route-board-model.ts index 13b39dc6c82..2a7fa7c0594 100644 --- a/gui/src/route-board-model.ts +++ b/gui/src/route-board-model.ts @@ -247,6 +247,29 @@ export function configuredMemberModels(providers: Readonly( + options: readonly T[], + catalogKeys: ReadonlySet, + configured: readonly T[], +): T[] { + const pending = new Map(configured + .filter((member) => !catalogKeys.has(channelKey(member.provider, member.id))) + .map((member) => [channelKey(member.provider, member.id), member])); + const merged = options.map((option) => { + const key = channelKey(option.provider, option.id); + const member = pending.get(key); + if (!member) return option; + pending.delete(key); + return { ...option, ...member }; + }); + return [...merged, ...pending.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, "")); diff --git a/gui/tests/route-board.test.tsx b/gui/tests/route-board.test.tsx index 79131f11253..e44d7e86c9d 100644 --- a/gui/tests/route-board.test.tsx +++ b/gui/tests/route-board.test.tsx @@ -19,6 +19,7 @@ import { parseProbeResponse, withInferredGaps, configuredMemberModels, + withConfiguredMembers, dragSlot, memberRestorePatch, memberSettingsPatch, @@ -596,6 +597,19 @@ describe("Combos overview page", () => { expect(window.location.hash).toBe("#models/combos"); }); + test("the context tag keeps an open editor's unsaved order, and the combined context follows the draft", 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(); }); + await act(async () => { row("alpha").querySelector(".rb-tag--button")!.click(); }); + const open = row("alpha").querySelector(".rb-editor")!; + expect(open).toBe(editor); + expect(open.querySelector(".rb-more-toggle")?.getAttribute("aria-expanded")).toBe("true"); + expect([...open.querySelectorAll(".rb-channel code")].map(code => code.textContent)).toEqual(["claude", "gpt-5"]); + expect(open.querySelector(".rb-members tfoot td")?.textContent).not.toContain("200K"); + }); + test("the fallback-only switch writes cooldownWaitPolicy", async () => { await renderPage(); await act(async () => { row("alpha").querySelector(".rb-row-toggle")!.click(); }); @@ -725,6 +739,20 @@ describe("member capability edits", () => { ]); }); + test("a default-model placeholder keeps its configured values; a catalog row keeps its own", () => { + const options = [{ provider: "zed", id: "listed", contextWindow: 100000 }, { provider: "zed", id: "default" }]; + const configured = [ + { provider: "zed", id: "listed", contextWindow: 1 }, + { provider: "zed", id: "default", contextWindow: 400000, sources: { context: "manual" as const, input: "unknown" as const, efforts: "unknown" as const } }, + { provider: "zed", id: "other", contextWindow: 8000 }, + ]; + expect(withConfiguredMembers(options, new Set([channelKey("zed", "listed")]), configured)).toEqual([ + { provider: "zed", id: "listed", contextWindow: 100000 }, + { provider: "zed", id: "default", contextWindow: 400000, sources: { context: "manual", input: "unknown", efforts: "unknown" } }, + { provider: "zed", id: "other", contextWindow: 8000 }, + ]); + }); + 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"); From 3dd3c069e7f0cd2b0d39e7feebb4e3c9d96a1b92 Mon Sep 17 00:00:00 2001 From: "Andrew (agent)" Date: Sat, 14 Nov 2026 01:25:02 -0500 Subject: [PATCH 11/21] fix(gui): member table scrolls inside More settings, Russian fallback-only hint states the right condition, structure table pipe --- gui/src/design/pages/route-board.css | 2 +- gui/src/i18n/ru.ts | 2 +- structure/dashboard-and-usage.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/gui/src/design/pages/route-board.css b/gui/src/design/pages/route-board.css index 4f5ae7aab27..0b462f55aa7 100644 --- a/gui/src/design/pages/route-board.css +++ b/gui/src/design/pages/route-board.css @@ -146,7 +146,7 @@ } .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-more-body { display: flex; flex-direction: column; gap: 2px; margin-top: 6px; overflow-x: auto; } .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; } diff --git a/gui/src/i18n/ru.ts b/gui/src/i18n/ru.ts index f679388a0b0..1abfc448785 100644 --- a/gui/src/i18n/ru.ts +++ b/gui/src/i18n/ru.ts @@ -4554,7 +4554,7 @@ export const ru: Record = { "routeBoard.jevInAdvanced": "Для JEV нужен сервис решений. Переключите здесь стратегию на JEV, проверьте, какой сервис принимает решение, и сохраните.", "routeBoard.edit.aria": "Каналы для {model}", "routeBoard.edit.drag": "Перетащите, чтобы изменить порядок", - "routeBoard.edit.lastResortHint": "Только резерв: используется, лишь когда ни один другой канал недоступен.", + "routeBoard.edit.lastResortHint": "Только резерв: используется, только когда все остальные каналы недоступны.", "routeBoard.edit.lastResortInert": "Не действует: включите «Резервные каналы — в последнюю очередь» в разделе «Другие настройки». До тех пор канал используется по порядку, как остальные.", "routeBoard.edit.moveUp": "Переместить {name} выше", "routeBoard.edit.moveDown": "Переместить {name} ниже", diff --git a/structure/dashboard-and-usage.md b/structure/dashboard-and-usage.md index 4338061ae18..2f8d2671365 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 | `#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. | +| 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. | From 660dbfdb190dd84491583ab506d6e6e64f95dd6a Mon Sep 17 00:00:00 2001 From: "Andrew (agent)" Date: Sat, 14 Nov 2026 01:28:15 -0500 Subject: [PATCH 12/21] fix(gui): a channel never borrows another model family's quota pool as its fallback --- gui/src/route-board-model.ts | 5 ++++- gui/tests/route-board.test.tsx | 16 ++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/gui/src/route-board-model.ts b/gui/src/route-board-model.ts index 2a7fa7c0594..5363b674f78 100644 --- a/gui/src/route-board-model.ts +++ b/gui/src/route-board-model.ts @@ -443,7 +443,10 @@ function pickWindows(windows: QuotaSummaryWindow[], models: readonly string[]): 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); + // Provider-wide windows stand in when nothing matches; another family's pool ("Gem" for a + // Claude channel) never does, so such a channel reads as unknown instead. + const generic = measured.filter((window) => window.labelKey !== undefined + || (window.modelId === undefined && quotaFamilyWindow(window.label ?? "") === null)); const pool = relevant.length > 0 ? relevant : generic; const rank = (window: QuotaSummaryWindow) => { if (window.modelId !== undefined) return -1; diff --git a/gui/tests/route-board.test.tsx b/gui/tests/route-board.test.tsx index e44d7e86c9d..2c8b410d48e 100644 --- a/gui/tests/route-board.test.tsx +++ b/gui/tests/route-board.test.tsx @@ -123,6 +123,22 @@ describe("route board model", () => { expect(quota.zed).toEqual({ kind: "unknown" }); }); + test("a channel whose only window is another family's pool shows unknown quota, not that pool", () => { + const [row] = buildRouteRows({ + combos: [combo("opus", [["google-antigravity", "claude-opus-5-5"]])], + catalog: {}, + lastResort: {}, + providers: [{ name: "google-antigravity", authMode: "oauth" }], + quotaReports: [{ + provider: "google-antigravity", + updatedAt: NOW, + quota: { customWindows: [{ label: "Gem", percent: 10, resetAt: NOW + 3_600_000 }], updatedAt: NOW }, + }], + now: NOW, + }); + expect(row!.quotas[0]!.quota).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]); From ec6604c7b19500d15854023abc1f55d44f5f5f56 Mon Sep 17 00:00:00 2001 From: "Andrew (agent)" Date: Sat, 14 Nov 2026 01:30:15 -0500 Subject: [PATCH 13/21] fix(gui): suggested-combo drafts survive quota reordering, extending skips a combo held in Advanced, exclusions wait for the stored list --- .../route-board/ComboSuggestions.tsx | 11 ++- .../route-board/use-suggestion-exclusions.ts | 18 +++- gui/src/pages/Combos.tsx | 3 +- gui/tests/combo-suggestions.test.tsx | 97 ++++++++++++++++++- 4 files changed, 121 insertions(+), 8 deletions(-) diff --git a/gui/src/components/route-board/ComboSuggestions.tsx b/gui/src/components/route-board/ComboSuggestions.tsx index 084d6c1b833..fec12e5eb3b 100644 --- a/gui/src/components/route-board/ComboSuggestions.tsx +++ b/gui/src/components/route-board/ComboSuggestions.tsx @@ -43,6 +43,8 @@ export interface ComboSuggestionsProps { /** Providers left out of suggestions (config.json); with `onExcludedChange`, offers to change them. */ excludedProviders?: readonly string[]; onExcludedChange?: (next: readonly string[]) => Promise; + /** A combo with unsaved Advanced edits; adding to it would reset that draft, so it is held. */ + lockedComboId?: string | null; } /** Suggested combos above the overview: same-name models across providers, one click to a draft. */ @@ -89,6 +91,7 @@ export function ComboSuggestions(props: ComboSuggestionsProps) { suggestion={suggestion} drafting={draftKey === suggestion.key} combos={props.combos} + locked={suggestion.kind === "extend" && suggestion.comboId === props.lockedComboId} tierOf={tierOf} validate={props.validate} errorText={props.errorText} @@ -127,6 +130,7 @@ function SuggestionCard({ suggestion, drafting, combos, + locked, tierOf, validate, errorText, @@ -138,6 +142,7 @@ function SuggestionCard({ suggestion: ComboSuggestion; drafting: boolean; combos: readonly ComboItem[]; + locked: boolean; tierOf: (provider: string, model: string) => ChannelTier; validate: ComboSuggestionsProps["validate"]; errorText: ComboSuggestionsProps["errorText"]; @@ -194,7 +199,8 @@ function SuggestionCard({