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

    {message}

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

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

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

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

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

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

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

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

    ; + case "busy": + return

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

    ; + case "failed": + return

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

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

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

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

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

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

    {adoptError.message}

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

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

    + {editing.error &&

    {editing.error}

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

    {message}

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

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

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

    {t("routeBoard.empty")}

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