From c21ac17b0c352ce667a0057bdd86e235a125cff9 Mon Sep 17 00:00:00 2001 From: JUN Date: Thu, 19 Nov 2026 00:08:29 +0900 Subject: [PATCH 01/23] feat(gui): suggest combos in the existing workspace Co-authored-by: Andrew (agent) --- .../src/content/docs/es/guides/combos.md | 4 + .../src/content/docs/fr/guides/combos.md | 4 + docs-site/src/content/docs/guides/combos.md | 4 + .../src/content/docs/ja/guides/combos.md | 4 + .../src/content/docs/ko/guides/combos.md | 4 + .../src/content/docs/ru/guides/combos.md | 4 + .../src/content/docs/tr/guides/combos.md | 4 + .../src/content/docs/zh-cn/guides/combos.md | 4 + .../src/content/docs/zh-tw/guides/combos.md | 4 + gui/src/combo-suggestions.ts | 263 ++++++++++ gui/src/combo-workspace-data.ts | 3 + gui/src/components/ComboWorkspace.tsx | 4 + gui/src/components/combo-workspace-types.ts | 3 + .../route-board/ComboSuggestions.tsx | 289 ++++++++++ .../SuggestionExcludeProviders.tsx | 73 +++ .../route-board/WorkspaceSuggestions.tsx | 61 +++ .../route-board/use-suggestion-exclusions.ts | 63 +++ gui/src/design/pages/combo-suggestions.css | 93 ++++ gui/src/design/theme.css | 1 + gui/src/i18n/de.ts | 28 + gui/src/i18n/en.ts | 28 + gui/src/i18n/fr.ts | 28 + gui/src/i18n/ja.ts | 28 + gui/src/i18n/ko.ts | 28 + gui/src/i18n/pt.ts | 28 + gui/src/i18n/ru.ts | 28 + gui/src/i18n/tr.ts | 28 + gui/src/i18n/vi.ts | 28 + gui/src/i18n/zh-TW.ts | 28 + gui/src/i18n/zh.ts | 28 + gui/src/pages/Combos.tsx | 21 +- gui/src/styles-combos-workspace.css | 6 + gui/tests/combo-suggestions.test.tsx | 494 ++++++++++++++++++ scripts/test-layout/layout.json | 2 +- src/config/schema/config-schema.ts | 3 + src/server/management/combo-routes.ts | 6 + .../management/combo-suggestion-routes.ts | 69 +++ src/server/management/route-registry.ts | 3 + src/types/config.ts | 5 + structure/config.md | 2 +- structure/dashboard-and-usage.md | 2 +- structure/gui-and-management-api.md | 2 +- tests/fixtures/test-layout-expected.json | 2 + tests/server/combo-suggestion-routes.test.ts | 83 +++ 44 files changed, 1892 insertions(+), 5 deletions(-) create mode 100644 gui/src/combo-suggestions.ts create mode 100644 gui/src/components/route-board/ComboSuggestions.tsx create mode 100644 gui/src/components/route-board/SuggestionExcludeProviders.tsx create mode 100644 gui/src/components/route-board/WorkspaceSuggestions.tsx create mode 100644 gui/src/components/route-board/use-suggestion-exclusions.ts create mode 100644 gui/src/design/pages/combo-suggestions.css create mode 100644 gui/tests/combo-suggestions.test.tsx create mode 100644 src/server/management/combo-suggestion-routes.ts create mode 100644 tests/server/combo-suggestion-routes.test.ts diff --git a/docs-site/src/content/docs/es/guides/combos.md b/docs-site/src/content/docs/es/guides/combos.md index 0c5a5d24ab5..22ed613e53b 100644 --- a/docs-site/src/content/docs/es/guides/combos.md +++ b/docs-site/src/content/docs/es/guides/combos.md @@ -787,3 +787,7 @@ El enfriamiento por combo es independiente del de cuenta y persiste con expiraci Los destinos RunTurn retienen razonamiento previo hasta un segundo: una finalización max_output_tokens sin salida dentro del plazo permite otro destino sin enfriar al sano. Al vencer o aparecer salida, se compromete y transmite lo retenido. También puede avanzar incomplete sin razón, adapter_eof, missing_terminal_event o upstream_stall_timeout antes de salida. `end_turn: false` o `incomplete_details.retryable` false conserva el destino. `pause_turn` Anthropic es pausa larga y sigue como `incomplete` con max_output_tokens, sin alternativa. Content_filter, razones semánticas explícitas, null explícito y límites tras salida son terminales. Si todos acaban así sin salida y sin exceso de contexto confirmado, se devuelve el último HTTP 200 incomplete con su uso, no 502. JSON nativo no streaming no se inspecciona. Los metadatos de tasa de Codex WebSocket no son salida; tras salida o límite de buffer nunca se reproduce en otro destino. Un rechazo estructurado de esfuerzo puede bajar una posición publicada cada vez en el mismo destino mientras quede presupuesto. Incluye `{"code":"invalid-argument","error":"Invalid reasoning effort."}` y las formas reconocidas de unsupported_value. Si ninguna sirve, solo formas de compatibilidad reconocidas avanzan sin enfriarlo; conserva el 400 si no quedan envíos. No convierte none ni generaliza a errores inválidos arbitrarios. Rechazos de política, cancelación o salida ya comprometida nunca se reproducen. Si un destino enfriado fija la recuperación más próxima, mensaje y Retry-After muestran el mismo plazo, por ejemplo `(retry in ~2m)`; Messages usa la misma espera. + +## Combos sugeridos + +En el espacio de trabajo de combos, **Generar** abre un borrador de conmutación por error para un modelo disponible en varios proveedores. **Añadir al combo** ofrece destinos que faltan en un combo existente. Las tarjetas descartadas quedan ocultas en este navegador. Usa **Excluir un proveedor…** para filtrar ambos tipos de sugerencias. El proxy guarda la selección como `comboSuggestionExcludedProviders` en `config.json`. Los miembros existentes se conservan. Los destinos sugeridos de pago por uso se marcan como medidos y siguen las reglas de consentimiento anteriores. diff --git a/docs-site/src/content/docs/fr/guides/combos.md b/docs-site/src/content/docs/fr/guides/combos.md index 43c8488cf42..12bfa5a240f 100644 --- a/docs-site/src/content/docs/fr/guides/combos.md +++ b/docs-site/src/content/docs/fr/guides/combos.md @@ -387,3 +387,7 @@ Exception aux erreurs 400 terminales : l'enveloppe opaque d'OpenRouter (`Provide ## Réservation d’une tentative de récupération Une tentative de récupération activée par `cooldownReprobe: { enabled: true }` appartient uniquement à la requête qui l’a réservée ; les autres requêtes restent soumises aux délais de refroidissement enregistrés. La réservation est conservée pendant l’attente et la sélection JEV. Une cible redevenue utilisable pendant l’attente peut être réessayée si son délai enregistré n’a pas changé. Un nouvel enregistrement annule la réservation de cette cible. Un succès ne supprime que le délai inchangé de la cible ayant répondu ; les cibles non essayées et les nouveaux échecs conservent leurs délais. La désactivation du fournisseur, les quotas, l’admissibilité de la requête et l’annulation restent vérifiés. Voir les [réglages et limites](/guides/combos/#retry-all-cooled-targets-opt-in). + +## Combos suggérés + +Dans l’espace Combos, générez un brouillon de basculement pour un modèle partagé ou ajoutez une cible manquante à un combo existant. Les cartes ignorées restent masquées dans ce navigateur. Excluez des fournisseurs des suggestions via `comboSuggestionExcludedProviders` dans `config.json`. Les membres existants sont conservés. Les cibles facturées à l’usage suivent les règles de consentement. diff --git a/docs-site/src/content/docs/guides/combos.md b/docs-site/src/content/docs/guides/combos.md index 9b7f49fa5ce..96d734e2cf8 100644 --- a/docs-site/src/content/docs/guides/combos.md +++ b/docs-site/src/content/docs/guides/combos.md @@ -1213,3 +1213,7 @@ waits and JEV selection. A target that becomes usable again during a wait can st be retried if its cooldown has not changed. A newer cooldown cancels that target's reservation. Success clears only the unchanged cooldown of the target that answered; untried targets and newer failures keep their cooldowns. + +## Suggested combos + +In the Combos workspace, **Generate** opens a failover draft for a model served by multiple providers. **Add to combo** offers missing targets for an existing combo. Dismissed cards stay hidden in this browser. Use **Exclude providers…** to filter both kinds of suggestions. The proxy stores your selection as `comboSuggestionExcludedProviders` in `config.json`. Existing combo members stay in place. Suggested pay-per-use targets are marked as metered and follow the combo consent rules above. diff --git a/docs-site/src/content/docs/ja/guides/combos.md b/docs-site/src/content/docs/ja/guides/combos.md index b86d67b61b4..4b683759838 100644 --- a/docs-site/src/content/docs/ja/guides/combos.md +++ b/docs-site/src/content/docs/ja/guides/combos.md @@ -285,3 +285,7 @@ ocx combo remove --yes ## クールダウン回復の予約 `cooldownReprobe: { enabled: true }` で有効にした回復試行は、予約したリクエストだけに属し、他のリクエストには保存済みのクールダウンが引き続き適用されます。予約はクールダウン待機と JEV 選択を経ても維持されます。待機中に再び利用可能になったターゲットは、クールダウンが変わっていなければ再試行できますが、新しいクールダウンの記録はそのターゲットの予約を無効にします。成功時は応答したターゲットの変更されていないクールダウンだけを解除し、未試行のターゲットや新しい失敗のクールダウンは残します。プロバイダーの無効化、クォータ、リクエストの適格性、キャンセルの確認は引き続き有効です。[設定と制限](/guides/combos/#retry-all-cooled-targets-opt-in)を参照してください。 + +## おすすめのコンボ + +コンボ画面では、複数のプロバイダーが提供するモデルのフェイルオーバー案を作成したり、既存コンボに候補を追加したりできます。閉じたカードはこのブラウザーで非表示になります。除外設定は `config.json` の `comboSuggestionExcludedProviders` に保存されます。既存のメンバーは保持され、従量課金の候補には同意の規則が適用されます。 diff --git a/docs-site/src/content/docs/ko/guides/combos.md b/docs-site/src/content/docs/ko/guides/combos.md index 53589443fda..95170207d6b 100644 --- a/docs-site/src/content/docs/ko/guides/combos.md +++ b/docs-site/src/content/docs/ko/guides/combos.md @@ -301,3 +301,7 @@ opencodex 인스턴스에 기록했는지 확인하세요. ## 쿨다운 복구 예약 `cooldownReprobe: { enabled: true }`로 활성화한 복구 시도는 이를 예약한 요청에만 속하며, 다른 요청에는 저장된 쿨다운이 계속 적용됩니다. 예약은 쿨다운 대기와 JEV 선택을 거쳐 유지됩니다. 대기 중 다시 사용 가능해진 대상은 기존 쿨다운이 바뀌지 않았다면 재시도할 수 있지만, 새 쿨다운 기록은 그 대상의 예약을 무효화합니다. 성공하면 응답한 대상의 변경되지 않은 쿨다운만 해제하며, 시도하지 않은 대상과 새로운 실패의 쿨다운은 유지합니다. 공급자 비활성화, 할당량, 요청 적격성 및 취소 검사는 계속 적용됩니다. [설정과 제한](/guides/combos/#retry-all-cooled-targets-opt-in)을 참고하세요. + +## 추천 콤보 + +콤보 화면에서 여러 공급자가 제공하는 모델의 장애 조치 초안을 만들거나 기존 콤보에 빠진 대상을 추가할 수 있습니다. 닫은 카드는 이 브라우저에서 숨겨집니다. 제외한 공급자는 `config.json`의 `comboSuggestionExcludedProviders`에 저장됩니다. 기존 구성원은 유지되며, 종량제 대상에는 사용 동의 규칙이 적용됩니다. diff --git a/docs-site/src/content/docs/ru/guides/combos.md b/docs-site/src/content/docs/ru/guides/combos.md index a76f46e2bbc..b8dbc2afd4d 100644 --- a/docs-site/src/content/docs/ru/guides/combos.md +++ b/docs-site/src/content/docs/ru/guides/combos.md @@ -345,3 +345,7 @@ CLI и дашборд показывают точное сообщение ва ## Резервирование восстановления после cooldown Попытка восстановления, включённая через `cooldownReprobe: { enabled: true }`, принадлежит только зарезервировавшему её запросу; для других запросов сохранённые cooldown продолжают действовать. Резервирование сохраняется при ожидании cooldown и выборе JEV. Если цель снова становится доступной во время ожидания, её можно повторно попробовать, пока запись cooldown не изменилась. Новая запись отменяет резервирование этой цели. Успех снимает только неизменённый cooldown ответившей цели; для непроверенных целей и новых сбоев cooldown сохраняется. Проверки отключения провайдера, квоты, допустимости запроса и отмены остаются в силе. См. [настройки и ограничения](/guides/combos/#retry-all-cooled-targets-opt-in). + +## Предложения комбо + +В рабочей области комбо можно создать черновик для переключения между поставщиками общей модели или добавить недостающую цель в существующее комбо. Закрытые карточки остаются скрытыми в этом браузере. Список исключений сохраняется в `comboSuggestionExcludedProviders` в `config.json`. Состав существующих комбо сохраняется, а для целей с оплатой по факту действуют правила согласия. diff --git a/docs-site/src/content/docs/tr/guides/combos.md b/docs-site/src/content/docs/tr/guides/combos.md index 8890281219b..0d3db6efc2f 100644 --- a/docs-site/src/content/docs/tr/guides/combos.md +++ b/docs-site/src/content/docs/tr/guides/combos.md @@ -426,3 +426,7 @@ Sonlandırıcı 400 hatalarının dar bir istisnası vardır: OpenRouter'ın opa ## Soğuma kurtarma rezervasyonu `cooldownReprobe: { enabled: true }` ile etkinleştirilen kurtarma denemesi yalnızca onu ayıran isteğe aittir; diğer istekler kayıtlı soğuma sürelerine uymaya devam eder. Rezervasyon, soğuma beklemesi ve JEV seçimi boyunca korunur. Bekleme sırasında yeniden kullanılabilir olan hedef, soğuma kaydı değişmediyse tekrar denenebilir. Yeni bir soğuma kaydı o hedefin rezervasyonunu geçersiz kılar. Başarı yalnızca yanıt veren hedefin değişmemiş soğuma kaydını kaldırır; denenmeyen hedefler ve yeni hatalar soğuma kayıtlarını korur. Sağlayıcının devre dışı olması, kota, istek uygunluğu ve iptal kontrolleri geçerliliğini korur. [Ayarlar ve sınırlar](/guides/combos/#retry-all-cooled-targets-opt-in) bölümüne bakın. + +## Önerilen kombolar + +Kombolar çalışma alanında, birden çok sağlayıcının sunduğu model için yük devretme taslağı oluşturabilir veya mevcut komboya eksik hedef ekleyebilirsiniz. Kapatılan kartlar bu tarayıcıda gizli kalır. Hariç tutulan sağlayıcılar `config.json` dosyasındaki `comboSuggestionExcludedProviders` alanına kaydedilir. Mevcut üyeler korunur ve kullanıma göre ücretlendirilen hedeflere onay kuralları uygulanır. 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..37ce5bd95ec 100644 --- a/docs-site/src/content/docs/zh-cn/guides/combos.md +++ b/docs-site/src/content/docs/zh-cn/guides/combos.md @@ -315,3 +315,7 @@ combo id 不存在。响应是 HTTP 404,类型为 `invalid_request_error`。 ## 冷却恢复预约 通过 `cooldownReprobe: { enabled: true }` 启用的恢复尝试只属于预约它的请求;其他请求仍受已保存的冷却限制。预约会在冷却等待和 JEV 选择期间保留。目标在等待期间重新可用时,只要其冷却记录没有变化,就仍可重试;新的冷却记录会使该目标的预约失效。成功后,只清除实际响应目标未改变的冷却记录;未尝试的目标和新的失败仍保留冷却。提供方禁用、配额、请求资格和取消检查仍然生效。请参阅[设置与限制](/guides/combos/#retry-all-cooled-targets-opt-in)。 + +## 推荐组合 + +在组合工作区,可为多个提供商共享的模型生成故障转移草稿,或向现有组合添加缺少的目标。关闭的卡片会在当前浏览器中隐藏。排除的提供商保存在 `config.json` 的 `comboSuggestionExcludedProviders` 中。现有成员会保留,按量计费的建议目标遵循授权规则。 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..96b1eea7ffc 100644 --- a/docs-site/src/content/docs/zh-tw/guides/combos.md +++ b/docs-site/src/content/docs/zh-tw/guides/combos.md @@ -309,3 +309,7 @@ Combo id 未知。回應為 HTTP 404 並帶 type `invalid_request_error`。執 ## 冷卻復原預約 透過 `cooldownReprobe: { enabled: true }` 啟用的復原嘗試只屬於預約它的請求;其他請求仍受已儲存的冷卻限制。預約會在冷卻等待與 JEV 選擇期間保留。目標在等待期間重新可用時,只要其冷卻紀錄沒有變更,就仍可重試;新的冷卻紀錄會使該目標的預約失效。成功後,只清除實際回應目標未變更的冷卻紀錄;未嘗試的目標與新的失敗仍保留冷卻。供應商停用、配額、請求資格與取消檢查仍然生效。請參閱[設定與限制](/guides/combos/#retry-all-cooled-targets-opt-in)。 + +## 建議組合 + +在組合工作區,可以為多個供應商共用的模型產生容錯移轉草稿,或將缺少的目標加入現有組合。關閉的卡片會在目前的瀏覽器中隱藏。排除的供應商儲存在 `config.json` 的 `comboSuggestionExcludedProviders` 中。現有成員會保留,按量計費的建議目標遵循授權規則。 diff --git a/gui/src/combo-suggestions.ts b/gui/src/combo-suggestions.ts new file mode 100644 index 00000000000..aba29ebe446 --- /dev/null +++ b/gui/src/combo-suggestions.ts @@ -0,0 +1,263 @@ +/** + * 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[]; + }; + +/** No `max`: it names distinct models (`gpt-5.1-codex-max` is not `gpt-5.1-codex` at max effort). */ +const EFFORT_SUFFIX = /-(?:minimal|low|medium|high|xhigh)$/; + +/** + * 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`; + * `gpt-5.1-codex-max-high` is `gpt-5-1-codex-max`). + */ +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())); + base = base.slice(0, 64); + if (!COMBO_ID_RE.test(base)) base = "suggested-combo"; + if (!taken.has(base.toLowerCase())) return base; + for (let n = 2; ; n++) { + const suffix = `-${n}`; + const candidate = base.slice(0, 64 - suffix.length) + suffix; + if (!taken.has(candidate.toLowerCase())) return candidate; + } +} + +export interface SuggestionInput { + combos: readonly ComboItem[]; + /** Catalog rows, combos excluded, hidden rows included: hiding a model only hides it from pickers. */ + models: readonly SuggestionModel[]; + /** `provider/model` keys hidden from the model catalog (`disabledModels`). */ + hiddenModels?: ReadonlySet; + providers: readonly SuggestionProvider[]; + remainingPercent?: (provider: string, model: string) => number | undefined; + dismissed?: ReadonlySet; + /** Providers the operator left out of suggestions: they join no suggested combo. */ + excludedProviders?: ReadonlySet; +} + +export function suggestionKey(kind: ComboSuggestion["kind"], model: string, comboId?: string): string { + return kind === "create" ? `create:${model}` : `extend:${comboId}:${model}`; +} + +export function buildComboSuggestions(input: SuggestionInput): ComboSuggestion[] { + const providers = new Map(input.providers.map((provider) => [provider.name, provider])); + /** model name → provider → that provider's id for it (the shortest spelling wins). */ + const byModel = new Map>(); + for (const row of input.models) { + const provider = providers.get(row.provider); + if (!provider || provider.disabled || provider.hiddenFromPicker || input.excludedProviders?.has(row.provider)) continue; + const name = normalizeModelName(row.id); + if (!name) continue; + const served = byModel.get(name) ?? new Map(); + const current = served.get(row.provider); + if (current === undefined || row.id.length < current.length) served.set(row.provider, row.id); + byModel.set(name, served); + } + + const member = (provider: string, model: string): SuggestedMember => { + const remaining = input.remainingPercent?.(provider, model); + return { + provider, + model, + tier: channelTier(providers.get(provider)!, model), + ...(remaining !== undefined ? { remainingPercent: remaining } : {}), + }; + }; + + const covering = new Map(); + for (const combo of input.combos) { + const name = comboModel(combo); + if (name !== undefined && !covering.has(name)) covering.set(name, combo); + } + + const creates: Array = []; + const extends_: Array = []; + for (const [name, served] of byModel) { + 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.filter((target) => normalizeModelName(target.model) === name).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; + } + if (served.size < 2) 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, ...(entry.tier === "metered" ? { metered: true } : {}) })), + }; +} + +/** + * 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, ...(entry.tier === "metered" ? { metered: true } : {}) })); + } + return { ...combo, targets }; +} diff --git a/gui/src/combo-workspace-data.ts b/gui/src/combo-workspace-data.ts index 5654f2bd81d..beec6e4a17b 100644 --- a/gui/src/combo-workspace-data.ts +++ b/gui/src/combo-workspace-data.ts @@ -106,6 +106,7 @@ export function intersectComboEfforts( } export interface ComboTarget { + metered?: boolean; provider: string; model: string; weight?: number; @@ -127,6 +128,7 @@ let comboTargetKeySeq = 0; export function newComboTarget(partial: Partial = {}): ComboTarget { return { + ...(partial.metered === true ? { metered: true } : {}), provider: partial.provider ?? "", model: partial.model ?? "", ...(partial.weight !== undefined ? { weight: partial.weight } : {}), @@ -544,6 +546,7 @@ export function toPutBody( targets: item.targets.map((target) => ({ provider: target.provider.trim(), model: target.model.trim(), + ...(target.metered === true ? { metered: true } : {}), ...(weighted ? { weight: target.weight ?? 1 } : {}), ...(target.reasoningEfforts !== undefined ? { reasoningEfforts: [...target.reasoningEfforts] } diff --git a/gui/src/components/ComboWorkspace.tsx b/gui/src/components/ComboWorkspace.tsx index 32ac369178b..a774a4c63be 100644 --- a/gui/src/components/ComboWorkspace.tsx +++ b/gui/src/components/ComboWorkspace.tsx @@ -37,6 +37,7 @@ export default function ComboWorkspace({ addDecisionProvider, onCloseAdd, onCreated, + renderSuggestions, }: ComboWorkspaceProps) { const t = useT(); const providerMap = useMemo( @@ -130,6 +131,8 @@ export default function ComboWorkspace({ }; return ( + <> + {renderSuggestions?.(detailDirty ? activeId : null)}
+ ) : null; + } + + const saveSuggestion = async (item: ComboItem, isCreate: boolean) => { + const failure = { ok: false, error: t("comboSuggest.saveChanged") }; + try { + const [configResponse, exclusionResponse, combosResponse] = await Promise.all([ + fetch(`${props.apiBase}/api/config`), + fetch(`${props.apiBase}/api/combo-suggestions`), + isCreate ? undefined : fetch(`${props.apiBase}/api/combos`), + ]); + if (!configResponse.ok || !exclusionResponse.ok || (combosResponse && !combosResponse.ok)) return failure; + const config = await configResponse.json() as { + providers?: Record>; + }; + const { excludedProviders } = await exclusionResponse.json() as { excludedProviders?: unknown }; + if (!Array.isArray(excludedProviders) || excludedProviders.some((name) => typeof name !== "string")) return failure; + const excluded = new Set(excludedProviders); + const old = props.combos.find((combo) => combo.id === item.id); + const live = combosResponse && parseComboList(await combosResponse.json()).find((combo) => combo.id === item.id); + if (!isCreate && (!old || !live)) return failure; + const hasTarget = (combo: ComboItem | undefined, provider: string, model: string) => + combo?.targets.some((target) => target.provider === provider && target.model === model); + const liveProviders = new Map(Object.entries(config.providers ?? {}).map(([name, provider]) => [name, { ...provider, name }])); + const tierOf = (provider: string, model: string) => { + const current = liveProviders.get(provider); + return current ? channelTier(current, model) : "metered"; + }; + const proposed = item.targets.filter(({ provider, model }) => isCreate || !hasTarget(old, provider, model)); + const additions = proposed.filter(({ provider, model }) => !live || !hasTarget(live, provider, model)) + .map(({ provider, model }) => ({ provider, model, tier: tierOf(provider, model) })); + if (!additions.length || additions.some(({ provider, tier }) => { + const current = liveProviders.get(provider); + return !current || current.disabled || current.adapter === "jev-decision" + || excluded.has(provider) + || (isMeteredTier(tier) && (!live || live.allowMeteredTargets !== true)); + })) return failure; + return await props.onSave(live ? extendedCombo(live, additions, tierOf) : item, isCreate); + } catch { + return failure; + } + }; const providerMap = Object.fromEntries(props.providers.map((provider) => [provider.name, provider])); const reports = freshQuotaReportsFromResponse(props.quotaReports, props.quotaNow); const quota = new Map(buildQuotaSummary(reports, (provider) => provider) @@ -52,10 +101,10 @@ export function WorkspaceSuggestions(props: Props) { }); }} errorText={(code, item) => comboDraftErrorText(t, code, item, providerMap)} - onCreate={(item) => props.onSave(item, true)} - onExtend={(item) => props.onSave(item, false)} + onCreate={(item) => saveSuggestion(item, true)} + onExtend={(item) => saveSuggestion(item, false)} excludedProviders={exclusions.excluded} - onExcludedChange={exclusions.ready ? exclusions.save : undefined} + onExcludedChange={exclusions.save} /> ); } diff --git a/gui/src/components/route-board/use-suggestion-exclusions.ts b/gui/src/components/route-board/use-suggestion-exclusions.ts index 7aab2699d60..9159adb35b9 100644 --- a/gui/src/components/route-board/use-suggestion-exclusions.ts +++ b/gui/src/components/route-board/use-suggestion-exclusions.ts @@ -9,6 +9,8 @@ export interface SuggestionExclusions { excluded: readonly string[]; /** True once the stored list is known; a save before that would replace it with a partial one. */ ready: boolean; + failed: boolean; + retry: () => void; /** Saves the whole list; resolves false when the proxy did not take it (the list stays as it was). */ save: (next: readonly string[]) => Promise; } @@ -16,12 +18,13 @@ export interface SuggestionExclusions { 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; + return Array.isArray(list) && list.every((name) => typeof name === "string") ? list : null; } export function useSuggestionExclusions(apiBase: string, active = true): SuggestionExclusions { - const [loaded, setLoaded] = useState<{ base: string; excluded: string[] }>(); - const current = loaded?.base === apiBase ? loaded : undefined; + const [attempt, setAttempt] = useState(0); + const [loaded, setLoaded] = useState<{ base: string; attempt: number; excluded: string[] | null }>(); + const current = active && loaded?.base === apiBase && loaded.attempt === attempt ? loaded : undefined; // Bumped by every save, so a read that started earlier cannot overwrite what was saved. const generation = useRef(0); @@ -33,16 +36,19 @@ export function useSuggestionExclusions(apiBase: string, active = true): Suggest .then((response) => (response.ok ? response.json() : null)) .then((body) => { const list = parse(body); - if (!list || controller.signal.aborted || generation.current !== started) return; - setLoaded({ base: apiBase, excluded: list }); + if (controller.signal.aborted || generation.current !== started) return; + setLoaded({ base: apiBase, attempt, excluded: list }); }) - // An older proxy without the route: nothing is excluded and the control stays hidden. - .catch(() => {}); + .catch(() => { + if (!controller.signal.aborted && generation.current === started) { + setLoaded({ base: apiBase, attempt, excluded: null }); + } + }); return () => controller.abort(); - }, [apiBase, active]); + }, [apiBase, active, attempt]); const save = useCallback(async (next: readonly string[]) => { - if (!current) return false; + if (!current?.excluded) return false; const started = ++generation.current; try { const response = await fetch(`${apiBase}/api/combo-suggestions`, { @@ -52,12 +58,18 @@ export function useSuggestionExclusions(apiBase: string, active = true): Suggest }); const list = response.ok ? parse(await response.json()) : null; if (!list || generation.current !== started) return false; - setLoaded({ base: apiBase, excluded: list }); + setLoaded({ base: apiBase, attempt, excluded: list }); return true; } catch { return false; } - }, [apiBase, current]); + }, [apiBase, attempt, current]); - return { excluded: current?.excluded ?? [], ready: current !== undefined, save }; + return { + excluded: current?.excluded ?? [], + ready: current?.excluded != null, + failed: current?.excluded === null, + retry: () => setAttempt((value) => value + 1), + save, + }; } diff --git a/gui/src/i18n/de.ts b/gui/src/i18n/de.ts index 759e3d602ed..60853704bc7 100644 --- a/gui/src/i18n/de.ts +++ b/gui/src/i18n/de.ts @@ -4536,7 +4536,9 @@ export const de: Record = { "comboSuggest.exclude.head": "Aus vorgeschlagenen Kombis ausnehmen", "comboSuggest.exclude.hint": "Ihre Modelle kommen in keine vorgeschlagene Kombi; bestehende Kombis behalten sie.", "comboSuggest.exclude.saveFailed": "Die ausgenommenen Anbieter konnten nicht gespeichert werden.", - "comboSuggest.exclude.none": "Ohne diese Anbieter bleiben keine Vorschläge.", + "comboSuggest.exclude.none": "Keine Vorschläge verfügbar.", + "comboSuggest.exclude.loadFailed": "Ausgeschlossene Anbieter konnten nicht geladen werden.", + "comboSuggest.saveChanged": "Die Vorschlagseinstellungen wurden geändert oder konnten nicht geprüft werden. Lade Combos neu und versuche es erneut.", "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 7e2e938c202..226cc502f13 100644 --- a/gui/src/i18n/en.ts +++ b/gui/src/i18n/en.ts @@ -4570,7 +4570,9 @@ export const en = { "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.saveFailed": "Could not save the excluded providers.", - "comboSuggest.exclude.none": "No suggestions left with these providers excluded.", + "comboSuggest.exclude.none": "No suggestions to show.", + "comboSuggest.exclude.loadFailed": "Could not load excluded providers.", + "comboSuggest.saveChanged": "Suggestion settings changed or could not be verified. Refresh Combos and try again.", "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 69b1c8978bd..44f4903ac09 100644 --- a/gui/src/i18n/fr.ts +++ b/gui/src/i18n/fr.ts @@ -4525,7 +4525,9 @@ export const fr: Record = { "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.saveFailed": "Impossible d'enregistrer les fournisseurs exclus.", - "comboSuggest.exclude.none": "Aucune suggestion ne reste avec ces fournisseurs exclus.", + "comboSuggest.exclude.none": "Aucune suggestion à afficher.", + "comboSuggest.exclude.loadFailed": "Impossible de charger les fournisseurs exclus.", + "comboSuggest.saveChanged": "Les paramètres de suggestion ont changé ou n’ont pas pu être vérifiés. Actualisez les combos et réessayez.", "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 08ac6138c4f..86a1ddfc117 100644 --- a/gui/src/i18n/ja.ts +++ b/gui/src/i18n/ja.ts @@ -4558,7 +4558,9 @@ export const ja: Record = { "comboSuggest.exclude.head": "おすすめの組み合わせから除外", "comboSuggest.exclude.hint": "そのモデルはおすすめの組み合わせに入りません。作成済みの組み合わせはそのままです。", "comboSuggest.exclude.saveFailed": "除外したプロバイダを保存できませんでした。", - "comboSuggest.exclude.none": "これらのプロバイダを除外すると、おすすめはありません。", + "comboSuggest.exclude.none": "表示できる候補はありません。", + "comboSuggest.exclude.loadFailed": "除外したプロバイダーを読み込めませんでした。", + "comboSuggest.saveChanged": "候補の設定が変更されたか、確認できませんでした。コンボを更新して再試行してください。", "comboSuggest.showAll": "すべて表示({count} 件)", "comboSuggest.showFewer": "折りたたむ", "comboSuggest.tier.ownSubscription": "提供元のサブスクリプション", diff --git a/gui/src/i18n/ko.ts b/gui/src/i18n/ko.ts index 78ed3351a2b..8c962efe4e5 100644 --- a/gui/src/i18n/ko.ts +++ b/gui/src/i18n/ko.ts @@ -4558,7 +4558,9 @@ export const ko: Record = { "comboSuggest.exclude.head": "추천 조합에서 제외", "comboSuggest.exclude.hint": "해당 모델은 추천 조합에 들어가지 않습니다. 이미 만든 조합은 그대로입니다.", "comboSuggest.exclude.saveFailed": "제외한 제공자를 저장하지 못했습니다.", - "comboSuggest.exclude.none": "이 제공자들을 제외하면 남은 추천이 없습니다.", + "comboSuggest.exclude.none": "표시할 추천이 없습니다.", + "comboSuggest.exclude.loadFailed": "제외한 공급자를 불러오지 못했습니다.", + "comboSuggest.saveChanged": "추천 설정이 변경되었거나 확인할 수 없습니다. 콤보를 새로고침한 후 다시 시도하세요.", "comboSuggest.showAll": "전체 {count}개 보기", "comboSuggest.showFewer": "접기", "comboSuggest.tier.ownSubscription": "제작사 구독", diff --git a/gui/src/i18n/pt.ts b/gui/src/i18n/pt.ts index 3b088a2f45c..a0d1d3af875 100644 --- a/gui/src/i18n/pt.ts +++ b/gui/src/i18n/pt.ts @@ -4531,7 +4531,9 @@ export const pt: Record = { "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.saveFailed": "Não foi possível salvar os provedores excluídos.", - "comboSuggest.exclude.none": "Sem sugestões com esses provedores excluídos.", + "comboSuggest.exclude.none": "Nenhuma sugestão para exibir.", + "comboSuggest.exclude.loadFailed": "Não foi possível carregar os provedores excluídos.", + "comboSuggest.saveChanged": "As configurações de sugestões mudaram ou não puderam ser verificadas. Atualize Combos e tente novamente.", "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 60e759be17f..6f5c26ff3bd 100644 --- a/gui/src/i18n/ru.ts +++ b/gui/src/i18n/ru.ts @@ -4559,7 +4559,9 @@ export const ru: Record = { "comboSuggest.exclude.head": "Не предлагать в комбо", "comboSuggest.exclude.hint": "Их модели не попадут в предлагаемые комбо; уже созданные комбо не меняются.", "comboSuggest.exclude.saveFailed": "Не удалось сохранить исключённых провайдеров.", - "comboSuggest.exclude.none": "С этими исключениями предложений не осталось.", + "comboSuggest.exclude.none": "Нет рекомендаций для показа.", + "comboSuggest.exclude.loadFailed": "Не удалось загрузить список исключённых провайдеров.", + "comboSuggest.saveChanged": "Настройки рекомендаций изменились или их не удалось проверить. Обновите список комбо и повторите попытку.", "comboSuggest.showAll": "Показать все ({count})", "comboSuggest.showFewer": "Свернуть", "comboSuggest.tier.ownSubscription": "подписка создателя модели", diff --git a/gui/src/i18n/tr.ts b/gui/src/i18n/tr.ts index 1db643a20cb..f48063004ff 100644 --- a/gui/src/i18n/tr.ts +++ b/gui/src/i18n/tr.ts @@ -4559,7 +4559,9 @@ export const tr: Record = { "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.saveFailed": "Hariç tutulan sağlayıcılar kaydedilemedi.", - "comboSuggest.exclude.none": "Bu sağlayıcılar hariç tutulunca öneri kalmadı.", + "comboSuggest.exclude.none": "Gösterilecek öneri yok.", + "comboSuggest.exclude.loadFailed": "Hariç tutulan sağlayıcılar yüklenemedi.", + "comboSuggest.saveChanged": "Öneri ayarları değişti veya doğrulanamadı. Komboları yenileyip tekrar deneyin.", "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 d85c0317ee5..395518072bb 100644 --- a/gui/src/i18n/vi.ts +++ b/gui/src/i18n/vi.ts @@ -4528,7 +4528,9 @@ export const vi: Record = { "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.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.exclude.none": "Không có đề xuất để hiển thị.", + "comboSuggest.exclude.loadFailed": "Không thể tải danh sách nhà cung cấp bị loại trừ.", + "comboSuggest.saveChanged": "Cài đặt đề xuất đã thay đổi hoặc không thể xác minh. Hãy làm mới danh sách combo và thử lại.", "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 3ee5ba2f41a..ad92ee3926d 100644 --- a/gui/src/i18n/zh-TW.ts +++ b/gui/src/i18n/zh-TW.ts @@ -4522,7 +4522,9 @@ export const zhTW: Record = { "comboSuggest.exclude.head": "不參與推薦組合", "comboSuggest.exclude.hint": "它們的模型不會出現在推薦組合裡;你已建好的組合不受影響。", "comboSuggest.exclude.saveFailed": "排除的供應商沒能儲存。", - "comboSuggest.exclude.none": "排除這些供應商後,沒有可推薦的組合了。", + "comboSuggest.exclude.none": "沒有可顯示的建議。", + "comboSuggest.exclude.loadFailed": "無法載入已排除的供應商。", + "comboSuggest.saveChanged": "建議設定已變更或無法驗證。請重新整理組合後再試。", "comboSuggest.showAll": "顯示全部 {count} 條", "comboSuggest.showFewer": "收起", "comboSuggest.tier.ownSubscription": "原廠訂閱", diff --git a/gui/src/i18n/zh.ts b/gui/src/i18n/zh.ts index 6ba8edc6336..8e2d26299ca 100644 --- a/gui/src/i18n/zh.ts +++ b/gui/src/i18n/zh.ts @@ -4557,7 +4557,9 @@ export const zh: Record = { "comboSuggest.exclude.head": "不参与推荐组合", "comboSuggest.exclude.hint": "它们的模型不会出现在推荐组合里;你已建好的组合不受影响。", "comboSuggest.exclude.saveFailed": "排除的供应商没能保存。", - "comboSuggest.exclude.none": "排除这些供应商后,没有可推荐的组合了。", + "comboSuggest.exclude.none": "暂无建议。", + "comboSuggest.exclude.loadFailed": "无法加载已排除的提供商。", + "comboSuggest.saveChanged": "建议设置已更改或无法验证。请刷新组合后重试。", "comboSuggest.showAll": "显示全部 {count} 条", "comboSuggest.showFewer": "收起", "comboSuggest.tier.ownSubscription": "原厂订阅", diff --git a/gui/src/pages/Combos.tsx b/gui/src/pages/Combos.tsx index 1d4985a2bc3..214cfa06034 100644 --- a/gui/src/pages/Combos.tsx +++ b/gui/src/pages/Combos.tsx @@ -26,6 +26,8 @@ type ProviderOption = { disabled?: boolean; hiddenFromPicker?: boolean; authMode?: string; + googleMode?: "ai-studio" | "vertex" | "cloud-code-assist"; + vertexCredentialKind?: "marker" | "ambient" | "reference" | "api-key"; adapter?: string; baseUrl?: string; defaultModel?: string; @@ -47,6 +49,8 @@ type ProviderDto = { defaultModel?: string; models?: string[]; authMode?: string; + googleMode?: "ai-studio" | "vertex" | "cloud-code-assist"; + vertexCredentialKind?: "marker" | "ambient" | "reference" | "api-key"; }; type ConfigDto = { providers?: Record }; type CachedCombosPage = { @@ -174,6 +178,8 @@ export default function Combos({ disabled: !!p.disabled, hiddenFromPicker: p.adapter === "jev-decision" || !Object.hasOwn(visibleProviders, name), authMode: p.authMode, + googleMode: p.googleMode, + vertexCredentialKind: p.vertexCredentialKind, adapter: p.adapter, baseUrl: p.baseUrl, ...(typeof p.defaultModel === "string" ? { defaultModel: p.defaultModel } : {}), diff --git a/gui/tests/combo-suggestions.test.tsx b/gui/tests/combo-suggestions.test.tsx index 91471747b5a..3793293acf0 100644 --- a/gui/tests/combo-suggestions.test.tsx +++ b/gui/tests/combo-suggestions.test.tsx @@ -1,6 +1,6 @@ import { afterEach, beforeEach, describe, expect, test } from "bun:test"; import { Window } from "happy-dom"; -import { act } from "react"; +import { act, useEffect } from "react"; import type { Root } from "react-dom/client"; import { buildComboSuggestions, @@ -17,6 +17,7 @@ import { import { isValidComboId, toPutBody, type ComboItem } from "../src/combo-workspace-data"; import { ComboSuggestions, type ComboSuggestionsProps } from "../src/components/route-board/ComboSuggestions"; import { useSuggestionExclusions, type SuggestionExclusions } from "../src/components/route-board/use-suggestion-exclusions"; +import { WorkspaceSuggestions } from "../src/components/route-board/WorkspaceSuggestions"; import { LanguageProvider } from "../src/i18n/provider"; const combo = (id: string, targets: Array<[string, string]>, extra: Partial = {}): ComboItem => ({ @@ -103,8 +104,9 @@ describe("buildComboSuggestions", () => { 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", () => { + test("consented extensions order subscriptions before Vertex, keys and relays", () => { expect(summary({ + combos: [combo("opus", [["openai", "claude-opus-5-5"]], { allowMeteredTargets: true })], models: models([ ["zayu-claude", "claude-opus-5-5"], ["anthropic-apikey", "claude-opus-5-5"], @@ -112,7 +114,7 @@ describe("buildComboSuggestions", () => { ["cursor", "claude-opus-5.5"], ["anthropic", "claude-opus-5-5"], ]), - })).toEqual(["create claude-opus-5-5: anthropic > cursor > google-vertex > zayu-claude > anthropic-apikey"]); + })).toEqual(["extend opus: anthropic > cursor > google-vertex > zayu-claude > anthropic-apikey"]); }); test("within a tier, more quota left goes first and unknown quota last", () => { @@ -170,17 +172,17 @@ describe("buildComboSuggestions", () => { }); 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 rows = models([["openai", "gpt-5.5"], ["cursor", "gpt-5.5"], ["anthropic", "claude-x"], ["cursor", "claude-x"], ["google-antigravity", "claude-x"]]); const excludedProviders = new Set(["cursor"]); - expect(summary({ models: rows, excludedProviders })).toEqual(["create claude-x: anthropic > zayu-claude"]); + expect(summary({ models: rows, excludedProviders })).toEqual(["create claude-x: anthropic > google-antigravity"]); const combos = [combo("claude-x", [["anthropic", "claude-x"]])]; - expect(summary({ combos, models: rows, excludedProviders })).toEqual(["extend claude-x: zayu-claude"]); + expect(summary({ combos, models: rows, excludedProviders })).toEqual(["extend claude-x: google-antigravity"]); }); 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"]); + const rows = models([["anthropic", "claude-x"], ["google-antigravity", "claude-x"]]); + expect(summary({ combos, models: rows, excludedProviders: new Set(["anthropic"]) })).toEqual(["extend claude-x: google-antigravity"]); expect(summary({ combos, models: rows.slice(0, 1) })).toEqual([]); expect(summary({ models: rows, excludedProviders: new Set(["anthropic"]) })).toEqual([]); }); @@ -200,7 +202,7 @@ describe("drafts", () => { 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 base = combo("opus", [["anthropic", "claude-opus-5-5"], ["zayu-claude", "claude-opus-5-5"], ["anthropic-apikey", "claude-opus-5-5"]], { allowMeteredTargets: true }); const next = extendedCombo(base, [ { provider: "cursor", model: "claude-opus-5.5", tier: "subscription" }, { provider: "relay-2", model: "claude-opus-5-5", tier: "metered" }, @@ -345,7 +347,7 @@ describe("ComboSuggestions card", () => { undefined} @@ -442,7 +444,11 @@ describe("ComboSuggestions card", () => { }) as typeof fetch; try { let state: SuggestionExclusions | null = null; - const Probe = ({ base }: { base: string }) => { state = useSuggestionExclusions(base); return null; }; + const Probe = ({ base }: { base: string }) => { + const exclusions = useSuggestionExclusions(base); + useEffect(() => { state = exclusions; }, [exclusions]); + return null; + }; await mount(); expect(state!.ready).toBe(false); await act(async () => { pending.shift()!({ excludedProviders: ["anthropic"] }); }); @@ -461,6 +467,83 @@ describe("ComboSuggestions card", () => { } }); + test("new cards and drafts omit paid Vertex and API-key members", async () => { + const name = "claude-opus-5-5"; + await mount( [provider, name]))} + providers={PROVIDERS} hiddenModels={new Set()} remainingPercent={() => undefined} + validate={() => null} errorText={() => "bad"} + onCreate={async () => ({ ok: true })} onExtend={async () => ({ ok: true })} + />); + const suggestion = card(name); + expect(suggestion.querySelectorAll(".rb-order-item")).toHaveLength(2); + await act(async () => { button(suggestion, "Generate").click(); }); + expect(suggestion.querySelectorAll(".rb-suggest-members li")).toHaveLength(2); + }); + + test("revoked metered consent blocks Add to combo and shows an error", async () => { + const originalFetch = globalThis.fetch; + const name = "claude-opus-5-5"; + const existing = combo("opus", [["anthropic", name]], { allowMeteredTargets: true }); + let saveCount = 0; + globalThis.fetch = (async (url: string) => { + if (url.endsWith("/api/combos")) return Response.json({ combos: [{ ...existing, allowMeteredTargets: false }] }); + if (url.endsWith("/api/config")) return Response.json({ + providers: Object.fromEntries(PROVIDERS.map((provider) => [provider.name, provider])), + }); + return Response.json({ excludedProviders: [] }); + }) as typeof fetch; + try { + await mount( { saveCount += 1; return { ok: true }; }} + />); + const extension = card("opus"); + expect(extension.textContent).toContain("Vertex"); + await act(async () => { button(extension, "Add to combo").click(); }); + expect(extension.querySelector('[role="alert"]')?.textContent).toContain("Suggestion settings changed"); + expect(saveCount).toBe(0); + } finally { + globalThis.fetch = originalFetch; + } + }); + + test("failed exclusions hide actions until a successful retry", async () => { + const originalFetch = globalThis.fetch; + const pending: Array<(response: Response) => void> = []; + globalThis.fetch = (() => new Promise((resolve) => pending.push(resolve))) as typeof fetch; + try { + await mount( ({ ok: true })} + />); + const visibleButtons = () => [...host.querySelectorAll("button")].map((item) => item.textContent?.trim()); + expect(visibleButtons()).not.toContain("Generate"); + await act(async () => { pending.shift()!(new Response(null, { status: 500 })); }); + expect(visibleButtons()).not.toContain("Generate"); + expect(host.querySelector('[role="alert"]')?.textContent).toContain("Could not load"); + await act(async () => { button(host, "Retry").click(); }); + await act(async () => { pending.shift()!(Response.json({ excludedProviders: [] })); }); + expect(visibleButtons()).toContain("Generate"); + } finally { + globalThis.fetch = originalFetch; + } + }); + + test("after dismissing the last card the exclusion control still works", async () => { + exclusionWrites.length = 0; + await render([], []); + await act(async () => { button(card("claude-opus-5-5"), "Dismiss").click(); }); + await act(async () => { button(card("gemini-3.8-flash"), "Dismiss").click(); }); + expect(host.querySelectorAll(".rb-suggest-card")).toHaveLength(0); + await act(async () => { button(host, "Exclude providers…").click(); }); + await act(async () => { host.querySelector('input[type="checkbox"]')!.click(); }); + expect(exclusionWrites[0]).toHaveLength(1); + }); + test("without an exclusion handler there is no exclude control", async () => { await render(); expect(host.querySelector(".rb-suggest-exclude")).toBeNull(); @@ -484,11 +567,12 @@ test("another model on the same provider does not hide a missing channel", () => expect(suggestion?.members.map(({ provider, model }) => [provider, model])).toEqual([["cursor", name]]); }); -test("the create and extension requests mark pay-per-use targets as metered", () => { - const member = { provider: "anthropic-apikey", model: "claude-opus-5-5", tier: "metered" } as const; - expect(toPutBody(suggestionDraft("opus", [member])).combo.targets[0]?.metered).toBe(true); +test("only consented extensions serialize paid targets, without writing consent", () => { + const member = { provider: "google-vertex", model: "claude-opus-5-5", tier: "vertex" } as const; + expect(suggestionDraft("opus", [member]).targets).toEqual([]); const current = combo("opus", [["anthropic", member.model]]); - const body = toPutBody(extendedCombo(current, [member], () => "own-subscription")).combo; + expect(extendedCombo(current, [member], () => "own-subscription").targets).toEqual(current.targets); + const body = toPutBody(extendedCombo({ ...current, allowMeteredTargets: true }, [member], () => "own-subscription")).combo; expect(body.targets.map(({ metered }) => metered)).toEqual([undefined, true]); expect(body).not.toHaveProperty("allowMeteredTargets"); }); diff --git a/structure/dashboard-and-usage.md b/structure/dashboard-and-usage.md index 965de459d8a..8261643b081 100644 --- a/structure/dashboard-and-usage.md +++ b/structure/dashboard-and-usage.md @@ -501,7 +501,7 @@ Dashboard overview polling observes authorization failures independently of stal The [explicit model-capability contract](config.md#explicit-per-model-capability-declarations) preserves operator declarations through provider storage and catalog capture; it does not infer upstream capability or change this surface's routing behavior. -Exact [model input declarations](config.md#explicit-per-model-capability-declarations) now feed text-only eligibility and catalog hints; existing image-description/omission handling consumes them before the main upstream send. The Combos page sends non-image members as the request-only `visionSidecarTargets` field on `PUT /api/combos` whenever the Image switch is enabled, so text-only enrollment needs no manual provider edit. The GUI classifies members from the authoritative `visionSidecarConsumer` flag served on `/api/models` rows, so a member covered only by legacy `noVisionModels` keeps its sidecar classification after reload. Members whose modalities are unknown or have no text input keep the switch unavailable and are named in the hint; a member later removed from the combo keeps its provider declaration until cleared in the provider editor. `gui/src/components/route-board/WorkspaceSuggestions.tsx` renders suggestion cards inside the Combos workspace. Generation uses the existing combo save flow, and extension is held while that combo has unsaved workspace edits. Dismissals are browser-local. Provider exclusions are persisted by the management API. Suggested pay-per-use targets retain metered consent requirements. +Exact [model input declarations](config.md#explicit-per-model-capability-declarations) now feed text-only eligibility and catalog hints; existing image-description/omission handling consumes them before the main upstream send. The Combos page sends non-image members as the request-only `visionSidecarTargets` field on `PUT /api/combos` whenever the Image switch is enabled, so text-only enrollment needs no manual provider edit. The GUI classifies members from the authoritative `visionSidecarConsumer` flag served on `/api/models` rows, so a member covered only by legacy `noVisionModels` keeps its sidecar classification after reload. Members whose modalities are unknown or have no text input keep the switch unavailable and are named in the hint; a member later removed from the combo keeps its provider declaration until cleared in the provider editor. `gui/src/components/route-board/WorkspaceSuggestions.tsx` renders suggestion cards inside the Combos workspace. Generation uses the existing combo save flow, and extension is held while that combo has unsaved workspace edits. Dismissals are browser-local. Provider exclusions are persisted by the management API. The workspace gates cards on a successful exclusion read for the current proxy and offers a retry on failure. The exclusion control remains available after the last card is dismissed. New drafts use unmetered targets. Extensions offer metered targets, including Vertex, only with existing explicit combo consent. The save path rechecks live provider configuration and combo consent, and the combo write leaves consent management to the existing server policy. The raw provider editor round-trips `autoReviewModel` and `autoReviewModelOverrides` through editor-owned DTO fields. POST/PATCH/PUT share validation; PUT copies schema-normalized values into the persisted and live candidate before adoption. Canonical `openai` rejects these fields, including clear forms. Field-masked writes (PATCH, editor PUT, reload) pin every registry-seed key and ignore operator overlays the seed never defines, most commonly `selectedModels`; POST keeps the exact-key comparison. Canonical `openai` still rejects `allowPrivateNetwork`, which must not short-circuit destination DNS checks on the ChatGPT forward row. Existing authentication, origin checks and stale-baseline protection still govern the writes. See [reviewer projection](catalog.md#provider-scoped-approval-reviewer). Stored Direct substitution follows the [credential identity contract](providers/openai-accounts.md#sidecars-management-and-ui): both synchronous and asynchronous materializers discard the caller account header before applying the stored credential; ordinary native Direct passthrough is unchanged. From a92582277504d9e6cad3d145ef2a4e0e1b5b971a Mon Sep 17 00:00:00 2001 From: JUN Date: Thu, 19 Nov 2026 00:35:01 +0900 Subject: [PATCH 03/23] fix(combos): enforce suggestion policy at config commit Co-authored-by: Andrew (agent) --- .../src/content/docs/es/guides/combos.md | 2 + .../docs/es/reference/management-api.md | 1 + docs-site/src/content/docs/guides/combos.md | 2 + .../content/docs/reference/management-api.md | 1 + gui/src/combo-suggestions.ts | 74 +-------- .../route-board/WorkspaceSuggestions.tsx | 149 +++++++++--------- gui/src/pages/Combos.tsx | 2 +- gui/tests/combo-suggestions.test.tsx | 22 +-- src/combos/suggestion-channel.ts | 72 +++++++++ src/server/management/combo-routes.ts | 2 +- .../management/combo-suggestion-routes.ts | 114 +++++++++++++- src/server/management/route-registry.ts | 1 + structure/config.md | 2 +- structure/gui-and-management-api.md | 2 +- tests/server/combo-suggestion-routes.test.ts | 70 +++++++- 15 files changed, 349 insertions(+), 167 deletions(-) create mode 100644 src/combos/suggestion-channel.ts diff --git a/docs-site/src/content/docs/es/guides/combos.md b/docs-site/src/content/docs/es/guides/combos.md index 69b88e647a9..5a7612bba4e 100644 --- a/docs-site/src/content/docs/es/guides/combos.md +++ b/docs-site/src/content/docs/es/guides/combos.md @@ -790,4 +790,6 @@ Un rechazo estructurado de esfuerzo puede bajar una posición publicada cada vez ## Combos sugeridos +Si los ajustes cambian antes de guardar una sugerencia, Combos actualiza las sugerencias y muestra un mensaje. Al guardar, se comprueban las exclusiones y el consentimiento de gasto vigentes. + En el espacio de trabajo de combos, **Generar** abre un borrador de conmutación por error para un modelo disponible en varios proveedores. **Añadir al combo** ofrece destinos que faltan en un combo existente. Las tarjetas descartadas quedan ocultas en este navegador. Usa **Excluir un proveedor…** para filtrar ambos tipos de sugerencias. El proxy guarda la selección como `comboSuggestionExcludedProviders` en `config.json`. Los miembros existentes se conservan. Los borradores nuevos usan destinos sin medición. Las ampliaciones ofrecen destinos de pago por uso, incluido Vertex, solo si el combo ya permite destinos medidos. El panel comprueba la configuración actual antes de guardar. El control de exclusión sigue disponible tras descartar todas las tarjetas. Si falla la carga de la lista de exclusión, vuelve a intentarlo para ver las sugerencias. diff --git a/docs-site/src/content/docs/es/reference/management-api.md b/docs-site/src/content/docs/es/reference/management-api.md index 0a2478fd9d9..c2c2583c14d 100644 --- a/docs-site/src/content/docs/es/reference/management-api.md +++ b/docs-site/src/content/docs/es/reference/management-api.md @@ -218,6 +218,7 @@ Las instantáneas de sesión incluyen `resumable`. Se vuelve cierto sólo despu | --- | --- | --- | | `GET /api/combos` | Lista de combos normalizados y sus ID de modelo público | El trabajo del catálogo puede devolver `catalog_busy` | | `PUT /api/combos` | Crea, sustituye o renombra un combo. | 400 si el identificador, destino, configuración o cambio de nombre son inválidos, o hay una colisión ordinaria; un 400 de validación también identifica el primer campo superior inválido en `field`, por ejemplo `targets` o `decisionProvider`. 409 si hay colisión con el espacio de nombres de una cuenta Codex. | +| `POST /api/combo-suggestions/save` | Guarda pares de proveedor y modelo sugeridos con `{ id, mode: "create" o "append", targets }` | 400 solicitud inválida; 409 si el consentimiento, las exclusiones, la disponibilidad o el estado del combo impiden guardar | | `DELETE /api/combos?id=...` | Eliminar un combo y borrar su estado de selección/enfriamiento | 400 id ausente; 404 combo desconocido | Consulte [Combos](/es/guides/combos/) para conocer las estrategias de destino, los tiempos de reutilización, los alias y los fallos de enrutamiento. diff --git a/docs-site/src/content/docs/guides/combos.md b/docs-site/src/content/docs/guides/combos.md index b90246f65c5..c237d817479 100644 --- a/docs-site/src/content/docs/guides/combos.md +++ b/docs-site/src/content/docs/guides/combos.md @@ -1216,4 +1216,6 @@ untried targets and newer failures keep their cooldowns. ## Suggested combos +When settings change before a suggestion is saved, Combos refreshes the suggestions and displays a message. Saving checks the current exclusions and spend consent. + In the Combos workspace, **Generate** opens a failover draft for a model served by multiple providers. **Add to combo** offers missing targets for an existing combo. Dismissed cards stay hidden in this browser. Use **Exclude providers…** to filter both kinds of suggestions. The proxy stores your selection as `comboSuggestionExcludedProviders` in `config.json`. Existing combo members stay in place. New drafts use unmetered targets. Extensions offer pay-per-use targets, including Vertex, only when the combo already allows metered targets. The dashboard checks the current configuration before saving. The exclusion control stays available when all cards are dismissed. If the exclusion list fails to load, retry the read to see suggestions. diff --git a/docs-site/src/content/docs/reference/management-api.md b/docs-site/src/content/docs/reference/management-api.md index 97941a8f94a..15d9b69b76b 100644 --- a/docs-site/src/content/docs/reference/management-api.md +++ b/docs-site/src/content/docs/reference/management-api.md @@ -247,6 +247,7 @@ completes. | --- | --- | --- | | `GET /api/combos` | List normalized combos and their public model ids | Catalog work can return `catalog_busy` | | `PUT /api/combos` | Create, replace, or rename one combo | 400 invalid id, target, config, rename, or ordinary collision (a combo validation 400 also names the first invalid top-level field in `field`, for example `targets` or `decisionProvider`); 409 Codex-account namespace collision | +| `POST /api/combo-suggestions/save` | Save suggested provider/model pairs using `{ id, mode: "create" or "append", targets }` | 400 invalid request; 409 when current consent, exclusions, provider availability, or combo state prevents the save | | `DELETE /api/combos?id=...` | Delete one combo and clear its selection/cooldown state | 400 missing id; 404 unknown combo | See [Combos](/guides/combos/) for target strategies, cooldowns, aliases, and routing failures. diff --git a/gui/src/combo-suggestions.ts b/gui/src/combo-suggestions.ts index be77ec57902..34e098181bc 100644 --- a/gui/src/combo-suggestions.ts +++ b/gui/src/combo-suggestions.ts @@ -9,30 +9,15 @@ * capability) and a trailing reasoning-effort suffix is dropped. */ import { COMBO_ID_RE, emptyDraft, newComboTarget, type ComboItem } from "./combo-workspace-data"; +import { channelTier, EFFORT_SUFFIX, isMeteredTier, normalizeModelName, TIER_RANK, type ChannelTier, type SuggestionProvider } from "../../src/combos/suggestion-channel"; +export { channelTier, isMeteredTier, normalizeModelName, type ChannelTier, type SuggestionProvider }; -export interface SuggestionProvider { - name: string; - disabled?: boolean; - hiddenFromPicker?: boolean; - authMode?: string; - googleMode?: string; - vertexCredentialKind?: 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; @@ -63,67 +48,12 @@ export type ComboSuggestion = members: SuggestedMember[]; }; -/** No `max`: it names distinct models (`gpt-5.1-codex-max` is not `gpt-5.1-codex` at max effort). */ -const EFFORT_SUFFIX = /-(?:minimal|low|medium|high|xhigh)$/; - -/** - * 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`; - * `gpt-5.1-codex-max-high` is `gpt-5-1-codex-max`). - */ -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 (provider.googleMode === "vertex" || provider.vertexCredentialKind || /(?:^|[.-])aiplatform\.googleapis\.com$/.test(host) || /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"; -} - -export function isMeteredTier(tier: ChannelTier): boolean { - return tier === "metered" || tier === "vertex"; -} - /** Tier first; within a tier more quota left first, unknown quota after; then catalog order. */ export function orderMembers(members: readonly SuggestedMember[]): SuggestedMember[] { return members diff --git a/gui/src/components/route-board/WorkspaceSuggestions.tsx b/gui/src/components/route-board/WorkspaceSuggestions.tsx index 6de8d1b6b2c..38b43fe67fe 100644 --- a/gui/src/components/route-board/WorkspaceSuggestions.tsx +++ b/gui/src/components/route-board/WorkspaceSuggestions.tsx @@ -1,5 +1,5 @@ -import { channelTier, extendedCombo, isMeteredTier, type SuggestionProvider } from "../../combo-suggestions"; -import { parseComboList, validateComboDraft, type ComboItem } from "../../combo-workspace-data"; +import { useState } from "react"; +import { validateComboDraft, type ComboItem } from "../../combo-workspace-data"; import { useT } from "../../i18n/shared"; import { freshQuotaReportsFromResponse } from "../../provider-workspace/report"; import { buildQuotaSummary } from "../../quota-summary"; @@ -8,8 +8,9 @@ import { comboDraftErrorText } from "../combo-workspace-utils"; import { ComboSuggestions } from "./ComboSuggestions"; import { useSuggestionExclusions } from "./use-suggestion-exclusions"; -type Props = Pick & { +type Props = Pick & { apiBase: string; + onRefresh: () => void; active: boolean; hiddenModels?: string[]; quotaReports: unknown; @@ -20,91 +21,87 @@ type Props = Pick - {t("comboSuggest.exclude.loadFailed")} - - - ) : null; - } + + const [conflict, setConflict] = useState(false); const saveSuggestion = async (item: ComboItem, isCreate: boolean) => { - const failure = { ok: false, error: t("comboSuggest.saveChanged") }; + setConflict(false); + const failure = { ok: false, error: t("cws.saveFailed") }; + const previous = props.combos.find((combo) => combo.id === item.id); + const targets = item.targets.filter(({ provider, model }) => isCreate + || !previous?.targets.some((target) => target.provider === provider && target.model === model)) + .map(({ provider, model }) => ({ provider, model })); try { - const [configResponse, exclusionResponse, combosResponse] = await Promise.all([ - fetch(`${props.apiBase}/api/config`), - fetch(`${props.apiBase}/api/combo-suggestions`), - isCreate ? undefined : fetch(`${props.apiBase}/api/combos`), - ]); - if (!configResponse.ok || !exclusionResponse.ok || (combosResponse && !combosResponse.ok)) return failure; - const config = await configResponse.json() as { - providers?: Record>; - }; - const { excludedProviders } = await exclusionResponse.json() as { excludedProviders?: unknown }; - if (!Array.isArray(excludedProviders) || excludedProviders.some((name) => typeof name !== "string")) return failure; - const excluded = new Set(excludedProviders); - const old = props.combos.find((combo) => combo.id === item.id); - const live = combosResponse && parseComboList(await combosResponse.json()).find((combo) => combo.id === item.id); - if (!isCreate && (!old || !live)) return failure; - const hasTarget = (combo: ComboItem | undefined, provider: string, model: string) => - combo?.targets.some((target) => target.provider === provider && target.model === model); - const liveProviders = new Map(Object.entries(config.providers ?? {}).map(([name, provider]) => [name, { ...provider, name }])); - const tierOf = (provider: string, model: string) => { - const current = liveProviders.get(provider); - return current ? channelTier(current, model) : "metered"; - }; - const proposed = item.targets.filter(({ provider, model }) => isCreate || !hasTarget(old, provider, model)); - const additions = proposed.filter(({ provider, model }) => !live || !hasTarget(live, provider, model)) - .map(({ provider, model }) => ({ provider, model, tier: tierOf(provider, model) })); - if (!additions.length || additions.some(({ provider, tier }) => { - const current = liveProviders.get(provider); - return !current || current.disabled || current.adapter === "jev-decision" - || excluded.has(provider) - || (isMeteredTier(tier) && (!live || live.allowMeteredTargets !== true)); - })) return failure; - return await props.onSave(live ? extendedCombo(live, additions, tierOf) : item, isCreate); + const response = await fetch(`${props.apiBase}/api/combo-suggestions/save`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ id: item.id, mode: isCreate ? "create" : "append", targets }), + }); + if (response.status === 409) { + setConflict(true); + exclusions.retry(); + props.onRefresh(); + return { ok: false, error: "" }; + } + if (!response.ok) return failure; + props.onRefresh(); + return { ok: true }; } catch { return failure; } }; + const conflictAlert = conflict &&

{t("comboSuggest.saveChanged")}

; + if (!exclusions.ready) { + return <> + {conflictAlert} + {exclusions.failed && ( +
+ {t("comboSuggest.exclude.loadFailed")} + +
+ )} + ; + } const providerMap = Object.fromEntries(props.providers.map((provider) => [provider.name, provider])); const reports = freshQuotaReportsFromResponse(props.quotaReports, props.quotaNow); const quota = new Map(buildQuotaSummary(reports, (provider) => provider) .filter((row) => !row.passive) .map((row) => [row.provider, row.windows])); return ( - { - const used = (quota.get(provider) ?? []).flatMap((window) => { - const family = (window.label ?? "").toLowerCase().split(/[\s(]/)[0]; - const matches = window.modelId - ? window.modelId.toLowerCase() === model.toLowerCase() - : !family || window.labelKey !== undefined || model.toLowerCase().startsWith(family); - return matches && window.percent !== undefined ? [window.percent] : []; - }); - return used.length ? Math.max(0, Math.min(100, 100 - Math.max(...used))) : undefined; - }} - validate={(item, isCreate) => { - const others = props.combos.filter((combo) => isCreate || combo.id !== item.id); - return validateComboDraft(item, { - existingIds: others.map((combo) => combo.id), - existingAliases: others.flatMap((combo) => combo.alias ? [combo.alias] : []), - combos: others, - isCreate, - providers: providerMap, - }); - }} - errorText={(code, item) => comboDraftErrorText(t, code, item, providerMap)} - onCreate={(item) => saveSuggestion(item, true)} - onExtend={(item) => saveSuggestion(item, false)} - excludedProviders={exclusions.excluded} - onExcludedChange={exclusions.save} - /> + <> + {conflictAlert} + { + const used = (quota.get(provider) ?? []).flatMap((window) => { + const family = (window.label ?? "").toLowerCase().split(/[\s(]/)[0]; + const matches = window.modelId + ? window.modelId.toLowerCase() === model.toLowerCase() + : !family || window.labelKey !== undefined || model.toLowerCase().startsWith(family); + return matches && window.percent !== undefined ? [window.percent] : []; + }); + return used.length ? Math.max(0, Math.min(100, 100 - Math.max(...used))) : undefined; + }} + validate={(item, isCreate) => { + const others = props.combos.filter((combo) => isCreate || combo.id !== item.id); + return validateComboDraft(item, { + existingIds: others.map((combo) => combo.id), + existingAliases: others.flatMap((combo) => combo.alias ? [combo.alias] : []), + combos: others, + isCreate, + providers: providerMap, + }); + }} + errorText={(code, item) => comboDraftErrorText(t, code, item, providerMap)} + onCreate={(item) => saveSuggestion(item, true)} + onExtend={(item) => saveSuggestion(item, false)} + excludedProviders={exclusions.excluded} + onExcludedChange={exclusions.save} + /> + ); } diff --git a/gui/src/pages/Combos.tsx b/gui/src/pages/Combos.tsx index 214cfa06034..e9f4d04187a 100644 --- a/gui/src/pages/Combos.tsx +++ b/gui/src/pages/Combos.tsx @@ -473,7 +473,7 @@ export default function Combos({ quotaReports={quotaReports} quotaNow={quotaNow} lockedComboId={lockedComboId} - onSave={saveCombo} + onRefresh={() => resource.refresh()} /> )} onSave={saveCombo} diff --git a/gui/tests/combo-suggestions.test.tsx b/gui/tests/combo-suggestions.test.tsx index 3793293acf0..3c0014c2e62 100644 --- a/gui/tests/combo-suggestions.test.tsx +++ b/gui/tests/combo-suggestions.test.tsx @@ -485,26 +485,28 @@ describe("ComboSuggestions card", () => { const originalFetch = globalThis.fetch; const name = "claude-opus-5-5"; const existing = combo("opus", [["anthropic", name]], { allowMeteredTargets: true }); - let saveCount = 0; + let refreshCount = 0; + let exclusionReads = 0; globalThis.fetch = (async (url: string) => { - if (url.endsWith("/api/combos")) return Response.json({ combos: [{ ...existing, allowMeteredTargets: false }] }); - if (url.endsWith("/api/config")) return Response.json({ - providers: Object.fromEntries(PROVIDERS.map((provider) => [provider.name, provider])), - }); - return Response.json({ excludedProviders: [] }); + if (url.endsWith("/api/combo-suggestions/save")) { + return Response.json({ code: "suggestion_consent_required" }, { status: 409 }); + } + exclusionReads += 1; + return Response.json({ excludedProviders: exclusionReads > 1 ? ["google-vertex"] : [] }); }) as typeof fetch; try { await mount( { saveCount += 1; return { ok: true }; }} + onRefresh={() => { refreshCount += 1; }} />); const extension = card("opus"); expect(extension.textContent).toContain("Vertex"); await act(async () => { button(extension, "Add to combo").click(); }); - expect(extension.querySelector('[role="alert"]')?.textContent).toContain("Suggestion settings changed"); - expect(saveCount).toBe(0); + expect(host.querySelector('[role="alert"]')?.textContent).toContain("Suggestion settings changed"); + expect(host.textContent).not.toContain("Add to combo"); + expect(refreshCount).toBe(1); } finally { globalThis.fetch = originalFetch; } @@ -518,7 +520,7 @@ describe("ComboSuggestions card", () => { await mount( ({ ok: true })} + quotaReports={null} quotaNow={0} lockedComboId={null} onRefresh={() => {}} />); const visibleButtons = () => [...host.querySelectorAll("button")].map((item) => item.textContent?.trim()); expect(visibleButtons()).not.toContain("Generate"); diff --git a/src/combos/suggestion-channel.ts b/src/combos/suggestion-channel.ts new file mode 100644 index 00000000000..15345c79bb0 --- /dev/null +++ b/src/combos/suggestion-channel.ts @@ -0,0 +1,72 @@ +export interface SuggestionProvider { + name: string; + disabled?: boolean; + hiddenFromPicker?: boolean; + authMode?: string; + googleMode?: string; + vertexCredentialKind?: string; + adapter?: string; + baseUrl?: 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"; +export const TIER_RANK: Record = { "own-subscription": 0, subscription: 1, vertex: 2, metered: 3 }; + +/** No `max`: it names distinct models (`gpt-5.1-codex-max` is not `gpt-5.1-codex` at max effort). */ +export const EFFORT_SUFFIX = /-(?:minimal|low|medium|high|xhigh)$/; + +/** + * 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`; + * `gpt-5.1-codex-max-high` is `gpt-5-1-codex-max`). + */ +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, ""); +} + +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 (provider.googleMode === "vertex" || provider.vertexCredentialKind || /(?:^|[.-])aiplatform\.googleapis\.com$/.test(host) || /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"; +} + +export function isMeteredTier(tier: ChannelTier): boolean { + return tier === "metered" || tier === "vertex"; +} diff --git a/src/server/management/combo-routes.ts b/src/server/management/combo-routes.ts index 6cdec5369c9..1314713c994 100644 --- a/src/server/management/combo-routes.ts +++ b/src/server/management/combo-routes.ts @@ -171,7 +171,7 @@ export async function handleComboRoutes(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); + if (url.pathname === "/api/combo-suggestions/save" && req.method === "POST") { + return await saveSuggestion(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; } @@ -67,3 +80,96 @@ async function writeExcluded(ctx: ManagementContext): Promise { else config.comboSuggestionExcludedProviders = excluded; return view(ctx); } + +type Target = Pick; + +function parseTargets(value: unknown): Target[] | null { + if (!Array.isArray(value) || !value.length || value.length > MAX_PROVIDERS) return null; + const targets: Target[] = []; + for (const entry of value) { + if (!isPlainRecord(entry) || Object.keys(entry).some(key => key !== "provider" && key !== "model") + || typeof entry.provider !== "string" || typeof entry.model !== "string") return null; + const provider = entry.provider.trim(); + const model = entry.model.trim(); + if (!provider || provider.length > MAX_NAME_LENGTH || !model) return null; + if (!targets.some(target => target.provider === provider && target.model === model)) { + targets.push({ provider, model }); + } + } + return targets; +} + +async function saveSuggestion(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 invalid = () => jsonResponse({ error: "invalid suggested combo", code: "invalid_request" }, 400, req, config); + if (!isPlainRecord(body) || Object.keys(body).some(key => key !== "id" && key !== "mode" && key !== "targets") + || typeof body.id !== "string" || (body.mode !== "create" && body.mode !== "append")) return invalid(); + const id = body.id.trim(); + const targets = parseTargets(body.targets); + if (!targets || !id) return invalid(); + const create = body.mode === "create"; + + const rejected = (code: string, status = 409) => ({ changed: false, value: { code, status } }); + const outcome = mutatePersistedConfig<{ code: string; status: number } | { combos: NonNullable }>(persisted => { + const previous = Object.hasOwn(persisted.combos ?? {}, id) ? persisted.combos![id] : undefined; + if (create ? previous : !previous) return rejected("suggestion_combo_changed"); + + const nextTargets = [...(previous?.targets ?? [])]; + const providerFor = (name: string) => Object.hasOwn(persisted.providers, name) ? persisted.providers[name] : undefined; + const tierOf = ({ provider, model }: Target) => { + const current = providerFor(provider); + return current ? channelTier({ ...current, name: provider }, model) : "metered"; + }; + for (const target of targets) { + if (nextTargets.some(({ provider, model }) => provider.trim() === target.provider && model.trim() === target.model)) continue; + const provider = providerFor(target.provider); + if (!provider || provider.disabled || provider.adapter === "jev-decision") { + return rejected("suggestion_provider_unavailable"); + } + if (persisted.comboSuggestionExcludedProviders?.includes(target.provider)) return rejected("suggestion_provider_excluded"); + const tier = tierOf(target); + const metered = isMeteredTier(tier); + if (metered && previous?.allowMeteredTargets !== true) return rejected("suggestion_consent_required"); + const at = create ? -1 : nextTargets.findIndex(existing => TIER_RANK[tierOf(existing)] > TIER_RANK[tier]); + nextTargets.splice(at < 0 ? nextTargets.length : at, 0, { ...target, ...(metered ? { metered: true } : {}) }); + } + + const combo: OcxComboConfig = { strategy: "failover", ...previous, targets: nextTargets }; + const combos = { ...persisted.combos, [id]: combo }; + const prospective = { ...persisted, combos }; + if (comboConfigIssues(id, combo, persisted.providers, { + requireEnabledTarget: true, + requireUsableDecisionService: true, + combos, + excludeComboId: id, + normalizeDecisionModel: model => normalizeDecisionModelSelector(prospective, model), + }).length) return rejected("invalid_request", 400); + if (codexAccountNamespaceForModel(persisted.codexAccountNamespaces, comboPublicModelId(id, combo))) { + return rejected("suggestion_combo_changed"); + } + if (Object.entries(combos).some(([comboId, row]) => row.decisionModel + && decisionModelRouteError(prospective, comboId, row.decisionModel))) return rejected("invalid_request", 400); + + persisted.combos = combos; + return { changed: nextTargets.length !== (previous?.targets.length ?? 0), value: { combos } }; + }); + if (outcome.status === "unavailable") { + return jsonResponse({ error: "suggestion could not be saved", code: "config_unavailable" }, 409, req, config); + } + if ("code" in outcome.value) { + return jsonResponse({ error: "suggestion could not be saved", code: outcome.value.code }, outcome.value.status, req, config); + } + config.combos = outcome.value.combos; + reconcileLiveStateStores(); + clearComboSelectionState(id); + clearComboTargetCooldowns(id); + const catalogRefresh = await ctx.convergeCodexCatalog(); + return jsonResponse({ success: true, catalogRefresh }, 200, req, config); +} diff --git a/src/server/management/route-registry.ts b/src/server/management/route-registry.ts index 64afa6b4d43..62ea6314c0f 100644 --- a/src/server/management/route-registry.ts +++ b/src/server/management/route-registry.ts @@ -229,6 +229,7 @@ export const MANAGEMENT_ROUTES: readonly ManagementRoute[] = [ // 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." } }, + { method: "POST", path: "/api/combo-suggestions/save", module: "server/management/combo-suggestion-routes", mutates: true, exempt: { reason: "gui-only", why: "Saves additions from dashboard suggestions against current config policy." } }, // 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/structure/config.md b/structure/config.md index 58daba09171..1d15bc64011 100644 --- a/structure/config.md +++ b/structure/config.md @@ -554,7 +554,7 @@ Account quota surfaces use [safe probe diagnostics](transports/inventory.md#acco The OpenCode launcher resolves the existing local management origin from the live bind and configured hub ingress. Its admin credential comes from the existing admin environment/file policy; an absent credential fails without substituting a data key. -The optional `autoReviewOverride` block stores a global approval reviewer selector and enabled flag. The Models settings route validates and normalizes writes, restores the live block when persistence fails before publication, and reports catalog convergence; the dashboard shows pending when the catalog did not commit. Malformed hand edits drop this block without discarding other configuration. Provider `autoReviewModel` and `autoReviewModelOverrides` accept validated final-catalog selectors. Per-model keys preserve case and accept the existing raw/encoded slash equivalence. File-load degradation removes malformed optional selectors only; management writes reject malformed shapes. Omitted provider saves preserve selectors, explicit clears remove them, and raw editor candidates adopt normalized values before persistence and live replacement. See [catalog ownership](catalog.md#provider-scoped-approval-reviewer). The optional `comboSuggestionExcludedProviders` array is owned by `src/config/schema/config-schema.ts`. It accepts up to 256 trimmed, deduplicated provider names of at most 256 characters each. A malformed value is dropped during parsing. Saving an empty list removes the key. The preference filters dashboard suggestions and leaves configured combo targets in place. +The optional `autoReviewOverride` block stores a global approval reviewer selector and enabled flag. The Models settings route validates and normalizes writes, restores the live block when persistence fails before publication, and reports catalog convergence; the dashboard shows pending when the catalog did not commit. Malformed hand edits drop this block without discarding other configuration. Provider `autoReviewModel` and `autoReviewModelOverrides` accept validated final-catalog selectors. Per-model keys preserve case and accept the existing raw/encoded slash equivalence. File-load degradation removes malformed optional selectors only; management writes reject malformed shapes. Omitted provider saves preserve selectors, explicit clears remove them, and raw editor candidates adopt normalized values before persistence and live replacement. See [catalog ownership](catalog.md#provider-scoped-approval-reviewer). The optional `comboSuggestionExcludedProviders` array is owned by `src/config/schema/config-schema.ts`. It accepts up to 256 trimmed, deduplicated provider names of at most 256 characters each. A malformed value is dropped during parsing. Saving an empty list removes the key. The preference filters dashboard suggestions and leaves configured combo targets in place. `src/server/management/combo-suggestion-routes.ts` reads the exclusions, provider metering, and stored combo consent from the same locked persisted snapshot used to save a suggestion. The mutation rechecks those conditions when it rebases. Display-name validation retains prototype-shaped model IDs as data; reviewer-target map validation remains separate and rejects its reserved keys. ## Explicit per-model capability declarations diff --git a/structure/gui-and-management-api.md b/structure/gui-and-management-api.md index 328d76f1736..5dac36c24f5 100644 --- a/structure/gui-and-management-api.md +++ b/structure/gui-and-management-api.md @@ -311,7 +311,7 @@ after the save, and a non-retryable skip (no managed catalog) is a clean save. C | File-integration plans | `src/server/management/integration-routes.ts` and `aside-profile-routes.ts` — `POST /api/client-integrations/preview`, `POST /api/client-integrations/restore/preview`, and `POST /api/client-integrations/aside/profiles/{profileId}/preview`. Management-authenticated, declared non-mutating, and they write nothing: no snapshot, no lock, no maintenance, no recovery. They answer `409 integration_preview_unavailable` rather than gathering a model roster, because discovery refreshes credentials and writes the provider cache. Responses carry only declared managed schema paths, closed change kinds and an opaque fingerprint; no value, filesystem location or selected member identity appears. Mutation routes accept `operation` and `planFingerprint` together or not at all, reject a half-bound request and an operation that disagrees with the change, and answer `409 integration_preview_stale` with a freshly computed plan. Binding is an optimistic token, never authorization. [The integration contract](clients/integrations.md) owns the ordering. | | Grok reset coupons | `src/server/management/grok-coupon-routes.ts` — `GET /api/grok/reset-coupons`, `POST /api/grok/reset-coupons/consume`. The dashboard owner is `gui/src/hooks/useGrokResetCoupons.ts` with `gui/src/components/provider-workspace/GrokResetCoupons.tsx`, wired into the xAI OAuth rows of `ProviderAuthPanel`. Redemption truth is the settled ledger `code`, not the HTTP status: a replayed failure returns 200 with `replayed: true`. See [`providers/xai-grok.md`](providers/xai-grok.md). The route returns `ledger_unavailable` before dispatch when the shared ledger cannot be read or locked; stale uncertain attempts are inspected without another redemption or inferred success. A late inspection refusal or a lost claim replays an identity-matching definitive winner; otherwise it returns `operation_state_changed` (late refusal) or `attempt_in_progress` (lost claim) and never replaces an attempted or terminal record. Unknown-outcome responses include the effective operation ID; the CLI mints it before dispatch. Uncertain and pending attempts live in a module-level hold store shared by all hook instances and mirrored to `sessionStorage` (`ocx.grok-coupon-holds.v1`), so they survive modal close/reopen, remount, and reload for the tab session; the pending hold is written before the POST, only a definitive response for the same `operationId` clears it, and only GET refreshes are allowed after uncertainty. Every response that cannot prove settlement under a supplied operation ID, including pre-open refusals, carries that `operationId`. A definitive failure releases the matching speculative pending hold. Supplied token IDs must be non-empty strings before journal admission, and omitted account/token retries recover the operation’s durable identity within retention. Legacy version-one opens are quarantined rather than dispatched. After confirmed redemption, local settlement has five attempts and four 20 ms waits only for a `ConfigMutationLockError` caused by `SQLITE_BUSY`; any other error or changed claim stops without another redemption. | | Claude reset grants | `src/server/management/anthropic-reset-grant-routes.ts` — `GET /api/anthropic/reset-grants`, `POST /api/anthropic/reset-grants/consume` (lazy-loaded). Wire and fail-closed parsing live in `src/providers/anthropic-reset-grants.ts` (the Claude Code 2.1.278 `cedar_ember` contract, sent with `CLAUDE_CLI_USER_AGENT` from `src/providers/claude-cli-identity.ts`; every bearer request refuses redirects, and a refused claim redirect is an unknown outcome); the journal is `src/providers/anthropic-reset-grant-ledger.ts`: a cross-process `BEGIN IMMEDIATE` lock around every synchronous read-modify-write, a 90 s lease, the operation id reused as the upstream `request_id`, same-id retry only inside the vendor's ten-minute window, at most one unresolved operation per account and organization within each pool's journal and that ten-minute window, whatever grant it names (a new id gets `409 unresolved_prior_operation`), no settlement inferred from a re-read, and a fail-closed `500 journal_write_failed` when an answer cannot be recorded. Spending requires the `gui-session` principal. A journaled `reset`, including a same-id replay of that code, lifts that account cooldown only when it is a 429 quota refusal recorded before the operation was first journaled (the claim fence, `claimedAt`) and the journal's cleared windows cover every window the refusal named (both when it named none); it then drops the cached quota row and rereads usage with its own request rather than joining an older read. Model-family exclusions stay until the usage reread proves a family is no longer rejected. A failed reread leaves them in place. The HTTP result stays the journal answer if the reread fails. Other result codes do not admit. The dashboard owner is `gui/src/hooks/useAnthropicResetGrants.ts` with `gui/src/components/provider-workspace/AnthropicResetGrants.tsx` on the Anthropic OAuth rows of `ProviderAuthPanel`; the dialog re-reads the account when it opens, lets the user choose the grant (default: the selectable grant that expires first; the server re-gates the chosen `grantId`), and after an unknown outcome only retries the same id with no picker shown. Design and audit record: [`../devlog/_fin/260923_claude_reset_grants/010_plan.md`](../devlog/_fin/260923_claude_reset_grants/010_plan.md). | -| Combos | `src/server/management/combo-routes.ts` — `GET/PUT/DELETE /api/combos` own provider combination and failover definitions. `PUT` keeps a stored field the body omits (`cooldownMs`, `waitForCooldownMs`, `defaultEffortMode`, `reasoningEffortMode`, `imageInput`, `cooldownWaitPolicy`, per-target `lastResort`, JEV `decisionQuotaSignals`/`decisionQuotaTiers`/`jevEffortMode`/`sessionPin` on updates/rename); quota false/null clears sparsely and switching away removes quota policy under [the owning contract](providers/jev-decision.md#loaded-advisory-quota). Explicit values replace it and defaults are stored sparse. A combo validation 400 is `{ error, field? }`, where `field` is the top-level combo field of the first issue. `GET /api/combo-suggestions` and `PUT /api/combo-suggestions` use the dashboard-only route in `src/server/management/combo-suggestion-routes.ts`. Both return `{ excludedProviders: string[] }`. PUT validates the full replacement list and persists it before publishing the live value. | +| Combos | `src/server/management/combo-routes.ts` — `GET/PUT/DELETE /api/combos` own provider combination and failover definitions. `PUT` keeps a stored field the body omits (`cooldownMs`, `waitForCooldownMs`, `defaultEffortMode`, `reasoningEffortMode`, `imageInput`, `cooldownWaitPolicy`, per-target `lastResort`, JEV `decisionQuotaSignals`/`decisionQuotaTiers`/`jevEffortMode`/`sessionPin` on updates/rename); quota false/null clears sparsely and switching away removes quota policy under [the owning contract](providers/jev-decision.md#loaded-advisory-quota). Explicit values replace it and defaults are stored sparse. A combo validation 400 is `{ error, field? }`, where `field` is the top-level combo field of the first issue. `GET /api/combo-suggestions` and `PUT /api/combo-suggestions` use the dashboard-only route in `src/server/management/combo-suggestion-routes.ts`. Both return `{ excludedProviders: string[] }`. PUT validates the full replacement list and persists it before publishing the live value. `POST /api/combo-suggestions/save` accepts a combo ID, a create or append mode, and provider/model pairs. The config mutation validates each new target against current provider classification, exclusions, and existing combo spend consent before commit. Create has no spend consent. Conflicts return a fixed reason code and the dashboard refreshes the suggestions. | | Protocol paths | `src/server/management/protocol-routes.ts` (lazy-loaded) — `GET /api/protocols` returns the contract version, the resolved API surfaces and protocol settings, the policy revision and the feature vocabulary; with `?provider=` (one non-empty name of at most 200 characters without control characters, else 400 `invalid_provider`; an unconfigured name is 404 `unknown_provider`, neither echoing the name) it adds a `provider` block from `src/protocols/provider-summary.ts` ([Protocol Paths](data-planes/protocol-paths.md#provider-wire-summary)); `POST /api/protocols/plan` takes `{ model, inbound, features? }` (model at most 200 characters, at most 24 features, any other key refused with 400) and returns a `ProtocolPlanV1` with `basis: "preview"` from `src/protocols/plan-snapshot.ts`. Both are read-only, never log their input, and send nothing upstream. `PATCH /api/protocols/settings` takes `{ messagesEnabled?, unrepresentable?, rollout? }` (strict: unknown keys and wrong types are 400), validates and applies through `src/server/management/protocol-settings-patch.ts`, persists with `saveConfigPreservingClaudeCode`, restores the live config if the save fails (409 on lock contention, 500 otherwise), and answers with the fresh `GET /api/protocols` body; closing Messages also writes `claudeCode.enabled = false` through `commitClaudeCodeBlock` ([Protocol Paths](data-planes/protocol-paths.md#settings)). The CLI drives all three through `ocx api protocols`, `ocx api explain` and `ocx api policy` ([Protocol Paths](data-planes/protocol-paths.md#cli)); none carries a route-registry exemption. | | Workflow budget | `src/server/management/workflow-budget-routes.ts` — `GET /api/workflow-budget` reads the tracked roots or one root, and `POST /api/workflow-budget/clear` clears exactly one. The clear moves the windowed send ring and the child map and nothing else: `active` belongs to turns still in flight, the spend ledger is a token budget an operator did not ask to forgive, and the lifetime send total survives so a clear cannot launder the record. A refusal event carries `spendScope` and `spendLimit` when a token ceiling fired, so the reason is readable without the config open beside it; no scope id is ever attached, because root ids are client thread headers and identity ids are credentials. Both are `deferred-verb` in the route registry — they are owed CLI verbs, and because the ledger is process memory there is no local projection the CLI could read instead. `GET`/`PUT /api/workflow-budget/settings` read and write the per-install count ceilings (`workflowBudget` in config: concurrent turns, sends and distinct children per window); the live config is bound in `src/lib/workflow-budget-config.ts` and read per decision by HTTP admission and the pre-dispatch send ceiling, so a write applies to the next request and never resets a root's usage. The window, interactive reserve and tracked-root bound stay fixed because a root's ring geometry is fixed when it first appears. The GET is `local-transport` (same block via `ocx config get`), the PUT `deferred-verb` with the other budget verbs. See [`../devlog/_fin/260915_workflow_budget_window/030_wfc_diff_plan.md`](../devlog/_fin/260915_workflow_budget_window/030_wfc_diff_plan.md). | | Codex accounts | `src/codex/auth-api/routes.ts` — `GET/POST/DELETE /api/codex-auth/accounts`, `PUT /api/codex-auth/accounts/alias`, `PUT /api/codex-auth/accounts/pause`, `PUT /api/codex-auth/accounts/pause-exhausted`, `POST /api/codex-auth/accounts/clear-cooldown`, `GET/PUT /api/codex-auth/active`, `PUT /api/codex-auth/auto-switch`, `PUT /api/codex-auth/pool-strategy`, `PUT /api/codex-auth/failover`, `GET /api/codex-auth/quota`, `GET /api/codex-auth/reset-credits` with `POST /api/codex-auth/reset-credits/consume`, and the login flow `POST /api/codex-auth/login`, `POST /api/codex-auth/login/code`, `POST /api/codex-auth/login/cancel`, `GET /api/codex-auth/login-status`. Per-account quota activation uses the existing `GET/PUT /api/settings` surface and `src/codex/quota-auto-refresh.ts`, keeping scheduled spending separate from credential/authentication mutation. Account ids are opaque handles and are serialized so the GUI can address an account; emails are masked and tokens are never serialized. New-account config commits add UI-managed selector bindings in the same config save; deletion deliberately retains existing bindings for fail-closed exact routing and re-add stability. Account mutations request catalog convergence only after config durability and expose only the boolean `catalogRefreshPending` completion projection. `showCodexCredits` is a default-off boolean in settings GET and successful PUT; partial PUT accepts a boolean and rolls back on persistence failure. See [credits exposure](providers/openai-accounts.md#display-only-codex-credits). | diff --git a/tests/server/combo-suggestion-routes.test.ts b/tests/server/combo-suggestion-routes.test.ts index 4060277277e..e3e18cda118 100644 --- a/tests/server/combo-suggestion-routes.test.ts +++ b/tests/server/combo-suggestion-routes.test.ts @@ -1,5 +1,5 @@ import { afterEach, beforeEach, expect, test } from "bun:test"; -import { mkdtempSync, readFileSync } from "node:fs"; +import { mkdtempSync, readFileSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { handleManagementAPI } from "../../src/server/management-api"; @@ -7,6 +7,7 @@ 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 { setPersistedConfigMutationBeforeCommitForTests } from "../../src/config/persisted-mutation"; import type { OcxConfig } from "../../src/types"; const previousHome = process.env.OPENCODEX_HOME; @@ -24,6 +25,7 @@ beforeEach(() => { }); afterEach(() => { + setPersistedConfigMutationBeforeCommitForTests(null); if (previousHome === undefined) delete process.env.OPENCODEX_HOME; else process.env.OPENCODEX_HOME = previousHome; removeTreeWithRetry(home); @@ -81,3 +83,69 @@ test("the config schema normalizes hand-edited exclusions and discards malformed expect(parsed.providers.mock).toBeDefined(); } }); + +const paidTarget = { provider: "paid", model: "gemini" }; + +async function saveSuggestion(live: OcxConfig, body: unknown) { + const headers = { ...managementHeaders(), "content-type": "application/json" }; + const url = new URL("http://localhost/api/combo-suggestions/save"); + const response = await handleManagementAPI(new ManagementRequest(url, { + method: "POST", headers, body: JSON.stringify(body), + }), url, live); + return response!; +} + +function seedPaidSuggestion() { + const live = loadConfig(); + live.providers.paid = { ...live.providers.mock!, authMode: "forward", baseUrl: "https://aiplatform.googleapis.com/v1", models: ["gemini"] }; + live.combos = { mix: { strategy: "failover", allowMeteredTargets: true, targets: [{ provider: "mock", model: "m" }] } }; + saveConfig(live); + return live; +} + +for (const code of ["suggestion_consent_required", "suggestion_provider_excluded"]) { + test(`append refuses ${code} when policy changes before commit`, async () => { + const live = seedPaidSuggestion(); + const changePolicy = () => { + const current = onDisk() as unknown as OcxConfig; + if (code === "suggestion_consent_required") delete current.combos!.mix!.allowMeteredTargets; + else current.comboSuggestionExcludedProviders = ["paid"]; + writeFileSync(join(home, "config.json"), JSON.stringify(current)); + }; + setPersistedConfigMutationBeforeCommitForTests(changePolicy); + const response = await saveSuggestion(live, { id: "mix", mode: "append", targets: [paidTarget] }); + expect(response.status).toBe(409); + expect(await response.json()).toMatchObject({ code }); + expect(loadConfig().combos?.mix?.targets).toHaveLength(1); + }); +} + +test("append uses the current combo and marks a consented Vertex target metered", async () => { + const live = seedPaidSuggestion(); + const current = loadConfig(); + current.combos!.mix!.displayName = "Current display name"; + saveConfig(current); + const response = await saveSuggestion(live, { id: "mix", mode: "append", targets: [paidTarget] }); + expect(response.status).toBe(200); + expect(loadConfig().combos?.mix).toMatchObject({ + displayName: "Current display name", allowMeteredTargets: true, + targets: [{ ...paidTarget, metered: true }, { provider: "mock", model: "m" }], + }); + expect(live.combos?.mix?.targets).toHaveLength(2); +}); + +test("create rejects paid Vertex and never accepts consent from the request", async () => { + const live = seedPaidSuggestion(); + const draft = { id: "draft", mode: "create", targets: [paidTarget] }; + expect((await saveSuggestion(live, { ...draft, allowMeteredTargets: true })).status).toBe(400); + const response = await saveSuggestion(live, draft); + expect(response.status).toBe(409); + expect(await response.json()).toMatchObject({ code: "suggestion_consent_required" }); + expect(loadConfig().combos?.draft).toBeUndefined(); + + const current = loadConfig(); + current.providers.mock!.authMode = "forward"; + saveConfig(current); + expect((await saveSuggestion(live, { ...draft, targets: [{ provider: "mock", model: "m" }] })).status).toBe(200); + expect(loadConfig().combos?.draft?.allowMeteredTargets).toBeUndefined(); +}); From 1ace1111a8dfa7e4747506c3152ae58147a34f97 Mon Sep 17 00:00:00 2001 From: JUN Date: Thu, 19 Nov 2026 00:41:42 +0900 Subject: [PATCH 04/23] fix(combos): require spend consent across active and persisted config Co-authored-by: Andrew (agent) --- .../docs/es/reference/management-api.md | 2 +- .../content/docs/reference/management-api.md | 2 +- .../management/combo-suggestion-routes.ts | 16 +++++---- structure/config.md | 2 +- structure/gui-and-management-api.md | 2 +- tests/server/combo-suggestion-routes.test.ts | 35 +++++++++++++++++++ 6 files changed, 48 insertions(+), 11 deletions(-) diff --git a/docs-site/src/content/docs/es/reference/management-api.md b/docs-site/src/content/docs/es/reference/management-api.md index c2c2583c14d..b08ae7471aa 100644 --- a/docs-site/src/content/docs/es/reference/management-api.md +++ b/docs-site/src/content/docs/es/reference/management-api.md @@ -218,7 +218,7 @@ Las instantáneas de sesión incluyen `resumable`. Se vuelve cierto sólo despu | --- | --- | --- | | `GET /api/combos` | Lista de combos normalizados y sus ID de modelo público | El trabajo del catálogo puede devolver `catalog_busy` | | `PUT /api/combos` | Crea, sustituye o renombra un combo. | 400 si el identificador, destino, configuración o cambio de nombre son inválidos, o hay una colisión ordinaria; un 400 de validación también identifica el primer campo superior inválido en `field`, por ejemplo `targets` o `decisionProvider`. 409 si hay colisión con el espacio de nombres de una cuenta Codex. | -| `POST /api/combo-suggestions/save` | Guarda pares de proveedor y modelo sugeridos con `{ id, mode: "create" o "append", targets }` | 400 solicitud inválida; 409 si el consentimiento, las exclusiones, la disponibilidad o el estado del combo impiden guardar | +| `POST /api/combo-suggestions/save` | Guarda pares de proveedor y modelo sugeridos con `{ id, mode: "create" o "append", targets }` | 400 solicitud inválida; 409 si el consentimiento, las exclusiones, la disponibilidad o el estado del combo impiden guardar. Si la configuración activa o la guardada clasifica un destino como de pago, se requiere el consentimiento existente del combo y el destino se guarda como medido. | | `DELETE /api/combos?id=...` | Eliminar un combo y borrar su estado de selección/enfriamiento | 400 id ausente; 404 combo desconocido | Consulte [Combos](/es/guides/combos/) para conocer las estrategias de destino, los tiempos de reutilización, los alias y los fallos de enrutamiento. diff --git a/docs-site/src/content/docs/reference/management-api.md b/docs-site/src/content/docs/reference/management-api.md index 15d9b69b76b..ec286887ebf 100644 --- a/docs-site/src/content/docs/reference/management-api.md +++ b/docs-site/src/content/docs/reference/management-api.md @@ -247,7 +247,7 @@ completes. | --- | --- | --- | | `GET /api/combos` | List normalized combos and their public model ids | Catalog work can return `catalog_busy` | | `PUT /api/combos` | Create, replace, or rename one combo | 400 invalid id, target, config, rename, or ordinary collision (a combo validation 400 also names the first invalid top-level field in `field`, for example `targets` or `decisionProvider`); 409 Codex-account namespace collision | -| `POST /api/combo-suggestions/save` | Save suggested provider/model pairs using `{ id, mode: "create" or "append", targets }` | 400 invalid request; 409 when current consent, exclusions, provider availability, or combo state prevents the save | +| `POST /api/combo-suggestions/save` | Save suggested provider/model pairs using `{ id, mode: "create" or "append", targets }` | 400 invalid request; 409 when consent, exclusions, provider availability, or combo state prevents the save. A target classified as paid in either the active or persisted config requires existing combo consent and is saved as metered. | | `DELETE /api/combos?id=...` | Delete one combo and clear its selection/cooldown state | 400 missing id; 404 unknown combo | See [Combos](/guides/combos/) for target strategies, cooldowns, aliases, and routing failures. diff --git a/src/server/management/combo-suggestion-routes.ts b/src/server/management/combo-suggestion-routes.ts index 48b711e5a9b..9567f3abdb0 100644 --- a/src/server/management/combo-suggestion-routes.ts +++ b/src/server/management/combo-suggestion-routes.ts @@ -122,22 +122,24 @@ async function saveSuggestion(ctx: ManagementContext): Promise { if (create ? previous : !previous) return rejected("suggestion_combo_changed"); const nextTargets = [...(previous?.targets ?? [])]; - const providerFor = (name: string) => Object.hasOwn(persisted.providers, name) ? persisted.providers[name] : undefined; - const tierOf = ({ provider, model }: Target) => { - const current = providerFor(provider); + const providerFor = (snapshot: OcxConfig, name: string) => + Object.hasOwn(snapshot.providers, name) ? snapshot.providers[name] : undefined; + const tierOf = (snapshot: OcxConfig, { provider, model }: Target) => { + const current = providerFor(snapshot, provider); return current ? channelTier({ ...current, name: provider }, model) : "metered"; }; for (const target of targets) { if (nextTargets.some(({ provider, model }) => provider.trim() === target.provider && model.trim() === target.model)) continue; - const provider = providerFor(target.provider); + const provider = providerFor(persisted, target.provider); if (!provider || provider.disabled || provider.adapter === "jev-decision") { return rejected("suggestion_provider_unavailable"); } if (persisted.comboSuggestionExcludedProviders?.includes(target.provider)) return rejected("suggestion_provider_excluded"); - const tier = tierOf(target); - const metered = isMeteredTier(tier); + const tier = tierOf(persisted, target); + const liveTier = tierOf(config, target); + const metered = isMeteredTier(tier) || isMeteredTier(liveTier); if (metered && previous?.allowMeteredTargets !== true) return rejected("suggestion_consent_required"); - const at = create ? -1 : nextTargets.findIndex(existing => TIER_RANK[tierOf(existing)] > TIER_RANK[tier]); + const at = create ? -1 : nextTargets.findIndex(existing => TIER_RANK[tierOf(persisted, existing)] > TIER_RANK[tier]); nextTargets.splice(at < 0 ? nextTargets.length : at, 0, { ...target, ...(metered ? { metered: true } : {}) }); } diff --git a/structure/config.md b/structure/config.md index 1d15bc64011..e4fab2f0aed 100644 --- a/structure/config.md +++ b/structure/config.md @@ -554,7 +554,7 @@ Account quota surfaces use [safe probe diagnostics](transports/inventory.md#acco The OpenCode launcher resolves the existing local management origin from the live bind and configured hub ingress. Its admin credential comes from the existing admin environment/file policy; an absent credential fails without substituting a data key. -The optional `autoReviewOverride` block stores a global approval reviewer selector and enabled flag. The Models settings route validates and normalizes writes, restores the live block when persistence fails before publication, and reports catalog convergence; the dashboard shows pending when the catalog did not commit. Malformed hand edits drop this block without discarding other configuration. Provider `autoReviewModel` and `autoReviewModelOverrides` accept validated final-catalog selectors. Per-model keys preserve case and accept the existing raw/encoded slash equivalence. File-load degradation removes malformed optional selectors only; management writes reject malformed shapes. Omitted provider saves preserve selectors, explicit clears remove them, and raw editor candidates adopt normalized values before persistence and live replacement. See [catalog ownership](catalog.md#provider-scoped-approval-reviewer). The optional `comboSuggestionExcludedProviders` array is owned by `src/config/schema/config-schema.ts`. It accepts up to 256 trimmed, deduplicated provider names of at most 256 characters each. A malformed value is dropped during parsing. Saving an empty list removes the key. The preference filters dashboard suggestions and leaves configured combo targets in place. `src/server/management/combo-suggestion-routes.ts` reads the exclusions, provider metering, and stored combo consent from the same locked persisted snapshot used to save a suggestion. The mutation rechecks those conditions when it rebases. +The optional `autoReviewOverride` block stores a global approval reviewer selector and enabled flag. The Models settings route validates and normalizes writes, restores the live block when persistence fails before publication, and reports catalog convergence; the dashboard shows pending when the catalog did not commit. Malformed hand edits drop this block without discarding other configuration. Provider `autoReviewModel` and `autoReviewModelOverrides` accept validated final-catalog selectors. Per-model keys preserve case and accept the existing raw/encoded slash equivalence. File-load degradation removes malformed optional selectors only; management writes reject malformed shapes. Omitted provider saves preserve selectors, explicit clears remove them, and raw editor candidates adopt normalized values before persistence and live replacement. See [catalog ownership](catalog.md#provider-scoped-approval-reviewer). The optional `comboSuggestionExcludedProviders` array is owned by `src/config/schema/config-schema.ts`. It accepts up to 256 trimmed, deduplicated provider names of at most 256 characters each. A malformed value is dropped during parsing. Saving an empty list removes the key. The preference filters dashboard suggestions and leaves configured combo targets in place. `src/server/management/combo-suggestion-routes.ts` reads exclusions and stored combo consent from the locked persisted snapshot used to save a suggestion. It checks provider metering against both that snapshot and the active config on every evaluation, including a rebase. Display-name validation retains prototype-shaped model IDs as data; reviewer-target map validation remains separate and rejects its reserved keys. ## Explicit per-model capability declarations diff --git a/structure/gui-and-management-api.md b/structure/gui-and-management-api.md index 5dac36c24f5..92c810a698a 100644 --- a/structure/gui-and-management-api.md +++ b/structure/gui-and-management-api.md @@ -311,7 +311,7 @@ after the save, and a non-retryable skip (no managed catalog) is a clean save. C | File-integration plans | `src/server/management/integration-routes.ts` and `aside-profile-routes.ts` — `POST /api/client-integrations/preview`, `POST /api/client-integrations/restore/preview`, and `POST /api/client-integrations/aside/profiles/{profileId}/preview`. Management-authenticated, declared non-mutating, and they write nothing: no snapshot, no lock, no maintenance, no recovery. They answer `409 integration_preview_unavailable` rather than gathering a model roster, because discovery refreshes credentials and writes the provider cache. Responses carry only declared managed schema paths, closed change kinds and an opaque fingerprint; no value, filesystem location or selected member identity appears. Mutation routes accept `operation` and `planFingerprint` together or not at all, reject a half-bound request and an operation that disagrees with the change, and answer `409 integration_preview_stale` with a freshly computed plan. Binding is an optimistic token, never authorization. [The integration contract](clients/integrations.md) owns the ordering. | | Grok reset coupons | `src/server/management/grok-coupon-routes.ts` — `GET /api/grok/reset-coupons`, `POST /api/grok/reset-coupons/consume`. The dashboard owner is `gui/src/hooks/useGrokResetCoupons.ts` with `gui/src/components/provider-workspace/GrokResetCoupons.tsx`, wired into the xAI OAuth rows of `ProviderAuthPanel`. Redemption truth is the settled ledger `code`, not the HTTP status: a replayed failure returns 200 with `replayed: true`. See [`providers/xai-grok.md`](providers/xai-grok.md). The route returns `ledger_unavailable` before dispatch when the shared ledger cannot be read or locked; stale uncertain attempts are inspected without another redemption or inferred success. A late inspection refusal or a lost claim replays an identity-matching definitive winner; otherwise it returns `operation_state_changed` (late refusal) or `attempt_in_progress` (lost claim) and never replaces an attempted or terminal record. Unknown-outcome responses include the effective operation ID; the CLI mints it before dispatch. Uncertain and pending attempts live in a module-level hold store shared by all hook instances and mirrored to `sessionStorage` (`ocx.grok-coupon-holds.v1`), so they survive modal close/reopen, remount, and reload for the tab session; the pending hold is written before the POST, only a definitive response for the same `operationId` clears it, and only GET refreshes are allowed after uncertainty. Every response that cannot prove settlement under a supplied operation ID, including pre-open refusals, carries that `operationId`. A definitive failure releases the matching speculative pending hold. Supplied token IDs must be non-empty strings before journal admission, and omitted account/token retries recover the operation’s durable identity within retention. Legacy version-one opens are quarantined rather than dispatched. After confirmed redemption, local settlement has five attempts and four 20 ms waits only for a `ConfigMutationLockError` caused by `SQLITE_BUSY`; any other error or changed claim stops without another redemption. | | Claude reset grants | `src/server/management/anthropic-reset-grant-routes.ts` — `GET /api/anthropic/reset-grants`, `POST /api/anthropic/reset-grants/consume` (lazy-loaded). Wire and fail-closed parsing live in `src/providers/anthropic-reset-grants.ts` (the Claude Code 2.1.278 `cedar_ember` contract, sent with `CLAUDE_CLI_USER_AGENT` from `src/providers/claude-cli-identity.ts`; every bearer request refuses redirects, and a refused claim redirect is an unknown outcome); the journal is `src/providers/anthropic-reset-grant-ledger.ts`: a cross-process `BEGIN IMMEDIATE` lock around every synchronous read-modify-write, a 90 s lease, the operation id reused as the upstream `request_id`, same-id retry only inside the vendor's ten-minute window, at most one unresolved operation per account and organization within each pool's journal and that ten-minute window, whatever grant it names (a new id gets `409 unresolved_prior_operation`), no settlement inferred from a re-read, and a fail-closed `500 journal_write_failed` when an answer cannot be recorded. Spending requires the `gui-session` principal. A journaled `reset`, including a same-id replay of that code, lifts that account cooldown only when it is a 429 quota refusal recorded before the operation was first journaled (the claim fence, `claimedAt`) and the journal's cleared windows cover every window the refusal named (both when it named none); it then drops the cached quota row and rereads usage with its own request rather than joining an older read. Model-family exclusions stay until the usage reread proves a family is no longer rejected. A failed reread leaves them in place. The HTTP result stays the journal answer if the reread fails. Other result codes do not admit. The dashboard owner is `gui/src/hooks/useAnthropicResetGrants.ts` with `gui/src/components/provider-workspace/AnthropicResetGrants.tsx` on the Anthropic OAuth rows of `ProviderAuthPanel`; the dialog re-reads the account when it opens, lets the user choose the grant (default: the selectable grant that expires first; the server re-gates the chosen `grantId`), and after an unknown outcome only retries the same id with no picker shown. Design and audit record: [`../devlog/_fin/260923_claude_reset_grants/010_plan.md`](../devlog/_fin/260923_claude_reset_grants/010_plan.md). | -| Combos | `src/server/management/combo-routes.ts` — `GET/PUT/DELETE /api/combos` own provider combination and failover definitions. `PUT` keeps a stored field the body omits (`cooldownMs`, `waitForCooldownMs`, `defaultEffortMode`, `reasoningEffortMode`, `imageInput`, `cooldownWaitPolicy`, per-target `lastResort`, JEV `decisionQuotaSignals`/`decisionQuotaTiers`/`jevEffortMode`/`sessionPin` on updates/rename); quota false/null clears sparsely and switching away removes quota policy under [the owning contract](providers/jev-decision.md#loaded-advisory-quota). Explicit values replace it and defaults are stored sparse. A combo validation 400 is `{ error, field? }`, where `field` is the top-level combo field of the first issue. `GET /api/combo-suggestions` and `PUT /api/combo-suggestions` use the dashboard-only route in `src/server/management/combo-suggestion-routes.ts`. Both return `{ excludedProviders: string[] }`. PUT validates the full replacement list and persists it before publishing the live value. `POST /api/combo-suggestions/save` accepts a combo ID, a create or append mode, and provider/model pairs. The config mutation validates each new target against current provider classification, exclusions, and existing combo spend consent before commit. Create has no spend consent. Conflicts return a fixed reason code and the dashboard refreshes the suggestions. | +| Combos | `src/server/management/combo-routes.ts` — `GET/PUT/DELETE /api/combos` own provider combination and failover definitions. `PUT` keeps a stored field the body omits (`cooldownMs`, `waitForCooldownMs`, `defaultEffortMode`, `reasoningEffortMode`, `imageInput`, `cooldownWaitPolicy`, per-target `lastResort`, JEV `decisionQuotaSignals`/`decisionQuotaTiers`/`jevEffortMode`/`sessionPin` on updates/rename); quota false/null clears sparsely and switching away removes quota policy under [the owning contract](providers/jev-decision.md#loaded-advisory-quota). Explicit values replace it and defaults are stored sparse. A combo validation 400 is `{ error, field? }`, where `field` is the top-level combo field of the first issue. `GET /api/combo-suggestions` and `PUT /api/combo-suggestions` use the dashboard-only route in `src/server/management/combo-suggestion-routes.ts`. Both return `{ excludedProviders: string[] }`. PUT validates the full replacement list and persists it before publishing the live value. `POST /api/combo-suggestions/save` accepts a combo ID, a create or append mode, and provider/model pairs. The locked config mutation checks each new target against provider classifications in both the active and persisted config, along with persisted exclusions and combo spend consent. A paid classification in either config requires stored consent and sets `metered: true` on the new target. Create has no spend consent. Conflicts return a fixed reason code and the dashboard refreshes the suggestions. | | Protocol paths | `src/server/management/protocol-routes.ts` (lazy-loaded) — `GET /api/protocols` returns the contract version, the resolved API surfaces and protocol settings, the policy revision and the feature vocabulary; with `?provider=` (one non-empty name of at most 200 characters without control characters, else 400 `invalid_provider`; an unconfigured name is 404 `unknown_provider`, neither echoing the name) it adds a `provider` block from `src/protocols/provider-summary.ts` ([Protocol Paths](data-planes/protocol-paths.md#provider-wire-summary)); `POST /api/protocols/plan` takes `{ model, inbound, features? }` (model at most 200 characters, at most 24 features, any other key refused with 400) and returns a `ProtocolPlanV1` with `basis: "preview"` from `src/protocols/plan-snapshot.ts`. Both are read-only, never log their input, and send nothing upstream. `PATCH /api/protocols/settings` takes `{ messagesEnabled?, unrepresentable?, rollout? }` (strict: unknown keys and wrong types are 400), validates and applies through `src/server/management/protocol-settings-patch.ts`, persists with `saveConfigPreservingClaudeCode`, restores the live config if the save fails (409 on lock contention, 500 otherwise), and answers with the fresh `GET /api/protocols` body; closing Messages also writes `claudeCode.enabled = false` through `commitClaudeCodeBlock` ([Protocol Paths](data-planes/protocol-paths.md#settings)). The CLI drives all three through `ocx api protocols`, `ocx api explain` and `ocx api policy` ([Protocol Paths](data-planes/protocol-paths.md#cli)); none carries a route-registry exemption. | | Workflow budget | `src/server/management/workflow-budget-routes.ts` — `GET /api/workflow-budget` reads the tracked roots or one root, and `POST /api/workflow-budget/clear` clears exactly one. The clear moves the windowed send ring and the child map and nothing else: `active` belongs to turns still in flight, the spend ledger is a token budget an operator did not ask to forgive, and the lifetime send total survives so a clear cannot launder the record. A refusal event carries `spendScope` and `spendLimit` when a token ceiling fired, so the reason is readable without the config open beside it; no scope id is ever attached, because root ids are client thread headers and identity ids are credentials. Both are `deferred-verb` in the route registry — they are owed CLI verbs, and because the ledger is process memory there is no local projection the CLI could read instead. `GET`/`PUT /api/workflow-budget/settings` read and write the per-install count ceilings (`workflowBudget` in config: concurrent turns, sends and distinct children per window); the live config is bound in `src/lib/workflow-budget-config.ts` and read per decision by HTTP admission and the pre-dispatch send ceiling, so a write applies to the next request and never resets a root's usage. The window, interactive reserve and tracked-root bound stay fixed because a root's ring geometry is fixed when it first appears. The GET is `local-transport` (same block via `ocx config get`), the PUT `deferred-verb` with the other budget verbs. See [`../devlog/_fin/260915_workflow_budget_window/030_wfc_diff_plan.md`](../devlog/_fin/260915_workflow_budget_window/030_wfc_diff_plan.md). | | Codex accounts | `src/codex/auth-api/routes.ts` — `GET/POST/DELETE /api/codex-auth/accounts`, `PUT /api/codex-auth/accounts/alias`, `PUT /api/codex-auth/accounts/pause`, `PUT /api/codex-auth/accounts/pause-exhausted`, `POST /api/codex-auth/accounts/clear-cooldown`, `GET/PUT /api/codex-auth/active`, `PUT /api/codex-auth/auto-switch`, `PUT /api/codex-auth/pool-strategy`, `PUT /api/codex-auth/failover`, `GET /api/codex-auth/quota`, `GET /api/codex-auth/reset-credits` with `POST /api/codex-auth/reset-credits/consume`, and the login flow `POST /api/codex-auth/login`, `POST /api/codex-auth/login/code`, `POST /api/codex-auth/login/cancel`, `GET /api/codex-auth/login-status`. Per-account quota activation uses the existing `GET/PUT /api/settings` surface and `src/codex/quota-auto-refresh.ts`, keeping scheduled spending separate from credential/authentication mutation. Account ids are opaque handles and are serialized so the GUI can address an account; emails are masked and tokens are never serialized. New-account config commits add UI-managed selector bindings in the same config save; deletion deliberately retains existing bindings for fail-closed exact routing and re-add stability. Account mutations request catalog convergence only after config durability and expose only the boolean `catalogRefreshPending` completion projection. `showCodexCredits` is a default-off boolean in settings GET and successful PUT; partial PUT accepts a boolean and rolls back on persistence failure. See [credits exposure](providers/openai-accounts.md#display-only-codex-credits). | diff --git a/tests/server/combo-suggestion-routes.test.ts b/tests/server/combo-suggestion-routes.test.ts index e3e18cda118..ea6cd15b93b 100644 --- a/tests/server/combo-suggestion-routes.test.ts +++ b/tests/server/combo-suggestion-routes.test.ts @@ -144,8 +144,43 @@ test("create rejects paid Vertex and never accepts consent from the request", as expect(loadConfig().combos?.draft).toBeUndefined(); const current = loadConfig(); + live.providers.mock!.authMode = "forward"; current.providers.mock!.authMode = "forward"; saveConfig(current); expect((await saveSuggestion(live, { ...draft, targets: [{ provider: "mock", model: "m" }] })).status).toBe(200); expect(loadConfig().combos?.draft?.allowMeteredTargets).toBeUndefined(); }); + +for (const paidSide of ["live", "persisted"] as const) { + test(`suggestion requires consent and marks the target metered when only ${paidSide} is paid`, async () => { + const live = seedPaidSuggestion(); + const persisted = loadConfig(); + const freeProvider = { ...live.providers.paid!, baseUrl: "https://example.com/v1", authMode: "forward" as const }; + const paidProvider = { ...freeProvider, authMode: "api-key" as const }; + live.providers.paid = paidSide === "live" ? paidProvider : freeProvider; + persisted.providers.paid = paidSide === "persisted" ? paidProvider : freeProvider; + delete live.combos!.mix!.allowMeteredTargets; + delete persisted.combos!.mix!.allowMeteredTargets; + saveConfig(persisted); + + const configPath = join(home, "config.json"); + const beforeDisk = readFileSync(configPath, "utf8"); + const beforeLive = structuredClone(live.combos); + const targets = [paidTarget]; + for (const request of [{ id: "draft", mode: "create", targets }, { id: "mix", mode: "append", targets }]) { + const response = await saveSuggestion(live, request); + expect(response.status).toBe(409); + expect(await response.json()).toMatchObject({ code: "suggestion_consent_required" }); + expect(readFileSync(configPath, "utf8")).toBe(beforeDisk); + expect(live.combos).toEqual(beforeLive); + } + + persisted.combos!.mix!.allowMeteredTargets = true; + saveConfig(persisted); + const response = await saveSuggestion(live, { id: "mix", mode: "append", targets }); + expect(response.status).toBe(200); + for (const config of [live, loadConfig()]) { + expect(config.combos?.mix?.targets).toContainEqual({ ...paidTarget, metered: true }); + } + }); +} From b55db82ec7a7feeeeae9252a7b25f99c49b1b3ab Mon Sep 17 00:00:00 2001 From: JUN Date: Thu, 19 Nov 2026 00:56:21 +0900 Subject: [PATCH 05/23] fix(combos): rank suggestions conservatively across configurations --- .../src/content/docs/es/guides/combos.md | 2 +- .../docs/es/reference/management-api.md | 2 +- docs-site/src/content/docs/guides/combos.md | 2 +- .../content/docs/reference/management-api.md | 2 +- .../management/combo-suggestion-routes.ts | 12 +++++---- structure/gui-and-management-api.md | 2 +- tests/server/combo-suggestion-routes.test.ts | 27 +++++++++++++++++-- 7 files changed, 37 insertions(+), 12 deletions(-) diff --git a/docs-site/src/content/docs/es/guides/combos.md b/docs-site/src/content/docs/es/guides/combos.md index 5a7612bba4e..1822dbc9d99 100644 --- a/docs-site/src/content/docs/es/guides/combos.md +++ b/docs-site/src/content/docs/es/guides/combos.md @@ -790,6 +790,6 @@ Un rechazo estructurado de esfuerzo puede bajar una posición publicada cada vez ## Combos sugeridos -Si los ajustes cambian antes de guardar una sugerencia, Combos actualiza las sugerencias y muestra un mensaje. Al guardar, se comprueban las exclusiones y el consentimiento de gasto vigentes. +Si los ajustes cambian antes de guardar una sugerencia, Combos actualiza las sugerencias y muestra un mensaje. Al guardar, se comprueban las exclusiones y el consentimiento de gasto vigentes. Al añadir sugerencias, el servidor aplica el nivel de mayor coste entre la configuración activa y la guardada. Trata los destinos existentes marcados explícitamente como medidos como destinos de pago por uso y conserva el orden relativo de los destinos existentes. En el espacio de trabajo de combos, **Generar** abre un borrador de conmutación por error para un modelo disponible en varios proveedores. **Añadir al combo** ofrece destinos que faltan en un combo existente. Las tarjetas descartadas quedan ocultas en este navegador. Usa **Excluir un proveedor…** para filtrar ambos tipos de sugerencias. El proxy guarda la selección como `comboSuggestionExcludedProviders` en `config.json`. Los miembros existentes se conservan. Los borradores nuevos usan destinos sin medición. Las ampliaciones ofrecen destinos de pago por uso, incluido Vertex, solo si el combo ya permite destinos medidos. El panel comprueba la configuración actual antes de guardar. El control de exclusión sigue disponible tras descartar todas las tarjetas. Si falla la carga de la lista de exclusión, vuelve a intentarlo para ver las sugerencias. diff --git a/docs-site/src/content/docs/es/reference/management-api.md b/docs-site/src/content/docs/es/reference/management-api.md index b08ae7471aa..835be563799 100644 --- a/docs-site/src/content/docs/es/reference/management-api.md +++ b/docs-site/src/content/docs/es/reference/management-api.md @@ -218,7 +218,7 @@ Las instantáneas de sesión incluyen `resumable`. Se vuelve cierto sólo despu | --- | --- | --- | | `GET /api/combos` | Lista de combos normalizados y sus ID de modelo público | El trabajo del catálogo puede devolver `catalog_busy` | | `PUT /api/combos` | Crea, sustituye o renombra un combo. | 400 si el identificador, destino, configuración o cambio de nombre son inválidos, o hay una colisión ordinaria; un 400 de validación también identifica el primer campo superior inválido en `field`, por ejemplo `targets` o `decisionProvider`. 409 si hay colisión con el espacio de nombres de una cuenta Codex. | -| `POST /api/combo-suggestions/save` | Guarda pares de proveedor y modelo sugeridos con `{ id, mode: "create" o "append", targets }` | 400 solicitud inválida; 409 si el consentimiento, las exclusiones, la disponibilidad o el estado del combo impiden guardar. Si la configuración activa o la guardada clasifica un destino como de pago, se requiere el consentimiento existente del combo y el destino se guarda como medido. | +| `POST /api/combo-suggestions/save` | Guarda pares de proveedor y modelo sugeridos con `{ id, mode: "create" o "append", targets }` | 400 solicitud inválida; 409 si el consentimiento, las exclusiones, la disponibilidad o el estado del combo impiden guardar. Si la configuración activa o la guardada clasifica un destino como de pago, se requiere el consentimiento existente del combo y el destino se guarda como medido. Al añadir sugerencias, el servidor aplica el nivel de mayor coste entre la configuración activa y la guardada. Trata los destinos existentes marcados explícitamente como medidos como destinos de pago por uso y conserva el orden relativo de los destinos existentes. | | `DELETE /api/combos?id=...` | Eliminar un combo y borrar su estado de selección/enfriamiento | 400 id ausente; 404 combo desconocido | Consulte [Combos](/es/guides/combos/) para conocer las estrategias de destino, los tiempos de reutilización, los alias y los fallos de enrutamiento. diff --git a/docs-site/src/content/docs/guides/combos.md b/docs-site/src/content/docs/guides/combos.md index c237d817479..4f09bc610be 100644 --- a/docs-site/src/content/docs/guides/combos.md +++ b/docs-site/src/content/docs/guides/combos.md @@ -1218,4 +1218,4 @@ untried targets and newer failures keep their cooldowns. When settings change before a suggestion is saved, Combos refreshes the suggestions and displays a message. Saving checks the current exclusions and spend consent. -In the Combos workspace, **Generate** opens a failover draft for a model served by multiple providers. **Add to combo** offers missing targets for an existing combo. Dismissed cards stay hidden in this browser. Use **Exclude providers…** to filter both kinds of suggestions. The proxy stores your selection as `comboSuggestionExcludedProviders` in `config.json`. Existing combo members stay in place. New drafts use unmetered targets. Extensions offer pay-per-use targets, including Vertex, only when the combo already allows metered targets. The dashboard checks the current configuration before saving. The exclusion control stays available when all cards are dismissed. If the exclusion list fails to load, retry the read to see suggestions. +In the Combos workspace, **Generate** opens a failover draft for a model served by multiple providers. **Add to combo** offers missing targets for an existing combo. Dismissed cards stay hidden in this browser. Use **Exclude providers…** to filter both kinds of suggestions. The proxy stores your selection as `comboSuggestionExcludedProviders` in `config.json`. When appending suggestions, the server uses the more costly tier from the active and saved configurations. It treats existing targets explicitly marked as metered as pay-per-use and preserves the relative order of existing targets. New drafts use unmetered targets. Extensions offer pay-per-use targets, including Vertex, only when the combo already allows metered targets. The dashboard checks the current configuration before saving. The exclusion control stays available when all cards are dismissed. If the exclusion list fails to load, retry the read to see suggestions. diff --git a/docs-site/src/content/docs/reference/management-api.md b/docs-site/src/content/docs/reference/management-api.md index ec286887ebf..5284cbbac5e 100644 --- a/docs-site/src/content/docs/reference/management-api.md +++ b/docs-site/src/content/docs/reference/management-api.md @@ -247,7 +247,7 @@ completes. | --- | --- | --- | | `GET /api/combos` | List normalized combos and their public model ids | Catalog work can return `catalog_busy` | | `PUT /api/combos` | Create, replace, or rename one combo | 400 invalid id, target, config, rename, or ordinary collision (a combo validation 400 also names the first invalid top-level field in `field`, for example `targets` or `decisionProvider`); 409 Codex-account namespace collision | -| `POST /api/combo-suggestions/save` | Save suggested provider/model pairs using `{ id, mode: "create" or "append", targets }` | 400 invalid request; 409 when consent, exclusions, provider availability, or combo state prevents the save. A target classified as paid in either the active or persisted config requires existing combo consent and is saved as metered. | +| `POST /api/combo-suggestions/save` | Save suggested provider/model pairs using `{ id, mode: "create" or "append", targets }` | 400 invalid request; 409 when consent, exclusions, provider availability, or combo state prevents the save. A target classified as paid in either the active or persisted config requires existing combo consent and is saved as metered. When appending suggestions, the server uses the more costly tier from the active and saved configurations. It treats existing targets explicitly marked as metered as pay-per-use and preserves the relative order of existing targets. | | `DELETE /api/combos?id=...` | Delete one combo and clear its selection/cooldown state | 400 missing id; 404 unknown combo | See [Combos](/guides/combos/) for target strategies, cooldowns, aliases, and routing failures. diff --git a/src/server/management/combo-suggestion-routes.ts b/src/server/management/combo-suggestion-routes.ts index 9567f3abdb0..f399f5a4f0a 100644 --- a/src/server/management/combo-suggestion-routes.ts +++ b/src/server/management/combo-suggestion-routes.ts @@ -5,7 +5,7 @@ */ import { clearComboSelectionState, clearComboTargetCooldowns, comboPublicModelId } from "../../combos"; import { comboConfigIssues } from "../../combos/types"; -import { channelTier, isMeteredTier, TIER_RANK } from "../../combos/suggestion-channel"; +import { channelTier, TIER_RANK } from "../../combos/suggestion-channel"; import { codexAccountNamespaceForModel } from "../../codex/account-namespace-match"; import { reconcileLiveStateStores } from "../../lib/state-store-registrations"; import type { OcxComboConfig, OcxConfig } from "../../types"; @@ -128,6 +128,8 @@ async function saveSuggestion(ctx: ManagementContext): Promise { const current = providerFor(snapshot, provider); return current ? channelTier({ ...current, name: provider }, model) : "metered"; }; + // A provider can have different billing in the running and saved config. + const rankOf = (target: Target) => Math.max(TIER_RANK[tierOf(persisted, target)], TIER_RANK[tierOf(config, target)]); for (const target of targets) { if (nextTargets.some(({ provider, model }) => provider.trim() === target.provider && model.trim() === target.model)) continue; const provider = providerFor(persisted, target.provider); @@ -135,11 +137,11 @@ async function saveSuggestion(ctx: ManagementContext): Promise { return rejected("suggestion_provider_unavailable"); } if (persisted.comboSuggestionExcludedProviders?.includes(target.provider)) return rejected("suggestion_provider_excluded"); - const tier = tierOf(persisted, target); - const liveTier = tierOf(config, target); - const metered = isMeteredTier(tier) || isMeteredTier(liveTier); + const rank = rankOf(target); + const metered = rank >= TIER_RANK.vertex; if (metered && previous?.allowMeteredTargets !== true) return rejected("suggestion_consent_required"); - const at = create ? -1 : nextTargets.findIndex(existing => TIER_RANK[tierOf(persisted, existing)] > TIER_RANK[tier]); + const at = create ? -1 : nextTargets.findIndex(existing => + (existing.metered === true ? TIER_RANK.metered : rankOf(existing)) > rank); nextTargets.splice(at < 0 ? nextTargets.length : at, 0, { ...target, ...(metered ? { metered: true } : {}) }); } diff --git a/structure/gui-and-management-api.md b/structure/gui-and-management-api.md index 92c810a698a..5b1dbe21945 100644 --- a/structure/gui-and-management-api.md +++ b/structure/gui-and-management-api.md @@ -311,7 +311,7 @@ after the save, and a non-retryable skip (no managed catalog) is a clean save. C | File-integration plans | `src/server/management/integration-routes.ts` and `aside-profile-routes.ts` — `POST /api/client-integrations/preview`, `POST /api/client-integrations/restore/preview`, and `POST /api/client-integrations/aside/profiles/{profileId}/preview`. Management-authenticated, declared non-mutating, and they write nothing: no snapshot, no lock, no maintenance, no recovery. They answer `409 integration_preview_unavailable` rather than gathering a model roster, because discovery refreshes credentials and writes the provider cache. Responses carry only declared managed schema paths, closed change kinds and an opaque fingerprint; no value, filesystem location or selected member identity appears. Mutation routes accept `operation` and `planFingerprint` together or not at all, reject a half-bound request and an operation that disagrees with the change, and answer `409 integration_preview_stale` with a freshly computed plan. Binding is an optimistic token, never authorization. [The integration contract](clients/integrations.md) owns the ordering. | | Grok reset coupons | `src/server/management/grok-coupon-routes.ts` — `GET /api/grok/reset-coupons`, `POST /api/grok/reset-coupons/consume`. The dashboard owner is `gui/src/hooks/useGrokResetCoupons.ts` with `gui/src/components/provider-workspace/GrokResetCoupons.tsx`, wired into the xAI OAuth rows of `ProviderAuthPanel`. Redemption truth is the settled ledger `code`, not the HTTP status: a replayed failure returns 200 with `replayed: true`. See [`providers/xai-grok.md`](providers/xai-grok.md). The route returns `ledger_unavailable` before dispatch when the shared ledger cannot be read or locked; stale uncertain attempts are inspected without another redemption or inferred success. A late inspection refusal or a lost claim replays an identity-matching definitive winner; otherwise it returns `operation_state_changed` (late refusal) or `attempt_in_progress` (lost claim) and never replaces an attempted or terminal record. Unknown-outcome responses include the effective operation ID; the CLI mints it before dispatch. Uncertain and pending attempts live in a module-level hold store shared by all hook instances and mirrored to `sessionStorage` (`ocx.grok-coupon-holds.v1`), so they survive modal close/reopen, remount, and reload for the tab session; the pending hold is written before the POST, only a definitive response for the same `operationId` clears it, and only GET refreshes are allowed after uncertainty. Every response that cannot prove settlement under a supplied operation ID, including pre-open refusals, carries that `operationId`. A definitive failure releases the matching speculative pending hold. Supplied token IDs must be non-empty strings before journal admission, and omitted account/token retries recover the operation’s durable identity within retention. Legacy version-one opens are quarantined rather than dispatched. After confirmed redemption, local settlement has five attempts and four 20 ms waits only for a `ConfigMutationLockError` caused by `SQLITE_BUSY`; any other error or changed claim stops without another redemption. | | Claude reset grants | `src/server/management/anthropic-reset-grant-routes.ts` — `GET /api/anthropic/reset-grants`, `POST /api/anthropic/reset-grants/consume` (lazy-loaded). Wire and fail-closed parsing live in `src/providers/anthropic-reset-grants.ts` (the Claude Code 2.1.278 `cedar_ember` contract, sent with `CLAUDE_CLI_USER_AGENT` from `src/providers/claude-cli-identity.ts`; every bearer request refuses redirects, and a refused claim redirect is an unknown outcome); the journal is `src/providers/anthropic-reset-grant-ledger.ts`: a cross-process `BEGIN IMMEDIATE` lock around every synchronous read-modify-write, a 90 s lease, the operation id reused as the upstream `request_id`, same-id retry only inside the vendor's ten-minute window, at most one unresolved operation per account and organization within each pool's journal and that ten-minute window, whatever grant it names (a new id gets `409 unresolved_prior_operation`), no settlement inferred from a re-read, and a fail-closed `500 journal_write_failed` when an answer cannot be recorded. Spending requires the `gui-session` principal. A journaled `reset`, including a same-id replay of that code, lifts that account cooldown only when it is a 429 quota refusal recorded before the operation was first journaled (the claim fence, `claimedAt`) and the journal's cleared windows cover every window the refusal named (both when it named none); it then drops the cached quota row and rereads usage with its own request rather than joining an older read. Model-family exclusions stay until the usage reread proves a family is no longer rejected. A failed reread leaves them in place. The HTTP result stays the journal answer if the reread fails. Other result codes do not admit. The dashboard owner is `gui/src/hooks/useAnthropicResetGrants.ts` with `gui/src/components/provider-workspace/AnthropicResetGrants.tsx` on the Anthropic OAuth rows of `ProviderAuthPanel`; the dialog re-reads the account when it opens, lets the user choose the grant (default: the selectable grant that expires first; the server re-gates the chosen `grantId`), and after an unknown outcome only retries the same id with no picker shown. Design and audit record: [`../devlog/_fin/260923_claude_reset_grants/010_plan.md`](../devlog/_fin/260923_claude_reset_grants/010_plan.md). | -| Combos | `src/server/management/combo-routes.ts` — `GET/PUT/DELETE /api/combos` own provider combination and failover definitions. `PUT` keeps a stored field the body omits (`cooldownMs`, `waitForCooldownMs`, `defaultEffortMode`, `reasoningEffortMode`, `imageInput`, `cooldownWaitPolicy`, per-target `lastResort`, JEV `decisionQuotaSignals`/`decisionQuotaTiers`/`jevEffortMode`/`sessionPin` on updates/rename); quota false/null clears sparsely and switching away removes quota policy under [the owning contract](providers/jev-decision.md#loaded-advisory-quota). Explicit values replace it and defaults are stored sparse. A combo validation 400 is `{ error, field? }`, where `field` is the top-level combo field of the first issue. `GET /api/combo-suggestions` and `PUT /api/combo-suggestions` use the dashboard-only route in `src/server/management/combo-suggestion-routes.ts`. Both return `{ excludedProviders: string[] }`. PUT validates the full replacement list and persists it before publishing the live value. `POST /api/combo-suggestions/save` accepts a combo ID, a create or append mode, and provider/model pairs. The locked config mutation checks each new target against provider classifications in both the active and persisted config, along with persisted exclusions and combo spend consent. A paid classification in either config requires stored consent and sets `metered: true` on the new target. Create has no spend consent. Conflicts return a fixed reason code and the dashboard refreshes the suggestions. | +| Combos | `src/server/management/combo-routes.ts` — `GET/PUT/DELETE /api/combos` own provider combination and failover definitions. `PUT` keeps a stored field the body omits (`cooldownMs`, `waitForCooldownMs`, `defaultEffortMode`, `reasoningEffortMode`, `imageInput`, `cooldownWaitPolicy`, per-target `lastResort`, JEV `decisionQuotaSignals`/`decisionQuotaTiers`/`jevEffortMode`/`sessionPin` on updates/rename); quota false/null clears sparsely and switching away removes quota policy under [the owning contract](providers/jev-decision.md#loaded-advisory-quota). Explicit values replace it and defaults are stored sparse. A combo validation 400 is `{ error, field? }`, where `field` is the top-level combo field of the first issue. `GET /api/combo-suggestions` and `PUT /api/combo-suggestions` use the dashboard-only route in `src/server/management/combo-suggestion-routes.ts`. Both return `{ excludedProviders: string[] }`. PUT validates the full replacement list and persists it before publishing the live value. `POST /api/combo-suggestions/save` accepts a combo ID, a create or append mode, and provider/model pairs. The locked config mutation checks each new target against provider classifications in both the active and persisted config, along with persisted exclusions and combo spend consent. A paid classification in either config requires stored consent and sets `metered: true` on the new target. Create has no spend consent. Conflicts return a fixed reason code and the dashboard refreshes the suggestions. When appending suggestions, the server uses the more costly tier from the active and saved configurations. It treats existing targets explicitly marked as metered as pay-per-use and preserves the relative order of existing targets. | | Protocol paths | `src/server/management/protocol-routes.ts` (lazy-loaded) — `GET /api/protocols` returns the contract version, the resolved API surfaces and protocol settings, the policy revision and the feature vocabulary; with `?provider=` (one non-empty name of at most 200 characters without control characters, else 400 `invalid_provider`; an unconfigured name is 404 `unknown_provider`, neither echoing the name) it adds a `provider` block from `src/protocols/provider-summary.ts` ([Protocol Paths](data-planes/protocol-paths.md#provider-wire-summary)); `POST /api/protocols/plan` takes `{ model, inbound, features? }` (model at most 200 characters, at most 24 features, any other key refused with 400) and returns a `ProtocolPlanV1` with `basis: "preview"` from `src/protocols/plan-snapshot.ts`. Both are read-only, never log their input, and send nothing upstream. `PATCH /api/protocols/settings` takes `{ messagesEnabled?, unrepresentable?, rollout? }` (strict: unknown keys and wrong types are 400), validates and applies through `src/server/management/protocol-settings-patch.ts`, persists with `saveConfigPreservingClaudeCode`, restores the live config if the save fails (409 on lock contention, 500 otherwise), and answers with the fresh `GET /api/protocols` body; closing Messages also writes `claudeCode.enabled = false` through `commitClaudeCodeBlock` ([Protocol Paths](data-planes/protocol-paths.md#settings)). The CLI drives all three through `ocx api protocols`, `ocx api explain` and `ocx api policy` ([Protocol Paths](data-planes/protocol-paths.md#cli)); none carries a route-registry exemption. | | Workflow budget | `src/server/management/workflow-budget-routes.ts` — `GET /api/workflow-budget` reads the tracked roots or one root, and `POST /api/workflow-budget/clear` clears exactly one. The clear moves the windowed send ring and the child map and nothing else: `active` belongs to turns still in flight, the spend ledger is a token budget an operator did not ask to forgive, and the lifetime send total survives so a clear cannot launder the record. A refusal event carries `spendScope` and `spendLimit` when a token ceiling fired, so the reason is readable without the config open beside it; no scope id is ever attached, because root ids are client thread headers and identity ids are credentials. Both are `deferred-verb` in the route registry — they are owed CLI verbs, and because the ledger is process memory there is no local projection the CLI could read instead. `GET`/`PUT /api/workflow-budget/settings` read and write the per-install count ceilings (`workflowBudget` in config: concurrent turns, sends and distinct children per window); the live config is bound in `src/lib/workflow-budget-config.ts` and read per decision by HTTP admission and the pre-dispatch send ceiling, so a write applies to the next request and never resets a root's usage. The window, interactive reserve and tracked-root bound stay fixed because a root's ring geometry is fixed when it first appears. The GET is `local-transport` (same block via `ocx config get`), the PUT `deferred-verb` with the other budget verbs. See [`../devlog/_fin/260915_workflow_budget_window/030_wfc_diff_plan.md`](../devlog/_fin/260915_workflow_budget_window/030_wfc_diff_plan.md). | | Codex accounts | `src/codex/auth-api/routes.ts` — `GET/POST/DELETE /api/codex-auth/accounts`, `PUT /api/codex-auth/accounts/alias`, `PUT /api/codex-auth/accounts/pause`, `PUT /api/codex-auth/accounts/pause-exhausted`, `POST /api/codex-auth/accounts/clear-cooldown`, `GET/PUT /api/codex-auth/active`, `PUT /api/codex-auth/auto-switch`, `PUT /api/codex-auth/pool-strategy`, `PUT /api/codex-auth/failover`, `GET /api/codex-auth/quota`, `GET /api/codex-auth/reset-credits` with `POST /api/codex-auth/reset-credits/consume`, and the login flow `POST /api/codex-auth/login`, `POST /api/codex-auth/login/code`, `POST /api/codex-auth/login/cancel`, `GET /api/codex-auth/login-status`. Per-account quota activation uses the existing `GET/PUT /api/settings` surface and `src/codex/quota-auto-refresh.ts`, keeping scheduled spending separate from credential/authentication mutation. Account ids are opaque handles and are serialized so the GUI can address an account; emails are masked and tokens are never serialized. New-account config commits add UI-managed selector bindings in the same config save; deletion deliberately retains existing bindings for fail-closed exact routing and re-add stability. Account mutations request catalog convergence only after config durability and expose only the boolean `catalogRefreshPending` completion projection. `showCodexCredits` is a default-off boolean in settings GET and successful PUT; partial PUT accepts a boolean and rolls back on persistence failure. See [credits exposure](providers/openai-accounts.md#display-only-codex-credits). | diff --git a/tests/server/combo-suggestion-routes.test.ts b/tests/server/combo-suggestion-routes.test.ts index ea6cd15b93b..64dd2c03b1d 100644 --- a/tests/server/combo-suggestion-routes.test.ts +++ b/tests/server/combo-suggestion-routes.test.ts @@ -155,10 +155,16 @@ for (const paidSide of ["live", "persisted"] as const) { test(`suggestion requires consent and marks the target metered when only ${paidSide} is paid`, async () => { const live = seedPaidSuggestion(); const persisted = loadConfig(); - const freeProvider = { ...live.providers.paid!, baseUrl: "https://example.com/v1", authMode: "forward" as const }; + const freeProvider = { ...live.providers.paid!, baseUrl: "https://generativelanguage.googleapis.com/v1", authMode: "forward" as const }; const paidProvider = { ...freeProvider, authMode: "api-key" as const }; live.providers.paid = paidSide === "live" ? paidProvider : freeProvider; persisted.providers.paid = paidSide === "persisted" ? paidProvider : freeProvider; + const subscription = { provider: "mock", model: "m" }; + const explicitlyMetered = { provider: "paid", model: "previous", metered: true }; + live.providers.mock!.authMode = "forward"; + persisted.providers.mock!.authMode = "forward"; + live.combos!.mix!.targets = [subscription, explicitlyMetered]; + persisted.combos!.mix!.targets = [subscription, explicitlyMetered]; delete live.combos!.mix!.allowMeteredTargets; delete persisted.combos!.mix!.allowMeteredTargets; saveConfig(persisted); @@ -180,7 +186,24 @@ for (const paidSide of ["live", "persisted"] as const) { const response = await saveSuggestion(live, { id: "mix", mode: "append", targets }); expect(response.status).toBe(200); for (const config of [live, loadConfig()]) { - expect(config.combos?.mix?.targets).toContainEqual({ ...paidTarget, metered: true }); + expect(config.combos?.mix?.targets).toEqual([subscription, explicitlyMetered, { ...paidTarget, metered: true }]); } }); } + +test("append inserts a subscription before explicitly metered targets without reordering them", async () => { + const live = seedPaidSuggestion(); + live.providers.mock!.authMode = "forward"; + const existing = [ + { provider: "mock", model: "first", metered: true }, + { provider: "mock", model: "second", metered: true }, + ]; + live.combos!.mix!.targets = existing; + saveConfig(live); + const target = { provider: "mock", model: "m" }; + const response = await saveSuggestion(live, { id: "mix", mode: "append", targets: [target] }); + expect(response.status).toBe(200); + for (const config of [live, loadConfig()]) { + expect(config.combos?.mix?.targets).toEqual([target, ...existing]); + } +}); From 98b79d2ebf40343cbec724d411c364d7715d3ab7 Mon Sep 17 00:00:00 2001 From: JUN Date: Thu, 19 Nov 2026 01:06:52 +0900 Subject: [PATCH 06/23] test(combos): cover dashboard-only suggestion admission --- tests/server/combo-suggestion-routes.test.ts | 52 +++++++++++++++----- 1 file changed, 41 insertions(+), 11 deletions(-) diff --git a/tests/server/combo-suggestion-routes.test.ts b/tests/server/combo-suggestion-routes.test.ts index 64dd2c03b1d..5d78e0cef46 100644 --- a/tests/server/combo-suggestion-routes.test.ts +++ b/tests/server/combo-suggestion-routes.test.ts @@ -3,8 +3,12 @@ import { mkdtempSync, readFileSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { handleManagementAPI } from "../../src/server/management-api"; +import { + initializeManagementAuthState, issueGuiSession, managementPrincipal, + managementSessionIssuance, requireManagementAuth, +} from "../../src/server/management-auth"; import { loadConfig, saveConfig } from "../../src/config"; -import { ManagementRequest, managementHeaders } from "../helpers/management-auth"; +import { ManagementRequest } from "../helpers/management-auth"; import { removeTreeWithRetry } from "../helpers/remove-tree"; import { parseExcludedProviders } from "../../src/server/management/combo-suggestion-routes"; import { setPersistedConfigMutationBeforeCommitForTests } from "../../src/config/persisted-mutation"; @@ -31,11 +35,28 @@ afterEach(() => { removeTreeWithRetry(home); }); +async function dispatch(config: OcxConfig, path: string, method: string, body?: unknown, adminOnly = false) { + const url = new URL(path, "http://localhost:10100"); + const state = initializeManagementAuthState(config); + const headers = new Headers({ Origin: url.origin, "content-type": "application/json" }); + if (adminOnly) { + headers.set("X-OpenCodex-API-Key", state.token!); + } else { + const session = issueGuiSession(new ManagementRequest(url, { headers }), config, state)!; + headers.set("X-OpenCodex-API-Key", session.token); + headers.set("X-OpenCodex-GUI-Origin", session.browserOrigin); + if (method !== "GET") headers.set("X-OpenCodex-CSRF-Token", session.csrfToken); + } + const req = new ManagementRequest(url, { method, headers, body: JSON.stringify(body) }); + expect(requireManagementAuth(req, state, config)).toBeNull(); + return (await handleManagementAPI(req, url, config, {}, managementPrincipal(req, state, config)!, undefined, { + trustedLoopback: true, + guiSessionIssuance: managementSessionIssuance(req, state), + }))!; +} + 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); + const response = await dispatch(config, "/api/combo-suggestions", method, body); return { status: response!.status, body: await response!.json() as Record }; } @@ -87,12 +108,7 @@ test("the config schema normalizes hand-edited exclusions and discards malformed const paidTarget = { provider: "paid", model: "gemini" }; async function saveSuggestion(live: OcxConfig, body: unknown) { - const headers = { ...managementHeaders(), "content-type": "application/json" }; - const url = new URL("http://localhost/api/combo-suggestions/save"); - const response = await handleManagementAPI(new ManagementRequest(url, { - method: "POST", headers, body: JSON.stringify(body), - }), url, live); - return response!; + return dispatch(live, "/api/combo-suggestions/save", "POST", body); } function seedPaidSuggestion() { @@ -103,6 +119,20 @@ function seedPaidSuggestion() { return live; } +test.each([ + ["GET", "/api/combo-suggestions", undefined], + ["PUT", "/api/combo-suggestions", { excludedProviders: ["other"] }], + ["POST", "/api/combo-suggestions/save", { id: "mix", mode: "append", targets: [paidTarget] }], +] as const)("%s %s requires a dashboard session", async (method, path, body) => { + const live = seedPaidSuggestion(); + const before = onDisk(); + const denied = await dispatch(live, path, method, body, true); + expect(denied.status).toBe(403); + expect(await denied.json()).toEqual({ error: "dashboard session required" }); + expect(onDisk()).toEqual(before); + expect((await dispatch(live, path, method, body)).status).toBe(200); +}); + for (const code of ["suggestion_consent_required", "suggestion_provider_excluded"]) { test(`append refuses ${code} when policy changes before commit`, async () => { const live = seedPaidSuggestion(); From 0e2719a44525a9298781c33423d73c418622d67f Mon Sep 17 00:00:00 2001 From: JUN Date: Thu, 19 Nov 2026 01:07:14 +0900 Subject: [PATCH 07/23] fix(combos): require a dashboard session for suggestion routes --- .../content/docs/es/reference/management-api.md | 4 +++- .../content/docs/reference/management-api.md | 4 +++- .../management/combo-suggestion-routes.ts | 17 ++++++++--------- structure/gui-and-management-api.md | 2 +- 4 files changed, 15 insertions(+), 12 deletions(-) diff --git a/docs-site/src/content/docs/es/reference/management-api.md b/docs-site/src/content/docs/es/reference/management-api.md index 835be563799..dd379cdedaa 100644 --- a/docs-site/src/content/docs/es/reference/management-api.md +++ b/docs-site/src/content/docs/es/reference/management-api.md @@ -218,9 +218,11 @@ Las instantáneas de sesión incluyen `resumable`. Se vuelve cierto sólo despu | --- | --- | --- | | `GET /api/combos` | Lista de combos normalizados y sus ID de modelo público | El trabajo del catálogo puede devolver `catalog_busy` | | `PUT /api/combos` | Crea, sustituye o renombra un combo. | 400 si el identificador, destino, configuración o cambio de nombre son inválidos, o hay una colisión ordinaria; un 400 de validación también identifica el primer campo superior inválido en `field`, por ejemplo `targets` o `decisionProvider`. 409 si hay colisión con el espacio de nombres de una cuenta Codex. | -| `POST /api/combo-suggestions/save` | Guarda pares de proveedor y modelo sugeridos con `{ id, mode: "create" o "append", targets }` | 400 solicitud inválida; 409 si el consentimiento, las exclusiones, la disponibilidad o el estado del combo impiden guardar. Si la configuración activa o la guardada clasifica un destino como de pago, se requiere el consentimiento existente del combo y el destino se guarda como medido. Al añadir sugerencias, el servidor aplica el nivel de mayor coste entre la configuración activa y la guardada. Trata los destinos existentes marcados explícitamente como medidos como destinos de pago por uso y conserva el orden relativo de los destinos existentes. | +| `POST /api/combo-suggestions/save` | Guarda pares de proveedor y modelo sugeridos con `{ id, mode, targets }` y modo `"create"` o `"append"` | 400 solicitud inválida; 403 si falta una sesión de panel válida; 409 si el consentimiento, las exclusiones, la disponibilidad o el estado del combo impiden guardar. Si la configuración activa o la guardada clasifica un destino como de pago, se requiere el consentimiento existente del combo y el destino se guarda como medido. Al añadir sugerencias, el servidor aplica el nivel de mayor coste entre la configuración activa y la guardada. Trata los destinos existentes marcados explícitamente como medidos como destinos de pago por uso y conserva el orden relativo de los destinos existentes. | | `DELETE /api/combos?id=...` | Eliminar un combo y borrar su estado de selección/enfriamiento | 400 id ausente; 404 combo desconocido | +Las tres operaciones de sugerencias (`GET /api/combo-suggestions`, `PUT /api/combo-suggestions` y `POST /api/combo-suggestions/save`) requieren una sesión de panel iniciada mediante el acceso local o el emparejamiento. Las credenciales de administrador y las sesiones recordadas reciben un 403. + Consulte [Combos](/es/guides/combos/) para conocer las estrategias de destino, los tiempos de reutilización, los alias y los fallos de enrutamiento. diff --git a/docs-site/src/content/docs/reference/management-api.md b/docs-site/src/content/docs/reference/management-api.md index 5284cbbac5e..1fe91e3bb66 100644 --- a/docs-site/src/content/docs/reference/management-api.md +++ b/docs-site/src/content/docs/reference/management-api.md @@ -247,9 +247,11 @@ completes. | --- | --- | --- | | `GET /api/combos` | List normalized combos and their public model ids | Catalog work can return `catalog_busy` | | `PUT /api/combos` | Create, replace, or rename one combo | 400 invalid id, target, config, rename, or ordinary collision (a combo validation 400 also names the first invalid top-level field in `field`, for example `targets` or `decisionProvider`); 409 Codex-account namespace collision | -| `POST /api/combo-suggestions/save` | Save suggested provider/model pairs using `{ id, mode: "create" or "append", targets }` | 400 invalid request; 409 when consent, exclusions, provider availability, or combo state prevents the save. A target classified as paid in either the active or persisted config requires existing combo consent and is saved as metered. When appending suggestions, the server uses the more costly tier from the active and saved configurations. It treats existing targets explicitly marked as metered as pay-per-use and preserves the relative order of existing targets. | +| `POST /api/combo-suggestions/save` | Save suggested provider/model pairs using `{ id, mode, targets }` with mode `"create"` or `"append"` | 400 invalid request; 403 without an eligible dashboard session; 409 when consent, exclusions, provider availability, or combo state prevents the save. A target classified as paid in either the active or persisted config requires existing combo consent and is saved as metered. When appending suggestions, the server uses the more costly tier from the active and saved configurations. It treats existing targets explicitly marked as metered as pay-per-use and preserves the relative order of existing targets. | | `DELETE /api/combos?id=...` | Delete one combo and clear its selection/cooldown state | 400 missing id; 404 unknown combo | +All three suggestion operations (`GET /api/combo-suggestions`, `PUT /api/combo-suggestions`, and `POST /api/combo-suggestions/save`) require a dashboard session issued through local bootstrap or pairing. Admin credentials and remembered sessions receive a 403. + See [Combos](/guides/combos/) for target strategies, cooldowns, aliases, and routing failures. ### Codex prompt layers diff --git a/src/server/management/combo-suggestion-routes.ts b/src/server/management/combo-suggestion-routes.ts index f399f5a4f0a..1c1f78b784e 100644 --- a/src/server/management/combo-suggestion-routes.ts +++ b/src/server/management/combo-suggestion-routes.ts @@ -14,6 +14,7 @@ import type { ManagementContext } from "./context"; import { jsonResponse } from "../auth-cors"; import { mutatePersistedConfig } from "../../config"; import { managementBodyTooLargeResponse, readManagementJsonBody } from "./body"; +import { hasHumanDashboardSession } from "./consent-session"; import { isPlainRecord } from "./shared"; const MAX_PROVIDERS = 256; @@ -40,16 +41,14 @@ function view(ctx: ManagementContext): Response { export async function handleComboSuggestionRoutes(ctx: ManagementContext): Promise { const { req, url } = ctx; - if (url.pathname === "/api/combo-suggestions/save" && req.method === "POST") { - return await saveSuggestion(ctx); + const exclusions = url.pathname === "/api/combo-suggestions" && (req.method === "GET" || req.method === "PUT"); + const save = url.pathname === "/api/combo-suggestions/save" && req.method === "POST"; + if (!exclusions && !save) return null; + if (!hasHumanDashboardSession(ctx)) { + return jsonResponse({ error: "dashboard session required" }, 403, req, ctx.config); } - 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; + if (save) return await saveSuggestion(ctx); + return req.method === "GET" ? view(ctx) : await writeExcluded(ctx); } async function writeExcluded(ctx: ManagementContext): Promise { diff --git a/structure/gui-and-management-api.md b/structure/gui-and-management-api.md index cdf503e0bda..37ae92d4e87 100644 --- a/structure/gui-and-management-api.md +++ b/structure/gui-and-management-api.md @@ -311,7 +311,7 @@ after the save, and a non-retryable skip (no managed catalog) is a clean save. C | File-integration plans | `src/server/management/integration-routes.ts` and `aside-profile-routes.ts` — `POST /api/client-integrations/preview`, `POST /api/client-integrations/restore/preview`, and `POST /api/client-integrations/aside/profiles/{profileId}/preview`. Management-authenticated, declared non-mutating, and they write nothing: no snapshot, no lock, no maintenance, no recovery. They answer `409 integration_preview_unavailable` rather than gathering a model roster, because discovery refreshes credentials and writes the provider cache. Responses carry only declared managed schema paths, closed change kinds and an opaque fingerprint; no value, filesystem location or selected member identity appears. Mutation routes accept `operation` and `planFingerprint` together or not at all, reject a half-bound request and an operation that disagrees with the change, and answer `409 integration_preview_stale` with a freshly computed plan. Binding is an optimistic token, never authorization. [The integration contract](clients/integrations.md) owns the ordering. | | Grok reset coupons | `src/server/management/grok-coupon-routes.ts` — `GET /api/grok/reset-coupons`, `POST /api/grok/reset-coupons/consume`. The dashboard owner is `gui/src/hooks/useGrokResetCoupons.ts` with `gui/src/components/provider-workspace/GrokResetCoupons.tsx`, wired into the xAI OAuth rows of `ProviderAuthPanel`. Redemption truth is the settled ledger `code`, not the HTTP status: a replayed failure returns 200 with `replayed: true`. See [`providers/xai-grok.md`](providers/xai-grok.md). The route returns `ledger_unavailable` before dispatch when the shared ledger cannot be read or locked; stale uncertain attempts are inspected without another redemption or inferred success. A late inspection refusal or a lost claim replays an identity-matching definitive winner; otherwise it returns `operation_state_changed` (late refusal) or `attempt_in_progress` (lost claim) and never replaces an attempted or terminal record. Unknown-outcome responses include the effective operation ID; the CLI mints it before dispatch. Uncertain and pending attempts live in a module-level hold store shared by all hook instances and mirrored to `sessionStorage` (`ocx.grok-coupon-holds.v1`), so they survive modal close/reopen, remount, and reload for the tab session; the pending hold is written before the POST, only a definitive response for the same `operationId` clears it, and only GET refreshes are allowed after uncertainty. Every response that cannot prove settlement under a supplied operation ID, including pre-open refusals, carries that `operationId`. A definitive failure releases the matching speculative pending hold. Supplied token IDs must be non-empty strings before journal admission, and omitted account/token retries recover the operation’s durable identity within retention. Legacy version-one opens are quarantined rather than dispatched. After confirmed redemption, local settlement has five attempts and four 20 ms waits only for a `ConfigMutationLockError` caused by `SQLITE_BUSY`; any other error or changed claim stops without another redemption. | | Claude reset grants | `src/server/management/anthropic-reset-grant-routes.ts` — `GET /api/anthropic/reset-grants`, `POST /api/anthropic/reset-grants/consume` (lazy-loaded). Wire and fail-closed parsing live in `src/providers/anthropic-reset-grants.ts` (the Claude Code 2.1.278 `cedar_ember` contract, sent with `CLAUDE_CLI_USER_AGENT` from `src/providers/claude-cli-identity.ts`; every bearer request refuses redirects, and a refused claim redirect is an unknown outcome); the journal is `src/providers/anthropic-reset-grant-ledger.ts`: a cross-process `BEGIN IMMEDIATE` lock around every synchronous read-modify-write, a 90 s lease, the operation id reused as the upstream `request_id`, same-id retry only inside the vendor's ten-minute window, at most one unresolved operation per account and organization within each pool's journal and that ten-minute window, whatever grant it names (a new id gets `409 unresolved_prior_operation`), no settlement inferred from a re-read, and a fail-closed `500 journal_write_failed` when an answer cannot be recorded. Spending requires the `gui-session` principal. A journaled `reset`, including a same-id replay of that code, lifts that account cooldown only when it is a 429 quota refusal recorded before the operation was first journaled (the claim fence, `claimedAt`) and the journal's cleared windows cover every window the refusal named (both when it named none); it then drops the cached quota row and rereads usage with its own request rather than joining an older read. Model-family exclusions stay until the usage reread proves a family is no longer rejected. A failed reread leaves them in place. The HTTP result stays the journal answer if the reread fails. Other result codes do not admit. The dashboard owner is `gui/src/hooks/useAnthropicResetGrants.ts` with `gui/src/components/provider-workspace/AnthropicResetGrants.tsx` on the Anthropic OAuth rows of `ProviderAuthPanel`; the dialog re-reads the account when it opens, lets the user choose the grant (default: the selectable grant that expires first; the server re-gates the chosen `grantId`), and after an unknown outcome only retries the same id with no picker shown. Design and audit record: [`../devlog/_fin/260923_claude_reset_grants/010_plan.md`](../devlog/_fin/260923_claude_reset_grants/010_plan.md). | -| Combos | `src/server/management/combo-routes.ts` — `GET/PUT/DELETE /api/combos` own provider combination and failover definitions. `PUT` keeps a stored field the body omits (`cooldownMs`, `waitForCooldownMs`, `defaultEffortMode`, `reasoningEffortMode`, `imageInput`, `cooldownWaitPolicy`, per-target `lastResort`, JEV `decisionQuotaSignals`/`decisionQuotaTiers`/`jevEffortMode`/`sessionPin` on updates/rename); quota false/null clears sparsely and switching away removes quota policy under [the owning contract](providers/jev-decision.md#loaded-advisory-quota). Explicit values replace it and defaults are stored sparse. A combo validation 400 is `{ error, field? }`, where `field` is the top-level combo field of the first issue. `GET /api/combo-suggestions` and `PUT /api/combo-suggestions` use the dashboard-only route in `src/server/management/combo-suggestion-routes.ts`. Both return `{ excludedProviders: string[] }`. PUT validates the full replacement list and persists it before publishing the live value. `POST /api/combo-suggestions/save` accepts a combo ID, a create or append mode, and provider/model pairs. The locked config mutation checks each new target against provider classifications in both the active and persisted config, along with persisted exclusions and combo spend consent. A paid classification in either config requires stored consent and sets `metered: true` on the new target. Create has no spend consent. Conflicts return a fixed reason code and the dashboard refreshes the suggestions. When appending suggestions, the server uses the more costly tier from the active and saved configurations. It treats existing targets explicitly marked as metered as pay-per-use and preserves the relative order of existing targets. | +| Combos | `src/server/management/combo-routes.ts` — `GET/PUT/DELETE /api/combos` own provider combination and failover definitions. `PUT` keeps a stored field the body omits (`cooldownMs`, `waitForCooldownMs`, `defaultEffortMode`, `reasoningEffortMode`, `imageInput`, `cooldownWaitPolicy`, per-target `lastResort`, JEV `decisionQuotaSignals`/`decisionQuotaTiers`/`jevEffortMode`/`sessionPin` on updates/rename); quota false/null clears sparsely and switching away removes quota policy under [the owning contract](providers/jev-decision.md#loaded-advisory-quota). Explicit values replace it and defaults are stored sparse. A combo validation 400 is `{ error, field? }`, where `field` is the top-level combo field of the first issue. `GET /api/combo-suggestions` and `PUT /api/combo-suggestions` use the dashboard-only route in `src/server/management/combo-suggestion-routes.ts`. All three suggestion operations require `hasHumanDashboardSession` before dispatch. Admin-token and remembered-admin callers receive 403. The two exclusion operations return `{ excludedProviders: string[] }`. PUT validates the full replacement list and persists it before publishing the live value. `POST /api/combo-suggestions/save` accepts a combo ID, a create or append mode, and provider/model pairs. The locked config mutation checks each new target against provider classifications in both the active and persisted config, along with persisted exclusions and combo spend consent. A paid classification in either config requires stored consent and sets `metered: true` on the new target. Create has no spend consent. Conflicts return a fixed reason code and the dashboard refreshes the suggestions. When appending suggestions, the server uses the more costly tier from the active and saved configurations. It treats existing targets explicitly marked as metered as pay-per-use and preserves the relative order of existing targets. | | Protocol paths | `src/server/management/protocol-routes.ts` (lazy-loaded) — `GET /api/protocols` returns the contract version, the resolved API surfaces and protocol settings, the policy revision and the feature vocabulary; with `?provider=` (one non-empty name of at most 200 characters without control characters, else 400 `invalid_provider`; an unconfigured name is 404 `unknown_provider`, neither echoing the name) it adds a `provider` block from `src/protocols/provider-summary.ts` ([Protocol Paths](data-planes/protocol-paths.md#provider-wire-summary)); `POST /api/protocols/plan` takes `{ model, inbound, features? }` (model at most 200 characters, at most 24 features, any other key refused with 400) and returns a `ProtocolPlanV1` with `basis: "preview"` from `src/protocols/plan-snapshot.ts`. Both are read-only, never log their input, and send nothing upstream. `PATCH /api/protocols/settings` takes `{ messagesEnabled?, unrepresentable?, rollout? }` (strict: unknown keys and wrong types are 400), validates and applies through `src/server/management/protocol-settings-patch.ts`, persists with `saveConfigPreservingClaudeCode`, restores the live config if the save fails (409 on lock contention, 500 otherwise), and answers with the fresh `GET /api/protocols` body; closing Messages also writes `claudeCode.enabled = false` through `commitClaudeCodeBlock` ([Protocol Paths](data-planes/protocol-paths.md#settings)). The CLI drives all three through `ocx api protocols`, `ocx api explain` and `ocx api policy` ([Protocol Paths](data-planes/protocol-paths.md#cli)); none carries a route-registry exemption. | | Workflow budget | `src/server/management/workflow-budget-routes.ts` — `GET /api/workflow-budget` reads the tracked roots or one root, and `POST /api/workflow-budget/clear` clears exactly one. The clear moves the windowed send ring and the child map and nothing else: `active` belongs to turns still in flight, the spend ledger is a token budget an operator did not ask to forgive, and the lifetime send total survives so a clear cannot launder the record. A refusal event carries `spendScope` and `spendLimit` when a token ceiling fired, so the reason is readable without the config open beside it; no scope id is ever attached, because root ids are client thread headers and identity ids are credentials. Both are `deferred-verb` in the route registry — they are owed CLI verbs, and because the ledger is process memory there is no local projection the CLI could read instead. `GET`/`PUT /api/workflow-budget/settings` read and write the per-install count ceilings (`workflowBudget` in config: concurrent turns, sends and distinct children per window); the live config is bound in `src/lib/workflow-budget-config.ts` and read per decision by HTTP admission and the pre-dispatch send ceiling, so a write applies to the next request and never resets a root's usage. The window, interactive reserve and tracked-root bound stay fixed because a root's ring geometry is fixed when it first appears. The GET is `local-transport` (same block via `ocx config get`), the PUT `deferred-verb` with the other budget verbs. See [`../devlog/_fin/260915_workflow_budget_window/030_wfc_diff_plan.md`](../devlog/_fin/260915_workflow_budget_window/030_wfc_diff_plan.md). | | Codex accounts | `src/codex/auth-api/routes.ts` — `GET/POST/DELETE /api/codex-auth/accounts`, `PUT /api/codex-auth/accounts/alias`, `PUT /api/codex-auth/accounts/pause`, `PUT /api/codex-auth/accounts/pause-exhausted`, `POST /api/codex-auth/accounts/clear-cooldown`, `GET/PUT /api/codex-auth/active`, `PUT /api/codex-auth/auto-switch`, `PUT /api/codex-auth/pool-strategy`, `PUT /api/codex-auth/failover`, `GET /api/codex-auth/quota`, `GET /api/codex-auth/reset-credits` with `POST /api/codex-auth/reset-credits/consume`, and the login flow `POST /api/codex-auth/login`, `POST /api/codex-auth/login/code`, `POST /api/codex-auth/login/cancel`, `GET /api/codex-auth/login-status`. Pool login cancellation through `POST /api/codex-auth/login/cancel` addresses the flow id returned by the pool start route and follows the [pool publication contract](providers/openai-accounts.md#pool-login-policy-and-cancellation). Per-account quota activation uses the existing `GET/PUT /api/settings` surface and `src/codex/quota-auto-refresh.ts`, keeping scheduled spending separate from credential/authentication mutation. Account ids are opaque handles and are serialized so the GUI can address an account; emails are masked and tokens are never serialized. New-account config commits add UI-managed selector bindings in the same config save; deletion deliberately retains existing bindings for fail-closed exact routing and re-add stability. Account mutations request catalog convergence only after config durability and expose only the boolean `catalogRefreshPending` completion projection. `showCodexCredits` is a default-off boolean in settings GET and successful PUT; partial PUT accepts a boolean and rolls back on persistence failure. See [credits exposure](providers/openai-accounts.md#display-only-codex-credits). | From 2474fd1ca812dce86657eca0c23a0f449fbdc23e Mon Sep 17 00:00:00 2001 From: JUN Date: Thu, 19 Nov 2026 01:13:51 +0900 Subject: [PATCH 08/23] docs(combos): include Tailscale dashboard sessions --- docs-site/src/content/docs/es/reference/management-api.md | 2 +- docs-site/src/content/docs/reference/management-api.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs-site/src/content/docs/es/reference/management-api.md b/docs-site/src/content/docs/es/reference/management-api.md index dd379cdedaa..fd6f0da221c 100644 --- a/docs-site/src/content/docs/es/reference/management-api.md +++ b/docs-site/src/content/docs/es/reference/management-api.md @@ -221,7 +221,7 @@ Las instantáneas de sesión incluyen `resumable`. Se vuelve cierto sólo despu | `POST /api/combo-suggestions/save` | Guarda pares de proveedor y modelo sugeridos con `{ id, mode, targets }` y modo `"create"` o `"append"` | 400 solicitud inválida; 403 si falta una sesión de panel válida; 409 si el consentimiento, las exclusiones, la disponibilidad o el estado del combo impiden guardar. Si la configuración activa o la guardada clasifica un destino como de pago, se requiere el consentimiento existente del combo y el destino se guarda como medido. Al añadir sugerencias, el servidor aplica el nivel de mayor coste entre la configuración activa y la guardada. Trata los destinos existentes marcados explícitamente como medidos como destinos de pago por uso y conserva el orden relativo de los destinos existentes. | | `DELETE /api/combos?id=...` | Eliminar un combo y borrar su estado de selección/enfriamiento | 400 id ausente; 404 combo desconocido | -Las tres operaciones de sugerencias (`GET /api/combo-suggestions`, `PUT /api/combo-suggestions` y `POST /api/combo-suggestions/save`) requieren una sesión de panel iniciada mediante el acceso local o el emparejamiento. Las credenciales de administrador y las sesiones recordadas reciben un 403. +Las tres operaciones de sugerencias (`GET /api/combo-suggestions`, `PUT /api/combo-suggestions` y `POST /api/combo-suggestions/save`) requieren una sesión de panel iniciada mediante el acceso local, una identidad de Tailscale verificada o el emparejamiento. Las credenciales de administrador y las sesiones recordadas reciben un 403. Consulte [Combos](/es/guides/combos/) para conocer las estrategias de destino, los tiempos de reutilización, los alias y los fallos de enrutamiento. diff --git a/docs-site/src/content/docs/reference/management-api.md b/docs-site/src/content/docs/reference/management-api.md index 1fe91e3bb66..2e9c8342797 100644 --- a/docs-site/src/content/docs/reference/management-api.md +++ b/docs-site/src/content/docs/reference/management-api.md @@ -250,7 +250,7 @@ completes. | `POST /api/combo-suggestions/save` | Save suggested provider/model pairs using `{ id, mode, targets }` with mode `"create"` or `"append"` | 400 invalid request; 403 without an eligible dashboard session; 409 when consent, exclusions, provider availability, or combo state prevents the save. A target classified as paid in either the active or persisted config requires existing combo consent and is saved as metered. When appending suggestions, the server uses the more costly tier from the active and saved configurations. It treats existing targets explicitly marked as metered as pay-per-use and preserves the relative order of existing targets. | | `DELETE /api/combos?id=...` | Delete one combo and clear its selection/cooldown state | 400 missing id; 404 unknown combo | -All three suggestion operations (`GET /api/combo-suggestions`, `PUT /api/combo-suggestions`, and `POST /api/combo-suggestions/save`) require a dashboard session issued through local bootstrap or pairing. Admin credentials and remembered sessions receive a 403. +All three suggestion operations (`GET /api/combo-suggestions`, `PUT /api/combo-suggestions`, and `POST /api/combo-suggestions/save`) require a dashboard session issued through local bootstrap, verified Tailscale identity, or pairing. Admin credentials and remembered sessions receive a 403. See [Combos](/guides/combos/) for target strategies, cooldowns, aliases, and routing failures. From 141dd5a8a3e2ad718700ba5f8a12aeb69f7959bd Mon Sep 17 00:00:00 2001 From: JUN Date: Thu, 19 Nov 2026 01:23:00 +0900 Subject: [PATCH 09/23] fix(combos): preserve management route discovery --- .../management/combo-suggestion-routes.ts | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/src/server/management/combo-suggestion-routes.ts b/src/server/management/combo-suggestion-routes.ts index 1c1f78b784e..902d0cb37f3 100644 --- a/src/server/management/combo-suggestion-routes.ts +++ b/src/server/management/combo-suggestion-routes.ts @@ -41,14 +41,18 @@ function view(ctx: ManagementContext): Response { export async function handleComboSuggestionRoutes(ctx: ManagementContext): Promise { const { req, url } = ctx; - const exclusions = url.pathname === "/api/combo-suggestions" && (req.method === "GET" || req.method === "PUT"); - const save = url.pathname === "/api/combo-suggestions/save" && req.method === "POST"; - if (!exclusions && !save) return null; - if (!hasHumanDashboardSession(ctx)) { - return jsonResponse({ error: "dashboard session required" }, 403, req, ctx.config); + const allowed = hasHumanDashboardSession(ctx); + const denied = () => jsonResponse({ error: "dashboard session required" }, 403, req, ctx.config); + if (url.pathname === "/api/combo-suggestions/save" && req.method === "POST") { + return allowed ? await saveSuggestion(ctx) : denied(); } - if (save) return await saveSuggestion(ctx); - return req.method === "GET" ? view(ctx) : await writeExcluded(ctx); + if (url.pathname === "/api/combo-suggestions" && req.method === "GET") { + return allowed ? view(ctx) : denied(); + } + if (url.pathname === "/api/combo-suggestions" && req.method === "PUT") { + return allowed ? await writeExcluded(ctx) : denied(); + } + return null; } async function writeExcluded(ctx: ManagementContext): Promise { From 3ea63dbe789f09a69e142476f05c8dff1094523c Mon Sep 17 00:00:00 2001 From: JUN Date: Thu, 19 Nov 2026 01:23:22 +0900 Subject: [PATCH 10/23] test(cli): account for dashboard-only combo suggestions --- tests/cli/cli-headless-parity.test.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/cli/cli-headless-parity.test.ts b/tests/cli/cli-headless-parity.test.ts index 7b0840e227b..9fefdfca983 100644 --- a/tests/cli/cli-headless-parity.test.ts +++ b/tests/cli/cli-headless-parity.test.ts @@ -601,6 +601,7 @@ describe("headless GUI parity CLI", () => { // inventory and writes one config key. There is no headless equivalent // today, and claiming one would be worse than saying so here. ["/api/codex-prompt", "(none — GUI prompt-layer surface; keys live in config.toml)"], + ["/api/combo-suggestions", "(none — Combos suggestions require a dashboard session)"], // Claude reset grants: reading is an owed CLI verb (deferred-verb in the route // registry) and spending is dashboard-session-only by design. ["/api/anthropic/reset-grants", "(none — GUI reset-grant dialog; spend requires a dashboard session)"], From 9842f7e79788c4acec9e56818d12028d273335c3 Mon Sep 17 00:00:00 2001 From: JUN Date: Thu, 19 Nov 2026 01:36:36 +0900 Subject: [PATCH 11/23] fix(combos): require consent for custom forward gateways --- .../src/content/docs/es/guides/combos.md | 2 +- docs-site/src/content/docs/guides/combos.md | 2 +- gui/src/pages/Combos.tsx | 3 ++ gui/tests/combo-suggestions.test.tsx | 25 ++++++++++- src/combos/suggestion-channel.ts | 5 +++ src/providers/openai-tiers-destination.ts | 3 +- src/server/auth-cors.ts | 2 + structure/config.md | 2 +- structure/dashboard-and-usage.md | 2 +- structure/gui-and-management-api.md | 2 +- structure/providers-and-adapters.md | 2 +- tests/server/combo-suggestion-routes.test.ts | 43 +++++++++++++------ 12 files changed, 72 insertions(+), 21 deletions(-) diff --git a/docs-site/src/content/docs/es/guides/combos.md b/docs-site/src/content/docs/es/guides/combos.md index 1822dbc9d99..7344c33736e 100644 --- a/docs-site/src/content/docs/es/guides/combos.md +++ b/docs-site/src/content/docs/es/guides/combos.md @@ -792,4 +792,4 @@ Un rechazo estructurado de esfuerzo puede bajar una posición publicada cada vez Si los ajustes cambian antes de guardar una sugerencia, Combos actualiza las sugerencias y muestra un mensaje. Al guardar, se comprueban las exclusiones y el consentimiento de gasto vigentes. Al añadir sugerencias, el servidor aplica el nivel de mayor coste entre la configuración activa y la guardada. Trata los destinos existentes marcados explícitamente como medidos como destinos de pago por uso y conserva el orden relativo de los destinos existentes. -En el espacio de trabajo de combos, **Generar** abre un borrador de conmutación por error para un modelo disponible en varios proveedores. **Añadir al combo** ofrece destinos que faltan en un combo existente. Las tarjetas descartadas quedan ocultas en este navegador. Usa **Excluir un proveedor…** para filtrar ambos tipos de sugerencias. El proxy guarda la selección como `comboSuggestionExcludedProviders` en `config.json`. Los miembros existentes se conservan. Los borradores nuevos usan destinos sin medición. Las ampliaciones ofrecen destinos de pago por uso, incluido Vertex, solo si el combo ya permite destinos medidos. El panel comprueba la configuración actual antes de guardar. El control de exclusión sigue disponible tras descartar todas las tarjetas. Si falla la carga de la lista de exclusión, vuelve a intentarlo para ver las sugerencias. +En el espacio de trabajo de combos, **Generar** abre un borrador de conmutación por error para un modelo disponible en varios proveedores. **Añadir al combo** ofrece destinos que faltan en un combo existente. Las tarjetas descartadas quedan ocultas en este navegador. Usa **Excluir un proveedor…** para filtrar ambos tipos de sugerencias. El proxy guarda la selección como `comboSuggestionExcludedProviders` en `config.json`. Los miembros existentes se conservan. Los borradores nuevos usan destinos sin medición. Las ampliaciones ofrecen destinos de pago por uso, incluido Vertex, solo si el combo ya permite destinos medidos. El panel comprueba la configuración actual antes de guardar. El control de exclusión sigue disponible tras descartar todas las tarjetas. Si falla la carga de la lista de exclusión, vuelve a intentarlo para ver las sugerencias. Las pasarelas con autenticación reenviada cuentan como destinos de pago por uso, salvo si usan el destino canónico de ChatGPT Codex. diff --git a/docs-site/src/content/docs/guides/combos.md b/docs-site/src/content/docs/guides/combos.md index 4f09bc610be..636b2315aa3 100644 --- a/docs-site/src/content/docs/guides/combos.md +++ b/docs-site/src/content/docs/guides/combos.md @@ -1218,4 +1218,4 @@ untried targets and newer failures keep their cooldowns. When settings change before a suggestion is saved, Combos refreshes the suggestions and displays a message. Saving checks the current exclusions and spend consent. -In the Combos workspace, **Generate** opens a failover draft for a model served by multiple providers. **Add to combo** offers missing targets for an existing combo. Dismissed cards stay hidden in this browser. Use **Exclude providers…** to filter both kinds of suggestions. The proxy stores your selection as `comboSuggestionExcludedProviders` in `config.json`. When appending suggestions, the server uses the more costly tier from the active and saved configurations. It treats existing targets explicitly marked as metered as pay-per-use and preserves the relative order of existing targets. New drafts use unmetered targets. Extensions offer pay-per-use targets, including Vertex, only when the combo already allows metered targets. The dashboard checks the current configuration before saving. The exclusion control stays available when all cards are dismissed. If the exclusion list fails to load, retry the read to see suggestions. +In the Combos workspace, **Generate** opens a failover draft for a model served by multiple providers. **Add to combo** offers missing targets for an existing combo. Dismissed cards stay hidden in this browser. Use **Exclude providers…** to filter both kinds of suggestions. The proxy stores your selection as `comboSuggestionExcludedProviders` in `config.json`. When appending suggestions, the server uses the more costly tier from the active and saved configurations. It treats existing targets explicitly marked as metered as pay-per-use and preserves the relative order of existing targets. New drafts use unmetered targets. Extensions offer pay-per-use targets, including Vertex, only when the combo already allows metered targets. The dashboard checks the current configuration before saving. The exclusion control stays available when all cards are dismissed. If the exclusion list fails to load, retry the read to see suggestions. Forward gateways count as pay-per-use unless they use the canonical ChatGPT Codex destination. diff --git a/gui/src/pages/Combos.tsx b/gui/src/pages/Combos.tsx index e9f4d04187a..9b6a0f9ae18 100644 --- a/gui/src/pages/Combos.tsx +++ b/gui/src/pages/Combos.tsx @@ -27,6 +27,7 @@ type ProviderOption = { hiddenFromPicker?: boolean; authMode?: string; googleMode?: "ai-studio" | "vertex" | "cloud-code-assist"; + canonicalOpenAiForward?: boolean; vertexCredentialKind?: "marker" | "ambient" | "reference" | "api-key"; adapter?: string; baseUrl?: string; @@ -50,6 +51,7 @@ type ProviderDto = { models?: string[]; authMode?: string; googleMode?: "ai-studio" | "vertex" | "cloud-code-assist"; + canonicalOpenAiForward?: boolean; vertexCredentialKind?: "marker" | "ambient" | "reference" | "api-key"; }; type ConfigDto = { providers?: Record }; @@ -178,6 +180,7 @@ export default function Combos({ disabled: !!p.disabled, hiddenFromPicker: p.adapter === "jev-decision" || !Object.hasOwn(visibleProviders, name), authMode: p.authMode, + canonicalOpenAiForward: p.canonicalOpenAiForward, googleMode: p.googleMode, vertexCredentialKind: p.vertexCredentialKind, adapter: p.adapter, diff --git a/gui/tests/combo-suggestions.test.tsx b/gui/tests/combo-suggestions.test.tsx index 3c0014c2e62..bc6ad1f706c 100644 --- a/gui/tests/combo-suggestions.test.tsx +++ b/gui/tests/combo-suggestions.test.tsx @@ -41,7 +41,7 @@ const PROVIDERS: SuggestionProvider[] = [ { 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: "openai", adapter: "openai-responses", 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 }, @@ -87,6 +87,27 @@ describe("buildComboSuggestions", () => { })).toEqual(["create gemini-3.8-flash: google-antigravity > cursor"]); }); + test("custom forward gateways stay out of drafts and require consent on append", () => { + const model = "gpt-6-luna"; + const input = { + providers: [...PROVIDERS, { name: "gateway", adapter: "openai-responses", authMode: "forward", baseUrl: "https://gateway.example/v1" }], + models: models([["openai", model], ["cursor", model], ["gateway", model]]), + }; + expect(summary(input)).toEqual(["create gpt-6-luna: openai > cursor"]); + expect(summary({ ...input, combos: [combo(model, [["openai", model], ["cursor", model]])] })).toEqual([]); + expect(summary({ ...input, combos: [combo(model, [["openai", model], ["cursor", model]], { allowMeteredTargets: true })] })) + .toEqual(["extend gpt-6-luna: gateway"]); + }); + + test("a sanitized forward URL cannot override the server's destination classification", () => { + const model = "gpt-6-luna"; + const gateway = { ...PROVIDERS.find((provider) => provider.name === "openai")!, name: "gateway", canonicalOpenAiForward: false }; + expect(summary({ + providers: [...PROVIDERS, gateway], + models: models([["openai", model], ["cursor", model], ["gateway", model]]), + })).toEqual(["create gpt-6-luna: openai > 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([]); }); @@ -215,7 +236,7 @@ describe("drafts", () => { 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: "anything", adapter: "openai-responses", authMode: "forward", baseUrl: "https://chatgpt.com/backend-api/codex" }, "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"); diff --git a/src/combos/suggestion-channel.ts b/src/combos/suggestion-channel.ts index 15345c79bb0..a7c958cccaf 100644 --- a/src/combos/suggestion-channel.ts +++ b/src/combos/suggestion-channel.ts @@ -1,8 +1,11 @@ +import { isCanonicalOpenAiForwardProvider } from "../providers/openai-tiers-destination"; + export interface SuggestionProvider { name: string; disabled?: boolean; hiddenFromPicker?: boolean; authMode?: string; + canonicalOpenAiForward?: boolean; googleMode?: string; vertexCredentialKind?: string; adapter?: string; @@ -60,6 +63,8 @@ function hostOf(baseUrl: string | undefined): string { export function channelTier(provider: SuggestionProvider, model: string): ChannelTier { const host = hostOf(provider.baseUrl); + if (provider.authMode === "forward" + && (provider.canonicalOpenAiForward === false || !isCanonicalOpenAiForwardProvider(provider))) return "metered"; if (provider.googleMode === "vertex" || provider.vertexCredentialKind || /(?:^|[.-])aiplatform\.googleapis\.com$/.test(host) || /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]; diff --git a/src/providers/openai-tiers-destination.ts b/src/providers/openai-tiers-destination.ts index 93d847bf3e7..682671fd5f3 100644 --- a/src/providers/openai-tiers-destination.ts +++ b/src/providers/openai-tiers-destination.ts @@ -19,9 +19,10 @@ function normalizedBaseUrl(value: string): string | undefined { } } -export function isCanonicalOpenAiForwardProvider(provider: OcxProviderConfig): boolean { +export function isCanonicalOpenAiForwardProvider(provider: { adapter?: string; authMode?: string; baseUrl?: string }): boolean { return provider.adapter === "openai-responses" && provider.authMode === "forward" + && provider.baseUrl !== undefined && normalizedBaseUrl(provider.baseUrl) === CODEX_FORWARD_BASE_URL; } diff --git a/src/server/auth-cors.ts b/src/server/auth-cors.ts index 157577c0505..44f2c449ffe 100644 --- a/src/server/auth-cors.ts +++ b/src/server/auth-cors.ts @@ -1,3 +1,4 @@ +import { isCanonicalOpenAiForwardProvider } from "../providers/openai-tiers-destination"; import { providerRelativeSendPathConfigError } from "../config/provider-relative-send-path"; import { contextTierRecordConfigError, modelCapabilitiesConfigError, providerInputModalitiesConfigError } from "../config/provider-validation"; import { createHmac, randomBytes, timingSafeEqual } from "node:crypto"; @@ -1473,6 +1474,7 @@ export function safeConfigDTO(config: OcxConfig): unknown { ...editor.providers[name], hasApiKey: !!provider.apiKey, hasHeaders: !!provider.headers && Object.keys(provider.headers).length > 0, + ...(provider.authMode === "forward" ? { canonicalOpenAiForward: isCanonicalOpenAiForwardProvider(provider) } : {}), }; const registry = getProviderRegistryEntry(name); const vertex = (provider.adapter === "google" && effectiveGoogleMode(name, provider) === "vertex") diff --git a/structure/config.md b/structure/config.md index e3e6345c70d..15ff67791ff 100644 --- a/structure/config.md +++ b/structure/config.md @@ -554,7 +554,7 @@ Account quota surfaces use [safe probe diagnostics](transports/inventory.md#acco The OpenCode launcher resolves the existing local management origin from the live bind and configured hub ingress. Its admin credential comes from the existing admin environment/file policy; an absent credential fails without substituting a data key. -The optional `autoReviewOverride` block stores a global approval reviewer selector and enabled flag. The Models settings route validates and normalizes writes, restores the live block when persistence fails before publication, and reports catalog convergence; the dashboard shows pending when the catalog did not commit. Malformed hand edits drop this block without discarding other configuration. Provider `autoReviewModel` and `autoReviewModelOverrides` accept validated final-catalog selectors. Per-model keys preserve case and accept the existing raw/encoded slash equivalence. File-load degradation removes malformed optional selectors only; management writes reject malformed shapes. Omitted provider saves preserve selectors, explicit clears remove them, and raw editor candidates adopt normalized values before persistence and live replacement. See [catalog ownership](catalog.md#provider-scoped-approval-reviewer). The optional `comboSuggestionExcludedProviders` array is owned by `src/config/schema/config-schema.ts`. It accepts up to 256 trimmed, deduplicated provider names of at most 256 characters each. A malformed value is dropped during parsing. Saving an empty list removes the key. The preference filters dashboard suggestions and leaves configured combo targets in place. `src/server/management/combo-suggestion-routes.ts` reads exclusions and stored combo consent from the locked persisted snapshot used to save a suggestion. It checks provider metering against both that snapshot and the active config on every evaluation, including a rebase. +The optional `autoReviewOverride` block stores a global approval reviewer selector and enabled flag. The Models settings route validates and normalizes writes, restores the live block when persistence fails before publication, and reports catalog convergence; the dashboard shows pending when the catalog did not commit. Malformed hand edits drop this block without discarding other configuration. Provider `autoReviewModel` and `autoReviewModelOverrides` accept validated final-catalog selectors. Per-model keys preserve case and accept the existing raw/encoded slash equivalence. File-load degradation removes malformed optional selectors only; management writes reject malformed shapes. Omitted provider saves preserve selectors, explicit clears remove them, and raw editor candidates adopt normalized values before persistence and live replacement. See [catalog ownership](catalog.md#provider-scoped-approval-reviewer). The optional `comboSuggestionExcludedProviders` array is owned by `src/config/schema/config-schema.ts`. It accepts up to 256 trimmed, deduplicated provider names of at most 256 characters each. A malformed value is dropped during parsing. Saving an empty list removes the key. The preference filters dashboard suggestions and leaves configured combo targets in place. `src/server/management/combo-suggestion-routes.ts` reads exclusions and stored combo consent from the locked persisted snapshot used to save a suggestion. It checks provider metering against both that snapshot and the active config on every evaluation, including a rebase. Combo suggestions classify forward gateways as metered unless the provider passes the same canonical ChatGPT Codex destination check as the Responses transport. Display-name validation retains prototype-shaped model IDs as data; reviewer-target map validation remains separate and rejects its reserved keys. ## Explicit per-model capability declarations diff --git a/structure/dashboard-and-usage.md b/structure/dashboard-and-usage.md index 8261643b081..9dc4ad13d2d 100644 --- a/structure/dashboard-and-usage.md +++ b/structure/dashboard-and-usage.md @@ -501,7 +501,7 @@ Dashboard overview polling observes authorization failures independently of stal The [explicit model-capability contract](config.md#explicit-per-model-capability-declarations) preserves operator declarations through provider storage and catalog capture; it does not infer upstream capability or change this surface's routing behavior. -Exact [model input declarations](config.md#explicit-per-model-capability-declarations) now feed text-only eligibility and catalog hints; existing image-description/omission handling consumes them before the main upstream send. The Combos page sends non-image members as the request-only `visionSidecarTargets` field on `PUT /api/combos` whenever the Image switch is enabled, so text-only enrollment needs no manual provider edit. The GUI classifies members from the authoritative `visionSidecarConsumer` flag served on `/api/models` rows, so a member covered only by legacy `noVisionModels` keeps its sidecar classification after reload. Members whose modalities are unknown or have no text input keep the switch unavailable and are named in the hint; a member later removed from the combo keeps its provider declaration until cleared in the provider editor. `gui/src/components/route-board/WorkspaceSuggestions.tsx` renders suggestion cards inside the Combos workspace. Generation uses the existing combo save flow, and extension is held while that combo has unsaved workspace edits. Dismissals are browser-local. Provider exclusions are persisted by the management API. The workspace gates cards on a successful exclusion read for the current proxy and offers a retry on failure. The exclusion control remains available after the last card is dismissed. New drafts use unmetered targets. Extensions offer metered targets, including Vertex, only with existing explicit combo consent. The save path rechecks live provider configuration and combo consent, and the combo write leaves consent management to the existing server policy. +Exact [model input declarations](config.md#explicit-per-model-capability-declarations) now feed text-only eligibility and catalog hints; existing image-description/omission handling consumes them before the main upstream send. The Combos page sends non-image members as the request-only `visionSidecarTargets` field on `PUT /api/combos` whenever the Image switch is enabled, so text-only enrollment needs no manual provider edit. The GUI classifies members from the authoritative `visionSidecarConsumer` flag served on `/api/models` rows, so a member covered only by legacy `noVisionModels` keeps its sidecar classification after reload. Members whose modalities are unknown or have no text input keep the switch unavailable and are named in the hint; a member later removed from the combo keeps its provider declaration until cleared in the provider editor. `gui/src/components/route-board/WorkspaceSuggestions.tsx` renders suggestion cards inside the Combos workspace. Generation uses the existing combo save flow, and extension is held while that combo has unsaved workspace edits. Dismissals are browser-local. Provider exclusions are persisted by the management API. The workspace gates cards on a successful exclusion read for the current proxy and offers a retry on failure. The exclusion control remains available after the last card is dismissed. New drafts use unmetered targets. Extensions offer metered targets, including Vertex, only with existing explicit combo consent. The save path rechecks live provider configuration and combo consent, and the combo write leaves consent management to the existing server policy. Forward gateways require spend consent unless they use the canonical ChatGPT Codex destination. The raw provider editor round-trips `autoReviewModel` and `autoReviewModelOverrides` through editor-owned DTO fields. POST/PATCH/PUT share validation; PUT copies schema-normalized values into the persisted and live candidate before adoption. Canonical `openai` rejects these fields, including clear forms. Field-masked writes (PATCH, editor PUT, reload) pin every registry-seed key and ignore operator overlays the seed never defines, most commonly `selectedModels`; POST keeps the exact-key comparison. Canonical `openai` still rejects `allowPrivateNetwork`, which must not short-circuit destination DNS checks on the ChatGPT forward row. Existing authentication, origin checks and stale-baseline protection still govern the writes. See [reviewer projection](catalog.md#provider-scoped-approval-reviewer). Stored Direct substitution follows the [credential identity contract](providers/openai-accounts.md#sidecars-management-and-ui): both synchronous and asynchronous materializers discard the caller account header before applying the stored credential; ordinary native Direct passthrough is unchanged. diff --git a/structure/gui-and-management-api.md b/structure/gui-and-management-api.md index 37ae92d4e87..a4c9e032c00 100644 --- a/structure/gui-and-management-api.md +++ b/structure/gui-and-management-api.md @@ -311,7 +311,7 @@ after the save, and a non-retryable skip (no managed catalog) is a clean save. C | File-integration plans | `src/server/management/integration-routes.ts` and `aside-profile-routes.ts` — `POST /api/client-integrations/preview`, `POST /api/client-integrations/restore/preview`, and `POST /api/client-integrations/aside/profiles/{profileId}/preview`. Management-authenticated, declared non-mutating, and they write nothing: no snapshot, no lock, no maintenance, no recovery. They answer `409 integration_preview_unavailable` rather than gathering a model roster, because discovery refreshes credentials and writes the provider cache. Responses carry only declared managed schema paths, closed change kinds and an opaque fingerprint; no value, filesystem location or selected member identity appears. Mutation routes accept `operation` and `planFingerprint` together or not at all, reject a half-bound request and an operation that disagrees with the change, and answer `409 integration_preview_stale` with a freshly computed plan. Binding is an optimistic token, never authorization. [The integration contract](clients/integrations.md) owns the ordering. | | Grok reset coupons | `src/server/management/grok-coupon-routes.ts` — `GET /api/grok/reset-coupons`, `POST /api/grok/reset-coupons/consume`. The dashboard owner is `gui/src/hooks/useGrokResetCoupons.ts` with `gui/src/components/provider-workspace/GrokResetCoupons.tsx`, wired into the xAI OAuth rows of `ProviderAuthPanel`. Redemption truth is the settled ledger `code`, not the HTTP status: a replayed failure returns 200 with `replayed: true`. See [`providers/xai-grok.md`](providers/xai-grok.md). The route returns `ledger_unavailable` before dispatch when the shared ledger cannot be read or locked; stale uncertain attempts are inspected without another redemption or inferred success. A late inspection refusal or a lost claim replays an identity-matching definitive winner; otherwise it returns `operation_state_changed` (late refusal) or `attempt_in_progress` (lost claim) and never replaces an attempted or terminal record. Unknown-outcome responses include the effective operation ID; the CLI mints it before dispatch. Uncertain and pending attempts live in a module-level hold store shared by all hook instances and mirrored to `sessionStorage` (`ocx.grok-coupon-holds.v1`), so they survive modal close/reopen, remount, and reload for the tab session; the pending hold is written before the POST, only a definitive response for the same `operationId` clears it, and only GET refreshes are allowed after uncertainty. Every response that cannot prove settlement under a supplied operation ID, including pre-open refusals, carries that `operationId`. A definitive failure releases the matching speculative pending hold. Supplied token IDs must be non-empty strings before journal admission, and omitted account/token retries recover the operation’s durable identity within retention. Legacy version-one opens are quarantined rather than dispatched. After confirmed redemption, local settlement has five attempts and four 20 ms waits only for a `ConfigMutationLockError` caused by `SQLITE_BUSY`; any other error or changed claim stops without another redemption. | | Claude reset grants | `src/server/management/anthropic-reset-grant-routes.ts` — `GET /api/anthropic/reset-grants`, `POST /api/anthropic/reset-grants/consume` (lazy-loaded). Wire and fail-closed parsing live in `src/providers/anthropic-reset-grants.ts` (the Claude Code 2.1.278 `cedar_ember` contract, sent with `CLAUDE_CLI_USER_AGENT` from `src/providers/claude-cli-identity.ts`; every bearer request refuses redirects, and a refused claim redirect is an unknown outcome); the journal is `src/providers/anthropic-reset-grant-ledger.ts`: a cross-process `BEGIN IMMEDIATE` lock around every synchronous read-modify-write, a 90 s lease, the operation id reused as the upstream `request_id`, same-id retry only inside the vendor's ten-minute window, at most one unresolved operation per account and organization within each pool's journal and that ten-minute window, whatever grant it names (a new id gets `409 unresolved_prior_operation`), no settlement inferred from a re-read, and a fail-closed `500 journal_write_failed` when an answer cannot be recorded. Spending requires the `gui-session` principal. A journaled `reset`, including a same-id replay of that code, lifts that account cooldown only when it is a 429 quota refusal recorded before the operation was first journaled (the claim fence, `claimedAt`) and the journal's cleared windows cover every window the refusal named (both when it named none); it then drops the cached quota row and rereads usage with its own request rather than joining an older read. Model-family exclusions stay until the usage reread proves a family is no longer rejected. A failed reread leaves them in place. The HTTP result stays the journal answer if the reread fails. Other result codes do not admit. The dashboard owner is `gui/src/hooks/useAnthropicResetGrants.ts` with `gui/src/components/provider-workspace/AnthropicResetGrants.tsx` on the Anthropic OAuth rows of `ProviderAuthPanel`; the dialog re-reads the account when it opens, lets the user choose the grant (default: the selectable grant that expires first; the server re-gates the chosen `grantId`), and after an unknown outcome only retries the same id with no picker shown. Design and audit record: [`../devlog/_fin/260923_claude_reset_grants/010_plan.md`](../devlog/_fin/260923_claude_reset_grants/010_plan.md). | -| Combos | `src/server/management/combo-routes.ts` — `GET/PUT/DELETE /api/combos` own provider combination and failover definitions. `PUT` keeps a stored field the body omits (`cooldownMs`, `waitForCooldownMs`, `defaultEffortMode`, `reasoningEffortMode`, `imageInput`, `cooldownWaitPolicy`, per-target `lastResort`, JEV `decisionQuotaSignals`/`decisionQuotaTiers`/`jevEffortMode`/`sessionPin` on updates/rename); quota false/null clears sparsely and switching away removes quota policy under [the owning contract](providers/jev-decision.md#loaded-advisory-quota). Explicit values replace it and defaults are stored sparse. A combo validation 400 is `{ error, field? }`, where `field` is the top-level combo field of the first issue. `GET /api/combo-suggestions` and `PUT /api/combo-suggestions` use the dashboard-only route in `src/server/management/combo-suggestion-routes.ts`. All three suggestion operations require `hasHumanDashboardSession` before dispatch. Admin-token and remembered-admin callers receive 403. The two exclusion operations return `{ excludedProviders: string[] }`. PUT validates the full replacement list and persists it before publishing the live value. `POST /api/combo-suggestions/save` accepts a combo ID, a create or append mode, and provider/model pairs. The locked config mutation checks each new target against provider classifications in both the active and persisted config, along with persisted exclusions and combo spend consent. A paid classification in either config requires stored consent and sets `metered: true` on the new target. Create has no spend consent. Conflicts return a fixed reason code and the dashboard refreshes the suggestions. When appending suggestions, the server uses the more costly tier from the active and saved configurations. It treats existing targets explicitly marked as metered as pay-per-use and preserves the relative order of existing targets. | +| Combos | `src/server/management/combo-routes.ts` — `GET/PUT/DELETE /api/combos` own provider combination and failover definitions. `PUT` keeps a stored field the body omits (`cooldownMs`, `waitForCooldownMs`, `defaultEffortMode`, `reasoningEffortMode`, `imageInput`, `cooldownWaitPolicy`, per-target `lastResort`, JEV `decisionQuotaSignals`/`decisionQuotaTiers`/`jevEffortMode`/`sessionPin` on updates/rename); quota false/null clears sparsely and switching away removes quota policy under [the owning contract](providers/jev-decision.md#loaded-advisory-quota). Explicit values replace it and defaults are stored sparse. A combo validation 400 is `{ error, field? }`, where `field` is the top-level combo field of the first issue. `GET /api/combo-suggestions` and `PUT /api/combo-suggestions` use the dashboard-only route in `src/server/management/combo-suggestion-routes.ts`. All three suggestion operations require `hasHumanDashboardSession` before dispatch. Admin-token and remembered-admin callers receive 403. The two exclusion operations return `{ excludedProviders: string[] }`. PUT validates the full replacement list and persists it before publishing the live value. `POST /api/combo-suggestions/save` accepts a combo ID, a create or append mode, and provider/model pairs. The locked config mutation checks each new target against provider classifications in both the active and persisted config, along with persisted exclusions and combo spend consent. A paid classification in either config requires stored consent and sets `metered: true` on the new target. Create has no spend consent. Conflicts return a fixed reason code and the dashboard refreshes the suggestions. When appending suggestions, the server uses the more costly tier from the active and saved configurations. It treats existing targets explicitly marked as metered as pay-per-use and preserves the relative order of existing targets. The dashboard and save route share the tier classifier. The config DTO carries the canonical forward decision computed before URL sanitization, so redaction cannot make a gateway appear unmetered. | | Protocol paths | `src/server/management/protocol-routes.ts` (lazy-loaded) — `GET /api/protocols` returns the contract version, the resolved API surfaces and protocol settings, the policy revision and the feature vocabulary; with `?provider=` (one non-empty name of at most 200 characters without control characters, else 400 `invalid_provider`; an unconfigured name is 404 `unknown_provider`, neither echoing the name) it adds a `provider` block from `src/protocols/provider-summary.ts` ([Protocol Paths](data-planes/protocol-paths.md#provider-wire-summary)); `POST /api/protocols/plan` takes `{ model, inbound, features? }` (model at most 200 characters, at most 24 features, any other key refused with 400) and returns a `ProtocolPlanV1` with `basis: "preview"` from `src/protocols/plan-snapshot.ts`. Both are read-only, never log their input, and send nothing upstream. `PATCH /api/protocols/settings` takes `{ messagesEnabled?, unrepresentable?, rollout? }` (strict: unknown keys and wrong types are 400), validates and applies through `src/server/management/protocol-settings-patch.ts`, persists with `saveConfigPreservingClaudeCode`, restores the live config if the save fails (409 on lock contention, 500 otherwise), and answers with the fresh `GET /api/protocols` body; closing Messages also writes `claudeCode.enabled = false` through `commitClaudeCodeBlock` ([Protocol Paths](data-planes/protocol-paths.md#settings)). The CLI drives all three through `ocx api protocols`, `ocx api explain` and `ocx api policy` ([Protocol Paths](data-planes/protocol-paths.md#cli)); none carries a route-registry exemption. | | Workflow budget | `src/server/management/workflow-budget-routes.ts` — `GET /api/workflow-budget` reads the tracked roots or one root, and `POST /api/workflow-budget/clear` clears exactly one. The clear moves the windowed send ring and the child map and nothing else: `active` belongs to turns still in flight, the spend ledger is a token budget an operator did not ask to forgive, and the lifetime send total survives so a clear cannot launder the record. A refusal event carries `spendScope` and `spendLimit` when a token ceiling fired, so the reason is readable without the config open beside it; no scope id is ever attached, because root ids are client thread headers and identity ids are credentials. Both are `deferred-verb` in the route registry — they are owed CLI verbs, and because the ledger is process memory there is no local projection the CLI could read instead. `GET`/`PUT /api/workflow-budget/settings` read and write the per-install count ceilings (`workflowBudget` in config: concurrent turns, sends and distinct children per window); the live config is bound in `src/lib/workflow-budget-config.ts` and read per decision by HTTP admission and the pre-dispatch send ceiling, so a write applies to the next request and never resets a root's usage. The window, interactive reserve and tracked-root bound stay fixed because a root's ring geometry is fixed when it first appears. The GET is `local-transport` (same block via `ocx config get`), the PUT `deferred-verb` with the other budget verbs. See [`../devlog/_fin/260915_workflow_budget_window/030_wfc_diff_plan.md`](../devlog/_fin/260915_workflow_budget_window/030_wfc_diff_plan.md). | | Codex accounts | `src/codex/auth-api/routes.ts` — `GET/POST/DELETE /api/codex-auth/accounts`, `PUT /api/codex-auth/accounts/alias`, `PUT /api/codex-auth/accounts/pause`, `PUT /api/codex-auth/accounts/pause-exhausted`, `POST /api/codex-auth/accounts/clear-cooldown`, `GET/PUT /api/codex-auth/active`, `PUT /api/codex-auth/auto-switch`, `PUT /api/codex-auth/pool-strategy`, `PUT /api/codex-auth/failover`, `GET /api/codex-auth/quota`, `GET /api/codex-auth/reset-credits` with `POST /api/codex-auth/reset-credits/consume`, and the login flow `POST /api/codex-auth/login`, `POST /api/codex-auth/login/code`, `POST /api/codex-auth/login/cancel`, `GET /api/codex-auth/login-status`. Pool login cancellation through `POST /api/codex-auth/login/cancel` addresses the flow id returned by the pool start route and follows the [pool publication contract](providers/openai-accounts.md#pool-login-policy-and-cancellation). Per-account quota activation uses the existing `GET/PUT /api/settings` surface and `src/codex/quota-auto-refresh.ts`, keeping scheduled spending separate from credential/authentication mutation. Account ids are opaque handles and are serialized so the GUI can address an account; emails are masked and tokens are never serialized. New-account config commits add UI-managed selector bindings in the same config save; deletion deliberately retains existing bindings for fail-closed exact routing and re-add stability. Account mutations request catalog convergence only after config durability and expose only the boolean `catalogRefreshPending` completion projection. `showCodexCredits` is a default-off boolean in settings GET and successful PUT; partial PUT accepts a boolean and rolls back on persistence failure. See [credits exposure](providers/openai-accounts.md#display-only-codex-credits). | diff --git a/structure/providers-and-adapters.md b/structure/providers-and-adapters.md index 1f5de472a41..14c4a03b065 100644 --- a/structure/providers-and-adapters.md +++ b/structure/providers-and-adapters.md @@ -202,7 +202,7 @@ rewrite rules and the routed-id settlement. | `src/combos/failover.ts` | Recognizes the exact bounded ChatGPT plan/model HTTP400 refusal in a bare message or a single `detail`/`error.message` envelope. OpenRouter's opaque numeric-400 `Provider returned error` wrapper with `metadata.raw: "ERROR"`, without `type`, may advance to another target without cooling the failed target; typed uncoded 400s, known malformed `response_format` schemas, an envelope root whose own code is a terminal request verdict (while a root that states only an ordinary hop signal adds no verdict and an empty code counts as absent, so HTTP and SSE agree), and other hard stops remain terminal. The root code and the record it wraps are both consulted, so a hop needs each to authorize one; request-local target incompatibilities defined in `structure/runtime.md` may advance. Competing envelopes stop before code-based hops; finite evidence survives display truncation and SSE error reconstruction without retaining raw bodies. This permits another declared target before output commitment, never credential revocation or provider-wide quota evidence. | | `src/combos/request.ts` | Clones each selected combo target request and applies the existing target capability ladder: adaptive unknown targets and explicit empty ladders strip effort and legacy alternative controls while retaining independent `reasoning.enabled` and summary; known ladders retain per-target resolution. | | `src/adapters/openai-responses.ts`, `src/adapters/openai-responses/` | Native OpenAI/ChatGPT Responses passthrough. Compaction parsing normalizes known incomplete aliases under the [incomplete reason contract](transports/responses-wire-shapes.md#adapter-incomplete-reasons). The canonical ChatGPT adapter forces its upstream-only `stream: true` requirement without changing caller `store`; downstream JSON negotiation remains owned by the [Responses HTTP/SSE contract](transports/responses.md#responses-httpsse). | -| `src/adapters/openai-responses/transport.ts` | Shared Responses URL, configured auth and caller-header construction for ordinary requests and explicitly enabled custom native v1 compact. Its compact-handoff metadata copier uses the existing client-header allowlist, never credentials, through internal request construction and Codex auth materialization. Protocol capability never grants canonical identity; v2 trigger and native blob replay remain independently declared. On the noncanonical forward path, configured `baseUrl` trailing-slash stripping is a linear scan that preserves interior slash runs and leaves the canonical forward base and non-forward auth modes untouched; `tests/responses/responses-forward-transport-baseurl.test.ts` pins it. | +| `src/adapters/openai-responses/transport.ts` | Shared Responses URL, configured auth and caller-header construction for ordinary requests and explicitly enabled custom native v1 compact. Its compact-handoff metadata copier uses the existing client-header allowlist, never credentials, through internal request construction and Codex auth materialization. Protocol capability never grants canonical identity; v2 trigger and native blob replay remain independently declared. On the noncanonical forward path, configured `baseUrl` trailing-slash stripping is a linear scan that preserves interior slash runs and leaves the canonical forward base and non-forward auth modes untouched; `tests/responses/responses-forward-transport-baseurl.test.ts` pins it. The combo suggestion classifier uses the Responses transport’s canonical ChatGPT Codex destination predicate for the forward subscription tier. Other forward gateways are metered. | | `src/responses/muse-tool-name-alias.ts` | Host-gated Meta Muse 64-char tool-name alias/restore used by the Responses passthrough. | | `src/adapters/openai-chat.ts`, `src/adapters/openai-chat/` | OpenAI-compatible Chat Completions bridge, split into leaves (`wire.ts`, `messages.ts`, `response-events.ts`, `passthrough.ts`, `parallel-tool-calls.ts`, `reasoning-wire.ts`, `serialized-tool-call-content.ts`, `serialized-tool-call-markup.ts`, `standalone-bare-tool-calls.ts`, `tool-call-validation.ts`, `tool-call-id-remint.ts`, `tool-schema.ts`, `errors.ts`). `parallel-tool-calls.ts` owns the `parallel_tool_calls` wire value for both the translated and native builders, so the three provider states — configured opt-out, configured opt-in, and the unset default that forwards only a caller's explicit `false` — cannot drift between them. `reasoning-wire.ts` applies explicit gateway-object and tool-bearing effort-omission declarations to both builders; absent declarations leave native raw forwarding unchanged. Its client delivery shapes in `src/chat/outbound.ts` and `src/server/chat-native-sse.ts` relay the upstream `service_tier` echo on non-stream, folded-stream, and synthesized-SSE bodies, never inventing the key when the upstream omits it. | | `src/adapters/anthropic.ts` | Anthropic Messages bridge. A `refusal` or `content_filter` stop reason yields an explicit `incomplete` event with `retryable: false` rather than `done` with that stopReason (#4312); `max_tokens` remains `done`. For a Responses client the bridge delivers that event, and the same one from the Kiro adapter, as a terminal `response.failed` ([Adapter-to-Responses bridge](transports/responses.md#adapter-to-responses-bridge)). It is the wire that defines `tools[*].strict` and `tools[*].allowed_callers`, so a rebuilt declaration carries both: an explicit `strict: true` and any `allowed_callers` the caller declared. An absent `strict` stays absent, because the Messages inbound records it as `false` and a `false` on the wire would read as an opt-out nobody asked for. Anthropic Fast uses the native `anthropic-speed` FastWire: a set decision sends `speed: "fast"` with `fast-mode-2026-02-01` in one case-insensitively merged, deduplicated `anthropic-beta` header that preserves OAuth betas. Stream and buffered `usage.speed` echoes confirm fast or downgrade to standard; no echo leaves the request assumed. `tests/adapters/anthropic/anthropic-fast-speed.test.ts` pins the wire and echoes. Anthropic Fast is opt-in: the registry marks both Anthropic entries `fastOptIn`, and `src/providers/fast-opt-in.ts` (`providerFastSwitchOff`) keeps Fast off until `providers..fastEnabled` is `true`. An off switch is provider capability `false`, applied in the FastPolicy authority (`service-tier.ts`), `resolveModelPolicy`, and router registry enrichment, so no model-level Fast toggle, `--fast` row, or proxy-generated `speed` field is produced. Native Claude Messages passthrough still forwards a `speed` field the caller sends itself, outside the proxy Fast policy. `tests/adapters/anthropic/anthropic-fast-opt-in.test.ts` pins the default, the switch, and the management PATCH/GET. For `api.anthropic.com` only, the Claude client's typed web tools (`parsed._anthropicServerTools`) follow the function tools unchanged, minus the caller's `cache_control`; a function tool of the same name wins, so the web-search sidecar's `web_search` keeps priority and `web_fetch` is still carried. No beta header is added: both tools are GA. Each streamed `web_search_tool_result` or `web_fetch_tool_result` becomes a `web_search_call_begin`/`web_search_call_end` pair (the query of its `server_tool_use` in the same response, hit URLs and titles, or `failed` for an error result) carrying `anthropic`: that `server_tool_use` with its complete streamed input and the result block, verbatim. An orphan result, a result with a different call id, or a result whose call input cannot be parsed is dropped with no synthetic call; the surrounding text is preserved. Streamed server-tool input retains at most 4,096 characters, slicing each incoming fragment to the remaining capacity; an oversized input that cannot be recovered drops its exchange under the same rule. The bridge and the direct encoder keep both on the `web_search_call` item as `anthropic_blocks` (a fetch is an `open_page` action), and the Claude outbound renders them back unchanged, with the original `srvtoolu_` id, `encrypted_content` and `page_age`; a fetch is not counted in `web_search_requests`. A search Anthropic defers beside a client `tool_use` has no result in that response and surfaces nothing. On the next turn, `messagesToAnthropicFormat` re-inserts the client's replayed pairs (`parsed._anthropicServerReplay`) ahead of the `tool_use`, text or thinking block that followed them, for `api.anthropic.com` only. An anchor must occur exactly once across assistant history, counting string and block content alike; repeated anchors drop their exchanges and preserve the other turns. Replay requires one-to-one call/result ids and matching tool types within the same assistant turn, with the call preceding its result in the original sequence. A single forward pass tracks pending calls and rejects reversed pairs, duplicate ids and orphan results. Calls require a plain input object with a nonempty `web_search.query` or `web_fetch.url` string; malformed input, a pair without `encrypted_content`, or a pair with no following anchor stays dropped. Stored `anthropic_blocks` restore only when call id, result id, tool/result types and input object agree; malformed metadata falls back to the rebuilt pair. Citations, a deferred search and `pause_turn` are not resumed. `tests/claude-integration/claude-translated-server-tools.test.ts` pins the wire, the sidecar priority, the bridge's client stream and JSON, and the direct encoder's stream. Claude Code's typed Advisor (`advisor_YYYYMMDD`) rides the same lane under `planAnthropicServerTools` in `src/adapters/anthropic/advisor-tool.ts`: the declaration and the client's completed Advisor exchanges go to an `anthropic`-adapter provider whose credential domain is first-party Anthropic, or to a gateway with `forwardAdvisorTool: true` (`false` opts out; the Zed delegate sets it because its wire is Zed), and only while no function tool named `advisor` (the proxy Advisor's synthetic tool) owns the name; either one adds the `advisor-tool-2026-03-01` beta. A streamed `advisor_tool_result` pairs with the same response's `server_tool_use`, whose input must be empty, and leaves as a `web_search_call_begin`/`web_search_call_end` pair with no queries whose `anthropic` carries both blocks verbatim (`failed` for `advisor_tool_result_error`, never counted in `web_search_requests`). A result whose content is not `advisor_result`, `advisor_redacted_result` or `advisor_tool_result_error` with string fields only is dropped, and the Claude outbound restores stored blocks under the same check. A call pending at `pause_turn` is not surfaced. `tests/claude-integration/claude-translated-advisor-tool.test.ts` pins the destinations, the beta, the three client lanes and replay. On translated Claude Messages requests, the inbound path carries the caller's last cache-marked system prefix out of the request body. When that prefix still matches the translated instructions after routed-model identity normalization and has a trailing system block, the Anthropic adapter splits it from the per-turn tail and moves its existing system cache breakpoint to the prefix; absent or mismatched prefixes keep the prior single-block behavior. `tests/claude-integration/claude-translated-cache-ttl.test.ts` checks the stable cached bytes across changing tails. Prompt-cache TTL: an omitted `cacheRetention` resolves through `src/adapters/anthropic/cache-retention.ts` to 1h (`ttl: "1h"`) for first-party `api.anthropic.com` (API key and OAuth pools) and to 5m for Anthropic-compatible endpoints, which do not document the 1h TTL; an explicit value wins everywhere. The direct native Messages passthrough upgrades caller breakpoints without a TTL to 1h under the same rule unless the caller pinned any breakpoint to another TTL; exact native combo replay preserves those source breakpoints unless the operator explicitly configures retention. Usage carries `cache_creation.ephemeral_1h_input_tokens` as `cacheCreation1hInputTokens`, which `src/usage/cost.ts` prices at 1.6x the 5m write rate (2x base input). `tests/adapters/adapter-usage.test.ts`, `tests/adapters/anthropic/anthropic-messages-passthrough.test.ts` and `tests/claude-integration/claude-translated-cache-ttl.test.ts` pin the defaults. | diff --git a/tests/server/combo-suggestion-routes.test.ts b/tests/server/combo-suggestion-routes.test.ts index 5d78e0cef46..3d5ff9cc7b1 100644 --- a/tests/server/combo-suggestion-routes.test.ts +++ b/tests/server/combo-suggestion-routes.test.ts @@ -111,14 +111,33 @@ async function saveSuggestion(live: OcxConfig, body: unknown) { return dispatch(live, "/api/combo-suggestions/save", "POST", body); } +function setCanonicalForward(config: OcxConfig) { + Object.assign(config.providers.mock!, { + adapter: "openai-responses", + authMode: "forward", + baseUrl: "https://chatgpt.com/backend-api/codex", + }); +} + function seedPaidSuggestion() { const live = loadConfig(); - live.providers.paid = { ...live.providers.mock!, authMode: "forward", baseUrl: "https://aiplatform.googleapis.com/v1", models: ["gemini"] }; + live.providers.paid = { ...live.providers.mock!, authMode: "api-key", baseUrl: "https://aiplatform.googleapis.com/v1", models: ["gemini"] }; live.combos = { mix: { strategy: "failover", allowMeteredTargets: true, targets: [{ provider: "mock", model: "m" }] } }; saveConfig(live); return live; } +test("config DTO computes forward eligibility before redacting provider URLs", async () => { + const { safeConfigDTO } = await import("../../src/server/auth-cors"); + const live = loadConfig(); + setCanonicalForward(live); + live.providers.gateway = { ...live.providers.mock!, baseUrl: "https://chatgpt.com/backend-api/codex?route=custom" }; + expect(safeConfigDTO(live)).toMatchObject({ providers: { + mock: { canonicalOpenAiForward: true }, + gateway: { baseUrl: live.providers.mock!.baseUrl, canonicalOpenAiForward: false }, + } }); +}); + test.each([ ["GET", "/api/combo-suggestions", undefined], ["PUT", "/api/combo-suggestions", { excludedProviders: ["other"] }], @@ -174,25 +193,25 @@ test("create rejects paid Vertex and never accepts consent from the request", as expect(loadConfig().combos?.draft).toBeUndefined(); const current = loadConfig(); - live.providers.mock!.authMode = "forward"; - current.providers.mock!.authMode = "forward"; + setCanonicalForward(live); + setCanonicalForward(current); saveConfig(current); expect((await saveSuggestion(live, { ...draft, targets: [{ provider: "mock", model: "m" }] })).status).toBe(200); expect(loadConfig().combos?.draft?.allowMeteredTargets).toBeUndefined(); }); -for (const paidSide of ["live", "persisted"] as const) { - test(`suggestion requires consent and marks the target metered when only ${paidSide} is paid`, async () => { +for (const paidSide of ["live", "persisted", "both"] as const) { + test(`suggestion requires consent and marks the target metered when ${paidSide} config is paid`, async () => { const live = seedPaidSuggestion(); const persisted = loadConfig(); - const freeProvider = { ...live.providers.paid!, baseUrl: "https://generativelanguage.googleapis.com/v1", authMode: "forward" as const }; - const paidProvider = { ...freeProvider, authMode: "api-key" as const }; - live.providers.paid = paidSide === "live" ? paidProvider : freeProvider; - persisted.providers.paid = paidSide === "persisted" ? paidProvider : freeProvider; + const freeProvider = { ...live.providers.paid!, adapter: "openai-responses" as const, baseUrl: "https://chatgpt.com/backend-api/codex", authMode: "forward" as const }; + const paidProvider = { ...freeProvider, baseUrl: "https://gateway.example/v1" }; + live.providers.paid = paidSide !== "persisted" ? paidProvider : freeProvider; + persisted.providers.paid = paidSide !== "live" ? paidProvider : freeProvider; const subscription = { provider: "mock", model: "m" }; const explicitlyMetered = { provider: "paid", model: "previous", metered: true }; - live.providers.mock!.authMode = "forward"; - persisted.providers.mock!.authMode = "forward"; + setCanonicalForward(live); + setCanonicalForward(persisted); live.combos!.mix!.targets = [subscription, explicitlyMetered]; persisted.combos!.mix!.targets = [subscription, explicitlyMetered]; delete live.combos!.mix!.allowMeteredTargets; @@ -223,7 +242,7 @@ for (const paidSide of ["live", "persisted"] as const) { test("append inserts a subscription before explicitly metered targets without reordering them", async () => { const live = seedPaidSuggestion(); - live.providers.mock!.authMode = "forward"; + setCanonicalForward(live); const existing = [ { provider: "mock", model: "first", metered: true }, { provider: "mock", model: "second", metered: true }, From 12f5b32a88698f8e56a9af7ea1b0f1e0be96ecc3 Mon Sep 17 00:00:00 2001 From: JUN Date: Thu, 19 Nov 2026 01:37:57 +0900 Subject: [PATCH 12/23] fix(gui): keep the forward destination predicate browser-safe --- src/combos/suggestion-channel.ts | 2 +- src/providers/openai-forward-destination.ts | 19 +++++++++++++++++ src/providers/openai-tiers-destination.ts | 23 +++------------------ src/server/auth-cors.ts | 2 +- 4 files changed, 24 insertions(+), 22 deletions(-) create mode 100644 src/providers/openai-forward-destination.ts diff --git a/src/combos/suggestion-channel.ts b/src/combos/suggestion-channel.ts index a7c958cccaf..de879d7518f 100644 --- a/src/combos/suggestion-channel.ts +++ b/src/combos/suggestion-channel.ts @@ -1,4 +1,4 @@ -import { isCanonicalOpenAiForwardProvider } from "../providers/openai-tiers-destination"; +import { isCanonicalOpenAiForwardProvider } from "../providers/openai-forward-destination"; export interface SuggestionProvider { name: string; diff --git a/src/providers/openai-forward-destination.ts b/src/providers/openai-forward-destination.ts new file mode 100644 index 00000000000..faead2437f9 --- /dev/null +++ b/src/providers/openai-forward-destination.ts @@ -0,0 +1,19 @@ +export const CODEX_FORWARD_BASE_URL = "https://chatgpt.com/backend-api/codex"; + +export function normalizedBaseUrl(value: string): string | undefined { + try { + const url = new URL(value.trim()); + if (url.username || url.password || url.search || url.hash) return undefined; + const path = url.pathname.replace(/\/+$/, ""); + return `${url.origin}${path}`; + } catch { + return undefined; + } +} + +export function isCanonicalOpenAiForwardProvider(provider: { adapter?: string; authMode?: string; baseUrl?: string }): boolean { + return provider.adapter === "openai-responses" + && provider.authMode === "forward" + && provider.baseUrl !== undefined + && normalizedBaseUrl(provider.baseUrl) === CODEX_FORWARD_BASE_URL; +} diff --git a/src/providers/openai-tiers-destination.ts b/src/providers/openai-tiers-destination.ts index 682671fd5f3..2c4b6af6a28 100644 --- a/src/providers/openai-tiers-destination.ts +++ b/src/providers/openai-tiers-destination.ts @@ -1,31 +1,14 @@ import type { OcxProviderConfig } from "../types"; import { openaiResponsesUrl } from "../adapters/openai-responses-url"; +import { isCanonicalOpenAiForwardProvider, normalizedBaseUrl } from "./openai-forward-destination"; + +export { CODEX_FORWARD_BASE_URL, isCanonicalOpenAiForwardProvider } from "./openai-forward-destination"; export const OPENAI_CODEX_PROVIDER_ID = "openai"; export const LEGACY_OPENAI_MULTI_PROVIDER_ID = "openai-multi"; export const OPENAI_API_PROVIDER_ID = "openai-apikey"; export const LEGACY_CHATGPT_PROVIDER_ID = "chatgpt"; -export const CODEX_FORWARD_BASE_URL = "https://chatgpt.com/backend-api/codex"; - -function normalizedBaseUrl(value: string): string | undefined { - try { - const url = new URL(value.trim()); - if (url.username || url.password || url.search || url.hash) return undefined; - const path = url.pathname.replace(/\/+$/, ""); - return `${url.origin}${path}`; - } catch { - return undefined; - } -} - -export function isCanonicalOpenAiForwardProvider(provider: { adapter?: string; authMode?: string; baseUrl?: string }): boolean { - return provider.adapter === "openai-responses" - && provider.authMode === "forward" - && provider.baseUrl !== undefined - && normalizedBaseUrl(provider.baseUrl) === CODEX_FORWARD_BASE_URL; -} - /** * Response evidence is separate from Fast capability and request serialization. Preserve the * known Codex exception (#2558); other destinations may declare their response contract without diff --git a/src/server/auth-cors.ts b/src/server/auth-cors.ts index 44f2c449ffe..0e86d61890b 100644 --- a/src/server/auth-cors.ts +++ b/src/server/auth-cors.ts @@ -1,4 +1,4 @@ -import { isCanonicalOpenAiForwardProvider } from "../providers/openai-tiers-destination"; +import { isCanonicalOpenAiForwardProvider } from "../providers/openai-forward-destination"; import { providerRelativeSendPathConfigError } from "../config/provider-relative-send-path"; import { contextTierRecordConfigError, modelCapabilitiesConfigError, providerInputModalitiesConfigError } from "../config/provider-validation"; import { createHmac, randomBytes, timingSafeEqual } from "node:crypto"; From 8ddb5b6fc2556bffad2dd7fc5009a285f7816cd6 Mon Sep 17 00:00:00 2001 From: JUN Date: Thu, 19 Nov 2026 01:49:34 +0900 Subject: [PATCH 13/23] fix(combos): require known subscription channels for unmetered suggestions Co-authored-by: Andrew (agent) --- .../src/content/docs/es/guides/combos.md | 2 +- docs-site/src/content/docs/guides/combos.md | 2 +- gui/src/pages/Combos.tsx | 3 + gui/tests/combo-suggestions.test.tsx | 242 ++++++++++-------- src/combos/suggestion-channel.ts | 38 ++- src/server/auth-cors.ts | 2 + structure/config.md | 21 +- structure/dashboard-and-usage.md | 2 +- structure/gui-and-management-api.md | 2 +- tests/fixtures/test-layout-expected.json | 1 - tests/server/combo-suggestion-routes.test.ts | 27 ++ 11 files changed, 209 insertions(+), 133 deletions(-) diff --git a/docs-site/src/content/docs/es/guides/combos.md b/docs-site/src/content/docs/es/guides/combos.md index 7344c33736e..329e70109de 100644 --- a/docs-site/src/content/docs/es/guides/combos.md +++ b/docs-site/src/content/docs/es/guides/combos.md @@ -792,4 +792,4 @@ Un rechazo estructurado de esfuerzo puede bajar una posición publicada cada vez Si los ajustes cambian antes de guardar una sugerencia, Combos actualiza las sugerencias y muestra un mensaje. Al guardar, se comprueban las exclusiones y el consentimiento de gasto vigentes. Al añadir sugerencias, el servidor aplica el nivel de mayor coste entre la configuración activa y la guardada. Trata los destinos existentes marcados explícitamente como medidos como destinos de pago por uso y conserva el orden relativo de los destinos existentes. -En el espacio de trabajo de combos, **Generar** abre un borrador de conmutación por error para un modelo disponible en varios proveedores. **Añadir al combo** ofrece destinos que faltan en un combo existente. Las tarjetas descartadas quedan ocultas en este navegador. Usa **Excluir un proveedor…** para filtrar ambos tipos de sugerencias. El proxy guarda la selección como `comboSuggestionExcludedProviders` en `config.json`. Los miembros existentes se conservan. Los borradores nuevos usan destinos sin medición. Las ampliaciones ofrecen destinos de pago por uso, incluido Vertex, solo si el combo ya permite destinos medidos. El panel comprueba la configuración actual antes de guardar. El control de exclusión sigue disponible tras descartar todas las tarjetas. Si falla la carga de la lista de exclusión, vuelve a intentarlo para ver las sugerencias. Las pasarelas con autenticación reenviada cuentan como destinos de pago por uso, salvo si usan el destino canónico de ChatGPT Codex. +En el espacio de trabajo de combos, **Generar** abre un borrador de conmutación por error para un modelo disponible en varios proveedores. **Añadir al combo** ofrece destinos que faltan en un combo existente. Las tarjetas descartadas quedan ocultas en este navegador. Usa **Excluir un proveedor…** para filtrar ambos tipos de sugerencias. El proxy guarda la selección como `comboSuggestionExcludedProviders` en `config.json`. Los miembros existentes se conservan. Los borradores nuevos usan destinos sin medición. Las ampliaciones ofrecen destinos de pago por uso, incluido Vertex, solo si el combo ya permite destinos medidos. El panel comprueba la configuración actual antes de guardar. El control de exclusión sigue disponible tras descartar todas las tarjetas. Si falla la carga de la lista de exclusión, vuelve a intentarlo para ver las sugerencias. Las sugerencias tratan los canales como medidos de forma predeterminada. La lista de suscripciones admitidas incluye el destino canónico de ChatGPT Codex con autenticación reenviada, Grok CLI con OAuth y Kimi Code Plan con OAuth en Chat y Responses. Los demás accesos mediante OAuth y las pasarelas personalizadas requieren consentimiento para usar destinos medidos. diff --git a/docs-site/src/content/docs/guides/combos.md b/docs-site/src/content/docs/guides/combos.md index 636b2315aa3..e9a860e7123 100644 --- a/docs-site/src/content/docs/guides/combos.md +++ b/docs-site/src/content/docs/guides/combos.md @@ -1218,4 +1218,4 @@ untried targets and newer failures keep their cooldowns. When settings change before a suggestion is saved, Combos refreshes the suggestions and displays a message. Saving checks the current exclusions and spend consent. -In the Combos workspace, **Generate** opens a failover draft for a model served by multiple providers. **Add to combo** offers missing targets for an existing combo. Dismissed cards stay hidden in this browser. Use **Exclude providers…** to filter both kinds of suggestions. The proxy stores your selection as `comboSuggestionExcludedProviders` in `config.json`. When appending suggestions, the server uses the more costly tier from the active and saved configurations. It treats existing targets explicitly marked as metered as pay-per-use and preserves the relative order of existing targets. New drafts use unmetered targets. Extensions offer pay-per-use targets, including Vertex, only when the combo already allows metered targets. The dashboard checks the current configuration before saving. The exclusion control stays available when all cards are dismissed. If the exclusion list fails to load, retry the read to see suggestions. Forward gateways count as pay-per-use unless they use the canonical ChatGPT Codex destination. +In the Combos workspace, **Generate** opens a failover draft for a model served by multiple providers. **Add to combo** offers missing targets for an existing combo. Dismissed cards stay hidden in this browser. Use **Exclude providers…** to filter both kinds of suggestions. The proxy stores your selection as `comboSuggestionExcludedProviders` in `config.json`. When appending suggestions, the server uses the more costly tier from the active and saved configurations. It treats existing targets explicitly marked as metered as pay-per-use and preserves the relative order of existing targets. New drafts use unmetered targets. Extensions offer pay-per-use targets, including Vertex, only when the combo already allows metered targets. The dashboard checks the current configuration before saving. The exclusion control stays available when all cards are dismissed. If the exclusion list fails to load, retry the read to see suggestions. Suggestions treat channels as metered by default. The subscription allowlist covers canonical ChatGPT Codex forward, Grok CLI OAuth, and Kimi Code Plan OAuth on Chat and Responses. Other OAuth logins and custom gateways require metered-target consent. diff --git a/gui/src/pages/Combos.tsx b/gui/src/pages/Combos.tsx index 9b6a0f9ae18..38739f8d434 100644 --- a/gui/src/pages/Combos.tsx +++ b/gui/src/pages/Combos.tsx @@ -28,6 +28,7 @@ type ProviderOption = { authMode?: string; googleMode?: "ai-studio" | "vertex" | "cloud-code-assist"; canonicalOpenAiForward?: boolean; + knownSubscriptionOAuth?: boolean; vertexCredentialKind?: "marker" | "ambient" | "reference" | "api-key"; adapter?: string; baseUrl?: string; @@ -52,6 +53,7 @@ type ProviderDto = { authMode?: string; googleMode?: "ai-studio" | "vertex" | "cloud-code-assist"; canonicalOpenAiForward?: boolean; + knownSubscriptionOAuth?: boolean; vertexCredentialKind?: "marker" | "ambient" | "reference" | "api-key"; }; type ConfigDto = { providers?: Record }; @@ -181,6 +183,7 @@ export default function Combos({ hiddenFromPicker: p.adapter === "jev-decision" || !Object.hasOwn(visibleProviders, name), authMode: p.authMode, canonicalOpenAiForward: p.canonicalOpenAiForward, + knownSubscriptionOAuth: p.knownSubscriptionOAuth, googleMode: p.googleMode, vertexCredentialKind: p.vertexCredentialKind, adapter: p.adapter, diff --git a/gui/tests/combo-suggestions.test.tsx b/gui/tests/combo-suggestions.test.tsx index bc6ad1f706c..cf76fea43e0 100644 --- a/gui/tests/combo-suggestions.test.tsx +++ b/gui/tests/combo-suggestions.test.tsx @@ -37,10 +37,10 @@ const combo = (id: string, targets: Array<[string, string]>, extra: Partial { test("max names a model, not an effort: codex-max stays apart from codex", () => { expect(normalizeModelName("gpt-5.1-codex-max")).toBe("gpt-5-1-codex-max"); expect(normalizeModelName("gpt-5.1-codex-max-high")).toBe("gpt-5-1-codex-max"); - expect(suggest({ models: models([["openai", "gpt-5.1-codex"], ["cursor", "gpt-5.1-codex-max"]]) })).toEqual([]); + expect(suggest({ models: models([["openai", "gpt-5.1-codex"], ["xai", "gpt-5.1-codex-max"]]) })).toEqual([]); }); }); @@ -79,23 +79,38 @@ 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"], + ["xai", "Gemini-3.8-Flash"], + ["kimi-responses", "gemini-3.8-flash"], + ["kimi-responses", "gemini-3.8-flash-high"], ["openai", "gpt-6-luna"], ]), - })).toEqual(["create gemini-3.8-flash: google-antigravity > cursor"]); + })).toEqual(["create gemini-3.8-flash: xai > kimi-responses"]); + }); + + test("Devin is omitted without spend consent", () => { + const model = "gpt-6-luna"; + const current = combo(model, [["openai", model]]); + const input = { + providers: [...PROVIDERS, { name: "devin", adapter: "devin", authMode: "oauth", baseUrl: "https://server.codeium.com" }], + models: models([["openai", model], ["devin", model]]), + }; + expect(summary({ ...input, combos: [current] })).toEqual([]); + expect(summary({ ...input, combos: [{ ...current, allowMeteredTargets: true }] })).toEqual(["extend gpt-6-luna: devin"]); + }); + + test("unknown OAuth providers default to metered", () => { + expect(channelTier({ name: "unknown", adapter: "openai-chat", authMode: "oauth", baseUrl: "https://unknown.example" }, "gpt-6-luna")).toBe("metered"); }); test("custom forward gateways stay out of drafts and require consent on append", () => { const model = "gpt-6-luna"; const input = { providers: [...PROVIDERS, { name: "gateway", adapter: "openai-responses", authMode: "forward", baseUrl: "https://gateway.example/v1" }], - models: models([["openai", model], ["cursor", model], ["gateway", model]]), + models: models([["openai", model], ["xai", model], ["gateway", model]]), }; - expect(summary(input)).toEqual(["create gpt-6-luna: openai > cursor"]); - expect(summary({ ...input, combos: [combo(model, [["openai", model], ["cursor", model]])] })).toEqual([]); - expect(summary({ ...input, combos: [combo(model, [["openai", model], ["cursor", model]], { allowMeteredTargets: true })] })) + expect(summary(input)).toEqual(["create gpt-6-luna: openai > xai"]); + expect(summary({ ...input, combos: [combo(model, [["openai", model], ["xai", model]])] })).toEqual([]); + expect(summary({ ...input, combos: [combo(model, [["openai", model], ["xai", model]], { allowMeteredTargets: true })] })) .toEqual(["extend gpt-6-luna: gateway"]); }); @@ -104,8 +119,8 @@ describe("buildComboSuggestions", () => { const gateway = { ...PROVIDERS.find((provider) => provider.name === "openai")!, name: "gateway", canonicalOpenAiForward: false }; expect(summary({ providers: [...PROVIDERS, gateway], - models: models([["openai", model], ["cursor", model], ["gateway", model]]), - })).toEqual(["create gpt-6-luna: openai > cursor"]); + models: models([["openai", model], ["xai", model], ["gateway", model]]), + })).toEqual(["create gpt-6-luna: openai > xai"]); }); test("a model only one provider serves is no suggestion", () => { @@ -113,13 +128,13 @@ describe("buildComboSuggestions", () => { }); test("disabled and picker-hidden providers do not count", () => { - expect(suggest({ models: models([["anthropic", "claude-x"], ["qoder", "claude-x"], ["jev", "claude-x"]]) })).toEqual([]); + expect(suggest({ models: models([["kimi", "kimi-x"], ["qoder", "kimi-x"], ["jev", "kimi-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 hiddenModels = new Set(["openai/gpt-5.5", "xai/gpt-5.5", "xai/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"]]), + models: models([["openai", "gpt-5.5"], ["xai", "gpt-5.5"], ["openai", "gpt-5.6-luna"], ["xai", "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]]); @@ -127,118 +142,133 @@ describe("buildComboSuggestions", () => { test("consented extensions order subscriptions before Vertex, keys and relays", () => { expect(summary({ - combos: [combo("opus", [["openai", "claude-opus-5-5"]], { allowMeteredTargets: true })], + combos: [combo("opus", [["openai", "kimi-k3-1-pro"]], { allowMeteredTargets: true })], 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"], + ["zayu-claude", "kimi-k3-1-pro"], + ["anthropic-apikey", "kimi-k3-1-pro"], + ["google-vertex", "kimi-k3-1-pro"], + ["xai", "kimi-k3.1-pro"], + ["kimi", "kimi-k3-1-pro"], ]), - })).toEqual(["extend opus: anthropic > cursor > google-vertex > zayu-claude > anthropic-apikey"]); + })).toEqual(["extend opus: kimi > xai > 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 remaining: Record = { kimi: 10, "kimi-responses": 80 }; const result = suggest({ - models: models([["cursor", "claude-sonnet-5-5"], ["anthropic", "claude-sonnet-5-5"], ["google-antigravity", "claude-sonnet-5-5"]]), + models: models([["xai", "kimi-k3-256k"], ["kimi", "kimi-k3-256k"], ["kimi-responses", "kimi-k3-256k"]]), remainingPercent: (provider) => remaining[provider], }); - // anthropic is the maker's own subscription, so it leads despite its lower quota. + // Both Kimi transports are the model maker; quota breaks that tie. expect(result[0]!.members.map((m) => [m.provider, m.remainingPercent])).toEqual([ - ["anthropic", 10], ["google-antigravity", 80], ["cursor", undefined], + ["kimi-responses", 80], ["kimi", 10], ["xai", 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"]); + const combos = [combo("kimi-k3-1-pro", [["kimi", "kimi-k3-1-pro"], ["zayu-claude", "kimi-k3-1-pro"]])]; + const rows = models([["kimi", "kimi-k3-1-pro"], ["zayu-claude", "kimi-k3-1-pro"], ["xai", "kimi-k3.1-pro"]]); + expect(summary({ combos, models: rows })).toEqual(["extend kimi-k3-1-pro: xai"]); 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 combos = [combo("gemini", [["kimi-responses", "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"]), + models: models([["kimi-responses", "gemini-3.8-flash"], ["xai", "gemini-3.8-flash"], ["openai", "gpt-5.5"], ["xai", "gpt-5.5"], ["openai", "gpt-6-luna"], ["xai", "gpt-6-luna"]]), + hiddenModels: new Set(["openai/gpt-5.5", "xai/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([]); + const combos = [combo("opus", [["kimi", "kimi-k3-1-pro"], ["xai", "kimi-k3.1-pro"]])]; + expect(suggest({ combos, models: models([["kimi", "kimi-k3-1-pro"], ["xai", "kimi-k3.1-pro"]]) })).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"]); + const combos = [combo("Reviewer", [["kimi", "kimi-k3-256k"], ["kimi-responses", "gemini-3.8-flash"]])]; + expect(summary({ combos, models: models([["kimi-responses", "gemini-3.8-flash"], ["xai", "gemini-3.8-flash"]]) })) + .toEqual(["create gemini-3.8-flash: kimi-responses > xai"]); }); 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" })]; + const combos = [combo("gpt-5.5", [["openai", "gpt-6-luna"], ["kimi", "kimi-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"); + expect(suggest({ combos, models: models([["openai", "gpt-5.5"], ["xai", "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 rows = models([["openai", "gpt-5.5"], ["xai", "gpt-5.5"], ["openai", "gpt-5.6-sol"], ["xai", "gpt-5.6-sol"]]); const all = suggest({ models: rows }); expect(all.map((s) => s.key)).toEqual(["create:gpt-5-5", "create:gpt-5-6-sol"]); expect(suggest({ models: rows, dismissed: new Set(["create:gpt-5-5"]) }).map((s) => s.comboId)).toEqual(["gpt-5.6-sol"]); }); test("an excluded provider joins no suggested combo, new or existing", () => { - const rows = models([["openai", "gpt-5.5"], ["cursor", "gpt-5.5"], ["anthropic", "claude-x"], ["cursor", "claude-x"], ["google-antigravity", "claude-x"]]); - const excludedProviders = new Set(["cursor"]); - expect(summary({ models: rows, excludedProviders })).toEqual(["create claude-x: anthropic > google-antigravity"]); - const combos = [combo("claude-x", [["anthropic", "claude-x"]])]; - expect(summary({ combos, models: rows, excludedProviders })).toEqual(["extend claude-x: google-antigravity"]); + const rows = models([["openai", "gpt-5.5"], ["xai", "gpt-5.5"], ["kimi", "kimi-x"], ["xai", "kimi-x"], ["kimi-responses", "kimi-x"]]); + const excludedProviders = new Set(["xai"]); + expect(summary({ models: rows, excludedProviders })).toEqual(["create kimi-x: kimi > kimi-responses"]); + const combos = [combo("kimi-x", [["kimi", "kimi-x"]])]; + expect(summary({ combos, models: rows, excludedProviders })).toEqual(["extend kimi-x: kimi-responses"]); }); 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"], ["google-antigravity", "claude-x"]]); - expect(summary({ combos, models: rows, excludedProviders: new Set(["anthropic"]) })).toEqual(["extend claude-x: google-antigravity"]); + const combos = [combo("kimi-x", [["kimi", "kimi-x"]])]; + const rows = models([["kimi", "kimi-x"], ["kimi-responses", "kimi-x"]]); + expect(summary({ combos, models: rows, excludedProviders: new Set(["kimi"]) })).toEqual(["extend kimi-x: kimi-responses"]); expect(summary({ combos, models: rows.slice(0, 1) })).toEqual([]); - expect(summary({ models: rows, excludedProviders: new Set(["anthropic"]) })).toEqual([]); + expect(summary({ models: rows, excludedProviders: new Set(["kimi"]) })).toEqual([]); }); }); 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: "xai", 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"]); + expect(draft.targets.map((t) => `${t.provider}/${t.model}`)).toEqual(["openai/gpt-5.5", "xai/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 tiers: Record = { kimi: "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"]], { allowMeteredTargets: true }); + const base = combo("opus", [["kimi", "kimi-k3-1-pro"], ["zayu-claude", "kimi-k3-1-pro"], ["anthropic-apikey", "kimi-k3-1-pro"]], { allowMeteredTargets: true }); const next = extendedCombo(base, [ - { provider: "cursor", model: "claude-opus-5.5", tier: "subscription" }, - { provider: "relay-2", model: "claude-opus-5-5", tier: "metered" }, + { provider: "xai", model: "kimi-k3.1-pro", tier: "subscription" }, + { provider: "relay-2", model: "kimi-k3-1-pro", 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"]); + expect(next.targets.map((t) => t.provider)).toEqual(["kimi", "xai", "zayu-claude", "anthropic-apikey", "relay-2"]); + const relayFirst = combo("opus", [["zayu-claude", "kimi-k3-1-pro"], ["kimi", "kimi-k3-1-pro"]]); + expect(extendedCombo(relayFirst, [{ provider: "xai", model: "kimi-k3.1-pro", tier: "subscription" }], tierOf).targets.map((t) => t.provider)) + .toEqual(["xai", "zayu-claude", "kimi"]); + }); + + test.each([ + ["xai", "openai-chat", "https://api.x.ai/v1", "grok-4.7"], + ["xai", "openai-chat", "https://cli-chat-proxy.grok.com/v1", "grok-4.7"], + ["kimi", "openai-chat", "https://api.kimi.com/coding/v1", "kimi-for-coding"], + ["kimi-responses", "openai-responses", "https://api.kimi.com/coding/v1", "kimi-for-coding"], + ])("%s requires OAuth on its registered subscription endpoint", (name, adapter, baseUrl, model) => { + const provider = { name, adapter, baseUrl, authMode: "oauth" }; + expect(channelTier(provider, model)).toBe("own-subscription"); + expect(channelTier(provider, "other-model")).toBe("subscription"); + expect(channelTier({ ...provider, knownSubscriptionOAuth: false }, model)).toBe("metered"); + expect(channelTier({ ...provider, authMode: "key" }, model)).toBe("metered"); + expect(channelTier({ ...provider, baseUrl: "https://gateway.example/v1" }, model)).toBe("metered"); }); 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", adapter: "openai-responses", authMode: "forward", baseUrl: "https://chatgpt.com/backend-api/codex" }, "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: "xai", adapter: "openai-chat", authMode: "oauth", baseUrl: "https://api.x.ai/v1" }, "grok-4.7")).toBe("own-subscription"); + expect(channelTier({ name: "anthropic", adapter: "anthropic", authMode: "oauth", baseUrl: "https://api.anthropic.com" }, "claude-sonnet-5")).toBe("metered"); + expect(channelTier({ name: "zed", authMode: "oauth", baseUrl: "https://cloud.zed.dev" }, "grok-4.7")).toBe("metered"); expect(channelTier({ name: "ollama", baseUrl: "http://localhost:11434" }, "llama")).toBe("metered"); }); }); @@ -283,7 +313,7 @@ describe("ComboSuggestions card", () => { undefined} @@ -319,43 +349,43 @@ 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 Google Antigravity gemini-3.8-flash down").click(); }); + await act(async () => { button(draft.querySelectorAll("li")[0]!, "Move Kimi 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"]], + ["create", "gemini-3.8-flash", "failover", ["xai", "kimi-responses"]], ]); }); 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 () => { button(card("kimi-k3-1-pro"), "Dismiss").click(); }); + expect(() => card("kimi-k3-1-pro")).toThrow(); await act(async () => { root?.unmount(); }); await render(); - expect(() => card("claude-opus-5-5")).toThrow(); + expect(() => card("kimi-k3-1-pro")).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"]])]); + await render([combo("gemini", [["kimi-responses", "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"]], + ["extend", "gemini", ["kimi-responses", "xai"]], ]); }); 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. + await render([], ["xai"]); + // Every suggestion here needs xai, so only the exclusion control and the empty note show. expect(host.querySelectorAll(".rb-suggest-card")).toHaveLength(0); - const toggle = button(host, "Excluded: Cursor"); + const toggle = button(host, "Excluded: xAI Grok"); await act(async () => { toggle.click(); }); const panel = host.querySelector(".rb-suggest-exclude-panel")!; - const cursor = panel.querySelector("input[type=checkbox]:checked")!; - await act(async () => { cursor.click(); }); + const xai = panel.querySelector("input[type=checkbox]:checked")!; + await act(async () => { xai.click(); }); expect(exclusionWrites).toEqual([[]]); }); @@ -368,7 +398,7 @@ describe("ComboSuggestions card", () => { undefined} @@ -384,10 +414,10 @@ describe("ComboSuggestions card", () => { 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().some((row) => row.includes("xAI Grok"))).toBe(true); + await act(async () => { root!.render(view(["xai"])); }); expect(draftProviders().length).toBe(2); - expect(draftProviders().some((row) => row.includes("Cursor"))).toBe(false); + expect(draftProviders().some((row) => row.includes("xAI Grok"))).toBe(false); }); async function mount(node: React.ReactNode) { @@ -401,7 +431,7 @@ describe("ComboSuggestions card", () => { undefined} @@ -416,7 +446,7 @@ describe("ComboSuggestions card", () => { test("quota reordering the same members keeps an open draft's edits", async () => { const leading = (first: string) => (provider: string) => (provider === first ? 90 : 10); - await mount(sonnet({ remainingPercent: leading("cursor") })); + await mount(sonnet({ remainingPercent: leading("xai") })); await act(async () => { button(card("claude-sonnet-5-5"), "Generate").click(); }); const draft = () => card("claude-sonnet-5-5").querySelector(".rb-suggest-draft")!; const idInput = () => draft().querySelector("input.rb-suggest-id")!; @@ -425,19 +455,19 @@ describe("ComboSuggestions card", () => { setValue.call(idInput(), "my-sonnet"); idInput().dispatchEvent(new testWindow.Event("input", { bubbles: true }) as unknown as Event); }); - await act(async () => { button(draft().querySelectorAll("li")[0]!, "Move Cursor claude-sonnet-5-5 down").click(); }); - await act(async () => { root!.render(sonnet({ remainingPercent: leading("google-antigravity") })); }); + await act(async () => { button(draft().querySelectorAll("li")[0]!, "Move xAI Grok claude-sonnet-5-5 down").click(); }); + await act(async () => { root!.render(sonnet({ remainingPercent: leading("kimi-responses") })); }); expect(idInput().value).toBe("my-sonnet"); expect([...draft().querySelectorAll("li code")].length).toBe(2); - expect(draft().querySelectorAll("li")[0]!.textContent).toContain("Google Antigravity"); + expect(draft().querySelectorAll("li")[0]!.textContent).toContain("Kimi"); }); test("adding to a combo with unsaved workspace edits is held", async () => { const extended: string[] = []; - const existing = [combo("gemini", [["google-antigravity", "gemini-3.8-flash"]])]; + const existing = [combo("gemini", [["kimi-responses", "gemini-3.8-flash"]])]; const view = (locked: string | null) => sonnet({ combos: existing, - models: models([["google-antigravity", "gemini-3.8-flash"], ["cursor", "gemini-3.8-flash"]]), + models: models([["kimi-responses", "gemini-3.8-flash"], ["xai", "gemini-3.8-flash"]]), onExtend: async (item) => { extended.push(item.id); return { ok: true }; }, lockedComboId: locked, }); @@ -472,26 +502,26 @@ describe("ComboSuggestions card", () => { }; await mount(); expect(state!.ready).toBe(false); - await act(async () => { pending.shift()!({ excludedProviders: ["anthropic"] }); }); - expect([state!.ready, state!.excluded]).toEqual([true, ["anthropic"]]); + await act(async () => { pending.shift()!({ excludedProviders: ["kimi"] }); }); + expect([state!.ready, state!.excluded]).toEqual([true, ["kimi"]]); await act(async () => { root!.render(); }); expect([state!.ready, state!.excluded]).toEqual([false, []]); - expect(await state!.save(["cursor"])).toBe(false); + expect(await state!.save(["xai"])).toBe(false); expect(puts).toEqual([]); await act(async () => { pending.shift()!({ excludedProviders: ["relay"] }); }); - await act(async () => { await state!.save(["cursor"]); }); - expect(puts).toEqual([{ excludedProviders: ["cursor"] }]); - expect(state!.excluded).toEqual(["cursor"]); + await act(async () => { await state!.save(["xai"]); }); + expect(puts).toEqual([{ excludedProviders: ["xai"] }]); + expect(state!.excluded).toEqual(["xai"]); } finally { globalThis.fetch = realFetch; } }); test("new cards and drafts omit paid Vertex and API-key members", async () => { - const name = "claude-opus-5-5"; + const name = "kimi-k3-1-pro"; await mount( [provider, name]))} + combos={[]} models={models(["kimi", "xai", "google-vertex", "anthropic-apikey"].map((provider) => [provider, name]))} providers={PROVIDERS} hiddenModels={new Set()} remainingPercent={() => undefined} validate={() => null} errorText={() => "bad"} onCreate={async () => ({ ok: true })} onExtend={async () => ({ ok: true })} @@ -504,8 +534,8 @@ describe("ComboSuggestions card", () => { test("revoked metered consent blocks Add to combo and shows an error", async () => { const originalFetch = globalThis.fetch; - const name = "claude-opus-5-5"; - const existing = combo("opus", [["anthropic", name]], { allowMeteredTargets: true }); + const name = "kimi-k3-1-pro"; + const existing = combo("opus", [["kimi", name]], { allowMeteredTargets: true }); let refreshCount = 0; let exclusionReads = 0; globalThis.fetch = (async (url: string) => { @@ -518,7 +548,7 @@ describe("ComboSuggestions card", () => { try { await mount( { refreshCount += 1; }} />); @@ -540,7 +570,7 @@ describe("ComboSuggestions card", () => { try { await mount( {}} />); const visibleButtons = () => [...host.querySelectorAll("button")].map((item) => item.textContent?.trim()); @@ -559,7 +589,7 @@ describe("ComboSuggestions card", () => { test("after dismissing the last card the exclusion control still works", async () => { exclusionWrites.length = 0; await render([], []); - await act(async () => { button(card("claude-opus-5-5"), "Dismiss").click(); }); + await act(async () => { button(card("kimi-k3-1-pro"), "Dismiss").click(); }); await act(async () => { button(card("gemini-3.8-flash"), "Dismiss").click(); }); expect(host.querySelectorAll(".rb-suggest-card")).toHaveLength(0); await act(async () => { button(host, "Exclude providers…").click(); }); @@ -581,19 +611,19 @@ test("generated ids remain valid when a long model name collides", () => { }); test("another model on the same provider does not hide a missing channel", () => { - const name = "claude-opus-5-5"; + const name = "kimi-k3-1-pro"; const [suggestion] = suggest({ - combos: [combo(name, [["anthropic", name], ["cursor", "gpt-6-luna"]])], - models: models([["anthropic", name], ["cursor", name]]), + combos: [combo(name, [["kimi", name], ["xai", "gpt-6-luna"]])], + models: models([["kimi", name], ["xai", name]]), }); expect(suggestion?.kind).toBe("extend"); - expect(suggestion?.members.map(({ provider, model }) => [provider, model])).toEqual([["cursor", name]]); + expect(suggestion?.members.map(({ provider, model }) => [provider, model])).toEqual([["xai", name]]); }); test("only consented extensions serialize paid targets, without writing consent", () => { - const member = { provider: "google-vertex", model: "claude-opus-5-5", tier: "vertex" } as const; + const member = { provider: "google-vertex", model: "kimi-k3-1-pro", tier: "vertex" } as const; expect(suggestionDraft("opus", [member]).targets).toEqual([]); - const current = combo("opus", [["anthropic", member.model]]); + const current = combo("opus", [["kimi", member.model]]); expect(extendedCombo(current, [member], () => "own-subscription").targets).toEqual(current.targets); const body = toPutBody(extendedCombo({ ...current, allowMeteredTargets: true }, [member], () => "own-subscription")).combo; expect(body.targets.map(({ metered }) => metered)).toEqual([undefined, true]); diff --git a/src/combos/suggestion-channel.ts b/src/combos/suggestion-channel.ts index de879d7518f..fcbe24b7d4f 100644 --- a/src/combos/suggestion-channel.ts +++ b/src/combos/suggestion-channel.ts @@ -1,4 +1,4 @@ -import { isCanonicalOpenAiForwardProvider } from "../providers/openai-forward-destination"; +import { isCanonicalOpenAiForwardProvider, normalizedBaseUrl } from "../providers/openai-forward-destination"; export interface SuggestionProvider { name: string; @@ -6,6 +6,7 @@ export interface SuggestionProvider { hiddenFromPicker?: boolean; authMode?: string; canonicalOpenAiForward?: boolean; + knownSubscriptionOAuth?: boolean; googleMode?: string; vertexCredentialKind?: string; adapter?: string; @@ -41,16 +42,31 @@ const MODEL_MAKERS: ReadonlyArray<[RegExp, string]> = [ [/^(?:gpt|o\d|codex|chatgpt)/, "openai"], [/^(?:gemini|gemma)/, "google"], [/^grok/, "xai"], - [/^deepseek/, "deepseek"], + [/^kimi/, "moonshot"], ]; -const PROVIDER_MAKERS: ReadonlyArray<[RegExp, string]> = [ - [/(?:^|\.)anthropic\.com$/, "anthropic"], - [/(?:^|\.)(?:openai\.com|chatgpt\.com)$/, "openai"], - [/(?:^|\.)googleapis\.com$/, "google"], - [/(?:^|\.)x\.ai$/, "xai"], - [/(?:^|\.)deepseek\.com$/, "deepseek"], -]; +// Keep this allowlist aligned with the documented subscription channels in structure/config.md. +const SUBSCRIPTION_OAUTH_CHANNELS = [ + { name: "xai", adapter: "openai-chat", baseUrl: "https://api.x.ai/v1", maker: "xai" }, + { name: "xai", adapter: "openai-chat", baseUrl: "https://cli-chat-proxy.grok.com/v1", maker: "xai" }, + { name: "kimi", adapter: "openai-chat", baseUrl: "https://api.kimi.com/coding/v1", maker: "moonshot" }, + { name: "kimi-responses", adapter: "openai-responses", baseUrl: "https://api.kimi.com/coding/v1", maker: "moonshot" }, +] as const; + +function subscriptionMaker(provider: SuggestionProvider): string | undefined { + if (provider.authMode === "forward") { + return provider.canonicalOpenAiForward !== false && isCanonicalOpenAiForwardProvider(provider) ? "openai" : undefined; + } + return provider.knownSubscriptionOAuth === false ? undefined : oauthSubscriptionMaker(provider); +} + +export function oauthSubscriptionMaker(provider: SuggestionProvider): string | undefined { + if (provider.authMode !== "oauth" || !provider.baseUrl) return undefined; + const baseUrl = normalizedBaseUrl(provider.baseUrl); + return SUBSCRIPTION_OAUTH_CHANNELS.find((channel) => + channel.name === provider.name && channel.adapter === provider.adapter && channel.baseUrl === baseUrl + )?.maker; +} function hostOf(baseUrl: string | undefined): string { if (!baseUrl) return ""; @@ -66,9 +82,9 @@ export function channelTier(provider: SuggestionProvider, model: string): Channe if (provider.authMode === "forward" && (provider.canonicalOpenAiForward === false || !isCanonicalOpenAiForwardProvider(provider))) return "metered"; if (provider.googleMode === "vertex" || provider.vertexCredentialKind || /(?:^|[.-])aiplatform\.googleapis\.com$/.test(host) || /vertex/i.test(provider.name)) return "vertex"; - if (provider.authMode !== "oauth" && provider.authMode !== "forward") return "metered"; + const providerMaker = subscriptionMaker(provider); + if (!providerMaker) 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"; } diff --git a/src/server/auth-cors.ts b/src/server/auth-cors.ts index 0e86d61890b..f25865bb352 100644 --- a/src/server/auth-cors.ts +++ b/src/server/auth-cors.ts @@ -1,3 +1,4 @@ +import { oauthSubscriptionMaker } from "../combos/suggestion-channel"; import { isCanonicalOpenAiForwardProvider } from "../providers/openai-forward-destination"; import { providerRelativeSendPathConfigError } from "../config/provider-relative-send-path"; import { contextTierRecordConfigError, modelCapabilitiesConfigError, providerInputModalitiesConfigError } from "../config/provider-validation"; @@ -1474,6 +1475,7 @@ export function safeConfigDTO(config: OcxConfig): unknown { ...editor.providers[name], hasApiKey: !!provider.apiKey, hasHeaders: !!provider.headers && Object.keys(provider.headers).length > 0, + ...(provider.authMode === "oauth" ? { knownSubscriptionOAuth: oauthSubscriptionMaker({ ...provider, name }) !== undefined } : {}), ...(provider.authMode === "forward" ? { canonicalOpenAiForward: isCanonicalOpenAiForwardProvider(provider) } : {}), }; const registry = getProviderRegistryEntry(name); diff --git a/structure/config.md b/structure/config.md index 15ff67791ff..9d7fa165cbe 100644 --- a/structure/config.md +++ b/structure/config.md @@ -554,7 +554,14 @@ Account quota surfaces use [safe probe diagnostics](transports/inventory.md#acco The OpenCode launcher resolves the existing local management origin from the live bind and configured hub ingress. Its admin credential comes from the existing admin environment/file policy; an absent credential fails without substituting a data key. -The optional `autoReviewOverride` block stores a global approval reviewer selector and enabled flag. The Models settings route validates and normalizes writes, restores the live block when persistence fails before publication, and reports catalog convergence; the dashboard shows pending when the catalog did not commit. Malformed hand edits drop this block without discarding other configuration. Provider `autoReviewModel` and `autoReviewModelOverrides` accept validated final-catalog selectors. Per-model keys preserve case and accept the existing raw/encoded slash equivalence. File-load degradation removes malformed optional selectors only; management writes reject malformed shapes. Omitted provider saves preserve selectors, explicit clears remove them, and raw editor candidates adopt normalized values before persistence and live replacement. See [catalog ownership](catalog.md#provider-scoped-approval-reviewer). The optional `comboSuggestionExcludedProviders` array is owned by `src/config/schema/config-schema.ts`. It accepts up to 256 trimmed, deduplicated provider names of at most 256 characters each. A malformed value is dropped during parsing. Saving an empty list removes the key. The preference filters dashboard suggestions and leaves configured combo targets in place. `src/server/management/combo-suggestion-routes.ts` reads exclusions and stored combo consent from the locked persisted snapshot used to save a suggestion. It checks provider metering against both that snapshot and the active config on every evaluation, including a rebase. Combo suggestions classify forward gateways as metered unless the provider passes the same canonical ChatGPT Codex destination check as the Responses transport. +The optional `autoReviewOverride` block stores a global approval reviewer selector and enabled flag. The Models settings route validates and normalizes writes, restores the live block when persistence fails before publication, and reports catalog convergence; the dashboard shows pending when the catalog did not commit. Malformed hand edits drop this block without discarding other configuration. Provider `autoReviewModel` and `autoReviewModelOverrides` accept validated final-catalog selectors. Per-model keys preserve case and accept the existing raw/encoded slash equivalence. File-load degradation removes malformed optional selectors only; management writes reject malformed shapes. Omitted provider saves preserve selectors, explicit clears remove them, and raw editor candidates adopt normalized values before persistence and live replacement. See [catalog ownership](catalog.md#provider-scoped-approval-reviewer). The optional `comboSuggestionExcludedProviders` array is owned by `src/config/schema/config-schema.ts`. It accepts up to 256 trimmed, deduplicated provider names of at most 256 characters each. A malformed value is dropped during parsing. Saving an empty list removes the key. The preference filters dashboard suggestions and leaves configured combo targets in place. `src/server/management/combo-suggestion-routes.ts` reads exclusions and stored combo consent from the locked persisted snapshot used to save a suggestion. It checks provider metering against both that snapshot and the active config on every evaluation, including a rebase. The dashboard and suggestion save route use the allowlist in `src/combos/suggestion-channel.ts`. Each OAuth entry requires the registered provider ID, adapter, auth mode, and exact normalized destination. See the [provider billing and account notes](../docs-site/src/content/docs/guides/providers.md). + +- Canonical ChatGPT Codex forward uses the Codex login account channel and the same destination predicate as Responses transport. +- `xai` OAuth uses the Grok CLI subscription gateway. The public API-key lane is metered. +- `kimi` OAuth uses Kimi Code Plan quota on the Chat wire. +- `kimi-responses` OAuth uses the same Kimi Code Plan entitlement on the Responses wire. + +Other channels require metered-target consent. The registry audit leaves Devin and Kiro metered because of credit billing, OrcaRouter because OAuth issues an inference API key, and Nous because its catalog mixes paid and free models. Claude OAuth instances can draw from extra-usage credits, including for third-party apps. Google Antigravity, Cursor, Zed, Command Code, WorkBuddy AI, DeepSeek Harness, Meta Muse and GitHub Copilot remain metered because the account and catalog descriptions do not establish flat-rate coverage for all requests. Vertex retains its separate metered tier. Custom forward gateways and unknown OAuth channels default to metered. Display-name validation retains prototype-shaped model IDs as data; reviewer-target map validation remains separate and rejects its reserved keys. ## Explicit per-model capability declarations @@ -565,16 +572,8 @@ Provider-wide `inputModalities` is an optional nonempty array of `text`, `image` The text-only consumer reads exact inputModalities declarations before legacy hints. CLI add/edit `--text-only` targets one model and preserves sibling declarations; `src/vision/eligibility.ts` routes declared text-only models into existing image-description or explicit-omission handling. Positive routed image declarations override stale candidate metadata, while native catalog authority retains its existing legacy policy. `PUT /api/combos` accepts a request-only `visionSidecarTargets` array of exact combo-member `{ provider, model }` pairs (validated against the submitted combo's normalized targets, deduplicated, rejected while `imageInput` is `"disabled"`). An entry whose provider is unconfigured, whose model already accepts image input through any source, or whose exact declaration, custom row, or provider `modelInputModalities` hint lacks `text` is rejected with 400 instead of being overwritten; an entry the sidecar already covers through any runtime source (exact declaration, custom row, `noVisionModels`, legacy record, registry enrichment) is skipped as a no-op. Accepted entries merge `inputModalities: ["text"]` through the same validation/merge helpers, and the combo write, reference migrations, disabled-selector rewrite and capability patches commit in one provider-patch transaction — a failed save restores all of them. The field never persists under `config.combos`, and removing a member from the combo leaves its provider declaration in place until cleared explicitly. -An explicit custom row is the operator's own definition of one routed model, so its -`customModels[].inputModalities` outranks the provider-level vision hints -(`noVisionModels`, `modelInputModalities`) for that exact `provider`/`modelId` identity. -`modelCapabilities` keeps the top slot as the dedicated capability axis, including for the -`ocx provider edit --text-only` write. The catalog overlay in -`src/codex/catalog/routed-gather.ts` copies that declaration onto the advertised row directly, -and the request-path predicates in `src/vision/eligibility.ts` and `src/vision/plan.ts` read the -same field through `customRowInputModalities`, so an advertised row and the dispatch decision can -no longer disagree about one model. A custom row that declares no modalities stays silent rather -than becoming a text-only claim. +An explicit custom row is the operator's own definition of one routed model, so its `customModels[].inputModalities` outranks the provider-level vision hints (`noVisionModels`, `modelInputModalities`) for that exact `provider`/`modelId` identity. `modelCapabilities` keeps the top slot as the dedicated capability axis, including for the `ocx provider edit --text-only` write. The catalog overlay in `src/codex/catalog/routed-gather.ts` copies that declaration onto the advertised row directly, and the request-path predicates in `src/vision/eligibility.ts` and `src/vision/plan.ts` read the same field through `customRowInputModalities`, so an advertised row and the dispatch decision can +no longer disagree about one model. A custom row that declares no modalities stays silent rather than becoming a text-only claim. Every consumer that answers "can this model take an image" applies one rule to the declaration: image is absent from the list. A row declaring only `audio` or `video` therefore counts as diff --git a/structure/dashboard-and-usage.md b/structure/dashboard-and-usage.md index 9dc4ad13d2d..e00b82fef92 100644 --- a/structure/dashboard-and-usage.md +++ b/structure/dashboard-and-usage.md @@ -501,7 +501,7 @@ Dashboard overview polling observes authorization failures independently of stal The [explicit model-capability contract](config.md#explicit-per-model-capability-declarations) preserves operator declarations through provider storage and catalog capture; it does not infer upstream capability or change this surface's routing behavior. -Exact [model input declarations](config.md#explicit-per-model-capability-declarations) now feed text-only eligibility and catalog hints; existing image-description/omission handling consumes them before the main upstream send. The Combos page sends non-image members as the request-only `visionSidecarTargets` field on `PUT /api/combos` whenever the Image switch is enabled, so text-only enrollment needs no manual provider edit. The GUI classifies members from the authoritative `visionSidecarConsumer` flag served on `/api/models` rows, so a member covered only by legacy `noVisionModels` keeps its sidecar classification after reload. Members whose modalities are unknown or have no text input keep the switch unavailable and are named in the hint; a member later removed from the combo keeps its provider declaration until cleared in the provider editor. `gui/src/components/route-board/WorkspaceSuggestions.tsx` renders suggestion cards inside the Combos workspace. Generation uses the existing combo save flow, and extension is held while that combo has unsaved workspace edits. Dismissals are browser-local. Provider exclusions are persisted by the management API. The workspace gates cards on a successful exclusion read for the current proxy and offers a retry on failure. The exclusion control remains available after the last card is dismissed. New drafts use unmetered targets. Extensions offer metered targets, including Vertex, only with existing explicit combo consent. The save path rechecks live provider configuration and combo consent, and the combo write leaves consent management to the existing server policy. Forward gateways require spend consent unless they use the canonical ChatGPT Codex destination. +Exact [model input declarations](config.md#explicit-per-model-capability-declarations) now feed text-only eligibility and catalog hints; existing image-description/omission handling consumes them before the main upstream send. The Combos page sends non-image members as the request-only `visionSidecarTargets` field on `PUT /api/combos` whenever the Image switch is enabled, so text-only enrollment needs no manual provider edit. The GUI classifies members from the authoritative `visionSidecarConsumer` flag served on `/api/models` rows, so a member covered only by legacy `noVisionModels` keeps its sidecar classification after reload. Members whose modalities are unknown or have no text input keep the switch unavailable and are named in the hint; a member later removed from the combo keeps its provider declaration until cleared in the provider editor. `gui/src/components/route-board/WorkspaceSuggestions.tsx` renders suggestion cards inside the Combos workspace. Generate opens a draft. Saving the draft and choosing Add to combo both use the dashboard-only `POST /api/combo-suggestions/save` endpoint. Extension is held while that combo has unsaved workspace edits. Dismissals are browser-local. Provider exclusions are persisted by the management API. The workspace gates cards on a successful exclusion read for the current proxy and offers a retry on failure. The exclusion control remains available after the last card is dismissed. New drafts use unmetered targets. Extensions offer metered targets, including Vertex, only with existing explicit combo consent. The dedicated save path validates the targets against active and locked persisted provider configuration, then checks persisted exclusions and combo consent before publishing the write. The shared [subscription allowlist](config.md) determines which channels can appear without metered-target consent. The raw provider editor round-trips `autoReviewModel` and `autoReviewModelOverrides` through editor-owned DTO fields. POST/PATCH/PUT share validation; PUT copies schema-normalized values into the persisted and live candidate before adoption. Canonical `openai` rejects these fields, including clear forms. Field-masked writes (PATCH, editor PUT, reload) pin every registry-seed key and ignore operator overlays the seed never defines, most commonly `selectedModels`; POST keeps the exact-key comparison. Canonical `openai` still rejects `allowPrivateNetwork`, which must not short-circuit destination DNS checks on the ChatGPT forward row. Existing authentication, origin checks and stale-baseline protection still govern the writes. See [reviewer projection](catalog.md#provider-scoped-approval-reviewer). Stored Direct substitution follows the [credential identity contract](providers/openai-accounts.md#sidecars-management-and-ui): both synchronous and asynchronous materializers discard the caller account header before applying the stored credential; ordinary native Direct passthrough is unchanged. diff --git a/structure/gui-and-management-api.md b/structure/gui-and-management-api.md index a4c9e032c00..179e760a5e6 100644 --- a/structure/gui-and-management-api.md +++ b/structure/gui-and-management-api.md @@ -311,7 +311,7 @@ after the save, and a non-retryable skip (no managed catalog) is a clean save. C | File-integration plans | `src/server/management/integration-routes.ts` and `aside-profile-routes.ts` — `POST /api/client-integrations/preview`, `POST /api/client-integrations/restore/preview`, and `POST /api/client-integrations/aside/profiles/{profileId}/preview`. Management-authenticated, declared non-mutating, and they write nothing: no snapshot, no lock, no maintenance, no recovery. They answer `409 integration_preview_unavailable` rather than gathering a model roster, because discovery refreshes credentials and writes the provider cache. Responses carry only declared managed schema paths, closed change kinds and an opaque fingerprint; no value, filesystem location or selected member identity appears. Mutation routes accept `operation` and `planFingerprint` together or not at all, reject a half-bound request and an operation that disagrees with the change, and answer `409 integration_preview_stale` with a freshly computed plan. Binding is an optimistic token, never authorization. [The integration contract](clients/integrations.md) owns the ordering. | | Grok reset coupons | `src/server/management/grok-coupon-routes.ts` — `GET /api/grok/reset-coupons`, `POST /api/grok/reset-coupons/consume`. The dashboard owner is `gui/src/hooks/useGrokResetCoupons.ts` with `gui/src/components/provider-workspace/GrokResetCoupons.tsx`, wired into the xAI OAuth rows of `ProviderAuthPanel`. Redemption truth is the settled ledger `code`, not the HTTP status: a replayed failure returns 200 with `replayed: true`. See [`providers/xai-grok.md`](providers/xai-grok.md). The route returns `ledger_unavailable` before dispatch when the shared ledger cannot be read or locked; stale uncertain attempts are inspected without another redemption or inferred success. A late inspection refusal or a lost claim replays an identity-matching definitive winner; otherwise it returns `operation_state_changed` (late refusal) or `attempt_in_progress` (lost claim) and never replaces an attempted or terminal record. Unknown-outcome responses include the effective operation ID; the CLI mints it before dispatch. Uncertain and pending attempts live in a module-level hold store shared by all hook instances and mirrored to `sessionStorage` (`ocx.grok-coupon-holds.v1`), so they survive modal close/reopen, remount, and reload for the tab session; the pending hold is written before the POST, only a definitive response for the same `operationId` clears it, and only GET refreshes are allowed after uncertainty. Every response that cannot prove settlement under a supplied operation ID, including pre-open refusals, carries that `operationId`. A definitive failure releases the matching speculative pending hold. Supplied token IDs must be non-empty strings before journal admission, and omitted account/token retries recover the operation’s durable identity within retention. Legacy version-one opens are quarantined rather than dispatched. After confirmed redemption, local settlement has five attempts and four 20 ms waits only for a `ConfigMutationLockError` caused by `SQLITE_BUSY`; any other error or changed claim stops without another redemption. | | Claude reset grants | `src/server/management/anthropic-reset-grant-routes.ts` — `GET /api/anthropic/reset-grants`, `POST /api/anthropic/reset-grants/consume` (lazy-loaded). Wire and fail-closed parsing live in `src/providers/anthropic-reset-grants.ts` (the Claude Code 2.1.278 `cedar_ember` contract, sent with `CLAUDE_CLI_USER_AGENT` from `src/providers/claude-cli-identity.ts`; every bearer request refuses redirects, and a refused claim redirect is an unknown outcome); the journal is `src/providers/anthropic-reset-grant-ledger.ts`: a cross-process `BEGIN IMMEDIATE` lock around every synchronous read-modify-write, a 90 s lease, the operation id reused as the upstream `request_id`, same-id retry only inside the vendor's ten-minute window, at most one unresolved operation per account and organization within each pool's journal and that ten-minute window, whatever grant it names (a new id gets `409 unresolved_prior_operation`), no settlement inferred from a re-read, and a fail-closed `500 journal_write_failed` when an answer cannot be recorded. Spending requires the `gui-session` principal. A journaled `reset`, including a same-id replay of that code, lifts that account cooldown only when it is a 429 quota refusal recorded before the operation was first journaled (the claim fence, `claimedAt`) and the journal's cleared windows cover every window the refusal named (both when it named none); it then drops the cached quota row and rereads usage with its own request rather than joining an older read. Model-family exclusions stay until the usage reread proves a family is no longer rejected. A failed reread leaves them in place. The HTTP result stays the journal answer if the reread fails. Other result codes do not admit. The dashboard owner is `gui/src/hooks/useAnthropicResetGrants.ts` with `gui/src/components/provider-workspace/AnthropicResetGrants.tsx` on the Anthropic OAuth rows of `ProviderAuthPanel`; the dialog re-reads the account when it opens, lets the user choose the grant (default: the selectable grant that expires first; the server re-gates the chosen `grantId`), and after an unknown outcome only retries the same id with no picker shown. Design and audit record: [`../devlog/_fin/260923_claude_reset_grants/010_plan.md`](../devlog/_fin/260923_claude_reset_grants/010_plan.md). | -| Combos | `src/server/management/combo-routes.ts` — `GET/PUT/DELETE /api/combos` own provider combination and failover definitions. `PUT` keeps a stored field the body omits (`cooldownMs`, `waitForCooldownMs`, `defaultEffortMode`, `reasoningEffortMode`, `imageInput`, `cooldownWaitPolicy`, per-target `lastResort`, JEV `decisionQuotaSignals`/`decisionQuotaTiers`/`jevEffortMode`/`sessionPin` on updates/rename); quota false/null clears sparsely and switching away removes quota policy under [the owning contract](providers/jev-decision.md#loaded-advisory-quota). Explicit values replace it and defaults are stored sparse. A combo validation 400 is `{ error, field? }`, where `field` is the top-level combo field of the first issue. `GET /api/combo-suggestions` and `PUT /api/combo-suggestions` use the dashboard-only route in `src/server/management/combo-suggestion-routes.ts`. All three suggestion operations require `hasHumanDashboardSession` before dispatch. Admin-token and remembered-admin callers receive 403. The two exclusion operations return `{ excludedProviders: string[] }`. PUT validates the full replacement list and persists it before publishing the live value. `POST /api/combo-suggestions/save` accepts a combo ID, a create or append mode, and provider/model pairs. The locked config mutation checks each new target against provider classifications in both the active and persisted config, along with persisted exclusions and combo spend consent. A paid classification in either config requires stored consent and sets `metered: true` on the new target. Create has no spend consent. Conflicts return a fixed reason code and the dashboard refreshes the suggestions. When appending suggestions, the server uses the more costly tier from the active and saved configurations. It treats existing targets explicitly marked as metered as pay-per-use and preserves the relative order of existing targets. The dashboard and save route share the tier classifier. The config DTO carries the canonical forward decision computed before URL sanitization, so redaction cannot make a gateway appear unmetered. | +| Combos | `src/server/management/combo-routes.ts` — `GET/PUT/DELETE /api/combos` own provider combination and failover definitions. `PUT` keeps a stored field the body omits (`cooldownMs`, `waitForCooldownMs`, `defaultEffortMode`, `reasoningEffortMode`, `imageInput`, `cooldownWaitPolicy`, per-target `lastResort`, JEV `decisionQuotaSignals`/`decisionQuotaTiers`/`jevEffortMode`/`sessionPin` on updates/rename); quota false/null clears sparsely and switching away removes quota policy under [the owning contract](providers/jev-decision.md#loaded-advisory-quota). Explicit values replace it and defaults are stored sparse. A combo validation 400 is `{ error, field? }`, where `field` is the top-level combo field of the first issue. `GET /api/combo-suggestions` and `PUT /api/combo-suggestions` use the dashboard-only route in `src/server/management/combo-suggestion-routes.ts`. All three suggestion operations require `hasHumanDashboardSession` before dispatch. Admin-token and remembered-admin callers receive 403. The two exclusion operations return `{ excludedProviders: string[] }`. PUT validates the full replacement list and persists it before publishing the live value. `POST /api/combo-suggestions/save` accepts a combo ID, a create or append mode, and provider/model pairs. The locked config mutation checks each new target against provider classifications in both the active and persisted config, along with persisted exclusions and combo spend consent. A paid classification in either config requires stored consent and sets `metered: true` on the new target. Create has no spend consent. Conflicts return a fixed reason code and the dashboard refreshes the suggestions. When appending suggestions, the server uses the more costly tier from the active and saved configurations. It treats existing targets explicitly marked as metered as pay-per-use and preserves the relative order of existing targets. The dashboard and save route share the tier classifier. The config DTO carries the canonical forward and known OAuth subscription decisions computed before URL sanitization, so redaction cannot make a gateway appear unmetered. | | Protocol paths | `src/server/management/protocol-routes.ts` (lazy-loaded) — `GET /api/protocols` returns the contract version, the resolved API surfaces and protocol settings, the policy revision and the feature vocabulary; with `?provider=` (one non-empty name of at most 200 characters without control characters, else 400 `invalid_provider`; an unconfigured name is 404 `unknown_provider`, neither echoing the name) it adds a `provider` block from `src/protocols/provider-summary.ts` ([Protocol Paths](data-planes/protocol-paths.md#provider-wire-summary)); `POST /api/protocols/plan` takes `{ model, inbound, features? }` (model at most 200 characters, at most 24 features, any other key refused with 400) and returns a `ProtocolPlanV1` with `basis: "preview"` from `src/protocols/plan-snapshot.ts`. Both are read-only, never log their input, and send nothing upstream. `PATCH /api/protocols/settings` takes `{ messagesEnabled?, unrepresentable?, rollout? }` (strict: unknown keys and wrong types are 400), validates and applies through `src/server/management/protocol-settings-patch.ts`, persists with `saveConfigPreservingClaudeCode`, restores the live config if the save fails (409 on lock contention, 500 otherwise), and answers with the fresh `GET /api/protocols` body; closing Messages also writes `claudeCode.enabled = false` through `commitClaudeCodeBlock` ([Protocol Paths](data-planes/protocol-paths.md#settings)). The CLI drives all three through `ocx api protocols`, `ocx api explain` and `ocx api policy` ([Protocol Paths](data-planes/protocol-paths.md#cli)); none carries a route-registry exemption. | | Workflow budget | `src/server/management/workflow-budget-routes.ts` — `GET /api/workflow-budget` reads the tracked roots or one root, and `POST /api/workflow-budget/clear` clears exactly one. The clear moves the windowed send ring and the child map and nothing else: `active` belongs to turns still in flight, the spend ledger is a token budget an operator did not ask to forgive, and the lifetime send total survives so a clear cannot launder the record. A refusal event carries `spendScope` and `spendLimit` when a token ceiling fired, so the reason is readable without the config open beside it; no scope id is ever attached, because root ids are client thread headers and identity ids are credentials. Both are `deferred-verb` in the route registry — they are owed CLI verbs, and because the ledger is process memory there is no local projection the CLI could read instead. `GET`/`PUT /api/workflow-budget/settings` read and write the per-install count ceilings (`workflowBudget` in config: concurrent turns, sends and distinct children per window); the live config is bound in `src/lib/workflow-budget-config.ts` and read per decision by HTTP admission and the pre-dispatch send ceiling, so a write applies to the next request and never resets a root's usage. The window, interactive reserve and tracked-root bound stay fixed because a root's ring geometry is fixed when it first appears. The GET is `local-transport` (same block via `ocx config get`), the PUT `deferred-verb` with the other budget verbs. See [`../devlog/_fin/260915_workflow_budget_window/030_wfc_diff_plan.md`](../devlog/_fin/260915_workflow_budget_window/030_wfc_diff_plan.md). | | Codex accounts | `src/codex/auth-api/routes.ts` — `GET/POST/DELETE /api/codex-auth/accounts`, `PUT /api/codex-auth/accounts/alias`, `PUT /api/codex-auth/accounts/pause`, `PUT /api/codex-auth/accounts/pause-exhausted`, `POST /api/codex-auth/accounts/clear-cooldown`, `GET/PUT /api/codex-auth/active`, `PUT /api/codex-auth/auto-switch`, `PUT /api/codex-auth/pool-strategy`, `PUT /api/codex-auth/failover`, `GET /api/codex-auth/quota`, `GET /api/codex-auth/reset-credits` with `POST /api/codex-auth/reset-credits/consume`, and the login flow `POST /api/codex-auth/login`, `POST /api/codex-auth/login/code`, `POST /api/codex-auth/login/cancel`, `GET /api/codex-auth/login-status`. Pool login cancellation through `POST /api/codex-auth/login/cancel` addresses the flow id returned by the pool start route and follows the [pool publication contract](providers/openai-accounts.md#pool-login-policy-and-cancellation). Per-account quota activation uses the existing `GET/PUT /api/settings` surface and `src/codex/quota-auto-refresh.ts`, keeping scheduled spending separate from credential/authentication mutation. Account ids are opaque handles and are serialized so the GUI can address an account; emails are masked and tokens are never serialized. New-account config commits add UI-managed selector bindings in the same config save; deletion deliberately retains existing bindings for fail-closed exact routing and re-add stability. Account mutations request catalog convergence only after config durability and expose only the boolean `catalogRefreshPending` completion projection. `showCodexCredits` is a default-off boolean in settings GET and successful PUT; partial PUT accepts a boolean and rolls back on persistence failure. See [credits exposure](providers/openai-accounts.md#display-only-codex-credits). | diff --git a/tests/fixtures/test-layout-expected.json b/tests/fixtures/test-layout-expected.json index 38356617863..c63e1128a78 100644 --- a/tests/fixtures/test-layout-expected.json +++ b/tests/fixtures/test-layout-expected.json @@ -395,7 +395,6 @@ "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", "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", diff --git a/tests/server/combo-suggestion-routes.test.ts b/tests/server/combo-suggestion-routes.test.ts index 3d5ff9cc7b1..67a4e7fa3dc 100644 --- a/tests/server/combo-suggestion-routes.test.ts +++ b/tests/server/combo-suggestion-routes.test.ts @@ -132,9 +132,11 @@ test("config DTO computes forward eligibility before redacting provider URLs", a const live = loadConfig(); setCanonicalForward(live); live.providers.gateway = { ...live.providers.mock!, baseUrl: "https://chatgpt.com/backend-api/codex?route=custom" }; + live.providers.kimi = { adapter: "openai-chat", authMode: "oauth", baseUrl: "https://api.kimi.com/coding/v1?route=custom", models: ["kimi-for-coding"] }; expect(safeConfigDTO(live)).toMatchObject({ providers: { mock: { canonicalOpenAiForward: true }, gateway: { baseUrl: live.providers.mock!.baseUrl, canonicalOpenAiForward: false }, + kimi: { baseUrl: "https://api.kimi.com/coding/v1", knownSubscriptionOAuth: false }, } }); }); @@ -256,3 +258,28 @@ test("append inserts a subscription before explicitly metered targets without re expect(config.combos?.mix?.targets).toEqual([target, ...existing]); } }); + +test.each(["create", "append"] as const)("Devin %s requires stored spend consent", async (mode) => { + const live = seedPaidSuggestion(); + live.providers.devin = { adapter: "devin", authMode: "oauth", baseUrl: "https://server.codeium.com", models: ["gemini"] }; + delete live.combos!.mix!.allowMeteredTargets; + saveConfig(live); + const target = { provider: "devin", model: "gemini" }; + const request = { id: mode === "create" ? "draft" : "mix", mode, targets: [target] }; + const before = onDisk(); + const denied = await saveSuggestion(live, request); + expect(denied.status).toBe(409); + expect(await denied.json()).toMatchObject({ code: "suggestion_consent_required" }); + expect(onDisk()).toEqual(before); + expect(live.combos?.draft).toBeUndefined(); + expect(live.combos?.mix?.targets).toHaveLength(1); + + if (mode === "append") { + live.combos!.mix!.allowMeteredTargets = true; + saveConfig(live); + expect((await saveSuggestion(live, request)).status).toBe(200); + for (const config of [live, loadConfig()]) { + expect(config.combos?.mix?.targets).toContainEqual({ ...target, metered: true }); + } + } +}); From 6685f3c1f6bc58f95279c35cee1093bd576768bb Mon Sep 17 00:00:00 2001 From: JUN Date: Thu, 19 Nov 2026 02:36:30 +0900 Subject: [PATCH 14/23] Require paid-target consent for all combo suggestions Co-authored-by: Andrew (agent) --- .../src/content/docs/es/guides/combos.md | 2 +- .../docs/es/reference/management-api.md | 2 +- docs-site/src/content/docs/guides/combos.md | 2 +- .../content/docs/reference/management-api.md | 2 +- gui/src/combo-suggestions.ts | 14 +++---- .../route-board/ComboSuggestions.tsx | 12 +++++- .../route-board/WorkspaceSuggestions.tsx | 2 +- gui/src/i18n/de.ts | 2 + gui/src/i18n/en.ts | 2 + gui/src/i18n/fr.ts | 2 + gui/src/i18n/ja.ts | 2 + gui/src/i18n/ko.ts | 2 + gui/src/i18n/pt.ts | 2 + gui/src/i18n/ru.ts | 2 + gui/src/i18n/tr.ts | 2 + gui/src/i18n/vi.ts | 2 + gui/src/i18n/zh-TW.ts | 2 + gui/src/i18n/zh.ts | 2 + gui/tests/combo-suggestions.test.tsx | 37 ++++++++++++------- src/combos/suggestion-channel.ts | 6 +-- .../management/combo-suggestion-routes.ts | 20 ++++++---- structure/config.md | 2 +- structure/dashboard-and-usage.md | 2 +- structure/gui-and-management-api.md | 2 +- tests/server/combo-suggestion-routes.test.ts | 31 +++++++++++++--- 25 files changed, 111 insertions(+), 47 deletions(-) diff --git a/docs-site/src/content/docs/es/guides/combos.md b/docs-site/src/content/docs/es/guides/combos.md index 329e70109de..8ca3352f36a 100644 --- a/docs-site/src/content/docs/es/guides/combos.md +++ b/docs-site/src/content/docs/es/guides/combos.md @@ -792,4 +792,4 @@ Un rechazo estructurado de esfuerzo puede bajar una posición publicada cada vez Si los ajustes cambian antes de guardar una sugerencia, Combos actualiza las sugerencias y muestra un mensaje. Al guardar, se comprueban las exclusiones y el consentimiento de gasto vigentes. Al añadir sugerencias, el servidor aplica el nivel de mayor coste entre la configuración activa y la guardada. Trata los destinos existentes marcados explícitamente como medidos como destinos de pago por uso y conserva el orden relativo de los destinos existentes. -En el espacio de trabajo de combos, **Generar** abre un borrador de conmutación por error para un modelo disponible en varios proveedores. **Añadir al combo** ofrece destinos que faltan en un combo existente. Las tarjetas descartadas quedan ocultas en este navegador. Usa **Excluir un proveedor…** para filtrar ambos tipos de sugerencias. El proxy guarda la selección como `comboSuggestionExcludedProviders` en `config.json`. Los miembros existentes se conservan. Los borradores nuevos usan destinos sin medición. Las ampliaciones ofrecen destinos de pago por uso, incluido Vertex, solo si el combo ya permite destinos medidos. El panel comprueba la configuración actual antes de guardar. El control de exclusión sigue disponible tras descartar todas las tarjetas. Si falla la carga de la lista de exclusión, vuelve a intentarlo para ver las sugerencias. Las sugerencias tratan los canales como medidos de forma predeterminada. La lista de suscripciones admitidas incluye el destino canónico de ChatGPT Codex con autenticación reenviada, Grok CLI con OAuth y Kimi Code Plan con OAuth en Chat y Responses. Los demás accesos mediante OAuth y las pasarelas personalizadas requieren consentimiento para usar destinos medidos. +En el espacio de trabajo de combos, **Generar** abre un borrador de conmutación por error para un modelo disponible en varios proveedores. **Añadir al combo** ofrece destinos que faltan en un combo existente. Las tarjetas descartadas quedan ocultas en este navegador. Usa **Excluir un proveedor…** para filtrar ambos tipos de sugerencias. El proxy guarda la selección como `comboSuggestionExcludedProviders` en `config.json`. Los miembros existentes se conservan. Todos los destinos sugeridos pueden generar cargos, incluso los canales de suscripción, como Codex con créditos comprados, Grok con Extra Usage y Kimi Code con Extra Usage. Para guardar un borrador, marca **Permitir destinos de pago**. Para añadir destinos, habilita primero los destinos de pago en el combo existente. El proxy guarda todos los destinos sugeridos con `metered: true`. El control de exclusión sigue disponible tras descartar todas las tarjetas. Si falla la carga de las exclusiones, vuelve a intentarlo. diff --git a/docs-site/src/content/docs/es/reference/management-api.md b/docs-site/src/content/docs/es/reference/management-api.md index fd6f0da221c..ba6633dba9c 100644 --- a/docs-site/src/content/docs/es/reference/management-api.md +++ b/docs-site/src/content/docs/es/reference/management-api.md @@ -218,7 +218,7 @@ Las instantáneas de sesión incluyen `resumable`. Se vuelve cierto sólo despu | --- | --- | --- | | `GET /api/combos` | Lista de combos normalizados y sus ID de modelo público | El trabajo del catálogo puede devolver `catalog_busy` | | `PUT /api/combos` | Crea, sustituye o renombra un combo. | 400 si el identificador, destino, configuración o cambio de nombre son inválidos, o hay una colisión ordinaria; un 400 de validación también identifica el primer campo superior inválido en `field`, por ejemplo `targets` o `decisionProvider`. 409 si hay colisión con el espacio de nombres de una cuenta Codex. | -| `POST /api/combo-suggestions/save` | Guarda pares de proveedor y modelo sugeridos con `{ id, mode, targets }` y modo `"create"` o `"append"` | 400 solicitud inválida; 403 si falta una sesión de panel válida; 409 si el consentimiento, las exclusiones, la disponibilidad o el estado del combo impiden guardar. Si la configuración activa o la guardada clasifica un destino como de pago, se requiere el consentimiento existente del combo y el destino se guarda como medido. Al añadir sugerencias, el servidor aplica el nivel de mayor coste entre la configuración activa y la guardada. Trata los destinos existentes marcados explícitamente como medidos como destinos de pago por uso y conserva el orden relativo de los destinos existentes. | +| `POST /api/combo-suggestions/save` | Guarda pares de proveedor y modelo sugeridos con `{ id, mode, targets }` y modo `"create"` o `"append"` | 400 solicitud inválida; 403 si falta una sesión de panel válida; 409 si el consentimiento, las exclusiones, la disponibilidad o el estado del combo impiden guardar. La creación requiere `allowMeteredTargets: true` en la solicitud y lo guarda en el combo. La ampliación rechaza ese campo y exige el consentimiento guardado en el combo. Todos los destinos sugeridos se guardan con `metered: true` porque incluso los canales de suscripción pueden cobrar créditos o uso adicional. Al añadir sugerencias, el servidor aplica el nivel de mayor coste entre la configuración activa y la guardada. Trata los destinos existentes marcados explícitamente como medidos como destinos de pago por uso y conserva el orden relativo de los destinos existentes. | | `DELETE /api/combos?id=...` | Eliminar un combo y borrar su estado de selección/enfriamiento | 400 id ausente; 404 combo desconocido | Las tres operaciones de sugerencias (`GET /api/combo-suggestions`, `PUT /api/combo-suggestions` y `POST /api/combo-suggestions/save`) requieren una sesión de panel iniciada mediante el acceso local, una identidad de Tailscale verificada o el emparejamiento. Las credenciales de administrador y las sesiones recordadas reciben un 403. diff --git a/docs-site/src/content/docs/guides/combos.md b/docs-site/src/content/docs/guides/combos.md index e9a860e7123..ef9500a5f3c 100644 --- a/docs-site/src/content/docs/guides/combos.md +++ b/docs-site/src/content/docs/guides/combos.md @@ -1218,4 +1218,4 @@ untried targets and newer failures keep their cooldowns. When settings change before a suggestion is saved, Combos refreshes the suggestions and displays a message. Saving checks the current exclusions and spend consent. -In the Combos workspace, **Generate** opens a failover draft for a model served by multiple providers. **Add to combo** offers missing targets for an existing combo. Dismissed cards stay hidden in this browser. Use **Exclude providers…** to filter both kinds of suggestions. The proxy stores your selection as `comboSuggestionExcludedProviders` in `config.json`. When appending suggestions, the server uses the more costly tier from the active and saved configurations. It treats existing targets explicitly marked as metered as pay-per-use and preserves the relative order of existing targets. New drafts use unmetered targets. Extensions offer pay-per-use targets, including Vertex, only when the combo already allows metered targets. The dashboard checks the current configuration before saving. The exclusion control stays available when all cards are dismissed. If the exclusion list fails to load, retry the read to see suggestions. Suggestions treat channels as metered by default. The subscription allowlist covers canonical ChatGPT Codex forward, Grok CLI OAuth, and Kimi Code Plan OAuth on Chat and Responses. Other OAuth logins and custom gateways require metered-target consent. +In the Combos workspace, **Generate** opens a failover draft for a model served by multiple providers. **Add to combo** offers missing targets for an existing combo. Dismissed cards stay hidden in this browser. Use **Exclude providers…** to filter both kinds of suggestions. The proxy stores your selection as `comboSuggestionExcludedProviders` in `config.json`. When appending suggestions, the server uses the more costly tier from the active and saved configurations. It treats existing targets explicitly marked as metered as pay-per-use and preserves the relative order of existing targets. Every suggested target can incur paid usage, including subscription channels such as Codex with purchased credits, Grok with Extra Usage, and Kimi Code with Extra Usage. To save a draft, check **Allow paid targets**. To append, first enable paid targets in the existing combo. The proxy saves every suggested target as `metered: true`. The exclusion control stays available after dismissing all cards. If exclusions fail to load, retry to see suggestions. diff --git a/docs-site/src/content/docs/reference/management-api.md b/docs-site/src/content/docs/reference/management-api.md index 2e9c8342797..e2941c9fcf2 100644 --- a/docs-site/src/content/docs/reference/management-api.md +++ b/docs-site/src/content/docs/reference/management-api.md @@ -247,7 +247,7 @@ completes. | --- | --- | --- | | `GET /api/combos` | List normalized combos and their public model ids | Catalog work can return `catalog_busy` | | `PUT /api/combos` | Create, replace, or rename one combo | 400 invalid id, target, config, rename, or ordinary collision (a combo validation 400 also names the first invalid top-level field in `field`, for example `targets` or `decisionProvider`); 409 Codex-account namespace collision | -| `POST /api/combo-suggestions/save` | Save suggested provider/model pairs using `{ id, mode, targets }` with mode `"create"` or `"append"` | 400 invalid request; 403 without an eligible dashboard session; 409 when consent, exclusions, provider availability, or combo state prevents the save. A target classified as paid in either the active or persisted config requires existing combo consent and is saved as metered. When appending suggestions, the server uses the more costly tier from the active and saved configurations. It treats existing targets explicitly marked as metered as pay-per-use and preserves the relative order of existing targets. | +| `POST /api/combo-suggestions/save` | Save suggested provider/model pairs using `{ id, mode, targets }` with mode `"create"` or `"append"` | 400 invalid request; 403 without an eligible dashboard session; 409 when consent, exclusions, provider availability, or combo state prevents the save. Create requires `allowMeteredTargets: true` in the request and stores it on the combo. Append rejects that field and requires stored combo consent. All suggested targets are saved with `metered: true` because even subscription channels may bill paid credits or extra usage. When appending suggestions, the server uses the more costly tier from the active and saved configurations. It treats existing targets explicitly marked as metered as pay-per-use and preserves the relative order of existing targets. | | `DELETE /api/combos?id=...` | Delete one combo and clear its selection/cooldown state | 400 missing id; 404 unknown combo | All three suggestion operations (`GET /api/combo-suggestions`, `PUT /api/combo-suggestions`, and `POST /api/combo-suggestions/save`) require a dashboard session issued through local bootstrap, verified Tailscale identity, or pairing. Admin credentials and remembered sessions receive a 403. diff --git a/gui/src/combo-suggestions.ts b/gui/src/combo-suggestions.ts index 34e098181bc..26bfdabc5df 100644 --- a/gui/src/combo-suggestions.ts +++ b/gui/src/combo-suggestions.ts @@ -9,8 +9,8 @@ * capability) and a trailing reasoning-effort suffix is dropped. */ import { COMBO_ID_RE, emptyDraft, newComboTarget, type ComboItem } from "./combo-workspace-data"; -import { channelTier, EFFORT_SUFFIX, isMeteredTier, normalizeModelName, TIER_RANK, type ChannelTier, type SuggestionProvider } from "../../src/combos/suggestion-channel"; -export { channelTier, isMeteredTier, normalizeModelName, type ChannelTier, type SuggestionProvider }; +import { channelTier, EFFORT_SUFFIX, normalizeModelName, TIER_RANK, type ChannelTier, type SuggestionProvider } from "../../src/combos/suggestion-channel"; +export { channelTier, normalizeModelName, type ChannelTier, type SuggestionProvider }; export interface SuggestionModel { @@ -141,8 +141,7 @@ export function buildComboSuggestions(input: SuggestionInput): ComboSuggestion[] const extends_: Array = []; for (const [name, served] of byModel) { const combo = covering.get(name); - const eligible = [...served].map(([p, m]) => member(p, m)) - .filter((entry) => combo?.allowMeteredTargets === true || !isMeteredTier(entry.tier)); + const eligible = [...served].map(([p, m]) => member(p, m)); // 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) { @@ -179,7 +178,8 @@ export function buildComboSuggestions(input: SuggestionInput): ComboSuggestion[] export function suggestionDraft(comboId: string, members: readonly SuggestedMember[]): ComboItem { return { ...emptyDraft(comboId), - targets: members.filter((entry) => !isMeteredTier(entry.tier)).map(({ provider, model }) => newComboTarget({ provider, model })), + allowMeteredTargets: true, + targets: members.map(({ provider, model }) => newComboTarget({ provider, model, metered: true })), }; } @@ -192,11 +192,11 @@ export function extendedCombo( members: readonly SuggestedMember[], tierOf: (provider: string, model: string) => ChannelTier, ): ComboItem { + if (combo.allowMeteredTargets !== true) return combo; const targets = [...combo.targets]; for (const entry of members) { - if (isMeteredTier(entry.tier) && combo.allowMeteredTargets !== true) continue; 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, ...(isMeteredTier(entry.tier) ? { metered: true } : {}) })); + targets.splice(at < 0 ? targets.length : at, 0, newComboTarget({ provider: entry.provider, model: entry.model, metered: true })); } return { ...combo, targets }; } diff --git a/gui/src/components/route-board/ComboSuggestions.tsx b/gui/src/components/route-board/ComboSuggestions.tsx index e44eebf4249..6158f706f4a 100644 --- a/gui/src/components/route-board/ComboSuggestions.tsx +++ b/gui/src/components/route-board/ComboSuggestions.tsx @@ -204,7 +204,7 @@ function SuggestionCard({ + {suggestion.kind === "extend" && target?.allowMeteredTargets !== true && ( +

{t("comboSuggest.enablePaid")}

+ )} {message &&

{message}

} {drafting && suggestion.kind === "create" && ( (suggestion.members); + const [allowPaid, setAllowPaid] = useState(false); const idOk = isValidComboId(comboId.trim()); return (
@@ -276,10 +280,14 @@ function SuggestionDraft({ ); })} +
{t("comboSuggest.draft.strategy")} - diff --git a/gui/src/components/route-board/WorkspaceSuggestions.tsx b/gui/src/components/route-board/WorkspaceSuggestions.tsx index 38b43fe67fe..6777634f0cf 100644 --- a/gui/src/components/route-board/WorkspaceSuggestions.tsx +++ b/gui/src/components/route-board/WorkspaceSuggestions.tsx @@ -35,7 +35,7 @@ export function WorkspaceSuggestions(props: Props) { const response = await fetch(`${props.apiBase}/api/combo-suggestions/save`, { method: "POST", headers: { "content-type": "application/json" }, - body: JSON.stringify({ id: item.id, mode: isCreate ? "create" : "append", targets }), + body: JSON.stringify({ id: item.id, mode: isCreate ? "create" : "append", targets, ...(isCreate ? { allowMeteredTargets: item.allowMeteredTargets } : {}) }), }); if (response.status === 409) { setConflict(true); diff --git a/gui/src/i18n/de.ts b/gui/src/i18n/de.ts index 81e88c7024f..65c7dd3b5bf 100644 --- a/gui/src/i18n/de.ts +++ b/gui/src/i18n/de.ts @@ -4553,6 +4553,8 @@ export const de: Record = { "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.strategy": "Strategie: Failover. Nach dem Speichern in der Zeile ändern.", + "comboSuggest.allowPaid": "Kostenpflichtige Ziele erlauben (zum Speichern erforderlich). Diese Ziele können kostenpflichtiges Guthaben oder Nutzung abrechnen.", + "comboSuggest.enablePaid": "Aktiviere zuerst kostenpflichtige Ziele für diese Kombination.", "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 8f422384eb0..a8544cd63fc 100644 --- a/gui/src/i18n/en.ts +++ b/gui/src/i18n/en.ts @@ -4587,6 +4587,8 @@ export const en = { "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.strategy": "Strategy: failover. Change it in the row after saving.", + "comboSuggest.allowPaid": "Allow paid targets (required to save). These targets may bill paid credits or usage.", + "comboSuggest.enablePaid": "Enable paid targets on this combo first.", "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 bd323d4cc79..c6dea67bb67 100644 --- a/gui/src/i18n/fr.ts +++ b/gui/src/i18n/fr.ts @@ -4542,6 +4542,8 @@ export const fr: Record = { "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.strategy": "Stratégie : basculement. Modifiez-la dans la ligne après l’enregistrement.", + "comboSuggest.allowPaid": "Autoriser les cibles payantes (requis pour enregistrer). Ces cibles peuvent facturer des crédits ou des frais d’utilisation.", + "comboSuggest.enablePaid": "Activez d’abord les cibles payantes pour cette combinaison.", "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 6f034d87f5f..0fddd63ecdb 100644 --- a/gui/src/i18n/ja.ts +++ b/gui/src/i18n/ja.ts @@ -4575,6 +4575,8 @@ export const ja: Record = { "comboSuggest.draft.orderHint": "上から順に試行されます。サブスクリプションが先、次に Vertex クレジット、従量課金の API キーとリレーは最後です。保存前に並べ替えや削除ができます。", "comboSuggest.draft.left": "残り {percent}%", "comboSuggest.draft.strategy": "戦略:フェイルオーバー。保存後に行内で変更できます。", + "comboSuggest.allowPaid": "有料ターゲットを許可する(保存に必須)。有料クレジットや従量料金が発生する場合があります。", + "comboSuggest.enablePaid": "先にこのコンボの有料ターゲットを有効にしてください。", "comboSuggest.draft.save": "コンボを保存", "comboSuggest.draft.saving": "保存中…", }; diff --git a/gui/src/i18n/ko.ts b/gui/src/i18n/ko.ts index aeaeb738720..bf67cdf71c5 100644 --- a/gui/src/i18n/ko.ts +++ b/gui/src/i18n/ko.ts @@ -4575,6 +4575,8 @@ export const ko: Record = { "comboSuggest.draft.orderHint": "위에서 아래 순서로 시도합니다. 구독이 먼저, 그다음 Vertex 크레딧, 종량제 키와 릴레이는 마지막입니다. 저장하기 전에 순서를 바꾸거나 삭제할 수 있습니다.", "comboSuggest.draft.left": "{percent}% 남음", "comboSuggest.draft.strategy": "전략: 장애 조치(failover). 저장 후 행에서 바꿀 수 있습니다.", + "comboSuggest.allowPaid": "유료 대상 허용(저장에 필요). 유료 크레딧이 차감되거나 사용 요금이 청구될 수 있습니다.", + "comboSuggest.enablePaid": "먼저 이 콤보에서 유료 대상을 허용하세요.", "comboSuggest.draft.save": "콤보 저장", "comboSuggest.draft.saving": "저장 중…", }; diff --git a/gui/src/i18n/pt.ts b/gui/src/i18n/pt.ts index d03cd8c6421..a4a8a2ea75b 100644 --- a/gui/src/i18n/pt.ts +++ b/gui/src/i18n/pt.ts @@ -4548,6 +4548,8 @@ export const pt: Record = { "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.strategy": "Estratégia: failover. Altere-a na linha depois de salvar.", + "comboSuggest.allowPaid": "Permitir destinos pagos (obrigatório para salvar). Esses destinos podem cobrar créditos ou taxas de uso.", + "comboSuggest.enablePaid": "Primeiro, habilite destinos pagos neste combo.", "comboSuggest.draft.save": "Salvar combo", "comboSuggest.draft.saving": "Salvando…", }; diff --git a/gui/src/i18n/ru.ts b/gui/src/i18n/ru.ts index 5324925408c..10d3ca65d59 100644 --- a/gui/src/i18n/ru.ts +++ b/gui/src/i18n/ru.ts @@ -4576,6 +4576,8 @@ export const ru: Record = { "comboSuggest.draft.orderHint": "Пробуются сверху вниз: сначала подписки, затем кредит Vertex, а ключи с оплатой по факту и ретрансляторы — в конце. Измените порядок или удалите лишнее перед сохранением.", "comboSuggest.draft.left": "осталось {percent}%", "comboSuggest.draft.strategy": "Стратегия: Failover. Изменить можно в строке после сохранения.", + "comboSuggest.allowPaid": "Разрешить платные цели (необходимо для сохранения). Возможны списания платных кредитов или оплата за использование.", + "comboSuggest.enablePaid": "Сначала разрешите платные цели для этой комбинации.", "comboSuggest.draft.save": "Сохранить комбо", "comboSuggest.draft.saving": "Сохранение…", }; diff --git a/gui/src/i18n/tr.ts b/gui/src/i18n/tr.ts index 04db9e9ddbe..e723d95be34 100644 --- a/gui/src/i18n/tr.ts +++ b/gui/src/i18n/tr.ts @@ -4576,6 +4576,8 @@ export const tr: Record = { "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.strategy": "Strateji: failover. Kaydettikten sonra satırda değiştirin.", + "comboSuggest.allowPaid": "Ücretli hedeflere izin ver (kaydetmek için gerekli). Bu hedefler ücretli kredi veya kullanım bedeli yansıtabilir.", + "comboSuggest.enablePaid": "Önce bu komboda ücretli hedeflere izin verin.", "comboSuggest.draft.save": "Komboyu kaydet", "comboSuggest.draft.saving": "Kaydediliyor…", }; diff --git a/gui/src/i18n/vi.ts b/gui/src/i18n/vi.ts index 1676c4562bd..4811048bd8a 100644 --- a/gui/src/i18n/vi.ts +++ b/gui/src/i18n/vi.ts @@ -4545,6 +4545,8 @@ export const vi: Record = { "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.strategy": "Chiến lược: failover. Đổi trong hàng sau khi lưu.", + "comboSuggest.allowPaid": "Cho phép đích trả phí (bắt buộc để lưu). Các đích này có thể tính phí tín dụng hoặc phí sử dụng.", + "comboSuggest.enablePaid": "Trước tiên, hãy bật đích trả phí cho tổ hợp nà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 8789178911a..5a774f65b17 100644 --- a/gui/src/i18n/zh-TW.ts +++ b/gui/src/i18n/zh-TW.ts @@ -4539,6 +4539,8 @@ export const zhTW: Record = { "comboSuggest.draft.orderHint": "從上往下依次嘗試:訂閱在前,其次 Vertex 贈金,按量 API key 和中轉站最後。儲存前可以調整順序或刪掉某一家。", "comboSuggest.draft.left": "剩 {percent}%", "comboSuggest.draft.strategy": "策略:容錯移轉。儲存後可以在列中改。", + "comboSuggest.allowPaid": "允許付費目標(儲存時必選)。這些目標可能消耗付費額度或產生用量費用。", + "comboSuggest.enablePaid": "請先為此組合啟用付費目標。", "comboSuggest.draft.save": "儲存組合", "comboSuggest.draft.saving": "正在儲存…", }; diff --git a/gui/src/i18n/zh.ts b/gui/src/i18n/zh.ts index 9490d77f251..7d138d7f753 100644 --- a/gui/src/i18n/zh.ts +++ b/gui/src/i18n/zh.ts @@ -4574,6 +4574,8 @@ export const zh: Record = { "comboSuggest.draft.orderHint": "从上往下依次尝试:订阅在前,其次 Vertex 赠金,按量 API key 和中转站最后。保存前可以调整顺序或删掉某一家。", "comboSuggest.draft.left": "剩 {percent}%", "comboSuggest.draft.strategy": "策略:故障转移。保存后可以在行里改。", + "comboSuggest.allowPaid": "允许付费目标(保存时必选)。这些目标可能消耗付费额度或产生用量费用。", + "comboSuggest.enablePaid": "请先为此组合启用付费目标。", "comboSuggest.draft.save": "保存组合", "comboSuggest.draft.saving": "正在保存…", }; diff --git a/gui/tests/combo-suggestions.test.tsx b/gui/tests/combo-suggestions.test.tsx index cf76fea43e0..8ccea53f66c 100644 --- a/gui/tests/combo-suggestions.test.tsx +++ b/gui/tests/combo-suggestions.test.tsx @@ -87,14 +87,14 @@ describe("buildComboSuggestions", () => { })).toEqual(["create gemini-3.8-flash: xai > kimi-responses"]); }); - test("Devin is omitted without spend consent", () => { + test("Devin remains visible when spend consent is required", () => { const model = "gpt-6-luna"; const current = combo(model, [["openai", model]]); const input = { providers: [...PROVIDERS, { name: "devin", adapter: "devin", authMode: "oauth", baseUrl: "https://server.codeium.com" }], models: models([["openai", model], ["devin", model]]), }; - expect(summary({ ...input, combos: [current] })).toEqual([]); + expect(summary({ ...input, combos: [current] })).toEqual(["extend gpt-6-luna: devin"]); expect(summary({ ...input, combos: [{ ...current, allowMeteredTargets: true }] })).toEqual(["extend gpt-6-luna: devin"]); }); @@ -102,14 +102,14 @@ describe("buildComboSuggestions", () => { expect(channelTier({ name: "unknown", adapter: "openai-chat", authMode: "oauth", baseUrl: "https://unknown.example" }, "gpt-6-luna")).toBe("metered"); }); - test("custom forward gateways stay out of drafts and require consent on append", () => { + test("custom forward gateways rank after subscription channels", () => { const model = "gpt-6-luna"; const input = { providers: [...PROVIDERS, { name: "gateway", adapter: "openai-responses", authMode: "forward", baseUrl: "https://gateway.example/v1" }], models: models([["openai", model], ["xai", model], ["gateway", model]]), }; - expect(summary(input)).toEqual(["create gpt-6-luna: openai > xai"]); - expect(summary({ ...input, combos: [combo(model, [["openai", model], ["xai", model]])] })).toEqual([]); + expect(summary(input)).toEqual(["create gpt-6-luna: openai > xai > gateway"]); + expect(summary({ ...input, combos: [combo(model, [["openai", model], ["xai", model]])] })).toEqual(["extend gpt-6-luna: gateway"]); expect(summary({ ...input, combos: [combo(model, [["openai", model], ["xai", model]], { allowMeteredTargets: true })] })) .toEqual(["extend gpt-6-luna: gateway"]); }); @@ -120,7 +120,7 @@ describe("buildComboSuggestions", () => { expect(summary({ providers: [...PROVIDERS, gateway], models: models([["openai", model], ["xai", model], ["gateway", model]]), - })).toEqual(["create gpt-6-luna: openai > xai"]); + })).toEqual(["create gpt-6-luna: openai > xai > gateway"]); }); test("a model only one provider serves is no suggestion", () => { @@ -246,7 +246,7 @@ describe("drafts", () => { expect(next.targets.map((t) => t.provider)).toEqual(["kimi", "xai", "zayu-claude", "anthropic-apikey", "relay-2"]); const relayFirst = combo("opus", [["zayu-claude", "kimi-k3-1-pro"], ["kimi", "kimi-k3-1-pro"]]); expect(extendedCombo(relayFirst, [{ provider: "xai", model: "kimi-k3.1-pro", tier: "subscription" }], tierOf).targets.map((t) => t.provider)) - .toEqual(["xai", "zayu-claude", "kimi"]); + .toEqual(["zayu-claude", "kimi"]); }); test.each([ @@ -349,6 +349,11 @@ describe("ComboSuggestions card", () => { expect(gemini.querySelector(".rb-order")?.textContent).toContain("→"); await act(async () => { button(gemini, "Generate").click(); }); const draft = gemini.querySelector(".rb-suggest-draft")!; + const consent = draft.querySelector('input[type="checkbox"]')!; + expect(consent.checked).toBe(false); + expect(draft.textContent).toContain("paid credits or usage"); + expect(button(draft, "Save combo").disabled).toBe(true); + await act(async () => { consent.click(); }); await act(async () => { button(draft.querySelectorAll("li")[0]!, "Move Kimi 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([ @@ -367,7 +372,13 @@ describe("ComboSuggestions card", () => { }); test("an existing combo missing a provider offers to add it", async () => { - await render([combo("gemini", [["kimi-responses", "gemini-3.8-flash"]])]); + const existing = combo("gemini", [["kimi-responses", "gemini-3.8-flash"]]); + await render([existing]); + expect(card("gemini").textContent).toContain("Enable paid targets on this combo first."); + expect(button(card("gemini"), "Add to combo").disabled).toBe(true); + await act(async () => { button(card("gemini"), "Add to combo").click(); }); + expect(saved).toEqual([]); + await render([{ ...existing, allowMeteredTargets: true }]); const extend = card("gemini"); expect(extend.textContent).toContain("can also use"); await act(async () => { button(extend, "Add to combo").click(); }); @@ -464,7 +475,7 @@ describe("ComboSuggestions card", () => { test("adding to a combo with unsaved workspace edits is held", async () => { const extended: string[] = []; - const existing = [combo("gemini", [["kimi-responses", "gemini-3.8-flash"]])]; + const existing = [combo("gemini", [["kimi-responses", "gemini-3.8-flash"]], { allowMeteredTargets: true })]; const view = (locked: string | null) => sonnet({ combos: existing, models: models([["kimi-responses", "gemini-3.8-flash"], ["xai", "gemini-3.8-flash"]]), @@ -518,7 +529,7 @@ describe("ComboSuggestions card", () => { } }); - test("new cards and drafts omit paid Vertex and API-key members", async () => { + test("new cards and drafts include paid Vertex and API-key members", async () => { const name = "kimi-k3-1-pro"; await mount( [provider, name]))} @@ -527,9 +538,9 @@ describe("ComboSuggestions card", () => { onCreate={async () => ({ ok: true })} onExtend={async () => ({ ok: true })} />); const suggestion = card(name); - expect(suggestion.querySelectorAll(".rb-order-item")).toHaveLength(2); + expect(suggestion.querySelectorAll(".rb-order-item")).toHaveLength(4); await act(async () => { button(suggestion, "Generate").click(); }); - expect(suggestion.querySelectorAll(".rb-suggest-members li")).toHaveLength(2); + expect(suggestion.querySelectorAll(".rb-suggest-members li")).toHaveLength(4); }); test("revoked metered consent blocks Add to combo and shows an error", async () => { @@ -622,7 +633,7 @@ test("another model on the same provider does not hide a missing channel", () => test("only consented extensions serialize paid targets, without writing consent", () => { const member = { provider: "google-vertex", model: "kimi-k3-1-pro", tier: "vertex" } as const; - expect(suggestionDraft("opus", [member]).targets).toEqual([]); + expect(suggestionDraft("opus", [member])).toMatchObject({ allowMeteredTargets: true, targets: [{ metered: true }] }); const current = combo("opus", [["kimi", member.model]]); expect(extendedCombo(current, [member], () => "own-subscription").targets).toEqual(current.targets); const body = toPutBody(extendedCombo({ ...current, allowMeteredTargets: true }, [member], () => "own-subscription")).combo; diff --git a/src/combos/suggestion-channel.ts b/src/combos/suggestion-channel.ts index fcbe24b7d4f..83fcb195711 100644 --- a/src/combos/suggestion-channel.ts +++ b/src/combos/suggestion-channel.ts @@ -14,7 +14,7 @@ export interface SuggestionProvider { } /** - * Order members are suggested in: a subscription from the model's own maker, any other + * Placement preference only. Every suggested target can incur charges. 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"; @@ -87,7 +87,3 @@ export function channelTier(provider: SuggestionProvider, model: string): Channe const modelMaker = MODEL_MAKERS.find(([re]) => re.test(normalizeModelName(model)))?.[1]; return modelMaker !== undefined && modelMaker === providerMaker ? "own-subscription" : "subscription"; } - -export function isMeteredTier(tier: ChannelTier): boolean { - return tier === "metered" || tier === "vertex"; -} diff --git a/src/server/management/combo-suggestion-routes.ts b/src/server/management/combo-suggestion-routes.ts index 902d0cb37f3..ad16a588f32 100644 --- a/src/server/management/combo-suggestion-routes.ts +++ b/src/server/management/combo-suggestion-routes.ts @@ -112,18 +112,23 @@ async function saveSuggestion(ctx: ManagementContext): Promise { ?? jsonResponse({ error: "invalid JSON body", code: "invalid_request" }, 400, req, config); } const invalid = () => jsonResponse({ error: "invalid suggested combo", code: "invalid_request" }, 400, req, config); - if (!isPlainRecord(body) || Object.keys(body).some(key => key !== "id" && key !== "mode" && key !== "targets") + if (!isPlainRecord(body) || Object.keys(body).some(key => key !== "id" && key !== "mode" && key !== "targets" && key !== "allowMeteredTargets") || typeof body.id !== "string" || (body.mode !== "create" && body.mode !== "append")) return invalid(); const id = body.id.trim(); const targets = parseTargets(body.targets); if (!targets || !id) return invalid(); const create = body.mode === "create"; + const consent = body.allowMeteredTargets; + if (!create && Object.hasOwn(body, "allowMeteredTargets")) return invalid(); const rejected = (code: string, status = 409) => ({ changed: false, value: { code, status } }); const outcome = mutatePersistedConfig<{ code: string; status: number } | { combos: NonNullable }>(persisted => { const previous = Object.hasOwn(persisted.combos ?? {}, id) ? persisted.combos![id] : undefined; if (create ? previous : !previous) return rejected("suggestion_combo_changed"); + if (create && consent !== undefined && typeof consent !== "boolean") return rejected("invalid_request", 400); + if ((create ? consent : previous?.allowMeteredTargets) !== true) return rejected("suggestion_consent_required"); + const nextTargets = [...(previous?.targets ?? [])]; const providerFor = (snapshot: OcxConfig, name: string) => Object.hasOwn(snapshot.providers, name) ? snapshot.providers[name] : undefined; @@ -131,8 +136,9 @@ async function saveSuggestion(ctx: ManagementContext): Promise { const current = providerFor(snapshot, provider); return current ? channelTier({ ...current, name: provider }, model) : "metered"; }; - // A provider can have different billing in the running and saved config. + // Use the lower placement preference when live and persisted channel classifications differ. const rankOf = (target: Target) => Math.max(TIER_RANK[tierOf(persisted, target)], TIER_RANK[tierOf(config, target)]); + const inserted = new Set(); for (const target of targets) { if (nextTargets.some(({ provider, model }) => provider.trim() === target.provider && model.trim() === target.model)) continue; const provider = providerFor(persisted, target.provider); @@ -141,14 +147,14 @@ async function saveSuggestion(ctx: ManagementContext): Promise { } if (persisted.comboSuggestionExcludedProviders?.includes(target.provider)) return rejected("suggestion_provider_excluded"); const rank = rankOf(target); - const metered = rank >= TIER_RANK.vertex; - if (metered && previous?.allowMeteredTargets !== true) return rejected("suggestion_consent_required"); const at = create ? -1 : nextTargets.findIndex(existing => - (existing.metered === true ? TIER_RANK.metered : rankOf(existing)) > rank); - nextTargets.splice(at < 0 ? nextTargets.length : at, 0, { ...target, ...(metered ? { metered: true } : {}) }); + (existing.metered === true && !inserted.has(existing) ? TIER_RANK.metered : rankOf(existing)) > rank); + const added = { ...target, metered: true }; + inserted.add(added); + nextTargets.splice(at < 0 ? nextTargets.length : at, 0, added); } - const combo: OcxComboConfig = { strategy: "failover", ...previous, targets: nextTargets }; + const combo: OcxComboConfig = { strategy: "failover", ...previous, allowMeteredTargets: true, targets: nextTargets }; const combos = { ...persisted.combos, [id]: combo }; const prospective = { ...persisted, combos }; if (comboConfigIssues(id, combo, persisted.providers, { diff --git a/structure/config.md b/structure/config.md index 9d7fa165cbe..226de09389c 100644 --- a/structure/config.md +++ b/structure/config.md @@ -554,7 +554,7 @@ Account quota surfaces use [safe probe diagnostics](transports/inventory.md#acco The OpenCode launcher resolves the existing local management origin from the live bind and configured hub ingress. Its admin credential comes from the existing admin environment/file policy; an absent credential fails without substituting a data key. -The optional `autoReviewOverride` block stores a global approval reviewer selector and enabled flag. The Models settings route validates and normalizes writes, restores the live block when persistence fails before publication, and reports catalog convergence; the dashboard shows pending when the catalog did not commit. Malformed hand edits drop this block without discarding other configuration. Provider `autoReviewModel` and `autoReviewModelOverrides` accept validated final-catalog selectors. Per-model keys preserve case and accept the existing raw/encoded slash equivalence. File-load degradation removes malformed optional selectors only; management writes reject malformed shapes. Omitted provider saves preserve selectors, explicit clears remove them, and raw editor candidates adopt normalized values before persistence and live replacement. See [catalog ownership](catalog.md#provider-scoped-approval-reviewer). The optional `comboSuggestionExcludedProviders` array is owned by `src/config/schema/config-schema.ts`. It accepts up to 256 trimmed, deduplicated provider names of at most 256 characters each. A malformed value is dropped during parsing. Saving an empty list removes the key. The preference filters dashboard suggestions and leaves configured combo targets in place. `src/server/management/combo-suggestion-routes.ts` reads exclusions and stored combo consent from the locked persisted snapshot used to save a suggestion. It checks provider metering against both that snapshot and the active config on every evaluation, including a rebase. The dashboard and suggestion save route use the allowlist in `src/combos/suggestion-channel.ts`. Each OAuth entry requires the registered provider ID, adapter, auth mode, and exact normalized destination. See the [provider billing and account notes](../docs-site/src/content/docs/guides/providers.md). +The optional `autoReviewOverride` block stores a global approval reviewer selector and enabled flag. The Models settings route validates and normalizes writes, restores the live block when persistence fails before publication, and reports catalog convergence; the dashboard shows pending when the catalog did not commit. Malformed hand edits drop this block without discarding other configuration. Provider `autoReviewModel` and `autoReviewModelOverrides` accept validated final-catalog selectors. Per-model keys preserve case and accept the existing raw/encoded slash equivalence. File-load degradation removes malformed optional selectors only; management writes reject malformed shapes. Omitted provider saves preserve selectors, explicit clears remove them, and raw editor candidates adopt normalized values before persistence and live replacement. See [catalog ownership](catalog.md#provider-scoped-approval-reviewer). The optional `comboSuggestionExcludedProviders` array is owned by `src/config/schema/config-schema.ts`. It accepts up to 256 trimmed, deduplicated provider names of at most 256 characters each. A malformed value is dropped during parsing. Saving an empty list removes the key. The preference filters dashboard suggestions and leaves configured combo targets in place. `src/server/management/combo-suggestion-routes.ts` reads exclusions and stored combo consent from the locked persisted snapshot used to save a suggestion. Every suggested target is metered because subscription channels can incur charges too. Create records explicit dashboard consent and append requires existing combo consent. The classifier in `src/combos/suggestion-channel.ts` ranks channels for placement. Each OAuth ranking entry requires the registered provider ID, adapter, auth mode, and exact normalized destination. See the [provider billing and account notes](../docs-site/src/content/docs/guides/providers.md). - Canonical ChatGPT Codex forward uses the Codex login account channel and the same destination predicate as Responses transport. - `xai` OAuth uses the Grok CLI subscription gateway. The public API-key lane is metered. diff --git a/structure/dashboard-and-usage.md b/structure/dashboard-and-usage.md index e00b82fef92..5bd2dfc5d24 100644 --- a/structure/dashboard-and-usage.md +++ b/structure/dashboard-and-usage.md @@ -501,7 +501,7 @@ Dashboard overview polling observes authorization failures independently of stal The [explicit model-capability contract](config.md#explicit-per-model-capability-declarations) preserves operator declarations through provider storage and catalog capture; it does not infer upstream capability or change this surface's routing behavior. -Exact [model input declarations](config.md#explicit-per-model-capability-declarations) now feed text-only eligibility and catalog hints; existing image-description/omission handling consumes them before the main upstream send. The Combos page sends non-image members as the request-only `visionSidecarTargets` field on `PUT /api/combos` whenever the Image switch is enabled, so text-only enrollment needs no manual provider edit. The GUI classifies members from the authoritative `visionSidecarConsumer` flag served on `/api/models` rows, so a member covered only by legacy `noVisionModels` keeps its sidecar classification after reload. Members whose modalities are unknown or have no text input keep the switch unavailable and are named in the hint; a member later removed from the combo keeps its provider declaration until cleared in the provider editor. `gui/src/components/route-board/WorkspaceSuggestions.tsx` renders suggestion cards inside the Combos workspace. Generate opens a draft. Saving the draft and choosing Add to combo both use the dashboard-only `POST /api/combo-suggestions/save` endpoint. Extension is held while that combo has unsaved workspace edits. Dismissals are browser-local. Provider exclusions are persisted by the management API. The workspace gates cards on a successful exclusion read for the current proxy and offers a retry on failure. The exclusion control remains available after the last card is dismissed. New drafts use unmetered targets. Extensions offer metered targets, including Vertex, only with existing explicit combo consent. The dedicated save path validates the targets against active and locked persisted provider configuration, then checks persisted exclusions and combo consent before publishing the write. The shared [subscription allowlist](config.md) determines which channels can appear without metered-target consent. +Exact [model input declarations](config.md#explicit-per-model-capability-declarations) now feed text-only eligibility and catalog hints; existing image-description/omission handling consumes them before the main upstream send. The Combos page sends non-image members as the request-only `visionSidecarTargets` field on `PUT /api/combos` whenever the Image switch is enabled, so text-only enrollment needs no manual provider edit. The GUI classifies members from the authoritative `visionSidecarConsumer` flag served on `/api/models` rows, so a member covered only by legacy `noVisionModels` keeps its sidecar classification after reload. Members whose modalities are unknown or have no text input keep the switch unavailable and are named in the hint; a member later removed from the combo keeps its provider declaration until cleared in the provider editor. `gui/src/components/route-board/WorkspaceSuggestions.tsx` renders suggestion cards inside the Combos workspace. Generate opens a draft. Saving the draft and choosing Add to combo both use the dashboard-only `POST /api/combo-suggestions/save` endpoint. Extension is held while that combo has unsaved workspace edits. Dismissals are browser-local. Provider exclusions are persisted by the management API. The workspace gates cards on a successful exclusion read for the current proxy and offers a retry on failure. The exclusion control remains available after the last card is dismissed. Generate shows an unchecked paid-target consent checkbox and disables saving until it is checked. Add to combo is disabled with an explanation until the existing combo permits paid targets. The dedicated save route rechecks persisted exclusions and spend consent and marks all added targets metered. The [channel classifier](config.md) is used for placement preference. The raw provider editor round-trips `autoReviewModel` and `autoReviewModelOverrides` through editor-owned DTO fields. POST/PATCH/PUT share validation; PUT copies schema-normalized values into the persisted and live candidate before adoption. Canonical `openai` rejects these fields, including clear forms. Field-masked writes (PATCH, editor PUT, reload) pin every registry-seed key and ignore operator overlays the seed never defines, most commonly `selectedModels`; POST keeps the exact-key comparison. Canonical `openai` still rejects `allowPrivateNetwork`, which must not short-circuit destination DNS checks on the ChatGPT forward row. Existing authentication, origin checks and stale-baseline protection still govern the writes. See [reviewer projection](catalog.md#provider-scoped-approval-reviewer). Stored Direct substitution follows the [credential identity contract](providers/openai-accounts.md#sidecars-management-and-ui): both synchronous and asynchronous materializers discard the caller account header before applying the stored credential; ordinary native Direct passthrough is unchanged. diff --git a/structure/gui-and-management-api.md b/structure/gui-and-management-api.md index 179e760a5e6..e256a144a47 100644 --- a/structure/gui-and-management-api.md +++ b/structure/gui-and-management-api.md @@ -311,7 +311,7 @@ after the save, and a non-retryable skip (no managed catalog) is a clean save. C | File-integration plans | `src/server/management/integration-routes.ts` and `aside-profile-routes.ts` — `POST /api/client-integrations/preview`, `POST /api/client-integrations/restore/preview`, and `POST /api/client-integrations/aside/profiles/{profileId}/preview`. Management-authenticated, declared non-mutating, and they write nothing: no snapshot, no lock, no maintenance, no recovery. They answer `409 integration_preview_unavailable` rather than gathering a model roster, because discovery refreshes credentials and writes the provider cache. Responses carry only declared managed schema paths, closed change kinds and an opaque fingerprint; no value, filesystem location or selected member identity appears. Mutation routes accept `operation` and `planFingerprint` together or not at all, reject a half-bound request and an operation that disagrees with the change, and answer `409 integration_preview_stale` with a freshly computed plan. Binding is an optimistic token, never authorization. [The integration contract](clients/integrations.md) owns the ordering. | | Grok reset coupons | `src/server/management/grok-coupon-routes.ts` — `GET /api/grok/reset-coupons`, `POST /api/grok/reset-coupons/consume`. The dashboard owner is `gui/src/hooks/useGrokResetCoupons.ts` with `gui/src/components/provider-workspace/GrokResetCoupons.tsx`, wired into the xAI OAuth rows of `ProviderAuthPanel`. Redemption truth is the settled ledger `code`, not the HTTP status: a replayed failure returns 200 with `replayed: true`. See [`providers/xai-grok.md`](providers/xai-grok.md). The route returns `ledger_unavailable` before dispatch when the shared ledger cannot be read or locked; stale uncertain attempts are inspected without another redemption or inferred success. A late inspection refusal or a lost claim replays an identity-matching definitive winner; otherwise it returns `operation_state_changed` (late refusal) or `attempt_in_progress` (lost claim) and never replaces an attempted or terminal record. Unknown-outcome responses include the effective operation ID; the CLI mints it before dispatch. Uncertain and pending attempts live in a module-level hold store shared by all hook instances and mirrored to `sessionStorage` (`ocx.grok-coupon-holds.v1`), so they survive modal close/reopen, remount, and reload for the tab session; the pending hold is written before the POST, only a definitive response for the same `operationId` clears it, and only GET refreshes are allowed after uncertainty. Every response that cannot prove settlement under a supplied operation ID, including pre-open refusals, carries that `operationId`. A definitive failure releases the matching speculative pending hold. Supplied token IDs must be non-empty strings before journal admission, and omitted account/token retries recover the operation’s durable identity within retention. Legacy version-one opens are quarantined rather than dispatched. After confirmed redemption, local settlement has five attempts and four 20 ms waits only for a `ConfigMutationLockError` caused by `SQLITE_BUSY`; any other error or changed claim stops without another redemption. | | Claude reset grants | `src/server/management/anthropic-reset-grant-routes.ts` — `GET /api/anthropic/reset-grants`, `POST /api/anthropic/reset-grants/consume` (lazy-loaded). Wire and fail-closed parsing live in `src/providers/anthropic-reset-grants.ts` (the Claude Code 2.1.278 `cedar_ember` contract, sent with `CLAUDE_CLI_USER_AGENT` from `src/providers/claude-cli-identity.ts`; every bearer request refuses redirects, and a refused claim redirect is an unknown outcome); the journal is `src/providers/anthropic-reset-grant-ledger.ts`: a cross-process `BEGIN IMMEDIATE` lock around every synchronous read-modify-write, a 90 s lease, the operation id reused as the upstream `request_id`, same-id retry only inside the vendor's ten-minute window, at most one unresolved operation per account and organization within each pool's journal and that ten-minute window, whatever grant it names (a new id gets `409 unresolved_prior_operation`), no settlement inferred from a re-read, and a fail-closed `500 journal_write_failed` when an answer cannot be recorded. Spending requires the `gui-session` principal. A journaled `reset`, including a same-id replay of that code, lifts that account cooldown only when it is a 429 quota refusal recorded before the operation was first journaled (the claim fence, `claimedAt`) and the journal's cleared windows cover every window the refusal named (both when it named none); it then drops the cached quota row and rereads usage with its own request rather than joining an older read. Model-family exclusions stay until the usage reread proves a family is no longer rejected. A failed reread leaves them in place. The HTTP result stays the journal answer if the reread fails. Other result codes do not admit. The dashboard owner is `gui/src/hooks/useAnthropicResetGrants.ts` with `gui/src/components/provider-workspace/AnthropicResetGrants.tsx` on the Anthropic OAuth rows of `ProviderAuthPanel`; the dialog re-reads the account when it opens, lets the user choose the grant (default: the selectable grant that expires first; the server re-gates the chosen `grantId`), and after an unknown outcome only retries the same id with no picker shown. Design and audit record: [`../devlog/_fin/260923_claude_reset_grants/010_plan.md`](../devlog/_fin/260923_claude_reset_grants/010_plan.md). | -| Combos | `src/server/management/combo-routes.ts` — `GET/PUT/DELETE /api/combos` own provider combination and failover definitions. `PUT` keeps a stored field the body omits (`cooldownMs`, `waitForCooldownMs`, `defaultEffortMode`, `reasoningEffortMode`, `imageInput`, `cooldownWaitPolicy`, per-target `lastResort`, JEV `decisionQuotaSignals`/`decisionQuotaTiers`/`jevEffortMode`/`sessionPin` on updates/rename); quota false/null clears sparsely and switching away removes quota policy under [the owning contract](providers/jev-decision.md#loaded-advisory-quota). Explicit values replace it and defaults are stored sparse. A combo validation 400 is `{ error, field? }`, where `field` is the top-level combo field of the first issue. `GET /api/combo-suggestions` and `PUT /api/combo-suggestions` use the dashboard-only route in `src/server/management/combo-suggestion-routes.ts`. All three suggestion operations require `hasHumanDashboardSession` before dispatch. Admin-token and remembered-admin callers receive 403. The two exclusion operations return `{ excludedProviders: string[] }`. PUT validates the full replacement list and persists it before publishing the live value. `POST /api/combo-suggestions/save` accepts a combo ID, a create or append mode, and provider/model pairs. The locked config mutation checks each new target against provider classifications in both the active and persisted config, along with persisted exclusions and combo spend consent. A paid classification in either config requires stored consent and sets `metered: true` on the new target. Create has no spend consent. Conflicts return a fixed reason code and the dashboard refreshes the suggestions. When appending suggestions, the server uses the more costly tier from the active and saved configurations. It treats existing targets explicitly marked as metered as pay-per-use and preserves the relative order of existing targets. The dashboard and save route share the tier classifier. The config DTO carries the canonical forward and known OAuth subscription decisions computed before URL sanitization, so redaction cannot make a gateway appear unmetered. | +| Combos | `src/server/management/combo-routes.ts` — `GET/PUT/DELETE /api/combos` own provider combination and failover definitions. `PUT` keeps a stored field the body omits (`cooldownMs`, `waitForCooldownMs`, `defaultEffortMode`, `reasoningEffortMode`, `imageInput`, `cooldownWaitPolicy`, per-target `lastResort`, JEV `decisionQuotaSignals`/`decisionQuotaTiers`/`jevEffortMode`/`sessionPin` on updates/rename); quota false/null clears sparsely and switching away removes quota policy under [the owning contract](providers/jev-decision.md#loaded-advisory-quota). Explicit values replace it and defaults are stored sparse. A combo validation 400 is `{ error, field? }`, where `field` is the top-level combo field of the first issue. `GET /api/combo-suggestions` and `PUT /api/combo-suggestions` use the dashboard-only route in `src/server/management/combo-suggestion-routes.ts`. All three suggestion operations require `hasHumanDashboardSession` before dispatch. Admin-token and remembered-admin callers receive 403. The two exclusion operations return `{ excludedProviders: string[] }`. PUT validates the full replacement list and persists it before publishing the live value. `POST /api/combo-suggestions/save` accepts a combo ID, a create or append mode, and provider/model pairs. The locked mutation validates persisted exclusions and spend consent. Create requires and stores explicit `allowMeteredTargets: true`. Append rejects request consent and requires stored consent. All new suggested targets have `metered: true`. Conflicts return a fixed reason code and the dashboard refreshes the suggestions. When appending suggestions, the server uses the more costly tier from the active and saved configurations. It treats existing targets explicitly marked as metered as pay-per-use and preserves the relative order of existing targets. The dashboard and save route share the tier classifier. The config DTO carries the canonical forward and known OAuth subscription decisions computed before URL sanitization, so redaction cannot change gateway placement. | | Protocol paths | `src/server/management/protocol-routes.ts` (lazy-loaded) — `GET /api/protocols` returns the contract version, the resolved API surfaces and protocol settings, the policy revision and the feature vocabulary; with `?provider=` (one non-empty name of at most 200 characters without control characters, else 400 `invalid_provider`; an unconfigured name is 404 `unknown_provider`, neither echoing the name) it adds a `provider` block from `src/protocols/provider-summary.ts` ([Protocol Paths](data-planes/protocol-paths.md#provider-wire-summary)); `POST /api/protocols/plan` takes `{ model, inbound, features? }` (model at most 200 characters, at most 24 features, any other key refused with 400) and returns a `ProtocolPlanV1` with `basis: "preview"` from `src/protocols/plan-snapshot.ts`. Both are read-only, never log their input, and send nothing upstream. `PATCH /api/protocols/settings` takes `{ messagesEnabled?, unrepresentable?, rollout? }` (strict: unknown keys and wrong types are 400), validates and applies through `src/server/management/protocol-settings-patch.ts`, persists with `saveConfigPreservingClaudeCode`, restores the live config if the save fails (409 on lock contention, 500 otherwise), and answers with the fresh `GET /api/protocols` body; closing Messages also writes `claudeCode.enabled = false` through `commitClaudeCodeBlock` ([Protocol Paths](data-planes/protocol-paths.md#settings)). The CLI drives all three through `ocx api protocols`, `ocx api explain` and `ocx api policy` ([Protocol Paths](data-planes/protocol-paths.md#cli)); none carries a route-registry exemption. | | Workflow budget | `src/server/management/workflow-budget-routes.ts` — `GET /api/workflow-budget` reads the tracked roots or one root, and `POST /api/workflow-budget/clear` clears exactly one. The clear moves the windowed send ring and the child map and nothing else: `active` belongs to turns still in flight, the spend ledger is a token budget an operator did not ask to forgive, and the lifetime send total survives so a clear cannot launder the record. A refusal event carries `spendScope` and `spendLimit` when a token ceiling fired, so the reason is readable without the config open beside it; no scope id is ever attached, because root ids are client thread headers and identity ids are credentials. Both are `deferred-verb` in the route registry — they are owed CLI verbs, and because the ledger is process memory there is no local projection the CLI could read instead. `GET`/`PUT /api/workflow-budget/settings` read and write the per-install count ceilings (`workflowBudget` in config: concurrent turns, sends and distinct children per window); the live config is bound in `src/lib/workflow-budget-config.ts` and read per decision by HTTP admission and the pre-dispatch send ceiling, so a write applies to the next request and never resets a root's usage. The window, interactive reserve and tracked-root bound stay fixed because a root's ring geometry is fixed when it first appears. The GET is `local-transport` (same block via `ocx config get`), the PUT `deferred-verb` with the other budget verbs. See [`../devlog/_fin/260915_workflow_budget_window/030_wfc_diff_plan.md`](../devlog/_fin/260915_workflow_budget_window/030_wfc_diff_plan.md). | | Codex accounts | `src/codex/auth-api/routes.ts` — `GET/POST/DELETE /api/codex-auth/accounts`, `PUT /api/codex-auth/accounts/alias`, `PUT /api/codex-auth/accounts/pause`, `PUT /api/codex-auth/accounts/pause-exhausted`, `POST /api/codex-auth/accounts/clear-cooldown`, `GET/PUT /api/codex-auth/active`, `PUT /api/codex-auth/auto-switch`, `PUT /api/codex-auth/pool-strategy`, `PUT /api/codex-auth/failover`, `GET /api/codex-auth/quota`, `GET /api/codex-auth/reset-credits` with `POST /api/codex-auth/reset-credits/consume`, and the login flow `POST /api/codex-auth/login`, `POST /api/codex-auth/login/code`, `POST /api/codex-auth/login/cancel`, `GET /api/codex-auth/login-status`. Pool login cancellation through `POST /api/codex-auth/login/cancel` addresses the flow id returned by the pool start route and follows the [pool publication contract](providers/openai-accounts.md#pool-login-policy-and-cancellation). Per-account quota activation uses the existing `GET/PUT /api/settings` surface and `src/codex/quota-auto-refresh.ts`, keeping scheduled spending separate from credential/authentication mutation. Account ids are opaque handles and are serialized so the GUI can address an account; emails are masked and tokens are never serialized. New-account config commits add UI-managed selector bindings in the same config save; deletion deliberately retains existing bindings for fail-closed exact routing and re-add stability. Account mutations request catalog convergence only after config durability and expose only the boolean `catalogRefreshPending` completion projection. `showCodexCredits` is a default-off boolean in settings GET and successful PUT; partial PUT accepts a boolean and rolls back on persistence failure. See [credits exposure](providers/openai-accounts.md#display-only-codex-credits). | diff --git a/tests/server/combo-suggestion-routes.test.ts b/tests/server/combo-suggestion-routes.test.ts index 67a4e7fa3dc..b81dd0d7b6e 100644 --- a/tests/server/combo-suggestion-routes.test.ts +++ b/tests/server/combo-suggestion-routes.test.ts @@ -144,6 +144,7 @@ test.each([ ["GET", "/api/combo-suggestions", undefined], ["PUT", "/api/combo-suggestions", { excludedProviders: ["other"] }], ["POST", "/api/combo-suggestions/save", { id: "mix", mode: "append", targets: [paidTarget] }], + ["POST", "/api/combo-suggestions/save", { id: "draft", mode: "create", targets: [paidTarget], allowMeteredTargets: true }], ] as const)("%s %s requires a dashboard session", async (method, path, body) => { const live = seedPaidSuggestion(); const before = onDisk(); @@ -185,10 +186,9 @@ test("append uses the current combo and marks a consented Vertex target metered" expect(live.combos?.mix?.targets).toHaveLength(2); }); -test("create rejects paid Vertex and never accepts consent from the request", async () => { +test("create requires explicit consent for every channel", async () => { const live = seedPaidSuggestion(); const draft = { id: "draft", mode: "create", targets: [paidTarget] }; - expect((await saveSuggestion(live, { ...draft, allowMeteredTargets: true })).status).toBe(400); const response = await saveSuggestion(live, draft); expect(response.status).toBe(409); expect(await response.json()).toMatchObject({ code: "suggestion_consent_required" }); @@ -198,8 +198,15 @@ test("create rejects paid Vertex and never accepts consent from the request", as setCanonicalForward(live); setCanonicalForward(current); saveConfig(current); - expect((await saveSuggestion(live, { ...draft, targets: [{ provider: "mock", model: "m" }] })).status).toBe(200); - expect(loadConfig().combos?.draft?.allowMeteredTargets).toBeUndefined(); + const targets = [{ provider: "mock", model: "m" }, paidTarget]; + expect((await saveSuggestion(live, { ...draft, targets })).status).toBe(409); + expect((await saveSuggestion(live, { ...draft, targets, allowMeteredTargets: true })).status).toBe(200); + for (const config of [live, loadConfig()]) { + expect(config.combos?.draft).toMatchObject({ + allowMeteredTargets: true, + targets: targets.map(target => ({ ...target, metered: true })), + }); + } }); for (const paidSide of ["live", "persisted", "both"] as const) { @@ -255,7 +262,7 @@ test("append inserts a subscription before explicitly metered targets without re const response = await saveSuggestion(live, { id: "mix", mode: "append", targets: [target] }); expect(response.status).toBe(200); for (const config of [live, loadConfig()]) { - expect(config.combos?.mix?.targets).toEqual([target, ...existing]); + expect(config.combos?.mix?.targets).toEqual([{ ...target, metered: true }, ...existing]); } }); @@ -283,3 +290,17 @@ test.each(["create", "append"] as const)("Devin %s requires stored spend consent } } }); + +test("append requires stored consent even for a canonical subscription and rejects request consent", async () => { + const live = seedPaidSuggestion(); + setCanonicalForward(live); + delete live.combos!.mix!.allowMeteredTargets; + saveConfig(live); + const before = onDisk(); + const request = { id: "mix", mode: "append", targets: [{ provider: "mock", model: "other" }] }; + expect((await saveSuggestion(live, { ...request, allowMeteredTargets: true })).status).toBe(400); + const denied = await saveSuggestion(live, request); + expect(denied.status).toBe(409); + expect(await denied.json()).toMatchObject({ code: "suggestion_consent_required" }); + expect(onDisk()).toEqual(before); +}); From 62123277244d894ef25ea5ee93706c9f176f24b7 Mon Sep 17 00:00:00 2001 From: JUN Date: Thu, 19 Nov 2026 02:49:53 +0900 Subject: [PATCH 15/23] Reconcile suggestion cards with persisted conflict policy Co-authored-by: Andrew (agent) --- .../src/content/docs/es/guides/combos.md | 2 +- docs-site/src/content/docs/guides/combos.md | 2 +- .../route-board/WorkspaceSuggestions.tsx | 17 ++++- .../route-board/use-suggestion-exclusions.ts | 8 +++ gui/tests/combo-suggestions.test.tsx | 66 +++++++++++-------- .../management/combo-suggestion-routes.ts | 16 ++++- structure/dashboard-and-usage.md | 2 +- structure/gui-and-management-api.md | 2 +- tests/server/combo-suggestion-routes.test.ts | 8 ++- 9 files changed, 84 insertions(+), 39 deletions(-) diff --git a/docs-site/src/content/docs/es/guides/combos.md b/docs-site/src/content/docs/es/guides/combos.md index 8ca3352f36a..60e779ad659 100644 --- a/docs-site/src/content/docs/es/guides/combos.md +++ b/docs-site/src/content/docs/es/guides/combos.md @@ -792,4 +792,4 @@ Un rechazo estructurado de esfuerzo puede bajar una posición publicada cada vez Si los ajustes cambian antes de guardar una sugerencia, Combos actualiza las sugerencias y muestra un mensaje. Al guardar, se comprueban las exclusiones y el consentimiento de gasto vigentes. Al añadir sugerencias, el servidor aplica el nivel de mayor coste entre la configuración activa y la guardada. Trata los destinos existentes marcados explícitamente como medidos como destinos de pago por uso y conserva el orden relativo de los destinos existentes. -En el espacio de trabajo de combos, **Generar** abre un borrador de conmutación por error para un modelo disponible en varios proveedores. **Añadir al combo** ofrece destinos que faltan en un combo existente. Las tarjetas descartadas quedan ocultas en este navegador. Usa **Excluir un proveedor…** para filtrar ambos tipos de sugerencias. El proxy guarda la selección como `comboSuggestionExcludedProviders` en `config.json`. Los miembros existentes se conservan. Todos los destinos sugeridos pueden generar cargos, incluso los canales de suscripción, como Codex con créditos comprados, Grok con Extra Usage y Kimi Code con Extra Usage. Para guardar un borrador, marca **Permitir destinos de pago**. Para añadir destinos, habilita primero los destinos de pago en el combo existente. El proxy guarda todos los destinos sugeridos con `metered: true`. El control de exclusión sigue disponible tras descartar todas las tarjetas. Si falla la carga de las exclusiones, vuelve a intentarlo. +En el espacio de trabajo de combos, **Generar** abre un borrador de conmutación por error para un modelo disponible en varios proveedores. **Añadir al combo** ofrece destinos que faltan en un combo existente. Las tarjetas descartadas quedan ocultas en este navegador. Usa **Excluir un proveedor…** para filtrar ambos tipos de sugerencias. El proxy guarda la selección como `comboSuggestionExcludedProviders` en `config.json`. Los miembros existentes se conservan. Todos los destinos sugeridos pueden generar cargos, incluso los canales de suscripción, como Codex con créditos comprados, Grok con Extra Usage y Kimi Code con Extra Usage. Para guardar un borrador, marca **Permitir destinos de pago**. Para añadir destinos, habilita primero los destinos de pago en el combo existente. El proxy guarda todos los destinos sugeridos con `metered: true`. El control de exclusión sigue disponible tras descartar todas las tarjetas. Si falla la carga de las exclusiones, vuelve a intentarlo. Si la política guardada cambia antes de guardar, el espacio de trabajo actualiza las tarjetas según las exclusiones actuales y el permiso guardado para los destinos de pago. diff --git a/docs-site/src/content/docs/guides/combos.md b/docs-site/src/content/docs/guides/combos.md index ef9500a5f3c..d4bab15f9b3 100644 --- a/docs-site/src/content/docs/guides/combos.md +++ b/docs-site/src/content/docs/guides/combos.md @@ -1218,4 +1218,4 @@ untried targets and newer failures keep their cooldowns. When settings change before a suggestion is saved, Combos refreshes the suggestions and displays a message. Saving checks the current exclusions and spend consent. -In the Combos workspace, **Generate** opens a failover draft for a model served by multiple providers. **Add to combo** offers missing targets for an existing combo. Dismissed cards stay hidden in this browser. Use **Exclude providers…** to filter both kinds of suggestions. The proxy stores your selection as `comboSuggestionExcludedProviders` in `config.json`. When appending suggestions, the server uses the more costly tier from the active and saved configurations. It treats existing targets explicitly marked as metered as pay-per-use and preserves the relative order of existing targets. Every suggested target can incur paid usage, including subscription channels such as Codex with purchased credits, Grok with Extra Usage, and Kimi Code with Extra Usage. To save a draft, check **Allow paid targets**. To append, first enable paid targets in the existing combo. The proxy saves every suggested target as `metered: true`. The exclusion control stays available after dismissing all cards. If exclusions fail to load, retry to see suggestions. +In the Combos workspace, **Generate** opens a failover draft for a model served by multiple providers. **Add to combo** offers missing targets for an existing combo. Dismissed cards stay hidden in this browser. Use **Exclude providers…** to filter both kinds of suggestions. The proxy stores your selection as `comboSuggestionExcludedProviders` in `config.json`. When appending suggestions, the server uses the more costly tier from the active and saved configurations. It treats existing targets explicitly marked as metered as pay-per-use and preserves the relative order of existing targets. Every suggested target can incur paid usage, including subscription channels such as Codex with purchased credits, Grok with Extra Usage, and Kimi Code with Extra Usage. To save a draft, check **Allow paid targets**. To append, first enable paid targets in the existing combo. The proxy saves every suggested target as `metered: true`. The exclusion control stays available after dismissing all cards. If exclusions fail to load, retry to see suggestions. If saved policy changes before you save, the workspace refreshes the cards using the current exclusions and the saved paid-target setting. diff --git a/gui/src/components/route-board/WorkspaceSuggestions.tsx b/gui/src/components/route-board/WorkspaceSuggestions.tsx index 6777634f0cf..c0f6665183f 100644 --- a/gui/src/components/route-board/WorkspaceSuggestions.tsx +++ b/gui/src/components/route-board/WorkspaceSuggestions.tsx @@ -23,6 +23,13 @@ export function WorkspaceSuggestions(props: Props) { const exclusions = useSuggestionExclusions(props.apiBase, props.active); const [conflict, setConflict] = useState(false); + const [consentOverrides, setConsentOverrides] = useState>({}); + const combos = props.combos.map((combo) => { + const key = JSON.stringify([props.apiBase, combo.id]); + return Object.hasOwn(consentOverrides, key) + ? { ...combo, allowMeteredTargets: consentOverrides[key] } + : combo; + }); const saveSuggestion = async (item: ComboItem, isCreate: boolean) => { setConflict(false); @@ -39,7 +46,13 @@ export function WorkspaceSuggestions(props: Props) { }); if (response.status === 409) { setConflict(true); - exclusions.retry(); + const body = await response.json().catch(() => null); + if (typeof body?.policy?.allowMeteredTargets === "boolean" && exclusions.applyPolicy(body.policy)) { + const key = JSON.stringify([props.apiBase, item.id]); + setConsentOverrides((current) => ({ ...current, [key]: body.policy.allowMeteredTargets })); + } else { + exclusions.retry(); + } props.onRefresh(); return { ok: false, error: "" }; } @@ -71,7 +84,7 @@ export function WorkspaceSuggestions(props: Props) { <> {conflictAlert} void; + applyPolicy: (policy: unknown) => boolean; /** Saves the whole list; resolves false when the proxy did not take it (the list stays as it was). */ save: (next: readonly string[]) => Promise; } @@ -70,6 +71,13 @@ export function useSuggestionExclusions(apiBase: string, active = true): Suggest ready: current?.excluded != null, failed: current?.excluded === null, retry: () => setAttempt((value) => value + 1), + applyPolicy: (policy) => { + const list = parse(policy); + if (!list) return false; + generation.current += 1; + setLoaded({ base: apiBase, attempt, excluded: list }); + return true; + }, save, }; } diff --git a/gui/tests/combo-suggestions.test.tsx b/gui/tests/combo-suggestions.test.tsx index 8ccea53f66c..4c62c75e1d2 100644 --- a/gui/tests/combo-suggestions.test.tsx +++ b/gui/tests/combo-suggestions.test.tsx @@ -543,36 +543,44 @@ describe("ComboSuggestions card", () => { expect(suggestion.querySelectorAll(".rb-suggest-members li")).toHaveLength(4); }); - test("revoked metered consent blocks Add to combo and shows an error", async () => { - const originalFetch = globalThis.fetch; - const name = "kimi-k3-1-pro"; - const existing = combo("opus", [["kimi", name]], { allowMeteredTargets: true }); - let refreshCount = 0; - let exclusionReads = 0; - globalThis.fetch = (async (url: string) => { - if (url.endsWith("/api/combo-suggestions/save")) { - return Response.json({ code: "suggestion_consent_required" }, { status: 409 }); + for (const excluded of [false, true]) { + test(`applies persisted suggestion policy after a conflict (excluded: ${excluded})`, async () => { + const originalFetch = globalThis.fetch; + const name = "kimi-k3-1-pro"; + const existing = combo("opus", [["kimi", name]], { allowMeteredTargets: true }); + let refreshCount = 0; + globalThis.fetch = (async (url: string) => { + if (url.endsWith("/api/combo-suggestions/save")) { + return Response.json({ + code: excluded ? "suggestion_provider_excluded" : "suggestion_consent_required", + policy: { allowMeteredTargets: excluded, excludedProviders: excluded ? ["google-vertex"] : [] }, + }, { status: 409 }); + } + return Response.json({ excludedProviders: [] }); + }) as typeof fetch; + try { + await mount( { refreshCount += 1; }} + />); + const extension = card("opus"); + expect(extension.textContent).toContain("Vertex"); + await act(async () => { button(extension, "Add to combo").click(); }); + expect(host.querySelector('[role="alert"]')?.textContent).toContain("Suggestion settings changed"); + if (excluded) { + expect(host.textContent).not.toContain("Add to combo"); + } else { + expect(button(card("opus"), "Add to combo").disabled).toBe(true); + expect(card("opus").textContent).toContain("Enable paid targets on this combo first."); + } + expect(refreshCount).toBe(1); + } finally { + globalThis.fetch = originalFetch; } - exclusionReads += 1; - return Response.json({ excludedProviders: exclusionReads > 1 ? ["google-vertex"] : [] }); - }) as typeof fetch; - try { - await mount( { refreshCount += 1; }} - />); - const extension = card("opus"); - expect(extension.textContent).toContain("Vertex"); - await act(async () => { button(extension, "Add to combo").click(); }); - expect(host.querySelector('[role="alert"]')?.textContent).toContain("Suggestion settings changed"); - expect(host.textContent).not.toContain("Add to combo"); - expect(refreshCount).toBe(1); - } finally { - globalThis.fetch = originalFetch; - } - }); + }); + } test("failed exclusions hide actions until a successful retry", async () => { const originalFetch = globalThis.fetch; diff --git a/src/server/management/combo-suggestion-routes.ts b/src/server/management/combo-suggestion-routes.ts index ad16a588f32..d52dd8244a6 100644 --- a/src/server/management/combo-suggestion-routes.ts +++ b/src/server/management/combo-suggestion-routes.ts @@ -102,6 +102,10 @@ function parseTargets(value: unknown): Target[] | null { return targets; } +type SuggestionSaveResult = + | { code: string; status: number; policy?: { allowMeteredTargets: boolean; excludedProviders: string[] } } + | { combos: NonNullable }; + async function saveSuggestion(ctx: ManagementContext): Promise { const { req, config } = ctx; let body: unknown; @@ -121,9 +125,15 @@ async function saveSuggestion(ctx: ManagementContext): Promise { const consent = body.allowMeteredTargets; if (!create && Object.hasOwn(body, "allowMeteredTargets")) return invalid(); - const rejected = (code: string, status = 409) => ({ changed: false, value: { code, status } }); - const outcome = mutatePersistedConfig<{ code: string; status: number } | { combos: NonNullable }>(persisted => { + const outcome = mutatePersistedConfig(persisted => { const previous = Object.hasOwn(persisted.combos ?? {}, id) ? persisted.combos![id] : undefined; + const policy = { + allowMeteredTargets: previous?.allowMeteredTargets === true, + excludedProviders: persisted.comboSuggestionExcludedProviders ?? [], + }; + const rejected = (code: string, status = 409) => ({ + changed: false, value: { code, status, policy: status === 409 ? policy : undefined }, + }); if (create ? previous : !previous) return rejected("suggestion_combo_changed"); if (create && consent !== undefined && typeof consent !== "boolean") return rejected("invalid_request", 400); @@ -177,7 +187,7 @@ async function saveSuggestion(ctx: ManagementContext): Promise { return jsonResponse({ error: "suggestion could not be saved", code: "config_unavailable" }, 409, req, config); } if ("code" in outcome.value) { - return jsonResponse({ error: "suggestion could not be saved", code: outcome.value.code }, outcome.value.status, req, config); + return jsonResponse({ error: "suggestion could not be saved", code: outcome.value.code, policy: outcome.value.policy }, outcome.value.status, req, config); } config.combos = outcome.value.combos; reconcileLiveStateStores(); diff --git a/structure/dashboard-and-usage.md b/structure/dashboard-and-usage.md index 5bd2dfc5d24..f536999e067 100644 --- a/structure/dashboard-and-usage.md +++ b/structure/dashboard-and-usage.md @@ -501,7 +501,7 @@ Dashboard overview polling observes authorization failures independently of stal The [explicit model-capability contract](config.md#explicit-per-model-capability-declarations) preserves operator declarations through provider storage and catalog capture; it does not infer upstream capability or change this surface's routing behavior. -Exact [model input declarations](config.md#explicit-per-model-capability-declarations) now feed text-only eligibility and catalog hints; existing image-description/omission handling consumes them before the main upstream send. The Combos page sends non-image members as the request-only `visionSidecarTargets` field on `PUT /api/combos` whenever the Image switch is enabled, so text-only enrollment needs no manual provider edit. The GUI classifies members from the authoritative `visionSidecarConsumer` flag served on `/api/models` rows, so a member covered only by legacy `noVisionModels` keeps its sidecar classification after reload. Members whose modalities are unknown or have no text input keep the switch unavailable and are named in the hint; a member later removed from the combo keeps its provider declaration until cleared in the provider editor. `gui/src/components/route-board/WorkspaceSuggestions.tsx` renders suggestion cards inside the Combos workspace. Generate opens a draft. Saving the draft and choosing Add to combo both use the dashboard-only `POST /api/combo-suggestions/save` endpoint. Extension is held while that combo has unsaved workspace edits. Dismissals are browser-local. Provider exclusions are persisted by the management API. The workspace gates cards on a successful exclusion read for the current proxy and offers a retry on failure. The exclusion control remains available after the last card is dismissed. Generate shows an unchecked paid-target consent checkbox and disables saving until it is checked. Add to combo is disabled with an explanation until the existing combo permits paid targets. The dedicated save route rechecks persisted exclusions and spend consent and marks all added targets metered. The [channel classifier](config.md) is used for placement preference. +Exact [model input declarations](config.md#explicit-per-model-capability-declarations) now feed text-only eligibility and catalog hints; existing image-description/omission handling consumes them before the main upstream send. The Combos page sends non-image members as the request-only `visionSidecarTargets` field on `PUT /api/combos` whenever the Image switch is enabled, so text-only enrollment needs no manual provider edit. The GUI classifies members from the authoritative `visionSidecarConsumer` flag served on `/api/models` rows, so a member covered only by legacy `noVisionModels` keeps its sidecar classification after reload. Members whose modalities are unknown or have no text input keep the switch unavailable and are named in the hint; a member later removed from the combo keeps its provider declaration until cleared in the provider editor. `gui/src/components/route-board/WorkspaceSuggestions.tsx` renders suggestion cards inside the Combos workspace. Generate opens a draft. Saving the draft and choosing Add to combo both use the dashboard-only `POST /api/combo-suggestions/save` endpoint. Extension is held while that combo has unsaved workspace edits. Dismissals are browser-local. Provider exclusions are persisted by the management API. The workspace gates cards on a successful exclusion read for the current proxy and offers a retry on failure. The exclusion control remains available after the last card is dismissed. Generate shows an unchecked paid-target consent checkbox and disables saving until it is checked. Add to combo is disabled with an explanation until the existing combo permits paid targets. On a save conflict with an available policy snapshot, the workspace applies its consent and exclusions to the cards immediately. The dedicated save route rechecks persisted exclusions and spend consent and marks all added targets metered. The [channel classifier](config.md) is used for placement preference. The raw provider editor round-trips `autoReviewModel` and `autoReviewModelOverrides` through editor-owned DTO fields. POST/PATCH/PUT share validation; PUT copies schema-normalized values into the persisted and live candidate before adoption. Canonical `openai` rejects these fields, including clear forms. Field-masked writes (PATCH, editor PUT, reload) pin every registry-seed key and ignore operator overlays the seed never defines, most commonly `selectedModels`; POST keeps the exact-key comparison. Canonical `openai` still rejects `allowPrivateNetwork`, which must not short-circuit destination DNS checks on the ChatGPT forward row. Existing authentication, origin checks and stale-baseline protection still govern the writes. See [reviewer projection](catalog.md#provider-scoped-approval-reviewer). Stored Direct substitution follows the [credential identity contract](providers/openai-accounts.md#sidecars-management-and-ui): both synchronous and asynchronous materializers discard the caller account header before applying the stored credential; ordinary native Direct passthrough is unchanged. diff --git a/structure/gui-and-management-api.md b/structure/gui-and-management-api.md index e256a144a47..e8a9196a9b7 100644 --- a/structure/gui-and-management-api.md +++ b/structure/gui-and-management-api.md @@ -311,7 +311,7 @@ after the save, and a non-retryable skip (no managed catalog) is a clean save. C | File-integration plans | `src/server/management/integration-routes.ts` and `aside-profile-routes.ts` — `POST /api/client-integrations/preview`, `POST /api/client-integrations/restore/preview`, and `POST /api/client-integrations/aside/profiles/{profileId}/preview`. Management-authenticated, declared non-mutating, and they write nothing: no snapshot, no lock, no maintenance, no recovery. They answer `409 integration_preview_unavailable` rather than gathering a model roster, because discovery refreshes credentials and writes the provider cache. Responses carry only declared managed schema paths, closed change kinds and an opaque fingerprint; no value, filesystem location or selected member identity appears. Mutation routes accept `operation` and `planFingerprint` together or not at all, reject a half-bound request and an operation that disagrees with the change, and answer `409 integration_preview_stale` with a freshly computed plan. Binding is an optimistic token, never authorization. [The integration contract](clients/integrations.md) owns the ordering. | | Grok reset coupons | `src/server/management/grok-coupon-routes.ts` — `GET /api/grok/reset-coupons`, `POST /api/grok/reset-coupons/consume`. The dashboard owner is `gui/src/hooks/useGrokResetCoupons.ts` with `gui/src/components/provider-workspace/GrokResetCoupons.tsx`, wired into the xAI OAuth rows of `ProviderAuthPanel`. Redemption truth is the settled ledger `code`, not the HTTP status: a replayed failure returns 200 with `replayed: true`. See [`providers/xai-grok.md`](providers/xai-grok.md). The route returns `ledger_unavailable` before dispatch when the shared ledger cannot be read or locked; stale uncertain attempts are inspected without another redemption or inferred success. A late inspection refusal or a lost claim replays an identity-matching definitive winner; otherwise it returns `operation_state_changed` (late refusal) or `attempt_in_progress` (lost claim) and never replaces an attempted or terminal record. Unknown-outcome responses include the effective operation ID; the CLI mints it before dispatch. Uncertain and pending attempts live in a module-level hold store shared by all hook instances and mirrored to `sessionStorage` (`ocx.grok-coupon-holds.v1`), so they survive modal close/reopen, remount, and reload for the tab session; the pending hold is written before the POST, only a definitive response for the same `operationId` clears it, and only GET refreshes are allowed after uncertainty. Every response that cannot prove settlement under a supplied operation ID, including pre-open refusals, carries that `operationId`. A definitive failure releases the matching speculative pending hold. Supplied token IDs must be non-empty strings before journal admission, and omitted account/token retries recover the operation’s durable identity within retention. Legacy version-one opens are quarantined rather than dispatched. After confirmed redemption, local settlement has five attempts and four 20 ms waits only for a `ConfigMutationLockError` caused by `SQLITE_BUSY`; any other error or changed claim stops without another redemption. | | Claude reset grants | `src/server/management/anthropic-reset-grant-routes.ts` — `GET /api/anthropic/reset-grants`, `POST /api/anthropic/reset-grants/consume` (lazy-loaded). Wire and fail-closed parsing live in `src/providers/anthropic-reset-grants.ts` (the Claude Code 2.1.278 `cedar_ember` contract, sent with `CLAUDE_CLI_USER_AGENT` from `src/providers/claude-cli-identity.ts`; every bearer request refuses redirects, and a refused claim redirect is an unknown outcome); the journal is `src/providers/anthropic-reset-grant-ledger.ts`: a cross-process `BEGIN IMMEDIATE` lock around every synchronous read-modify-write, a 90 s lease, the operation id reused as the upstream `request_id`, same-id retry only inside the vendor's ten-minute window, at most one unresolved operation per account and organization within each pool's journal and that ten-minute window, whatever grant it names (a new id gets `409 unresolved_prior_operation`), no settlement inferred from a re-read, and a fail-closed `500 journal_write_failed` when an answer cannot be recorded. Spending requires the `gui-session` principal. A journaled `reset`, including a same-id replay of that code, lifts that account cooldown only when it is a 429 quota refusal recorded before the operation was first journaled (the claim fence, `claimedAt`) and the journal's cleared windows cover every window the refusal named (both when it named none); it then drops the cached quota row and rereads usage with its own request rather than joining an older read. Model-family exclusions stay until the usage reread proves a family is no longer rejected. A failed reread leaves them in place. The HTTP result stays the journal answer if the reread fails. Other result codes do not admit. The dashboard owner is `gui/src/hooks/useAnthropicResetGrants.ts` with `gui/src/components/provider-workspace/AnthropicResetGrants.tsx` on the Anthropic OAuth rows of `ProviderAuthPanel`; the dialog re-reads the account when it opens, lets the user choose the grant (default: the selectable grant that expires first; the server re-gates the chosen `grantId`), and after an unknown outcome only retries the same id with no picker shown. Design and audit record: [`../devlog/_fin/260923_claude_reset_grants/010_plan.md`](../devlog/_fin/260923_claude_reset_grants/010_plan.md). | -| Combos | `src/server/management/combo-routes.ts` — `GET/PUT/DELETE /api/combos` own provider combination and failover definitions. `PUT` keeps a stored field the body omits (`cooldownMs`, `waitForCooldownMs`, `defaultEffortMode`, `reasoningEffortMode`, `imageInput`, `cooldownWaitPolicy`, per-target `lastResort`, JEV `decisionQuotaSignals`/`decisionQuotaTiers`/`jevEffortMode`/`sessionPin` on updates/rename); quota false/null clears sparsely and switching away removes quota policy under [the owning contract](providers/jev-decision.md#loaded-advisory-quota). Explicit values replace it and defaults are stored sparse. A combo validation 400 is `{ error, field? }`, where `field` is the top-level combo field of the first issue. `GET /api/combo-suggestions` and `PUT /api/combo-suggestions` use the dashboard-only route in `src/server/management/combo-suggestion-routes.ts`. All three suggestion operations require `hasHumanDashboardSession` before dispatch. Admin-token and remembered-admin callers receive 403. The two exclusion operations return `{ excludedProviders: string[] }`. PUT validates the full replacement list and persists it before publishing the live value. `POST /api/combo-suggestions/save` accepts a combo ID, a create or append mode, and provider/model pairs. The locked mutation validates persisted exclusions and spend consent. Create requires and stores explicit `allowMeteredTargets: true`. Append rejects request consent and requires stored consent. All new suggested targets have `metered: true`. Conflicts return a fixed reason code and the dashboard refreshes the suggestions. When appending suggestions, the server uses the more costly tier from the active and saved configurations. It treats existing targets explicitly marked as metered as pay-per-use and preserves the relative order of existing targets. The dashboard and save route share the tier classifier. The config DTO carries the canonical forward and known OAuth subscription decisions computed before URL sanitization, so redaction cannot change gateway placement. | +| Combos | `src/server/management/combo-routes.ts` — `GET/PUT/DELETE /api/combos` own provider combination and failover definitions. `PUT` keeps a stored field the body omits (`cooldownMs`, `waitForCooldownMs`, `defaultEffortMode`, `reasoningEffortMode`, `imageInput`, `cooldownWaitPolicy`, per-target `lastResort`, JEV `decisionQuotaSignals`/`decisionQuotaTiers`/`jevEffortMode`/`sessionPin` on updates/rename); quota false/null clears sparsely and switching away removes quota policy under [the owning contract](providers/jev-decision.md#loaded-advisory-quota). Explicit values replace it and defaults are stored sparse. A combo validation 400 is `{ error, field? }`, where `field` is the top-level combo field of the first issue. `GET /api/combo-suggestions` and `PUT /api/combo-suggestions` use the dashboard-only route in `src/server/management/combo-suggestion-routes.ts`. All three suggestion operations require `hasHumanDashboardSession` before dispatch. Admin-token and remembered-admin callers receive 403. The two exclusion operations return `{ excludedProviders: string[] }`. PUT validates the full replacement list and persists it before publishing the live value. `POST /api/combo-suggestions/save` accepts a combo ID, a create or append mode, and provider/model pairs. The locked mutation validates persisted exclusions and spend consent. Create requires and stores explicit `allowMeteredTargets: true`. Append rejects request consent and requires stored consent. All new suggested targets have `metered: true`. Conflicts return a fixed reason code. When the saved policy is available, the response includes the target combo consent flag and excluded providers from the locked config snapshot. When appending suggestions, the server uses the more costly tier from the active and saved configurations. It treats existing targets explicitly marked as metered as pay-per-use and preserves the relative order of existing targets. The dashboard and save route share the tier classifier. The config DTO carries the canonical forward and known OAuth subscription decisions computed before URL sanitization, so redaction cannot change gateway placement. | | Protocol paths | `src/server/management/protocol-routes.ts` (lazy-loaded) — `GET /api/protocols` returns the contract version, the resolved API surfaces and protocol settings, the policy revision and the feature vocabulary; with `?provider=` (one non-empty name of at most 200 characters without control characters, else 400 `invalid_provider`; an unconfigured name is 404 `unknown_provider`, neither echoing the name) it adds a `provider` block from `src/protocols/provider-summary.ts` ([Protocol Paths](data-planes/protocol-paths.md#provider-wire-summary)); `POST /api/protocols/plan` takes `{ model, inbound, features? }` (model at most 200 characters, at most 24 features, any other key refused with 400) and returns a `ProtocolPlanV1` with `basis: "preview"` from `src/protocols/plan-snapshot.ts`. Both are read-only, never log their input, and send nothing upstream. `PATCH /api/protocols/settings` takes `{ messagesEnabled?, unrepresentable?, rollout? }` (strict: unknown keys and wrong types are 400), validates and applies through `src/server/management/protocol-settings-patch.ts`, persists with `saveConfigPreservingClaudeCode`, restores the live config if the save fails (409 on lock contention, 500 otherwise), and answers with the fresh `GET /api/protocols` body; closing Messages also writes `claudeCode.enabled = false` through `commitClaudeCodeBlock` ([Protocol Paths](data-planes/protocol-paths.md#settings)). The CLI drives all three through `ocx api protocols`, `ocx api explain` and `ocx api policy` ([Protocol Paths](data-planes/protocol-paths.md#cli)); none carries a route-registry exemption. | | Workflow budget | `src/server/management/workflow-budget-routes.ts` — `GET /api/workflow-budget` reads the tracked roots or one root, and `POST /api/workflow-budget/clear` clears exactly one. The clear moves the windowed send ring and the child map and nothing else: `active` belongs to turns still in flight, the spend ledger is a token budget an operator did not ask to forgive, and the lifetime send total survives so a clear cannot launder the record. A refusal event carries `spendScope` and `spendLimit` when a token ceiling fired, so the reason is readable without the config open beside it; no scope id is ever attached, because root ids are client thread headers and identity ids are credentials. Both are `deferred-verb` in the route registry — they are owed CLI verbs, and because the ledger is process memory there is no local projection the CLI could read instead. `GET`/`PUT /api/workflow-budget/settings` read and write the per-install count ceilings (`workflowBudget` in config: concurrent turns, sends and distinct children per window); the live config is bound in `src/lib/workflow-budget-config.ts` and read per decision by HTTP admission and the pre-dispatch send ceiling, so a write applies to the next request and never resets a root's usage. The window, interactive reserve and tracked-root bound stay fixed because a root's ring geometry is fixed when it first appears. The GET is `local-transport` (same block via `ocx config get`), the PUT `deferred-verb` with the other budget verbs. See [`../devlog/_fin/260915_workflow_budget_window/030_wfc_diff_plan.md`](../devlog/_fin/260915_workflow_budget_window/030_wfc_diff_plan.md). | | Codex accounts | `src/codex/auth-api/routes.ts` — `GET/POST/DELETE /api/codex-auth/accounts`, `PUT /api/codex-auth/accounts/alias`, `PUT /api/codex-auth/accounts/pause`, `PUT /api/codex-auth/accounts/pause-exhausted`, `POST /api/codex-auth/accounts/clear-cooldown`, `GET/PUT /api/codex-auth/active`, `PUT /api/codex-auth/auto-switch`, `PUT /api/codex-auth/pool-strategy`, `PUT /api/codex-auth/failover`, `GET /api/codex-auth/quota`, `GET /api/codex-auth/reset-credits` with `POST /api/codex-auth/reset-credits/consume`, and the login flow `POST /api/codex-auth/login`, `POST /api/codex-auth/login/code`, `POST /api/codex-auth/login/cancel`, `GET /api/codex-auth/login-status`. Pool login cancellation through `POST /api/codex-auth/login/cancel` addresses the flow id returned by the pool start route and follows the [pool publication contract](providers/openai-accounts.md#pool-login-policy-and-cancellation). Per-account quota activation uses the existing `GET/PUT /api/settings` surface and `src/codex/quota-auto-refresh.ts`, keeping scheduled spending separate from credential/authentication mutation. Account ids are opaque handles and are serialized so the GUI can address an account; emails are masked and tokens are never serialized. New-account config commits add UI-managed selector bindings in the same config save; deletion deliberately retains existing bindings for fail-closed exact routing and re-add stability. Account mutations request catalog convergence only after config durability and expose only the boolean `catalogRefreshPending` completion projection. `showCodexCredits` is a default-off boolean in settings GET and successful PUT; partial PUT accepts a boolean and rolls back on persistence failure. See [credits exposure](providers/openai-accounts.md#display-only-codex-credits). | diff --git a/tests/server/combo-suggestion-routes.test.ts b/tests/server/combo-suggestion-routes.test.ts index b81dd0d7b6e..dcea9a92995 100644 --- a/tests/server/combo-suggestion-routes.test.ts +++ b/tests/server/combo-suggestion-routes.test.ts @@ -167,7 +167,13 @@ for (const code of ["suggestion_consent_required", "suggestion_provider_excluded setPersistedConfigMutationBeforeCommitForTests(changePolicy); const response = await saveSuggestion(live, { id: "mix", mode: "append", targets: [paidTarget] }); expect(response.status).toBe(409); - expect(await response.json()).toMatchObject({ code }); + expect(await response.json()).toMatchObject({ + code, + policy: { + allowMeteredTargets: code !== "suggestion_consent_required", + excludedProviders: code === "suggestion_provider_excluded" ? ["paid"] : [], + }, + }); expect(loadConfig().combos?.mix?.targets).toHaveLength(1); }); } From 58f6e126fd850329046843595c6ea54ab6eb7e5f Mon Sep 17 00:00:00 2001 From: JUN Date: Thu, 19 Nov 2026 03:03:15 +0900 Subject: [PATCH 16/23] Keep combo suggestion conflict policy deny-only Co-authored-by: Andrew (agent) --- docs-site/src/content/docs/guides/combos.md | 2 +- .../route-board/WorkspaceSuggestions.tsx | 12 ++++++----- .../route-board/use-suggestion-exclusions.ts | 5 ++++- gui/tests/combo-suggestions.test.tsx | 21 +++++++++++++------ structure/dashboard-and-usage.md | 2 +- 5 files changed, 28 insertions(+), 14 deletions(-) diff --git a/docs-site/src/content/docs/guides/combos.md b/docs-site/src/content/docs/guides/combos.md index d4bab15f9b3..1fcdd3c3324 100644 --- a/docs-site/src/content/docs/guides/combos.md +++ b/docs-site/src/content/docs/guides/combos.md @@ -1218,4 +1218,4 @@ untried targets and newer failures keep their cooldowns. When settings change before a suggestion is saved, Combos refreshes the suggestions and displays a message. Saving checks the current exclusions and spend consent. -In the Combos workspace, **Generate** opens a failover draft for a model served by multiple providers. **Add to combo** offers missing targets for an existing combo. Dismissed cards stay hidden in this browser. Use **Exclude providers…** to filter both kinds of suggestions. The proxy stores your selection as `comboSuggestionExcludedProviders` in `config.json`. When appending suggestions, the server uses the more costly tier from the active and saved configurations. It treats existing targets explicitly marked as metered as pay-per-use and preserves the relative order of existing targets. Every suggested target can incur paid usage, including subscription channels such as Codex with purchased credits, Grok with Extra Usage, and Kimi Code with Extra Usage. To save a draft, check **Allow paid targets**. To append, first enable paid targets in the existing combo. The proxy saves every suggested target as `metered: true`. The exclusion control stays available after dismissing all cards. If exclusions fail to load, retry to see suggestions. If saved policy changes before you save, the workspace refreshes the cards using the current exclusions and the saved paid-target setting. +In the Combos workspace, **Generate** opens a failover draft for a model served by multiple providers. **Add to combo** offers missing targets for an existing combo. Dismissed cards stay hidden in this browser. Use **Exclude providers…** to filter both kinds of suggestions. The proxy stores your selection as `comboSuggestionExcludedProviders` in `config.json`. When appending suggestions, the server uses the more costly tier from the active and saved configurations. It treats existing targets explicitly marked as metered as pay-per-use and preserves the relative order of existing targets. Every suggested target can incur paid usage, including subscription channels such as Codex with purchased credits, Grok with Extra Usage, and Kimi Code with Extra Usage. To save a draft, check **Allow paid targets**. To append, first enable paid targets in the existing combo. The proxy saves every suggested target as `metered: true`. The exclusion control stays available after dismissing all cards. If exclusions fail to load, retry to see suggestions. If saved policy changes before you save, the workspace refreshes the combos and immediately hides providers excluded by the conflict. If the conflict reports that paid targets are disabled, reopen the Combos workspace after enabling them to make **Add to combo** available again. diff --git a/gui/src/components/route-board/WorkspaceSuggestions.tsx b/gui/src/components/route-board/WorkspaceSuggestions.tsx index c0f6665183f..c1380a68d59 100644 --- a/gui/src/components/route-board/WorkspaceSuggestions.tsx +++ b/gui/src/components/route-board/WorkspaceSuggestions.tsx @@ -23,11 +23,11 @@ export function WorkspaceSuggestions(props: Props) { const exclusions = useSuggestionExclusions(props.apiBase, props.active); const [conflict, setConflict] = useState(false); - const [consentOverrides, setConsentOverrides] = useState>({}); + const [consentDenials, setConsentDenials] = useState>(new Set()); const combos = props.combos.map((combo) => { const key = JSON.stringify([props.apiBase, combo.id]); - return Object.hasOwn(consentOverrides, key) - ? { ...combo, allowMeteredTargets: consentOverrides[key] } + return consentDenials.has(key) + ? { ...combo, allowMeteredTargets: false } : combo; }); @@ -48,8 +48,10 @@ export function WorkspaceSuggestions(props: Props) { setConflict(true); const body = await response.json().catch(() => null); if (typeof body?.policy?.allowMeteredTargets === "boolean" && exclusions.applyPolicy(body.policy)) { - const key = JSON.stringify([props.apiBase, item.id]); - setConsentOverrides((current) => ({ ...current, [key]: body.policy.allowMeteredTargets })); + if (!body.policy.allowMeteredTargets) { + const key = JSON.stringify([props.apiBase, item.id]); + setConsentDenials((current) => new Set([...current, key])); + } } else { exclusions.retry(); } diff --git a/gui/src/components/route-board/use-suggestion-exclusions.ts b/gui/src/components/route-board/use-suggestion-exclusions.ts index 7fbda11010c..cc491fe7291 100644 --- a/gui/src/components/route-board/use-suggestion-exclusions.ts +++ b/gui/src/components/route-board/use-suggestion-exclusions.ts @@ -75,7 +75,10 @@ export function useSuggestionExclusions(apiBase: string, active = true): Suggest const list = parse(policy); if (!list) return false; generation.current += 1; - setLoaded({ base: apiBase, attempt, excluded: list }); + setLoaded((previous) => { + if (previous?.base !== apiBase || previous.attempt !== attempt || !previous.excluded) return previous; + return { ...previous, excluded: [...new Set([...previous.excluded, ...list])] }; + }); return true; }, save, diff --git a/gui/tests/combo-suggestions.test.tsx b/gui/tests/combo-suggestions.test.tsx index 4c62c75e1d2..bba774432c1 100644 --- a/gui/tests/combo-suggestions.test.tsx +++ b/gui/tests/combo-suggestions.test.tsx @@ -548,6 +548,9 @@ describe("ComboSuggestions card", () => { const originalFetch = globalThis.fetch; const name = "kimi-k3-1-pro"; const existing = combo("opus", [["kimi", name]], { allowMeteredTargets: true }); + const catalog = models(excluded + ? [["kimi", name], ["google-vertex", name], ["xai", name], ["anthropic-apikey", name]] + : [["kimi", name], ["google-vertex", name]]); let refreshCount = 0; globalThis.fetch = (async (url: string) => { if (url.endsWith("/api/combo-suggestions/save")) { @@ -556,21 +559,27 @@ describe("ComboSuggestions card", () => { policy: { allowMeteredTargets: excluded, excludedProviders: excluded ? ["google-vertex"] : [] }, }, { status: 409 }); } - return Response.json({ excludedProviders: [] }); + return Response.json({ excludedProviders: excluded ? ["anthropic-apikey"] : [] }); }) as typeof fetch; try { - await mount( { refreshCount += 1; }} - />); + />; + await mount(view(true)); const extension = card("opus"); expect(extension.textContent).toContain("Vertex"); await act(async () => { button(extension, "Add to combo").click(); }); expect(host.querySelector('[role="alert"]')?.textContent).toContain("Suggestion settings changed"); if (excluded) { - expect(host.textContent).not.toContain("Add to combo"); + expect(card("opus").textContent).not.toContain("Vertex"); + expect(card("opus").textContent).not.toContain("Anthropic"); + expect(button(card("opus"), "Add to combo").disabled).toBe(false); + await act(async () => { root!.render(view(false)); }); + expect(button(card("opus"), "Add to combo").disabled).toBe(true); + expect(card("opus").textContent).toContain("Enable paid targets on this combo first."); } else { expect(button(card("opus"), "Add to combo").disabled).toBe(true); expect(card("opus").textContent).toContain("Enable paid targets on this combo first."); diff --git a/structure/dashboard-and-usage.md b/structure/dashboard-and-usage.md index f536999e067..8b9905a5431 100644 --- a/structure/dashboard-and-usage.md +++ b/structure/dashboard-and-usage.md @@ -501,7 +501,7 @@ Dashboard overview polling observes authorization failures independently of stal The [explicit model-capability contract](config.md#explicit-per-model-capability-declarations) preserves operator declarations through provider storage and catalog capture; it does not infer upstream capability or change this surface's routing behavior. -Exact [model input declarations](config.md#explicit-per-model-capability-declarations) now feed text-only eligibility and catalog hints; existing image-description/omission handling consumes them before the main upstream send. The Combos page sends non-image members as the request-only `visionSidecarTargets` field on `PUT /api/combos` whenever the Image switch is enabled, so text-only enrollment needs no manual provider edit. The GUI classifies members from the authoritative `visionSidecarConsumer` flag served on `/api/models` rows, so a member covered only by legacy `noVisionModels` keeps its sidecar classification after reload. Members whose modalities are unknown or have no text input keep the switch unavailable and are named in the hint; a member later removed from the combo keeps its provider declaration until cleared in the provider editor. `gui/src/components/route-board/WorkspaceSuggestions.tsx` renders suggestion cards inside the Combos workspace. Generate opens a draft. Saving the draft and choosing Add to combo both use the dashboard-only `POST /api/combo-suggestions/save` endpoint. Extension is held while that combo has unsaved workspace edits. Dismissals are browser-local. Provider exclusions are persisted by the management API. The workspace gates cards on a successful exclusion read for the current proxy and offers a retry on failure. The exclusion control remains available after the last card is dismissed. Generate shows an unchecked paid-target consent checkbox and disables saving until it is checked. Add to combo is disabled with an explanation until the existing combo permits paid targets. On a save conflict with an available policy snapshot, the workspace applies its consent and exclusions to the cards immediately. The dedicated save route rechecks persisted exclusions and spend consent and marks all added targets metered. The [channel classifier](config.md) is used for placement preference. +Exact [model input declarations](config.md#explicit-per-model-capability-declarations) now feed text-only eligibility and catalog hints; existing image-description/omission handling consumes them before the main upstream send. The Combos page sends non-image members as the request-only `visionSidecarTargets` field on `PUT /api/combos` whenever the Image switch is enabled, so text-only enrollment needs no manual provider edit. The GUI classifies members from the authoritative `visionSidecarConsumer` flag served on `/api/models` rows, so a member covered only by legacy `noVisionModels` keeps its sidecar classification after reload. Members whose modalities are unknown or have no text input keep the switch unavailable and are named in the hint; a member later removed from the combo keeps its provider declaration until cleared in the provider editor. `gui/src/components/route-board/WorkspaceSuggestions.tsx` renders suggestion cards inside the Combos workspace. Generate opens a draft. Saving the draft and choosing Add to combo both use the dashboard-only `POST /api/combo-suggestions/save` endpoint. Extension is held while that combo has unsaved workspace edits. Dismissals are browser-local. Provider exclusions are persisted by the management API. The workspace gates cards on a successful exclusion read for the current proxy and offers a retry on failure. The exclusion control remains available after the last card is dismissed. Generate shows an unchecked paid-target consent checkbox and disables saving until it is checked. Add to combo is disabled with an explanation until the existing combo permits paid targets. On a save conflict with an available policy snapshot, the workspace immediately adds the snapshot’s provider exclusions to the loaded list and keeps any consent denial for the lifetime of the mounted workspace. Paid additions also require consent in the current combo data. The dedicated save route rechecks persisted exclusions and spend consent and marks all added targets metered. The [channel classifier](config.md) is used for placement preference. The raw provider editor round-trips `autoReviewModel` and `autoReviewModelOverrides` through editor-owned DTO fields. POST/PATCH/PUT share validation; PUT copies schema-normalized values into the persisted and live candidate before adoption. Canonical `openai` rejects these fields, including clear forms. Field-masked writes (PATCH, editor PUT, reload) pin every registry-seed key and ignore operator overlays the seed never defines, most commonly `selectedModels`; POST keeps the exact-key comparison. Canonical `openai` still rejects `allowPrivateNetwork`, which must not short-circuit destination DNS checks on the ChatGPT forward row. Existing authentication, origin checks and stale-baseline protection still govern the writes. See [reviewer projection](catalog.md#provider-scoped-approval-reviewer). Stored Direct substitution follows the [credential identity contract](providers/openai-accounts.md#sidecars-management-and-ui): both synchronous and asynchronous materializers discard the caller account header before applying the stored credential; ordinary native Direct passthrough is unchanged. From c49b1b9e0c6245367384469af3c25df84577b291 Mon Sep 17 00:00:00 2001 From: JUN Date: Thu, 19 Nov 2026 03:21:14 +0900 Subject: [PATCH 17/23] Refresh combo suggestions from persisted policy Co-authored-by: Andrew (agent) --- .../src/content/docs/es/guides/combos.md | 2 +- docs-site/src/content/docs/guides/combos.md | 2 +- .../route-board/ComboSuggestions.tsx | 2 +- .../SuggestionExcludeProviders.tsx | 5 +- .../route-board/WorkspaceSuggestions.tsx | 24 ++----- .../route-board/use-suggestion-exclusions.ts | 71 +++++++++---------- gui/tests/combo-suggestions.test.tsx | 54 ++++++++------ .../management/combo-suggestion-routes.ts | 62 +++++++++------- structure/config.md | 2 +- structure/dashboard-and-usage.md | 2 +- structure/gui-and-management-api.md | 2 +- tests/server/combo-suggestion-routes.test.ts | 38 ++++++---- 12 files changed, 146 insertions(+), 120 deletions(-) diff --git a/docs-site/src/content/docs/es/guides/combos.md b/docs-site/src/content/docs/es/guides/combos.md index 60e779ad659..c728e474339 100644 --- a/docs-site/src/content/docs/es/guides/combos.md +++ b/docs-site/src/content/docs/es/guides/combos.md @@ -792,4 +792,4 @@ Un rechazo estructurado de esfuerzo puede bajar una posición publicada cada vez Si los ajustes cambian antes de guardar una sugerencia, Combos actualiza las sugerencias y muestra un mensaje. Al guardar, se comprueban las exclusiones y el consentimiento de gasto vigentes. Al añadir sugerencias, el servidor aplica el nivel de mayor coste entre la configuración activa y la guardada. Trata los destinos existentes marcados explícitamente como medidos como destinos de pago por uso y conserva el orden relativo de los destinos existentes. -En el espacio de trabajo de combos, **Generar** abre un borrador de conmutación por error para un modelo disponible en varios proveedores. **Añadir al combo** ofrece destinos que faltan en un combo existente. Las tarjetas descartadas quedan ocultas en este navegador. Usa **Excluir un proveedor…** para filtrar ambos tipos de sugerencias. El proxy guarda la selección como `comboSuggestionExcludedProviders` en `config.json`. Los miembros existentes se conservan. Todos los destinos sugeridos pueden generar cargos, incluso los canales de suscripción, como Codex con créditos comprados, Grok con Extra Usage y Kimi Code con Extra Usage. Para guardar un borrador, marca **Permitir destinos de pago**. Para añadir destinos, habilita primero los destinos de pago en el combo existente. El proxy guarda todos los destinos sugeridos con `metered: true`. El control de exclusión sigue disponible tras descartar todas las tarjetas. Si falla la carga de las exclusiones, vuelve a intentarlo. Si la política guardada cambia antes de guardar, el espacio de trabajo actualiza las tarjetas según las exclusiones actuales y el permiso guardado para los destinos de pago. +En el espacio de trabajo de combos, **Generar** abre un borrador de conmutación por error para un modelo disponible en varios proveedores. **Añadir al combo** ofrece destinos que faltan en un combo existente. Las tarjetas descartadas quedan ocultas en este navegador. Usa **Excluir un proveedor…** para filtrar ambos tipos de sugerencias. El proxy guarda la selección como `comboSuggestionExcludedProviders` en `config.json`. Los miembros existentes se conservan. Todos los destinos sugeridos pueden generar cargos, incluso los canales de suscripción, como Codex con créditos comprados, Grok con Extra Usage y Kimi Code con Extra Usage. Para guardar un borrador, marca **Permitir destinos de pago**. Para añadir destinos, habilita primero los destinos de pago en el combo existente. El proxy guarda todos los destinos sugeridos con `metered: true`. El control de exclusión sigue disponible tras descartar todas las tarjetas. Si no se pueden cargar los ajustes de sugerencias, selecciona **Reintentar**. Si los ajustes guardados cambian antes de que guardes una sugerencia, el espacio de trabajo actualiza las tarjetas según las exclusiones y el permiso de pago vigentes. Si **Añadir al combo** está deshabilitado, activa **Permitir destinos de pago** en el editor del combo y guarda los cambios. La siguiente actualización del combo habilita la acción si hay destinos aptos para añadir. diff --git a/docs-site/src/content/docs/guides/combos.md b/docs-site/src/content/docs/guides/combos.md index 1fcdd3c3324..cef0f28c2de 100644 --- a/docs-site/src/content/docs/guides/combos.md +++ b/docs-site/src/content/docs/guides/combos.md @@ -1218,4 +1218,4 @@ untried targets and newer failures keep their cooldowns. When settings change before a suggestion is saved, Combos refreshes the suggestions and displays a message. Saving checks the current exclusions and spend consent. -In the Combos workspace, **Generate** opens a failover draft for a model served by multiple providers. **Add to combo** offers missing targets for an existing combo. Dismissed cards stay hidden in this browser. Use **Exclude providers…** to filter both kinds of suggestions. The proxy stores your selection as `comboSuggestionExcludedProviders` in `config.json`. When appending suggestions, the server uses the more costly tier from the active and saved configurations. It treats existing targets explicitly marked as metered as pay-per-use and preserves the relative order of existing targets. Every suggested target can incur paid usage, including subscription channels such as Codex with purchased credits, Grok with Extra Usage, and Kimi Code with Extra Usage. To save a draft, check **Allow paid targets**. To append, first enable paid targets in the existing combo. The proxy saves every suggested target as `metered: true`. The exclusion control stays available after dismissing all cards. If exclusions fail to load, retry to see suggestions. If saved policy changes before you save, the workspace refreshes the combos and immediately hides providers excluded by the conflict. If the conflict reports that paid targets are disabled, reopen the Combos workspace after enabling them to make **Add to combo** available again. +In the Combos workspace, **Generate** opens a failover draft for a model served by multiple providers. **Add to combo** offers missing targets for an existing combo. Dismissed cards stay hidden in this browser. Use **Exclude providers…** to filter both kinds of suggestions. The proxy stores your selection as `comboSuggestionExcludedProviders` in `config.json`. When appending suggestions, the server uses the more costly tier from the active and saved configurations. It treats existing targets explicitly marked as metered as pay-per-use and preserves the relative order of existing targets. Every suggested target can incur paid usage, including subscription channels such as Codex with purchased credits, Grok with Extra Usage, and Kimi Code with Extra Usage. To save a draft, check **Allow paid targets**. To append, first enable paid targets in the existing combo. The proxy saves every suggested target as `metered: true`. The exclusion control stays available after dismissing all cards. If suggestion settings fail to load, select **Retry**. If saved settings change before you save a suggestion, the workspace refreshes the cards using the current exclusions and paid-target consent. If **Add to combo** is disabled, enable **Allow paid targets** in the combo editor and save. The next combo refresh makes the action available when there are eligible targets to add. diff --git a/gui/src/components/route-board/ComboSuggestions.tsx b/gui/src/components/route-board/ComboSuggestions.tsx index 6158f706f4a..94ec25599f2 100644 --- a/gui/src/components/route-board/ComboSuggestions.tsx +++ b/gui/src/components/route-board/ComboSuggestions.tsx @@ -47,7 +47,7 @@ export interface ComboSuggestionsProps { 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; + onExcludedChange?: (provider: string, excluded: boolean) => Promise; /** A combo with unsaved workspace edits; adding to it would reset that draft, so it is held. */ lockedComboId?: string | null; } diff --git a/gui/src/components/route-board/SuggestionExcludeProviders.tsx b/gui/src/components/route-board/SuggestionExcludeProviders.tsx index 1185d309eb8..2013497fbe5 100644 --- a/gui/src/components/route-board/SuggestionExcludeProviders.tsx +++ b/gui/src/components/route-board/SuggestionExcludeProviders.tsx @@ -16,7 +16,7 @@ export function SuggestionExcludeProviders({ /** Provider names that can be left out, in display order. */ providers: readonly string[]; excluded: readonly string[]; - onChange: (next: readonly string[]) => Promise; + onChange: (provider: string, excluded: boolean) => Promise; }) { const t = useT(); const [open, setOpen] = useState(false); @@ -31,8 +31,7 @@ export function SuggestionExcludeProviders({ 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); + const ok = await onChange(name, exclude); setBusy(false); if (!ok) setFailed(true); }; diff --git a/gui/src/components/route-board/WorkspaceSuggestions.tsx b/gui/src/components/route-board/WorkspaceSuggestions.tsx index c1380a68d59..8620f0a2e1d 100644 --- a/gui/src/components/route-board/WorkspaceSuggestions.tsx +++ b/gui/src/components/route-board/WorkspaceSuggestions.tsx @@ -20,16 +20,14 @@ type Props = Pick & { export function WorkspaceSuggestions(props: Props) { const t = useT(); - const exclusions = useSuggestionExclusions(props.apiBase, props.active); + const exclusions = useSuggestionExclusions(props.apiBase, props.active, props.combos); const [conflict, setConflict] = useState(false); - const [consentDenials, setConsentDenials] = useState>(new Set()); - const combos = props.combos.map((combo) => { - const key = JSON.stringify([props.apiBase, combo.id]); - return consentDenials.has(key) - ? { ...combo, allowMeteredTargets: false } - : combo; - }); + const meteredComboIds = new Set(exclusions.meteredComboIds); + const combos = props.combos.map((combo) => ({ + ...combo, + allowMeteredTargets: meteredComboIds.has(combo.id), + })); const saveSuggestion = async (item: ComboItem, isCreate: boolean) => { setConflict(false); @@ -46,15 +44,7 @@ export function WorkspaceSuggestions(props: Props) { }); if (response.status === 409) { setConflict(true); - const body = await response.json().catch(() => null); - if (typeof body?.policy?.allowMeteredTargets === "boolean" && exclusions.applyPolicy(body.policy)) { - if (!body.policy.allowMeteredTargets) { - const key = JSON.stringify([props.apiBase, item.id]); - setConsentDenials((current) => new Set([...current, key])); - } - } else { - exclusions.retry(); - } + exclusions.retry(); props.onRefresh(); return { ok: false, error: "" }; } diff --git a/gui/src/components/route-board/use-suggestion-exclusions.ts b/gui/src/components/route-board/use-suggestion-exclusions.ts index cc491fe7291..d23c7c1ca33 100644 --- a/gui/src/components/route-board/use-suggestion-exclusions.ts +++ b/gui/src/components/route-board/use-suggestion-exclusions.ts @@ -3,28 +3,28 @@ * (`comboSuggestionExcludedProviders`, `GET|PUT /api/combo-suggestions`) so the choice follows * the operator across browsers. */ -import { useCallback, useEffect, useRef, useState } from "react"; +import { useEffect, useRef, useState } from "react"; +import type { ComboItem } from "../../combo-workspace-data"; -export interface SuggestionExclusions { - excluded: readonly string[]; - /** True once the stored list is known; a save before that would replace it with a partial one. */ - ready: boolean; - failed: boolean; - retry: () => void; - applyPolicy: (policy: unknown) => boolean; - /** Saves the whole list; resolves false when the proxy did not take it (the list stays as it was). */ - save: (next: readonly string[]) => Promise; +interface SuggestionPolicy { + excludedProviders: string[]; + meteredComboIds: string[]; } -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.every((name) => typeof name === "string") ? list : null; +function isStringList(value: unknown): value is string[] { + return Array.isArray(value) && value.every((entry) => typeof entry === "string"); } -export function useSuggestionExclusions(apiBase: string, active = true): SuggestionExclusions { +function parse(body: unknown): SuggestionPolicy | null { + if (!body || typeof body !== "object" || !("excludedProviders" in body) || !("meteredComboIds" in body)) return null; + const { excludedProviders, meteredComboIds } = body; + return isStringList(excludedProviders) && isStringList(meteredComboIds) ? { excludedProviders, meteredComboIds } : null; +} + +export function useSuggestionExclusions(apiBase: string, active = true, combos?: readonly ComboItem[]) { + const retry = () => setAttempt((value) => value + 1); const [attempt, setAttempt] = useState(0); - const [loaded, setLoaded] = useState<{ base: string; attempt: number; excluded: string[] | null }>(); + const [loaded, setLoaded] = useState<{ base: string; attempt: number; policy: SuggestionPolicy | null }>(); const current = active && loaded?.base === apiBase && loaded.attempt === attempt ? loaded : undefined; // Bumped by every save, so a read that started earlier cannot overwrite what was saved. const generation = useRef(0); @@ -38,49 +38,44 @@ export function useSuggestionExclusions(apiBase: string, active = true): Suggest .then((body) => { const list = parse(body); if (controller.signal.aborted || generation.current !== started) return; - setLoaded({ base: apiBase, attempt, excluded: list }); + setLoaded({ base: apiBase, attempt, policy: list }); }) .catch(() => { if (!controller.signal.aborted && generation.current === started) { - setLoaded({ base: apiBase, attempt, excluded: null }); + setLoaded({ base: apiBase, attempt, policy: null }); } }); return () => controller.abort(); - }, [apiBase, active, attempt]); + }, [apiBase, active, attempt, combos]); - const save = useCallback(async (next: readonly string[]) => { - if (!current?.excluded) return false; + const save = async (provider: string, excluded: boolean) => { + if (!current?.policy) return false; const started = ++generation.current; try { const response = await fetch(`${apiBase}/api/combo-suggestions`, { method: "PUT", headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ excludedProviders: next }), + body: JSON.stringify({ provider, excluded }), }); + if (response.status === 409 && generation.current === started) { + setAttempt((value) => value + 1); + return false; + } const list = response.ok ? parse(await response.json()) : null; if (!list || generation.current !== started) return false; - setLoaded({ base: apiBase, attempt, excluded: list }); + setLoaded({ base: apiBase, attempt, policy: list }); return true; } catch { return false; } - }, [apiBase, attempt, current]); + }; return { - excluded: current?.excluded ?? [], - ready: current?.excluded != null, - failed: current?.excluded === null, - retry: () => setAttempt((value) => value + 1), - applyPolicy: (policy) => { - const list = parse(policy); - if (!list) return false; - generation.current += 1; - setLoaded((previous) => { - if (previous?.base !== apiBase || previous.attempt !== attempt || !previous.excluded) return previous; - return { ...previous, excluded: [...new Set([...previous.excluded, ...list])] }; - }); - return true; - }, + excluded: current?.policy?.excludedProviders ?? [], + meteredComboIds: current?.policy?.meteredComboIds ?? [], + ready: current?.policy != null, + failed: current?.policy === null, + retry, save, }; } diff --git a/gui/tests/combo-suggestions.test.tsx b/gui/tests/combo-suggestions.test.tsx index bba774432c1..14cda3164e2 100644 --- a/gui/tests/combo-suggestions.test.tsx +++ b/gui/tests/combo-suggestions.test.tsx @@ -16,7 +16,7 @@ import { } from "../src/combo-suggestions"; import { isValidComboId, toPutBody, type ComboItem } from "../src/combo-workspace-data"; import { ComboSuggestions, type ComboSuggestionsProps } from "../src/components/route-board/ComboSuggestions"; -import { useSuggestionExclusions, type SuggestionExclusions } from "../src/components/route-board/use-suggestion-exclusions"; +import { useSuggestionExclusions } from "../src/components/route-board/use-suggestion-exclusions"; import { WorkspaceSuggestions } from "../src/components/route-board/WorkspaceSuggestions"; import { LanguageProvider } from "../src/i18n/provider"; @@ -301,7 +301,7 @@ describe("ComboSuggestions card", () => { }); const saved: Array<{ kind: string; item: ComboItem }> = []; - const exclusionWrites: string[][] = []; + const exclusionWrites: Array<[string, boolean]> = []; async function render(combos: ComboItem[] = [], excluded?: string[]) { saved.length = 0; const { createRoot } = await import("react-dom/client"); @@ -323,7 +323,7 @@ describe("ComboSuggestions card", () => { onExtend={async (item) => { saved.push({ kind: "extend", item }); return { ok: true }; }} {...(excluded ? { excludedProviders: excluded, - onExcludedChange: async (next: readonly string[]) => { exclusionWrites.push([...next]); return true; }, + onExcludedChange: async (provider: string, excluded: boolean) => { exclusionWrites.push([provider, excluded]); return true; }, } : {})} /> , @@ -397,7 +397,7 @@ describe("ComboSuggestions card", () => { const panel = host.querySelector(".rb-suggest-exclude-panel")!; const xai = panel.querySelector("input[type=checkbox]:checked")!; await act(async () => { xai.click(); }); - expect(exclusionWrites).toEqual([[]]); + expect(exclusionWrites).toEqual([["xai", false]]); }); test("excluding a provider while its draft is open drops it from the draft", async () => { @@ -500,12 +500,12 @@ describe("ComboSuggestions card", () => { if (init?.method === "PUT") { const body = JSON.parse(String(init.body)); puts.push(body); - return new Response(JSON.stringify(body)); + return Response.json({ excludedProviders: ["relay", body.provider], meteredComboIds: [] }); } return new Promise((resolve) => pending.push((body) => resolve(new Response(JSON.stringify(body))))); }) as typeof fetch; try { - let state: SuggestionExclusions | null = null; + let state: ReturnType | null = null; const Probe = ({ base }: { base: string }) => { const exclusions = useSuggestionExclusions(base); useEffect(() => { state = exclusions; }, [exclusions]); @@ -513,17 +513,17 @@ describe("ComboSuggestions card", () => { }; await mount(); expect(state!.ready).toBe(false); - await act(async () => { pending.shift()!({ excludedProviders: ["kimi"] }); }); + await act(async () => { pending.shift()!({ excludedProviders: ["kimi"], meteredComboIds: [] }); }); expect([state!.ready, state!.excluded]).toEqual([true, ["kimi"]]); await act(async () => { root!.render(); }); expect([state!.ready, state!.excluded]).toEqual([false, []]); - expect(await state!.save(["xai"])).toBe(false); + expect(await state!.save("xai", true)).toBe(false); expect(puts).toEqual([]); - await act(async () => { pending.shift()!({ excludedProviders: ["relay"] }); }); - await act(async () => { await state!.save(["xai"]); }); - expect(puts).toEqual([{ excludedProviders: ["xai"] }]); - expect(state!.excluded).toEqual(["xai"]); + await act(async () => { pending.shift()!({ excludedProviders: ["relay"], meteredComboIds: [] }); }); + await act(async () => { await state!.save("xai", true); }); + expect(puts).toEqual([{ provider: "xai", excluded: true }]); + expect(state!.excluded).toEqual(["relay", "xai"]); } finally { globalThis.fetch = realFetch; } @@ -552,14 +552,18 @@ describe("ComboSuggestions card", () => { ? [["kimi", name], ["google-vertex", name], ["xai", name], ["anthropic-apikey", name]] : [["kimi", name], ["google-vertex", name]]); let refreshCount = 0; + let persistedConsent = true; + let persistedExclusions = excluded ? ["anthropic-apikey"] : []; globalThis.fetch = (async (url: string) => { if (url.endsWith("/api/combo-suggestions/save")) { - return Response.json({ - code: excluded ? "suggestion_provider_excluded" : "suggestion_consent_required", - policy: { allowMeteredTargets: excluded, excludedProviders: excluded ? ["google-vertex"] : [] }, - }, { status: 409 }); + persistedConsent = excluded; + if (excluded) persistedExclusions = ["google-vertex"]; + return Response.json({ policy: { + allowMeteredTargets: excluded, + excludedProviders: excluded ? ["google-vertex"] : [], + } }, { status: 409 }); } - return Response.json({ excludedProviders: excluded ? ["anthropic-apikey"] : [] }); + return Response.json({ excludedProviders: persistedExclusions, meteredComboIds: persistedConsent ? ["opus"] : [] }); }) as typeof fetch; try { const view = (allowMeteredTargets: boolean) => { expect(host.querySelector('[role="alert"]')?.textContent).toContain("Suggestion settings changed"); if (excluded) { expect(card("opus").textContent).not.toContain("Vertex"); - expect(card("opus").textContent).not.toContain("Anthropic"); + const filter = host.querySelector(".rb-suggest-exclude-toggle")!; + expect(filter.textContent).toContain("Vertex"); + expect(filter.textContent).not.toContain("Anthropic"); + await act(async () => { filter.click(); }); + const selectedProviders = [...host.querySelectorAll('input[type="checkbox"]:checked')] + .map((input) => input.closest("label")?.textContent); + expect(selectedProviders).toEqual([expect.stringContaining("Vertex")]); expect(button(card("opus"), "Add to combo").disabled).toBe(false); + persistedConsent = false; await act(async () => { root!.render(view(false)); }); expect(button(card("opus"), "Add to combo").disabled).toBe(true); expect(card("opus").textContent).toContain("Enable paid targets on this combo first."); @@ -584,6 +595,9 @@ describe("ComboSuggestions card", () => { expect(button(card("opus"), "Add to combo").disabled).toBe(true); expect(card("opus").textContent).toContain("Enable paid targets on this combo first."); } + persistedConsent = true; + await act(async () => { root!.render(view(true)); }); + expect(button(card("opus"), "Add to combo").disabled).toBe(false); expect(refreshCount).toBe(1); } finally { globalThis.fetch = originalFetch; @@ -607,7 +621,7 @@ describe("ComboSuggestions card", () => { expect(visibleButtons()).not.toContain("Generate"); expect(host.querySelector('[role="alert"]')?.textContent).toContain("Could not load"); await act(async () => { button(host, "Retry").click(); }); - await act(async () => { pending.shift()!(Response.json({ excludedProviders: [] })); }); + await act(async () => { pending.shift()!(Response.json({ excludedProviders: [], meteredComboIds: [] })); }); expect(visibleButtons()).toContain("Generate"); } finally { globalThis.fetch = originalFetch; @@ -622,7 +636,7 @@ describe("ComboSuggestions card", () => { expect(host.querySelectorAll(".rb-suggest-card")).toHaveLength(0); await act(async () => { button(host, "Exclude providers…").click(); }); await act(async () => { host.querySelector('input[type="checkbox"]')!.click(); }); - expect(exclusionWrites[0]).toHaveLength(1); + expect(exclusionWrites[0]?.[1]).toBe(true); }); test("without an exclusion handler there is no exclude control", async () => { diff --git a/src/server/management/combo-suggestion-routes.ts b/src/server/management/combo-suggestion-routes.ts index d52dd8244a6..895d0368aff 100644 --- a/src/server/management/combo-suggestion-routes.ts +++ b/src/server/management/combo-suggestion-routes.ts @@ -12,6 +12,7 @@ import type { OcxComboConfig, OcxConfig } from "../../types"; import { normalizeDecisionModelSelector, decisionModelRouteError } from "./decision-model-validation"; import type { ManagementContext } from "./context"; import { jsonResponse } from "../auth-cors"; +import { readConfigFileSnapshot } from "../../config/diagnostics"; import { mutatePersistedConfig } from "../../config"; import { managementBodyTooLargeResponse, readManagementJsonBody } from "./body"; import { hasHumanDashboardSession } from "./consent-session"; @@ -33,8 +34,17 @@ export function parseExcludedProviders(value: unknown): string[] | null { return out; } -function view(ctx: ManagementContext): Response { - const response = jsonResponse({ excludedProviders: ctx.config.comboSuggestionExcludedProviders ?? [] }, 200, ctx.req, ctx.config); +function suggestionPolicy(config: OcxConfig) { + return { + excludedProviders: config.comboSuggestionExcludedProviders ?? [], + meteredComboIds: Object.entries(config.combos ?? {}) + .filter(([, combo]) => combo.allowMeteredTargets === true) + .map(([id]) => id), + }; +} + +function view(ctx: ManagementContext, policy: ReturnType): Response { + const response = jsonResponse(policy, 200, ctx.req, ctx.config); response.headers.set("cache-control", "no-store"); return response; } @@ -47,7 +57,11 @@ export async function handleComboSuggestionRoutes(ctx: ManagementContext): Promi return allowed ? await saveSuggestion(ctx) : denied(); } if (url.pathname === "/api/combo-suggestions" && req.method === "GET") { - return allowed ? view(ctx) : denied(); + if (!allowed) return denied(); + const { diagnostics } = readConfigFileSnapshot(); + return diagnostics.source === "file" + ? view(ctx, suggestionPolicy(diagnostics.config)) + : jsonResponse({ error: "suggestion policy unavailable", code: "config_unavailable" }, 409, req, ctx.config); } if (url.pathname === "/api/combo-suggestions" && req.method === "PUT") { return allowed ? await writeExcluded(ctx) : denied(); @@ -64,24 +78,30 @@ async function writeExcluded(ctx: ManagementContext): Promise { 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); + if (!isPlainRecord(body) || Object.keys(body).some(key => key !== "provider" && key !== "excluded") + || typeof body.excluded !== "boolean") { + return jsonResponse({ error: "expected a provider and exclusion state", code: "invalid_request" }, 400, req, config); } + const provider = parseExcludedProviders([body.provider])?.[0]; + if (!provider) return jsonResponse({ error: "invalid provider name", code: "invalid_request" }, 400, req, config); + const { excluded } = body; 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 }; + const before = persisted.comboSuggestionExcludedProviders ?? []; + if (before.includes(provider) === excluded) return { changed: false, value: suggestionPolicy(persisted) }; + const next = excluded ? [...before, provider] : before.filter(name => name !== provider); + if (next.length > MAX_PROVIDERS) return { changed: false, value: null }; + if (next.length === 0) delete persisted.comboSuggestionExcludedProviders; + else persisted.comboSuggestionExcludedProviders = next; + return { changed: true, value: suggestionPolicy(persisted) }; }); 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); + if (!outcome.value) return jsonResponse({ error: "too many excluded providers", code: "invalid_request" }, 400, req, config); + const { excludedProviders } = outcome.value; + if (excludedProviders.length === 0) delete config.comboSuggestionExcludedProviders; + else config.comboSuggestionExcludedProviders = excludedProviders; + return view(ctx, outcome.value); } type Target = Pick; @@ -103,7 +123,7 @@ function parseTargets(value: unknown): Target[] | null { } type SuggestionSaveResult = - | { code: string; status: number; policy?: { allowMeteredTargets: boolean; excludedProviders: string[] } } + | { code: string; status: number } | { combos: NonNullable }; async function saveSuggestion(ctx: ManagementContext): Promise { @@ -127,13 +147,7 @@ async function saveSuggestion(ctx: ManagementContext): Promise { const outcome = mutatePersistedConfig(persisted => { const previous = Object.hasOwn(persisted.combos ?? {}, id) ? persisted.combos![id] : undefined; - const policy = { - allowMeteredTargets: previous?.allowMeteredTargets === true, - excludedProviders: persisted.comboSuggestionExcludedProviders ?? [], - }; - const rejected = (code: string, status = 409) => ({ - changed: false, value: { code, status, policy: status === 409 ? policy : undefined }, - }); + const rejected = (code: string, status = 409) => ({ changed: false, value: { code, status } }); if (create ? previous : !previous) return rejected("suggestion_combo_changed"); if (create && consent !== undefined && typeof consent !== "boolean") return rejected("invalid_request", 400); @@ -187,7 +201,7 @@ async function saveSuggestion(ctx: ManagementContext): Promise { return jsonResponse({ error: "suggestion could not be saved", code: "config_unavailable" }, 409, req, config); } if ("code" in outcome.value) { - return jsonResponse({ error: "suggestion could not be saved", code: outcome.value.code, policy: outcome.value.policy }, outcome.value.status, req, config); + return jsonResponse({ error: "suggestion could not be saved", code: outcome.value.code }, outcome.value.status, req, config); } config.combos = outcome.value.combos; reconcileLiveStateStores(); diff --git a/structure/config.md b/structure/config.md index 226de09389c..1d91bbc283b 100644 --- a/structure/config.md +++ b/structure/config.md @@ -554,7 +554,7 @@ Account quota surfaces use [safe probe diagnostics](transports/inventory.md#acco The OpenCode launcher resolves the existing local management origin from the live bind and configured hub ingress. Its admin credential comes from the existing admin environment/file policy; an absent credential fails without substituting a data key. -The optional `autoReviewOverride` block stores a global approval reviewer selector and enabled flag. The Models settings route validates and normalizes writes, restores the live block when persistence fails before publication, and reports catalog convergence; the dashboard shows pending when the catalog did not commit. Malformed hand edits drop this block without discarding other configuration. Provider `autoReviewModel` and `autoReviewModelOverrides` accept validated final-catalog selectors. Per-model keys preserve case and accept the existing raw/encoded slash equivalence. File-load degradation removes malformed optional selectors only; management writes reject malformed shapes. Omitted provider saves preserve selectors, explicit clears remove them, and raw editor candidates adopt normalized values before persistence and live replacement. See [catalog ownership](catalog.md#provider-scoped-approval-reviewer). The optional `comboSuggestionExcludedProviders` array is owned by `src/config/schema/config-schema.ts`. It accepts up to 256 trimmed, deduplicated provider names of at most 256 characters each. A malformed value is dropped during parsing. Saving an empty list removes the key. The preference filters dashboard suggestions and leaves configured combo targets in place. `src/server/management/combo-suggestion-routes.ts` reads exclusions and stored combo consent from the locked persisted snapshot used to save a suggestion. Every suggested target is metered because subscription channels can incur charges too. Create records explicit dashboard consent and append requires existing combo consent. The classifier in `src/combos/suggestion-channel.ts` ranks channels for placement. Each OAuth ranking entry requires the registered provider ID, adapter, auth mode, and exact normalized destination. See the [provider billing and account notes](../docs-site/src/content/docs/guides/providers.md). +The optional `autoReviewOverride` block stores a global approval reviewer selector and enabled flag. The Models settings route validates and normalizes writes, restores the live block when persistence fails before publication, and reports catalog convergence; the dashboard shows pending when the catalog did not commit. Malformed hand edits drop this block without discarding other configuration. Provider `autoReviewModel` and `autoReviewModelOverrides` accept validated final-catalog selectors. Per-model keys preserve case and accept the existing raw/encoded slash equivalence. File-load degradation removes malformed optional selectors only; management writes reject malformed shapes. Omitted provider saves preserve selectors, explicit clears remove them, and raw editor candidates adopt normalized values before persistence and live replacement. See [catalog ownership](catalog.md#provider-scoped-approval-reviewer). The optional `comboSuggestionExcludedProviders` array is owned by `src/config/schema/config-schema.ts`. It accepts up to 256 trimmed, deduplicated provider names of at most 256 characters each. A malformed value is dropped during parsing. Removing the last exclusion removes the key. Each exclusion write changes one provider under the config mutation lock. The preference filters dashboard suggestions and leaves configured combo targets in place. `src/server/management/combo-suggestion-routes.ts` reads exclusions and stored combo consent from persisted configuration for the policy GET and rechecks both under the mutation lock when saving a suggestion. Every suggested target is metered because subscription channels can incur charges too. Create records explicit dashboard consent and append requires existing combo consent. The classifier in `src/combos/suggestion-channel.ts` ranks channels for placement. Each OAuth ranking entry requires the registered provider ID, adapter, auth mode, and exact normalized destination. See the [provider billing and account notes](../docs-site/src/content/docs/guides/providers.md). - Canonical ChatGPT Codex forward uses the Codex login account channel and the same destination predicate as Responses transport. - `xai` OAuth uses the Grok CLI subscription gateway. The public API-key lane is metered. diff --git a/structure/dashboard-and-usage.md b/structure/dashboard-and-usage.md index 8b9905a5431..94e43d463b2 100644 --- a/structure/dashboard-and-usage.md +++ b/structure/dashboard-and-usage.md @@ -501,7 +501,7 @@ Dashboard overview polling observes authorization failures independently of stal The [explicit model-capability contract](config.md#explicit-per-model-capability-declarations) preserves operator declarations through provider storage and catalog capture; it does not infer upstream capability or change this surface's routing behavior. -Exact [model input declarations](config.md#explicit-per-model-capability-declarations) now feed text-only eligibility and catalog hints; existing image-description/omission handling consumes them before the main upstream send. The Combos page sends non-image members as the request-only `visionSidecarTargets` field on `PUT /api/combos` whenever the Image switch is enabled, so text-only enrollment needs no manual provider edit. The GUI classifies members from the authoritative `visionSidecarConsumer` flag served on `/api/models` rows, so a member covered only by legacy `noVisionModels` keeps its sidecar classification after reload. Members whose modalities are unknown or have no text input keep the switch unavailable and are named in the hint; a member later removed from the combo keeps its provider declaration until cleared in the provider editor. `gui/src/components/route-board/WorkspaceSuggestions.tsx` renders suggestion cards inside the Combos workspace. Generate opens a draft. Saving the draft and choosing Add to combo both use the dashboard-only `POST /api/combo-suggestions/save` endpoint. Extension is held while that combo has unsaved workspace edits. Dismissals are browser-local. Provider exclusions are persisted by the management API. The workspace gates cards on a successful exclusion read for the current proxy and offers a retry on failure. The exclusion control remains available after the last card is dismissed. Generate shows an unchecked paid-target consent checkbox and disables saving until it is checked. Add to combo is disabled with an explanation until the existing combo permits paid targets. On a save conflict with an available policy snapshot, the workspace immediately adds the snapshot’s provider exclusions to the loaded list and keeps any consent denial for the lifetime of the mounted workspace. Paid additions also require consent in the current combo data. The dedicated save route rechecks persisted exclusions and spend consent and marks all added targets metered. The [channel classifier](config.md) is used for placement preference. +Exact [model input declarations](config.md#explicit-per-model-capability-declarations) now feed text-only eligibility and catalog hints; existing image-description/omission handling consumes them before the main upstream send. The Combos page sends non-image members as the request-only `visionSidecarTargets` field on `PUT /api/combos` whenever the Image switch is enabled, so text-only enrollment needs no manual provider edit. The GUI classifies members from the authoritative `visionSidecarConsumer` flag served on `/api/models` rows, so a member covered only by legacy `noVisionModels` keeps its sidecar classification after reload. Members whose modalities are unknown or have no text input keep the switch unavailable and are named in the hint; a member later removed from the combo keeps its provider declaration until cleared in the provider editor. `gui/src/components/route-board/WorkspaceSuggestions.tsx` renders suggestion cards inside the Combos workspace. Generate opens a draft. Saving the draft and choosing Add to combo both use the dashboard-only `POST /api/combo-suggestions/save` endpoint. Extension is held while that combo has unsaved workspace edits. Dismissals are browser-local. Provider exclusions are persisted by the management API. The workspace gates cards on a successful persisted policy read for the current proxy and offers a retry on failure. The exclusion control remains available after the last card is dismissed. Generate shows an unchecked paid-target consent checkbox and disables saving until it is checked. Add to combo is disabled with an explanation until the existing combo permits paid targets. A save conflict triggers a fresh policy and combo read. A combo data refresh also re-reads persisted consent, so saving paid-target consent in the editor restores Add to combo on the next refresh. The dedicated save route rechecks persisted exclusions and spend consent and marks all added targets metered. The [channel classifier](config.md) is used for placement preference. The raw provider editor round-trips `autoReviewModel` and `autoReviewModelOverrides` through editor-owned DTO fields. POST/PATCH/PUT share validation; PUT copies schema-normalized values into the persisted and live candidate before adoption. Canonical `openai` rejects these fields, including clear forms. Field-masked writes (PATCH, editor PUT, reload) pin every registry-seed key and ignore operator overlays the seed never defines, most commonly `selectedModels`; POST keeps the exact-key comparison. Canonical `openai` still rejects `allowPrivateNetwork`, which must not short-circuit destination DNS checks on the ChatGPT forward row. Existing authentication, origin checks and stale-baseline protection still govern the writes. See [reviewer projection](catalog.md#provider-scoped-approval-reviewer). Stored Direct substitution follows the [credential identity contract](providers/openai-accounts.md#sidecars-management-and-ui): both synchronous and asynchronous materializers discard the caller account header before applying the stored credential; ordinary native Direct passthrough is unchanged. diff --git a/structure/gui-and-management-api.md b/structure/gui-and-management-api.md index e8a9196a9b7..78d0b7f1d3d 100644 --- a/structure/gui-and-management-api.md +++ b/structure/gui-and-management-api.md @@ -311,7 +311,7 @@ after the save, and a non-retryable skip (no managed catalog) is a clean save. C | File-integration plans | `src/server/management/integration-routes.ts` and `aside-profile-routes.ts` — `POST /api/client-integrations/preview`, `POST /api/client-integrations/restore/preview`, and `POST /api/client-integrations/aside/profiles/{profileId}/preview`. Management-authenticated, declared non-mutating, and they write nothing: no snapshot, no lock, no maintenance, no recovery. They answer `409 integration_preview_unavailable` rather than gathering a model roster, because discovery refreshes credentials and writes the provider cache. Responses carry only declared managed schema paths, closed change kinds and an opaque fingerprint; no value, filesystem location or selected member identity appears. Mutation routes accept `operation` and `planFingerprint` together or not at all, reject a half-bound request and an operation that disagrees with the change, and answer `409 integration_preview_stale` with a freshly computed plan. Binding is an optimistic token, never authorization. [The integration contract](clients/integrations.md) owns the ordering. | | Grok reset coupons | `src/server/management/grok-coupon-routes.ts` — `GET /api/grok/reset-coupons`, `POST /api/grok/reset-coupons/consume`. The dashboard owner is `gui/src/hooks/useGrokResetCoupons.ts` with `gui/src/components/provider-workspace/GrokResetCoupons.tsx`, wired into the xAI OAuth rows of `ProviderAuthPanel`. Redemption truth is the settled ledger `code`, not the HTTP status: a replayed failure returns 200 with `replayed: true`. See [`providers/xai-grok.md`](providers/xai-grok.md). The route returns `ledger_unavailable` before dispatch when the shared ledger cannot be read or locked; stale uncertain attempts are inspected without another redemption or inferred success. A late inspection refusal or a lost claim replays an identity-matching definitive winner; otherwise it returns `operation_state_changed` (late refusal) or `attempt_in_progress` (lost claim) and never replaces an attempted or terminal record. Unknown-outcome responses include the effective operation ID; the CLI mints it before dispatch. Uncertain and pending attempts live in a module-level hold store shared by all hook instances and mirrored to `sessionStorage` (`ocx.grok-coupon-holds.v1`), so they survive modal close/reopen, remount, and reload for the tab session; the pending hold is written before the POST, only a definitive response for the same `operationId` clears it, and only GET refreshes are allowed after uncertainty. Every response that cannot prove settlement under a supplied operation ID, including pre-open refusals, carries that `operationId`. A definitive failure releases the matching speculative pending hold. Supplied token IDs must be non-empty strings before journal admission, and omitted account/token retries recover the operation’s durable identity within retention. Legacy version-one opens are quarantined rather than dispatched. After confirmed redemption, local settlement has five attempts and four 20 ms waits only for a `ConfigMutationLockError` caused by `SQLITE_BUSY`; any other error or changed claim stops without another redemption. | | Claude reset grants | `src/server/management/anthropic-reset-grant-routes.ts` — `GET /api/anthropic/reset-grants`, `POST /api/anthropic/reset-grants/consume` (lazy-loaded). Wire and fail-closed parsing live in `src/providers/anthropic-reset-grants.ts` (the Claude Code 2.1.278 `cedar_ember` contract, sent with `CLAUDE_CLI_USER_AGENT` from `src/providers/claude-cli-identity.ts`; every bearer request refuses redirects, and a refused claim redirect is an unknown outcome); the journal is `src/providers/anthropic-reset-grant-ledger.ts`: a cross-process `BEGIN IMMEDIATE` lock around every synchronous read-modify-write, a 90 s lease, the operation id reused as the upstream `request_id`, same-id retry only inside the vendor's ten-minute window, at most one unresolved operation per account and organization within each pool's journal and that ten-minute window, whatever grant it names (a new id gets `409 unresolved_prior_operation`), no settlement inferred from a re-read, and a fail-closed `500 journal_write_failed` when an answer cannot be recorded. Spending requires the `gui-session` principal. A journaled `reset`, including a same-id replay of that code, lifts that account cooldown only when it is a 429 quota refusal recorded before the operation was first journaled (the claim fence, `claimedAt`) and the journal's cleared windows cover every window the refusal named (both when it named none); it then drops the cached quota row and rereads usage with its own request rather than joining an older read. Model-family exclusions stay until the usage reread proves a family is no longer rejected. A failed reread leaves them in place. The HTTP result stays the journal answer if the reread fails. Other result codes do not admit. The dashboard owner is `gui/src/hooks/useAnthropicResetGrants.ts` with `gui/src/components/provider-workspace/AnthropicResetGrants.tsx` on the Anthropic OAuth rows of `ProviderAuthPanel`; the dialog re-reads the account when it opens, lets the user choose the grant (default: the selectable grant that expires first; the server re-gates the chosen `grantId`), and after an unknown outcome only retries the same id with no picker shown. Design and audit record: [`../devlog/_fin/260923_claude_reset_grants/010_plan.md`](../devlog/_fin/260923_claude_reset_grants/010_plan.md). | -| Combos | `src/server/management/combo-routes.ts` — `GET/PUT/DELETE /api/combos` own provider combination and failover definitions. `PUT` keeps a stored field the body omits (`cooldownMs`, `waitForCooldownMs`, `defaultEffortMode`, `reasoningEffortMode`, `imageInput`, `cooldownWaitPolicy`, per-target `lastResort`, JEV `decisionQuotaSignals`/`decisionQuotaTiers`/`jevEffortMode`/`sessionPin` on updates/rename); quota false/null clears sparsely and switching away removes quota policy under [the owning contract](providers/jev-decision.md#loaded-advisory-quota). Explicit values replace it and defaults are stored sparse. A combo validation 400 is `{ error, field? }`, where `field` is the top-level combo field of the first issue. `GET /api/combo-suggestions` and `PUT /api/combo-suggestions` use the dashboard-only route in `src/server/management/combo-suggestion-routes.ts`. All three suggestion operations require `hasHumanDashboardSession` before dispatch. Admin-token and remembered-admin callers receive 403. The two exclusion operations return `{ excludedProviders: string[] }`. PUT validates the full replacement list and persists it before publishing the live value. `POST /api/combo-suggestions/save` accepts a combo ID, a create or append mode, and provider/model pairs. The locked mutation validates persisted exclusions and spend consent. Create requires and stores explicit `allowMeteredTargets: true`. Append rejects request consent and requires stored consent. All new suggested targets have `metered: true`. Conflicts return a fixed reason code. When the saved policy is available, the response includes the target combo consent flag and excluded providers from the locked config snapshot. When appending suggestions, the server uses the more costly tier from the active and saved configurations. It treats existing targets explicitly marked as metered as pay-per-use and preserves the relative order of existing targets. The dashboard and save route share the tier classifier. The config DTO carries the canonical forward and known OAuth subscription decisions computed before URL sanitization, so redaction cannot change gateway placement. | +| Combos | `src/server/management/combo-routes.ts` — `GET/PUT/DELETE /api/combos` own provider combination and failover definitions. `PUT` keeps a stored field the body omits (`cooldownMs`, `waitForCooldownMs`, `defaultEffortMode`, `reasoningEffortMode`, `imageInput`, `cooldownWaitPolicy`, per-target `lastResort`, JEV `decisionQuotaSignals`/`decisionQuotaTiers`/`jevEffortMode`/`sessionPin` on updates/rename); quota false/null clears sparsely and switching away removes quota policy under [the owning contract](providers/jev-decision.md#loaded-advisory-quota). Explicit values replace it and defaults are stored sparse. A combo validation 400 is `{ error, field? }`, where `field` is the top-level combo field of the first issue. `GET /api/combo-suggestions` and `PUT /api/combo-suggestions` use the dashboard-only route in `src/server/management/combo-suggestion-routes.ts`. All three suggestion operations require `hasHumanDashboardSession` before dispatch. Admin-token and remembered-admin callers receive 403. GET reads the saved policy and returns `{ excludedProviders: string[], meteredComboIds: string[] }`. PUT accepts `{ provider: string, excluded: boolean }`, changes only that provider in the locked persisted configuration, and returns the resulting policy. `POST /api/combo-suggestions/save` accepts a combo ID, a create or append mode, and provider/model pairs. The locked mutation validates persisted exclusions and spend consent. Create requires and stores explicit `allowMeteredTargets: true`. Append rejects request consent and requires stored consent. All new suggested targets have `metered: true`. Conflicts return a fixed reason code. When appending suggestions, the server uses the more costly tier from the active and saved configurations. It treats existing targets explicitly marked as metered as pay-per-use and preserves the relative order of existing targets. The dashboard and save route share the tier classifier. The config DTO carries the canonical forward and known OAuth subscription decisions computed before URL sanitization, so redaction cannot change gateway placement. | | Protocol paths | `src/server/management/protocol-routes.ts` (lazy-loaded) — `GET /api/protocols` returns the contract version, the resolved API surfaces and protocol settings, the policy revision and the feature vocabulary; with `?provider=` (one non-empty name of at most 200 characters without control characters, else 400 `invalid_provider`; an unconfigured name is 404 `unknown_provider`, neither echoing the name) it adds a `provider` block from `src/protocols/provider-summary.ts` ([Protocol Paths](data-planes/protocol-paths.md#provider-wire-summary)); `POST /api/protocols/plan` takes `{ model, inbound, features? }` (model at most 200 characters, at most 24 features, any other key refused with 400) and returns a `ProtocolPlanV1` with `basis: "preview"` from `src/protocols/plan-snapshot.ts`. Both are read-only, never log their input, and send nothing upstream. `PATCH /api/protocols/settings` takes `{ messagesEnabled?, unrepresentable?, rollout? }` (strict: unknown keys and wrong types are 400), validates and applies through `src/server/management/protocol-settings-patch.ts`, persists with `saveConfigPreservingClaudeCode`, restores the live config if the save fails (409 on lock contention, 500 otherwise), and answers with the fresh `GET /api/protocols` body; closing Messages also writes `claudeCode.enabled = false` through `commitClaudeCodeBlock` ([Protocol Paths](data-planes/protocol-paths.md#settings)). The CLI drives all three through `ocx api protocols`, `ocx api explain` and `ocx api policy` ([Protocol Paths](data-planes/protocol-paths.md#cli)); none carries a route-registry exemption. | | Workflow budget | `src/server/management/workflow-budget-routes.ts` — `GET /api/workflow-budget` reads the tracked roots or one root, and `POST /api/workflow-budget/clear` clears exactly one. The clear moves the windowed send ring and the child map and nothing else: `active` belongs to turns still in flight, the spend ledger is a token budget an operator did not ask to forgive, and the lifetime send total survives so a clear cannot launder the record. A refusal event carries `spendScope` and `spendLimit` when a token ceiling fired, so the reason is readable without the config open beside it; no scope id is ever attached, because root ids are client thread headers and identity ids are credentials. Both are `deferred-verb` in the route registry — they are owed CLI verbs, and because the ledger is process memory there is no local projection the CLI could read instead. `GET`/`PUT /api/workflow-budget/settings` read and write the per-install count ceilings (`workflowBudget` in config: concurrent turns, sends and distinct children per window); the live config is bound in `src/lib/workflow-budget-config.ts` and read per decision by HTTP admission and the pre-dispatch send ceiling, so a write applies to the next request and never resets a root's usage. The window, interactive reserve and tracked-root bound stay fixed because a root's ring geometry is fixed when it first appears. The GET is `local-transport` (same block via `ocx config get`), the PUT `deferred-verb` with the other budget verbs. See [`../devlog/_fin/260915_workflow_budget_window/030_wfc_diff_plan.md`](../devlog/_fin/260915_workflow_budget_window/030_wfc_diff_plan.md). | | Codex accounts | `src/codex/auth-api/routes.ts` — `GET/POST/DELETE /api/codex-auth/accounts`, `PUT /api/codex-auth/accounts/alias`, `PUT /api/codex-auth/accounts/pause`, `PUT /api/codex-auth/accounts/pause-exhausted`, `POST /api/codex-auth/accounts/clear-cooldown`, `GET/PUT /api/codex-auth/active`, `PUT /api/codex-auth/auto-switch`, `PUT /api/codex-auth/pool-strategy`, `PUT /api/codex-auth/failover`, `GET /api/codex-auth/quota`, `GET /api/codex-auth/reset-credits` with `POST /api/codex-auth/reset-credits/consume`, and the login flow `POST /api/codex-auth/login`, `POST /api/codex-auth/login/code`, `POST /api/codex-auth/login/cancel`, `GET /api/codex-auth/login-status`. Pool login cancellation through `POST /api/codex-auth/login/cancel` addresses the flow id returned by the pool start route and follows the [pool publication contract](providers/openai-accounts.md#pool-login-policy-and-cancellation). Per-account quota activation uses the existing `GET/PUT /api/settings` surface and `src/codex/quota-auto-refresh.ts`, keeping scheduled spending separate from credential/authentication mutation. Account ids are opaque handles and are serialized so the GUI can address an account; emails are masked and tokens are never serialized. New-account config commits add UI-managed selector bindings in the same config save; deletion deliberately retains existing bindings for fail-closed exact routing and re-add stability. Account mutations request catalog convergence only after config durability and expose only the boolean `catalogRefreshPending` completion projection. `showCodexCredits` is a default-off boolean in settings GET and successful PUT; partial PUT accepts a boolean and rolls back on persistence failure. See [credits exposure](providers/openai-accounts.md#display-only-codex-credits). | diff --git a/tests/server/combo-suggestion-routes.test.ts b/tests/server/combo-suggestion-routes.test.ts index dcea9a92995..628c207a04a 100644 --- a/tests/server/combo-suggestion-routes.test.ts +++ b/tests/server/combo-suggestion-routes.test.ts @@ -64,21 +64,34 @@ const onDisk = () => JSON.parse(readFileSync(join(home, "config.json"), "utf8")) 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, "GET")).toEqual({ status: 200, body: { meteredComboIds: [], excludedProviders: [] } }); - expect(await call(live, "PUT", { excludedProviders: [" cursor ", "cursor", "trae"] })) - .toEqual({ status: 200, body: { excludedProviders: ["cursor", "trae"] } }); + expect((await call(live, "PUT", { provider: " cursor ", excluded: true })).status).toBe(200); + expect((await call(live, "PUT", { provider: "cursor", excluded: true })).status).toBe(200); + expect(await call(live, "PUT", { provider: "trae", excluded: true })) + .toEqual({ status: 200, body: { meteredComboIds: [], excludedProviders: ["cursor", "trae"] } }); expect(onDisk().comboSuggestionExcludedProviders).toEqual(["cursor", "trae"]); - // The running server reads the in-memory config, so the write must land there too. expect(live.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(loadConfig(), "GET")).toEqual({ status: 200, body: { meteredComboIds: [], excludedProviders: ["cursor", "trae"] } }); - expect(await call(live, "PUT", { excludedProviders: [] })).toEqual({ status: 200, body: { excludedProviders: [] } }); + expect((await call(live, "PUT", { provider: "cursor", excluded: false })).status).toBe(200); + expect(await call(live, "PUT", { provider: "trae", excluded: false })) + .toEqual({ status: 200, body: { meteredComboIds: [], excludedProviders: [] } }); expect("comboSuggestionExcludedProviders" in onDisk()).toBe(false); expect(live.comboSuggestionExcludedProviders).toBeUndefined(); }); +test("a stale dashboard excluding a second provider preserves a removal elsewhere", async () => { + const first = seedPaidSuggestion(); + const second = loadConfig(); + expect((await call(second, "PUT", { provider: "paid", excluded: true })).status).toBe(200); + expect((await saveSuggestion(first, { id: "mix", mode: "append", targets: [paidTarget] })).status).toBe(409); + expect((await call(first, "GET")).body.excludedProviders).toEqual(["paid"]); + expect((await call(second, "PUT", { provider: "paid", excluded: false })).status).toBe(200); + expect((await call(first, "PUT", { provider: "other", excluded: true })).status).toBe(200); + expect(onDisk().comboSuggestionExcludedProviders).toEqual(["other"]); +}); + test("a malformed write is refused and changes nothing", async () => { const live = loadConfig(); for (const body of [{ excludedProviders: "cursor" }, { excludedProviders: [1] }, { excludedProviders: [""] }, { other: [] }]) { @@ -142,7 +155,7 @@ test("config DTO computes forward eligibility before redacting provider URLs", a test.each([ ["GET", "/api/combo-suggestions", undefined], - ["PUT", "/api/combo-suggestions", { excludedProviders: ["other"] }], + ["PUT", "/api/combo-suggestions", { provider: "other", excluded: true }], ["POST", "/api/combo-suggestions/save", { id: "mix", mode: "append", targets: [paidTarget] }], ["POST", "/api/combo-suggestions/save", { id: "draft", mode: "create", targets: [paidTarget], allowMeteredTargets: true }], ] as const)("%s %s requires a dashboard session", async (method, path, body) => { @@ -167,10 +180,11 @@ for (const code of ["suggestion_consent_required", "suggestion_provider_excluded setPersistedConfigMutationBeforeCommitForTests(changePolicy); const response = await saveSuggestion(live, { id: "mix", mode: "append", targets: [paidTarget] }); expect(response.status).toBe(409); - expect(await response.json()).toMatchObject({ - code, - policy: { - allowMeteredTargets: code !== "suggestion_consent_required", + expect(await response.json()).toMatchObject({ code }); + expect(await call(live, "GET")).toEqual({ + status: 200, + body: { + meteredComboIds: code === "suggestion_consent_required" ? [] : ["mix"], excludedProviders: code === "suggestion_provider_excluded" ? ["paid"] : [], }, }); From 3644c08798880d03adc634a2c7a4552e10124ea9 Mon Sep 17 00:00:00 2001 From: JUN Date: Thu, 19 Nov 2026 03:37:22 +0900 Subject: [PATCH 18/23] test(gui): reproduce stale combo suggestion policy after refresh --- gui/tests/combo-suggestions.test.tsx | 41 ++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/gui/tests/combo-suggestions.test.tsx b/gui/tests/combo-suggestions.test.tsx index 14cda3164e2..9397cf54dd3 100644 --- a/gui/tests/combo-suggestions.test.tsx +++ b/gui/tests/combo-suggestions.test.tsx @@ -529,6 +529,47 @@ describe("ComboSuggestions card", () => { } }); + test("a delayed exclusion acknowledgment cannot restore revoked consent or old exclusions", async () => { + const originalFetch = globalThis.fetch; + const name = "kimi-k3-1-pro"; + const existing = combo("opus", [["kimi", name]], { allowMeteredTargets: true }); + const catalog = models([["kimi", name], ["google-vertex", name], ["xai", name]]); + let acknowledge!: (response: Response) => void; + let revoke = false; + let reads = 0; + globalThis.fetch = (async (_url: string, init?: RequestInit) => { + if (init?.method === "PUT") return new Promise((resolve) => { acknowledge = resolve; }); + reads += 1; + return Response.json({ excludedProviders: [], meteredComboIds: revoke ? [] : ["opus"] }); + }) as typeof fetch; + try { + const view = (combos: ComboItem[]) => {}} + />; + await mount(view([existing])); + expect(button(card("opus"), "Add to combo").disabled).toBe(false); + await act(async () => { host.querySelector(".rb-suggest-exclude-toggle")!.click(); }); + const vertex = [...host.querySelectorAll('input[type="checkbox"]')] + .find((input) => input.closest("label")?.textContent?.includes("Vertex"))!; + await act(async () => { vertex.click(); }); + + revoke = true; + await act(async () => { root!.render(view([{ ...existing }])); }); + expect(button(card("opus"), "Add to combo").disabled).toBe(true); + await act(async () => { + acknowledge(Response.json({ excludedProviders: ["google-vertex"], meteredComboIds: ["opus"] })); + }); + + expect(button(card("opus"), "Add to combo").disabled).toBe(true); + expect(card("opus").textContent).toContain("Enable paid targets on this combo first."); + expect(card("opus").textContent).toContain("Vertex"); + expect(reads).toBe(3); + } finally { + globalThis.fetch = originalFetch; + } + }); + test("new cards and drafts include paid Vertex and API-key members", async () => { const name = "kimi-k3-1-pro"; await mount( Date: Thu, 19 Nov 2026 03:38:13 +0900 Subject: [PATCH 19/23] Fix combo suggestion policy refresh and consent guidance Co-authored-by: Andrew (agent) --- .../src/content/docs/es/guides/combos.md | 2 +- docs-site/src/content/docs/guides/combos.md | 2 +- .../route-board/ComboSuggestions.tsx | 2 +- .../route-board/WorkspaceSuggestions.tsx | 77 ++++++++++--------- .../route-board/use-suggestion-exclusions.ts | 34 ++++---- gui/src/design/pages/combo-suggestions.css | 2 + gui/src/i18n/de.ts | 2 +- gui/src/i18n/en.ts | 2 +- gui/src/i18n/fr.ts | 2 +- gui/src/i18n/ja.ts | 2 +- gui/src/i18n/ko.ts | 2 +- gui/src/i18n/pt.ts | 2 +- gui/src/i18n/ru.ts | 2 +- gui/src/i18n/tr.ts | 2 +- gui/src/i18n/vi.ts | 2 +- gui/src/i18n/zh-TW.ts | 2 +- gui/src/i18n/zh.ts | 2 +- gui/tests/combo-suggestions.test.tsx | 12 +-- structure/dashboard-and-usage.md | 2 +- 19 files changed, 80 insertions(+), 75 deletions(-) diff --git a/docs-site/src/content/docs/es/guides/combos.md b/docs-site/src/content/docs/es/guides/combos.md index c728e474339..9b785fc745e 100644 --- a/docs-site/src/content/docs/es/guides/combos.md +++ b/docs-site/src/content/docs/es/guides/combos.md @@ -792,4 +792,4 @@ Un rechazo estructurado de esfuerzo puede bajar una posición publicada cada vez Si los ajustes cambian antes de guardar una sugerencia, Combos actualiza las sugerencias y muestra un mensaje. Al guardar, se comprueban las exclusiones y el consentimiento de gasto vigentes. Al añadir sugerencias, el servidor aplica el nivel de mayor coste entre la configuración activa y la guardada. Trata los destinos existentes marcados explícitamente como medidos como destinos de pago por uso y conserva el orden relativo de los destinos existentes. -En el espacio de trabajo de combos, **Generar** abre un borrador de conmutación por error para un modelo disponible en varios proveedores. **Añadir al combo** ofrece destinos que faltan en un combo existente. Las tarjetas descartadas quedan ocultas en este navegador. Usa **Excluir un proveedor…** para filtrar ambos tipos de sugerencias. El proxy guarda la selección como `comboSuggestionExcludedProviders` en `config.json`. Los miembros existentes se conservan. Todos los destinos sugeridos pueden generar cargos, incluso los canales de suscripción, como Codex con créditos comprados, Grok con Extra Usage y Kimi Code con Extra Usage. Para guardar un borrador, marca **Permitir destinos de pago**. Para añadir destinos, habilita primero los destinos de pago en el combo existente. El proxy guarda todos los destinos sugeridos con `metered: true`. El control de exclusión sigue disponible tras descartar todas las tarjetas. Si no se pueden cargar los ajustes de sugerencias, selecciona **Reintentar**. Si los ajustes guardados cambian antes de que guardes una sugerencia, el espacio de trabajo actualiza las tarjetas según las exclusiones y el permiso de pago vigentes. Si **Añadir al combo** está deshabilitado, activa **Permitir destinos de pago** en el editor del combo y guarda los cambios. La siguiente actualización del combo habilita la acción si hay destinos aptos para añadir. +En el espacio de trabajo de combos, **Generar** abre un borrador de conmutación por error para un modelo disponible en varios proveedores. **Añadir al combo** ofrece destinos que faltan en un combo existente. Las tarjetas descartadas quedan ocultas en este navegador. Usa **Excluir un proveedor…** para filtrar ambos tipos de sugerencias. El proxy guarda la selección como `comboSuggestionExcludedProviders` en `config.json`. Los miembros existentes se conservan. Todos los destinos sugeridos pueden generar cargos, incluso los canales de suscripción, como Codex con créditos comprados, Grok con Extra Usage y Kimi Code con Extra Usage. Para guardar un borrador, marca **Permitir destinos de pago**. Para añadir destinos, habilita primero los destinos de pago en el combo existente. El proxy guarda todos los destinos sugeridos con `metered: true`. El control de exclusión sigue disponible tras descartar todas las tarjetas. Si no se pueden cargar los ajustes de sugerencias, selecciona **Reintentar**. Si los ajustes guardados cambian antes de que guardes una sugerencia, el espacio de trabajo actualiza las tarjetas según las exclusiones y el permiso de pago vigentes. Si **Añadir al combo** está deshabilitado, ejecuta `ocx combo update --allow-metered-targets on` y sustituye `` por el identificador del combo guardado. La siguiente actualización del combo habilita la acción si hay destinos aptos para añadir. diff --git a/docs-site/src/content/docs/guides/combos.md b/docs-site/src/content/docs/guides/combos.md index cef0f28c2de..562f8813233 100644 --- a/docs-site/src/content/docs/guides/combos.md +++ b/docs-site/src/content/docs/guides/combos.md @@ -1218,4 +1218,4 @@ untried targets and newer failures keep their cooldowns. When settings change before a suggestion is saved, Combos refreshes the suggestions and displays a message. Saving checks the current exclusions and spend consent. -In the Combos workspace, **Generate** opens a failover draft for a model served by multiple providers. **Add to combo** offers missing targets for an existing combo. Dismissed cards stay hidden in this browser. Use **Exclude providers…** to filter both kinds of suggestions. The proxy stores your selection as `comboSuggestionExcludedProviders` in `config.json`. When appending suggestions, the server uses the more costly tier from the active and saved configurations. It treats existing targets explicitly marked as metered as pay-per-use and preserves the relative order of existing targets. Every suggested target can incur paid usage, including subscription channels such as Codex with purchased credits, Grok with Extra Usage, and Kimi Code with Extra Usage. To save a draft, check **Allow paid targets**. To append, first enable paid targets in the existing combo. The proxy saves every suggested target as `metered: true`. The exclusion control stays available after dismissing all cards. If suggestion settings fail to load, select **Retry**. If saved settings change before you save a suggestion, the workspace refreshes the cards using the current exclusions and paid-target consent. If **Add to combo** is disabled, enable **Allow paid targets** in the combo editor and save. The next combo refresh makes the action available when there are eligible targets to add. +In the Combos workspace, **Generate** opens a failover draft for a model served by multiple providers. **Add to combo** offers missing targets for an existing combo. Dismissed cards stay hidden in this browser. Use **Exclude providers…** to filter both kinds of suggestions. The proxy stores your selection as `comboSuggestionExcludedProviders` in `config.json`. When appending suggestions, the server uses the more costly tier from the active and saved configurations. It treats existing targets explicitly marked as metered as pay-per-use and preserves the relative order of existing targets. Every suggested target can incur paid usage, including subscription channels such as Codex with purchased credits, Grok with Extra Usage, and Kimi Code with Extra Usage. To save a draft, check **Allow paid targets**. To append, first enable paid targets in the existing combo. The proxy saves every suggested target as `metered: true`. The exclusion control stays available after dismissing all cards. If suggestion settings fail to load, select **Retry**. If saved settings change before you save a suggestion, the workspace refreshes the cards using the current exclusions and paid-target consent. If **Add to combo** is disabled, run `ocx combo update --allow-metered-targets on`, replacing `` with the saved combo ID. The next combo refresh makes the action available when there are eligible targets to add. diff --git a/gui/src/components/route-board/ComboSuggestions.tsx b/gui/src/components/route-board/ComboSuggestions.tsx index 94ec25599f2..b0dedab2e72 100644 --- a/gui/src/components/route-board/ComboSuggestions.tsx +++ b/gui/src/components/route-board/ComboSuggestions.tsx @@ -215,7 +215,7 @@ function SuggestionCard({
{suggestion.kind === "extend" && target?.allowMeteredTargets !== true && ( -

{t("comboSuggest.enablePaid")}

+

{t("comboSuggest.enablePaid", { command: `ocx combo update ${suggestion.comboId} --allow-metered-targets on` })}

)} {message &&

{message}

} {drafting && suggestion.kind === "create" && ( diff --git a/gui/src/components/route-board/WorkspaceSuggestions.tsx b/gui/src/components/route-board/WorkspaceSuggestions.tsx index 8620f0a2e1d..b96474beec4 100644 --- a/gui/src/components/route-board/WorkspaceSuggestions.tsx +++ b/gui/src/components/route-board/WorkspaceSuggestions.tsx @@ -19,8 +19,12 @@ type Props = Pick & { }; export function WorkspaceSuggestions(props: Props) { + return props.active ? : null; +} + +function ActiveWorkspaceSuggestions(props: Props) { const t = useT(); - const exclusions = useSuggestionExclusions(props.apiBase, props.active, props.combos); + const exclusions = useSuggestionExclusions(props.apiBase, props.combos); const [conflict, setConflict] = useState(false); const meteredComboIds = new Set(exclusions.meteredComboIds); @@ -30,8 +34,9 @@ export function WorkspaceSuggestions(props: Props) { })); const saveSuggestion = async (item: ComboItem, isCreate: boolean) => { - setConflict(false); const failure = { ok: false, error: t("cws.saveFailed") }; + if (!exclusions.ready) return failure; + setConflict(false); const previous = props.combos.find((combo) => combo.id === item.id); const targets = item.targets.filter(({ provider, model }) => isCreate || !previous?.targets.some((target) => target.provider === provider && target.model === model)) @@ -56,7 +61,7 @@ export function WorkspaceSuggestions(props: Props) { } }; const conflictAlert = conflict &&

{t("comboSuggest.saveChanged")}

; - if (!exclusions.ready) { + if (!exclusions.available) { return <> {conflictAlert} {exclusions.failed && ( @@ -75,38 +80,40 @@ export function WorkspaceSuggestions(props: Props) { return ( <> {conflictAlert} - { - const used = (quota.get(provider) ?? []).flatMap((window) => { - const family = (window.label ?? "").toLowerCase().split(/[\s(]/)[0]; - const matches = window.modelId - ? window.modelId.toLowerCase() === model.toLowerCase() - : !family || window.labelKey !== undefined || model.toLowerCase().startsWith(family); - return matches && window.percent !== undefined ? [window.percent] : []; - }); - return used.length ? Math.max(0, Math.min(100, 100 - Math.max(...used))) : undefined; - }} - validate={(item, isCreate) => { - const others = props.combos.filter((combo) => isCreate || combo.id !== item.id); - return validateComboDraft(item, { - existingIds: others.map((combo) => combo.id), - existingAliases: others.flatMap((combo) => combo.alias ? [combo.alias] : []), - combos: others, - isCreate, - providers: providerMap, - }); - }} - errorText={(code, item) => comboDraftErrorText(t, code, item, providerMap)} - onCreate={(item) => saveSuggestion(item, true)} - onExtend={(item) => saveSuggestion(item, false)} - excludedProviders={exclusions.excluded} - onExcludedChange={exclusions.save} - /> +
+ { + const used = (quota.get(provider) ?? []).flatMap((window) => { + const family = (window.label ?? "").toLowerCase().split(/[\s(]/)[0]; + const matches = window.modelId + ? window.modelId.toLowerCase() === model.toLowerCase() + : !family || window.labelKey !== undefined || model.toLowerCase().startsWith(family); + return matches && window.percent !== undefined ? [window.percent] : []; + }); + return used.length ? Math.max(0, Math.min(100, 100 - Math.max(...used))) : undefined; + }} + validate={(item, isCreate) => { + const others = props.combos.filter((combo) => isCreate || combo.id !== item.id); + return validateComboDraft(item, { + existingIds: others.map((combo) => combo.id), + existingAliases: others.flatMap((combo) => combo.alias ? [combo.alias] : []), + combos: others, + isCreate, + providers: providerMap, + }); + }} + errorText={(code, item) => comboDraftErrorText(t, code, item, providerMap)} + onCreate={(item) => saveSuggestion(item, true)} + onExtend={(item) => saveSuggestion(item, false)} + excludedProviders={exclusions.excluded} + onExcludedChange={exclusions.save} + /> +
); } diff --git a/gui/src/components/route-board/use-suggestion-exclusions.ts b/gui/src/components/route-board/use-suggestion-exclusions.ts index d23c7c1ca33..a56e92aadbb 100644 --- a/gui/src/components/route-board/use-suggestion-exclusions.ts +++ b/gui/src/components/route-board/use-suggestion-exclusions.ts @@ -21,58 +21,52 @@ function parse(body: unknown): SuggestionPolicy | null { return isStringList(excludedProviders) && isStringList(meteredComboIds) ? { excludedProviders, meteredComboIds } : null; } -export function useSuggestionExclusions(apiBase: string, active = true, combos?: readonly ComboItem[]) { +export function useSuggestionExclusions(apiBase: string, combos?: readonly ComboItem[]) { const retry = () => setAttempt((value) => value + 1); const [attempt, setAttempt] = useState(0); - const [loaded, setLoaded] = useState<{ base: string; attempt: number; policy: SuggestionPolicy | null }>(); - const current = active && loaded?.base === apiBase && loaded.attempt === attempt ? loaded : undefined; - // Bumped by every save, so a read that started earlier cannot overwrite what was saved. + const [loaded, setLoaded] = useState<{ base: string; attempt: number; combos?: readonly ComboItem[]; policy: SuggestionPolicy | null }>(); + const cached = loaded?.base === apiBase ? loaded : undefined; + const current = cached?.attempt === attempt && cached.combos === combos ? cached : undefined; + // Only the latest policy read can publish. const generation = useRef(0); useEffect(() => { - if (!active) return; const controller = new AbortController(); - const started = generation.current; + const started = ++generation.current; void fetch(`${apiBase}/api/combo-suggestions`, { signal: controller.signal }) .then((response) => (response.ok ? response.json() : null)) .then((body) => { const list = parse(body); if (controller.signal.aborted || generation.current !== started) return; - setLoaded({ base: apiBase, attempt, policy: list }); + setLoaded({ base: apiBase, attempt, combos, policy: list }); }) .catch(() => { if (!controller.signal.aborted && generation.current === started) { - setLoaded({ base: apiBase, attempt, policy: null }); + setLoaded({ base: apiBase, attempt, combos, policy: null }); } }); return () => controller.abort(); - }, [apiBase, active, attempt, combos]); + }, [apiBase, attempt, combos]); const save = async (provider: string, excluded: boolean) => { if (!current?.policy) return false; - const started = ++generation.current; try { const response = await fetch(`${apiBase}/api/combo-suggestions`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ provider, excluded }), }); - if (response.status === 409 && generation.current === started) { - setAttempt((value) => value + 1); - return false; - } - const list = response.ok ? parse(await response.json()) : null; - if (!list || generation.current !== started) return false; - setLoaded({ base: apiBase, attempt, policy: list }); - return true; + if (response.ok || response.status === 409) retry(); + return response.ok; } catch { return false; } }; return { - excluded: current?.policy?.excludedProviders ?? [], - meteredComboIds: current?.policy?.meteredComboIds ?? [], + excluded: cached?.policy?.excludedProviders ?? [], + meteredComboIds: cached?.policy?.meteredComboIds ?? [], + available: cached?.policy != null, ready: current?.policy != null, failed: current?.policy === null, retry, diff --git a/gui/src/design/pages/combo-suggestions.css b/gui/src/design/pages/combo-suggestions.css index 393fa3dfa2e..5968ab1db7d 100644 --- a/gui/src/design/pages/combo-suggestions.css +++ b/gui/src/design/pages/combo-suggestions.css @@ -18,6 +18,8 @@ .rb-order-item { display: inline-flex; align-items: baseline; gap: 4px; } .rb-order-sep { color: var(--ocx-fg-subtle); } .rb-row-message { margin: 0; padding: 0 16px 10px 68px; color: var(--ocx-danger); font-size: 12.5px; } +.rb-suggest-policy { display: contents; } + .rb-suggest { margin-bottom: 16px; padding: 12px 0 4px; diff --git a/gui/src/i18n/de.ts b/gui/src/i18n/de.ts index 65c7dd3b5bf..d5389ff4e07 100644 --- a/gui/src/i18n/de.ts +++ b/gui/src/i18n/de.ts @@ -4554,7 +4554,7 @@ export const de: Record = { "comboSuggest.draft.left": "{percent}% übrig", "comboSuggest.draft.strategy": "Strategie: Failover. Nach dem Speichern in der Zeile ändern.", "comboSuggest.allowPaid": "Kostenpflichtige Ziele erlauben (zum Speichern erforderlich). Diese Ziele können kostenpflichtiges Guthaben oder Nutzung abrechnen.", - "comboSuggest.enablePaid": "Aktiviere zuerst kostenpflichtige Ziele für diese Kombination.", + "comboSuggest.enablePaid": "Führe {command} aus, um kostenpflichtige Ziele zu erlauben. Die Vorschläge übernehmen die Änderung beim nächsten Aktualisieren der Kombinationen.", "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 a8544cd63fc..7acc028f4bc 100644 --- a/gui/src/i18n/en.ts +++ b/gui/src/i18n/en.ts @@ -4588,7 +4588,7 @@ export const en = { "comboSuggest.draft.left": "{percent}% left", "comboSuggest.draft.strategy": "Strategy: failover. Change it in the row after saving.", "comboSuggest.allowPaid": "Allow paid targets (required to save). These targets may bill paid credits or usage.", - "comboSuggest.enablePaid": "Enable paid targets on this combo first.", + "comboSuggest.enablePaid": "Run {command} to allow paid targets. Suggestions pick up the change on the next combo refresh.", "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 c6dea67bb67..79f1a2c9114 100644 --- a/gui/src/i18n/fr.ts +++ b/gui/src/i18n/fr.ts @@ -4543,7 +4543,7 @@ export const fr: Record = { "comboSuggest.draft.left": "{percent} % restants", "comboSuggest.draft.strategy": "Stratégie : basculement. Modifiez-la dans la ligne après l’enregistrement.", "comboSuggest.allowPaid": "Autoriser les cibles payantes (requis pour enregistrer). Ces cibles peuvent facturer des crédits ou des frais d’utilisation.", - "comboSuggest.enablePaid": "Activez d’abord les cibles payantes pour cette combinaison.", + "comboSuggest.enablePaid": "Exécutez {command} pour autoriser les cibles payantes. Les suggestions appliquent ce changement à la prochaine actualisation des combinaisons.", "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 0fddd63ecdb..263f4016e24 100644 --- a/gui/src/i18n/ja.ts +++ b/gui/src/i18n/ja.ts @@ -4576,7 +4576,7 @@ export const ja: Record = { "comboSuggest.draft.left": "残り {percent}%", "comboSuggest.draft.strategy": "戦略:フェイルオーバー。保存後に行内で変更できます。", "comboSuggest.allowPaid": "有料ターゲットを許可する(保存に必須)。有料クレジットや従量料金が発生する場合があります。", - "comboSuggest.enablePaid": "先にこのコンボの有料ターゲットを有効にしてください。", + "comboSuggest.enablePaid": "有料ターゲットを許可するには {command} を実行してください。次回コンボを更新すると候補に反映されます。", "comboSuggest.draft.save": "コンボを保存", "comboSuggest.draft.saving": "保存中…", }; diff --git a/gui/src/i18n/ko.ts b/gui/src/i18n/ko.ts index bf67cdf71c5..17768a59a77 100644 --- a/gui/src/i18n/ko.ts +++ b/gui/src/i18n/ko.ts @@ -4576,7 +4576,7 @@ export const ko: Record = { "comboSuggest.draft.left": "{percent}% 남음", "comboSuggest.draft.strategy": "전략: 장애 조치(failover). 저장 후 행에서 바꿀 수 있습니다.", "comboSuggest.allowPaid": "유료 대상 허용(저장에 필요). 유료 크레딧이 차감되거나 사용 요금이 청구될 수 있습니다.", - "comboSuggest.enablePaid": "먼저 이 콤보에서 유료 대상을 허용하세요.", + "comboSuggest.enablePaid": "유료 대상을 허용하려면 {command} 명령을 실행하세요. 다음에 콤보를 새로고침하면 제안에 반영됩니다.", "comboSuggest.draft.save": "콤보 저장", "comboSuggest.draft.saving": "저장 중…", }; diff --git a/gui/src/i18n/pt.ts b/gui/src/i18n/pt.ts index a4a8a2ea75b..1a94bd6b99c 100644 --- a/gui/src/i18n/pt.ts +++ b/gui/src/i18n/pt.ts @@ -4549,7 +4549,7 @@ export const pt: Record = { "comboSuggest.draft.left": "{percent}% restante", "comboSuggest.draft.strategy": "Estratégia: failover. Altere-a na linha depois de salvar.", "comboSuggest.allowPaid": "Permitir destinos pagos (obrigatório para salvar). Esses destinos podem cobrar créditos ou taxas de uso.", - "comboSuggest.enablePaid": "Primeiro, habilite destinos pagos neste combo.", + "comboSuggest.enablePaid": "Execute {command} para permitir destinos pagos. As sugestões refletem a mudança na próxima atualização dos combos.", "comboSuggest.draft.save": "Salvar combo", "comboSuggest.draft.saving": "Salvando…", }; diff --git a/gui/src/i18n/ru.ts b/gui/src/i18n/ru.ts index 10d3ca65d59..3a4536e75fd 100644 --- a/gui/src/i18n/ru.ts +++ b/gui/src/i18n/ru.ts @@ -4577,7 +4577,7 @@ export const ru: Record = { "comboSuggest.draft.left": "осталось {percent}%", "comboSuggest.draft.strategy": "Стратегия: Failover. Изменить можно в строке после сохранения.", "comboSuggest.allowPaid": "Разрешить платные цели (необходимо для сохранения). Возможны списания платных кредитов или оплата за использование.", - "comboSuggest.enablePaid": "Сначала разрешите платные цели для этой комбинации.", + "comboSuggest.enablePaid": "Выполните {command}, чтобы разрешить платные цели. Изменение отразится в предложениях при следующем обновлении комбинаций.", "comboSuggest.draft.save": "Сохранить комбо", "comboSuggest.draft.saving": "Сохранение…", }; diff --git a/gui/src/i18n/tr.ts b/gui/src/i18n/tr.ts index e723d95be34..e90d7e3a714 100644 --- a/gui/src/i18n/tr.ts +++ b/gui/src/i18n/tr.ts @@ -4577,7 +4577,7 @@ export const tr: Record = { "comboSuggest.draft.left": "%{percent} kaldı", "comboSuggest.draft.strategy": "Strateji: failover. Kaydettikten sonra satırda değiştirin.", "comboSuggest.allowPaid": "Ücretli hedeflere izin ver (kaydetmek için gerekli). Bu hedefler ücretli kredi veya kullanım bedeli yansıtabilir.", - "comboSuggest.enablePaid": "Önce bu komboda ücretli hedeflere izin verin.", + "comboSuggest.enablePaid": "Ücretli hedeflere izin vermek için {command} komutunu çalıştırın. Değişiklik, kombolar bir sonraki yenilendiğinde önerilere yansır.", "comboSuggest.draft.save": "Komboyu kaydet", "comboSuggest.draft.saving": "Kaydediliyor…", }; diff --git a/gui/src/i18n/vi.ts b/gui/src/i18n/vi.ts index 4811048bd8a..2663c877bf9 100644 --- a/gui/src/i18n/vi.ts +++ b/gui/src/i18n/vi.ts @@ -4546,7 +4546,7 @@ export const vi: Record = { "comboSuggest.draft.left": "còn {percent}%", "comboSuggest.draft.strategy": "Chiến lược: failover. Đổi trong hàng sau khi lưu.", "comboSuggest.allowPaid": "Cho phép đích trả phí (bắt buộc để lưu). Các đích này có thể tính phí tín dụng hoặc phí sử dụng.", - "comboSuggest.enablePaid": "Trước tiên, hãy bật đích trả phí cho tổ hợp này.", + "comboSuggest.enablePaid": "Chạy {command} để cho phép đích trả phí. Đề xuất sẽ áp dụng thay đổi khi làm mới danh sách tổ hợp lần tiếp theo.", "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 5a774f65b17..e6ef6e86754 100644 --- a/gui/src/i18n/zh-TW.ts +++ b/gui/src/i18n/zh-TW.ts @@ -4540,7 +4540,7 @@ export const zhTW: Record = { "comboSuggest.draft.left": "剩 {percent}%", "comboSuggest.draft.strategy": "策略:容錯移轉。儲存後可以在列中改。", "comboSuggest.allowPaid": "允許付費目標(儲存時必選)。這些目標可能消耗付費額度或產生用量費用。", - "comboSuggest.enablePaid": "請先為此組合啟用付費目標。", + "comboSuggest.enablePaid": "執行 {command} 以允許付費目標。下次重新整理組合時,建議將反映此變更。", "comboSuggest.draft.save": "儲存組合", "comboSuggest.draft.saving": "正在儲存…", }; diff --git a/gui/src/i18n/zh.ts b/gui/src/i18n/zh.ts index 7d138d7f753..3c73259155b 100644 --- a/gui/src/i18n/zh.ts +++ b/gui/src/i18n/zh.ts @@ -4575,7 +4575,7 @@ export const zh: Record = { "comboSuggest.draft.left": "剩 {percent}%", "comboSuggest.draft.strategy": "策略:故障转移。保存后可以在行里改。", "comboSuggest.allowPaid": "允许付费目标(保存时必选)。这些目标可能消耗付费额度或产生用量费用。", - "comboSuggest.enablePaid": "请先为此组合启用付费目标。", + "comboSuggest.enablePaid": "运行 {command} 以允许付费目标。下次刷新组合时,建议将反映此更改。", "comboSuggest.draft.save": "保存组合", "comboSuggest.draft.saving": "正在保存…", }; diff --git a/gui/tests/combo-suggestions.test.tsx b/gui/tests/combo-suggestions.test.tsx index 9397cf54dd3..bdc00f03dad 100644 --- a/gui/tests/combo-suggestions.test.tsx +++ b/gui/tests/combo-suggestions.test.tsx @@ -374,7 +374,7 @@ describe("ComboSuggestions card", () => { test("an existing combo missing a provider offers to add it", async () => { const existing = combo("gemini", [["kimi-responses", "gemini-3.8-flash"]]); await render([existing]); - expect(card("gemini").textContent).toContain("Enable paid targets on this combo first."); + expect(card("gemini").textContent).toContain("ocx combo update gemini --allow-metered-targets on"); expect(button(card("gemini"), "Add to combo").disabled).toBe(true); await act(async () => { button(card("gemini"), "Add to combo").click(); }); expect(saved).toEqual([]); @@ -500,7 +500,7 @@ describe("ComboSuggestions card", () => { if (init?.method === "PUT") { const body = JSON.parse(String(init.body)); puts.push(body); - return Response.json({ excludedProviders: ["relay", body.provider], meteredComboIds: [] }); + return new Response(null, { status: 204 }); } return new Promise((resolve) => pending.push((body) => resolve(new Response(JSON.stringify(body))))); }) as typeof fetch; @@ -523,6 +523,8 @@ describe("ComboSuggestions card", () => { await act(async () => { pending.shift()!({ excludedProviders: ["relay"], meteredComboIds: [] }); }); await act(async () => { await state!.save("xai", true); }); expect(puts).toEqual([{ provider: "xai", excluded: true }]); + expect(state!.ready).toBe(false); + await act(async () => { pending.shift()!({ excludedProviders: ["relay", "xai"], meteredComboIds: [] }); }); expect(state!.excluded).toEqual(["relay", "xai"]); } finally { globalThis.fetch = realFetch; @@ -562,7 +564,7 @@ describe("ComboSuggestions card", () => { }); expect(button(card("opus"), "Add to combo").disabled).toBe(true); - expect(card("opus").textContent).toContain("Enable paid targets on this combo first."); + expect(card("opus").textContent).toContain("ocx combo update opus --allow-metered-targets on"); expect(card("opus").textContent).toContain("Vertex"); expect(reads).toBe(3); } finally { @@ -631,10 +633,10 @@ describe("ComboSuggestions card", () => { persistedConsent = false; await act(async () => { root!.render(view(false)); }); expect(button(card("opus"), "Add to combo").disabled).toBe(true); - expect(card("opus").textContent).toContain("Enable paid targets on this combo first."); + expect(card("opus").textContent).toContain("ocx combo update opus --allow-metered-targets on"); } else { expect(button(card("opus"), "Add to combo").disabled).toBe(true); - expect(card("opus").textContent).toContain("Enable paid targets on this combo first."); + expect(card("opus").textContent).toContain("ocx combo update opus --allow-metered-targets on"); } persistedConsent = true; await act(async () => { root!.render(view(true)); }); diff --git a/structure/dashboard-and-usage.md b/structure/dashboard-and-usage.md index 94e43d463b2..c7e13e9e69d 100644 --- a/structure/dashboard-and-usage.md +++ b/structure/dashboard-and-usage.md @@ -501,7 +501,7 @@ Dashboard overview polling observes authorization failures independently of stal The [explicit model-capability contract](config.md#explicit-per-model-capability-declarations) preserves operator declarations through provider storage and catalog capture; it does not infer upstream capability or change this surface's routing behavior. -Exact [model input declarations](config.md#explicit-per-model-capability-declarations) now feed text-only eligibility and catalog hints; existing image-description/omission handling consumes them before the main upstream send. The Combos page sends non-image members as the request-only `visionSidecarTargets` field on `PUT /api/combos` whenever the Image switch is enabled, so text-only enrollment needs no manual provider edit. The GUI classifies members from the authoritative `visionSidecarConsumer` flag served on `/api/models` rows, so a member covered only by legacy `noVisionModels` keeps its sidecar classification after reload. Members whose modalities are unknown or have no text input keep the switch unavailable and are named in the hint; a member later removed from the combo keeps its provider declaration until cleared in the provider editor. `gui/src/components/route-board/WorkspaceSuggestions.tsx` renders suggestion cards inside the Combos workspace. Generate opens a draft. Saving the draft and choosing Add to combo both use the dashboard-only `POST /api/combo-suggestions/save` endpoint. Extension is held while that combo has unsaved workspace edits. Dismissals are browser-local. Provider exclusions are persisted by the management API. The workspace gates cards on a successful persisted policy read for the current proxy and offers a retry on failure. The exclusion control remains available after the last card is dismissed. Generate shows an unchecked paid-target consent checkbox and disables saving until it is checked. Add to combo is disabled with an explanation until the existing combo permits paid targets. A save conflict triggers a fresh policy and combo read. A combo data refresh also re-reads persisted consent, so saving paid-target consent in the editor restores Add to combo on the next refresh. The dedicated save route rechecks persisted exclusions and spend consent and marks all added targets metered. The [channel classifier](config.md) is used for placement preference. +Exact [model input declarations](config.md#explicit-per-model-capability-declarations) now feed text-only eligibility and catalog hints; existing image-description/omission handling consumes them before the main upstream send. The Combos page sends non-image members as the request-only `visionSidecarTargets` field on `PUT /api/combos` whenever the Image switch is enabled, so text-only enrollment needs no manual provider edit. The GUI classifies members from the authoritative `visionSidecarConsumer` flag served on `/api/models` rows, so a member covered only by legacy `noVisionModels` keeps its sidecar classification after reload. Members whose modalities are unknown or have no text input keep the switch unavailable and are named in the hint; a member later removed from the combo keeps its provider declaration until cleared in the provider editor. `gui/src/components/route-board/WorkspaceSuggestions.tsx` renders suggestion cards inside the Combos workspace. Generate opens a draft. Saving the draft and choosing Add to combo both use the dashboard-only `POST /api/combo-suggestions/save` endpoint. Extension is held while that combo has unsaved workspace edits. Dismissals are browser-local. Provider exclusions are persisted by the management API. The workspace gates cards on a successful persisted policy read for the current proxy and offers a retry on failure. The exclusion control remains available after the last card is dismissed. Generate shows an unchecked paid-target consent checkbox and disables saving until it is checked. Add to combo is disabled with an explanation until the existing combo permits paid targets. A save conflict triggers a fresh policy and combo read. A combo refresh re-reads paid-target consent granted by `ocx combo update --allow-metered-targets on`. An exclusion PUT acknowledges the write and triggers a policy GET. Actions are gated until the latest policy GET settles. The dedicated save route rechecks persisted exclusions and spend consent and marks all added targets metered. The [channel classifier](config.md) is used for placement preference. The raw provider editor round-trips `autoReviewModel` and `autoReviewModelOverrides` through editor-owned DTO fields. POST/PATCH/PUT share validation; PUT copies schema-normalized values into the persisted and live candidate before adoption. Canonical `openai` rejects these fields, including clear forms. Field-masked writes (PATCH, editor PUT, reload) pin every registry-seed key and ignore operator overlays the seed never defines, most commonly `selectedModels`; POST keeps the exact-key comparison. Canonical `openai` still rejects `allowPrivateNetwork`, which must not short-circuit destination DNS checks on the ChatGPT forward row. Existing authentication, origin checks and stale-baseline protection still govern the writes. See [reviewer projection](catalog.md#provider-scoped-approval-reviewer). Stored Direct substitution follows the [credential identity contract](providers/openai-accounts.md#sidecars-management-and-ui): both synchronous and asynchronous materializers discard the caller account header before applying the stored credential; ordinary native Direct passthrough is unchanged. From d7280d507174ed5f6490cb5b2c7fca43d664c5c7 Mon Sep 17 00:00:00 2001 From: JUN Date: Thu, 19 Nov 2026 03:47:35 +0900 Subject: [PATCH 20/23] Hold combo suggestion actions during exclusion writes Re-read persisted policy after every exclusion write outcome and keep suggestion actions gated until the read succeeds. Co-authored-by: Andrew (agent) --- .../src/content/docs/es/guides/combos.md | 2 +- docs-site/src/content/docs/guides/combos.md | 2 +- .../route-board/use-suggestion-exclusions.ts | 12 ++- gui/tests/combo-suggestions.test.tsx | 75 ++++++++++++++++--- structure/dashboard-and-usage.md | 2 +- 5 files changed, 75 insertions(+), 18 deletions(-) diff --git a/docs-site/src/content/docs/es/guides/combos.md b/docs-site/src/content/docs/es/guides/combos.md index 9b785fc745e..224c4d52792 100644 --- a/docs-site/src/content/docs/es/guides/combos.md +++ b/docs-site/src/content/docs/es/guides/combos.md @@ -792,4 +792,4 @@ Un rechazo estructurado de esfuerzo puede bajar una posición publicada cada vez Si los ajustes cambian antes de guardar una sugerencia, Combos actualiza las sugerencias y muestra un mensaje. Al guardar, se comprueban las exclusiones y el consentimiento de gasto vigentes. Al añadir sugerencias, el servidor aplica el nivel de mayor coste entre la configuración activa y la guardada. Trata los destinos existentes marcados explícitamente como medidos como destinos de pago por uso y conserva el orden relativo de los destinos existentes. -En el espacio de trabajo de combos, **Generar** abre un borrador de conmutación por error para un modelo disponible en varios proveedores. **Añadir al combo** ofrece destinos que faltan en un combo existente. Las tarjetas descartadas quedan ocultas en este navegador. Usa **Excluir un proveedor…** para filtrar ambos tipos de sugerencias. El proxy guarda la selección como `comboSuggestionExcludedProviders` en `config.json`. Los miembros existentes se conservan. Todos los destinos sugeridos pueden generar cargos, incluso los canales de suscripción, como Codex con créditos comprados, Grok con Extra Usage y Kimi Code con Extra Usage. Para guardar un borrador, marca **Permitir destinos de pago**. Para añadir destinos, habilita primero los destinos de pago en el combo existente. El proxy guarda todos los destinos sugeridos con `metered: true`. El control de exclusión sigue disponible tras descartar todas las tarjetas. Si no se pueden cargar los ajustes de sugerencias, selecciona **Reintentar**. Si los ajustes guardados cambian antes de que guardes una sugerencia, el espacio de trabajo actualiza las tarjetas según las exclusiones y el permiso de pago vigentes. Si **Añadir al combo** está deshabilitado, ejecuta `ocx combo update --allow-metered-targets on` y sustituye `` por el identificador del combo guardado. La siguiente actualización del combo habilita la acción si hay destinos aptos para añadir. +En el espacio de trabajo de combos, **Generar** abre un borrador de conmutación por error para un modelo disponible en varios proveedores. **Añadir al combo** ofrece destinos que faltan en un combo existente. Las tarjetas descartadas quedan ocultas en este navegador. Usa **Excluir un proveedor…** para filtrar ambos tipos de sugerencias. El proxy guarda la selección como `comboSuggestionExcludedProviders` en `config.json`. Los miembros existentes se conservan. Todos los destinos sugeridos pueden generar cargos, incluso los canales de suscripción, como Codex con créditos comprados, Grok con Extra Usage y Kimi Code con Extra Usage. Para guardar un borrador, marca **Permitir destinos de pago**. Para añadir destinos, habilita primero los destinos de pago en el combo existente. El proxy guarda todos los destinos sugeridos con `metered: true`. El control de exclusión sigue disponible tras descartar todas las tarjetas. Al cambiar una exclusión, las acciones de sugerencias quedan deshabilitadas hasta que el panel vuelva a cargar los ajustes guardados, aunque se pierda la respuesta del guardado. Si no se pueden cargar los ajustes de sugerencias, selecciona **Reintentar**. Si los ajustes guardados cambian antes de que guardes una sugerencia, el espacio de trabajo actualiza las tarjetas según las exclusiones y el permiso de pago vigentes. Si **Añadir al combo** está deshabilitado, ejecuta `ocx combo update --allow-metered-targets on` y sustituye `` por el identificador del combo guardado. La siguiente actualización del combo habilita la acción si hay destinos aptos para añadir. diff --git a/docs-site/src/content/docs/guides/combos.md b/docs-site/src/content/docs/guides/combos.md index 562f8813233..35fe814bb40 100644 --- a/docs-site/src/content/docs/guides/combos.md +++ b/docs-site/src/content/docs/guides/combos.md @@ -1218,4 +1218,4 @@ untried targets and newer failures keep their cooldowns. When settings change before a suggestion is saved, Combos refreshes the suggestions and displays a message. Saving checks the current exclusions and spend consent. -In the Combos workspace, **Generate** opens a failover draft for a model served by multiple providers. **Add to combo** offers missing targets for an existing combo. Dismissed cards stay hidden in this browser. Use **Exclude providers…** to filter both kinds of suggestions. The proxy stores your selection as `comboSuggestionExcludedProviders` in `config.json`. When appending suggestions, the server uses the more costly tier from the active and saved configurations. It treats existing targets explicitly marked as metered as pay-per-use and preserves the relative order of existing targets. Every suggested target can incur paid usage, including subscription channels such as Codex with purchased credits, Grok with Extra Usage, and Kimi Code with Extra Usage. To save a draft, check **Allow paid targets**. To append, first enable paid targets in the existing combo. The proxy saves every suggested target as `metered: true`. The exclusion control stays available after dismissing all cards. If suggestion settings fail to load, select **Retry**. If saved settings change before you save a suggestion, the workspace refreshes the cards using the current exclusions and paid-target consent. If **Add to combo** is disabled, run `ocx combo update --allow-metered-targets on`, replacing `` with the saved combo ID. The next combo refresh makes the action available when there are eligible targets to add. +In the Combos workspace, **Generate** opens a failover draft for a model served by multiple providers. **Add to combo** offers missing targets for an existing combo. Dismissed cards stay hidden in this browser. Use **Exclude providers…** to filter both kinds of suggestions. The proxy stores your selection as `comboSuggestionExcludedProviders` in `config.json`. When appending suggestions, the server uses the more costly tier from the active and saved configurations. It treats existing targets explicitly marked as metered as pay-per-use and preserves the relative order of existing targets. Every suggested target can incur paid usage, including subscription channels such as Codex with purchased credits, Grok with Extra Usage, and Kimi Code with Extra Usage. To save a draft, check **Allow paid targets**. To append, first enable paid targets in the existing combo. The proxy saves every suggested target as `metered: true`. The exclusion control stays available after dismissing all cards. Changing an exclusion disables suggestion actions until the dashboard reloads the saved settings, even if the save response is lost. If suggestion settings fail to load, select **Retry**. If saved settings change before you save a suggestion, the workspace refreshes the cards using the current exclusions and paid-target consent. If **Add to combo** is disabled, run `ocx combo update --allow-metered-targets on`, replacing `` with the saved combo ID. The next combo refresh makes the action available when there are eligible targets to add. diff --git a/gui/src/components/route-board/use-suggestion-exclusions.ts b/gui/src/components/route-board/use-suggestion-exclusions.ts index a56e92aadbb..c90d66de8c0 100644 --- a/gui/src/components/route-board/use-suggestion-exclusions.ts +++ b/gui/src/components/route-board/use-suggestion-exclusions.ts @@ -23,6 +23,7 @@ function parse(body: unknown): SuggestionPolicy | null { export function useSuggestionExclusions(apiBase: string, combos?: readonly ComboItem[]) { const retry = () => setAttempt((value) => value + 1); + const [saving, setSaving] = useState(false); const [attempt, setAttempt] = useState(0); const [loaded, setLoaded] = useState<{ base: string; attempt: number; combos?: readonly ComboItem[]; policy: SuggestionPolicy | null }>(); const cached = loaded?.base === apiBase ? loaded : undefined; @@ -49,17 +50,20 @@ export function useSuggestionExclusions(apiBase: string, combos?: readonly Combo }, [apiBase, attempt, combos]); const save = async (provider: string, excluded: boolean) => { - if (!current?.policy) return false; + if (saving || !current?.policy) return false; + setSaving(true); try { const response = await fetch(`${apiBase}/api/combo-suggestions`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ provider, excluded }), }); - if (response.ok || response.status === 409) retry(); return response.ok; } catch { return false; + } finally { + retry(); + setSaving(false); } }; @@ -67,8 +71,8 @@ export function useSuggestionExclusions(apiBase: string, combos?: readonly Combo excluded: cached?.policy?.excludedProviders ?? [], meteredComboIds: cached?.policy?.meteredComboIds ?? [], available: cached?.policy != null, - ready: current?.policy != null, - failed: current?.policy === null, + ready: !saving && current?.policy != null, + failed: !saving && current?.policy === null, retry, save, }; diff --git a/gui/tests/combo-suggestions.test.tsx b/gui/tests/combo-suggestions.test.tsx index bdc00f03dad..b048d219aca 100644 --- a/gui/tests/combo-suggestions.test.tsx +++ b/gui/tests/combo-suggestions.test.tsx @@ -531,18 +531,28 @@ describe("ComboSuggestions card", () => { } }); - test("a delayed exclusion acknowledgment cannot restore revoked consent or old exclusions", async () => { + test.each(["delayed", "lost", "lost with read failure"])("%s exclusion acknowledgment requires a fresh policy before saving", async (ack) => { const originalFetch = globalThis.fetch; const name = "kimi-k3-1-pro"; const existing = combo("opus", [["kimi", name]], { allowMeteredTargets: true }); - const catalog = models([["kimi", name], ["google-vertex", name], ["xai", name]]); + const draftModel = "gemini-3.8-flash"; + const catalog = models([["kimi", name], ["google-vertex", name], ["xai", name], ["kimi", draftModel], ["xai", draftModel]]); let acknowledge!: (response: Response) => void; + let loseAcknowledgment!: (error: Error) => void; + let finishRead!: (response: Response) => void; + let suggestionsSaved = 0; let revoke = false; + let persistedExclusions: string[] = []; let reads = 0; - globalThis.fetch = (async (_url: string, init?: RequestInit) => { - if (init?.method === "PUT") return new Promise((resolve) => { acknowledge = resolve; }); + globalThis.fetch = (async (url: string, init?: RequestInit) => { + if (url.endsWith("/save")) suggestionsSaved += 1; + if (init?.method === "PUT") return new Promise((resolve, reject) => { + acknowledge = resolve; + loseAcknowledgment = reject; + }); reads += 1; - return Response.json({ excludedProviders: [], meteredComboIds: revoke ? [] : ["opus"] }); + if (reads === 3) return new Promise((resolve) => { finishRead = resolve; }); + return Response.json({ excludedProviders: persistedExclusions, meteredComboIds: revoke ? [] : ["opus"] }); }) as typeof fetch; try { const view = (combos: ComboItem[]) => { />; await mount(view([existing])); expect(button(card("opus"), "Add to combo").disabled).toBe(false); + await act(async () => { button(card(draftModel), "Generate").click(); }); + const draft = card(draftModel).querySelector(".rb-suggest-draft")!; + await act(async () => { draft.querySelector('input[type="checkbox"]')!.click(); }); + const add = button(card("opus"), "Add to combo"); + const save = button(draft, "Save combo"); + // Happy DOM does not include inherited fieldset state in :disabled. + const isDisabled = (control: HTMLButtonElement) => control.disabled || !!control.closest("fieldset[disabled]"); + expect(isDisabled(add)).toBe(false); + expect(isDisabled(save)).toBe(false); await act(async () => { host.querySelector(".rb-suggest-exclude-toggle")!.click(); }); const vertex = [...host.querySelectorAll('input[type="checkbox"]')] .find((input) => input.closest("label")?.textContent?.includes("Vertex"))!; await act(async () => { vertex.click(); }); - revoke = true; + const expectActionsDisabled = async () => { + expect(isDisabled(add)).toBe(true); + expect(isDisabled(save)).toBe(true); + await act(async () => { add.click(); save.click(); }); + expect(suggestionsSaved).toBe(0); + expect(existing.targets.map(({ provider }) => provider)).toEqual(["kimi"]); + }; + await expectActionsDisabled(); + expect(card("opus").textContent).toContain("Vertex"); + + revoke = ack === "delayed"; await act(async () => { root!.render(view([{ ...existing }])); }); - expect(button(card("opus"), "Add to combo").disabled).toBe(true); + await expectActionsDisabled(); + persistedExclusions = revoke ? [] : ["google-vertex"]; await act(async () => { - acknowledge(Response.json({ excludedProviders: ["google-vertex"], meteredComboIds: ["opus"] })); + if (ack === "delayed") { + acknowledge(Response.json({ excludedProviders: ["google-vertex"], meteredComboIds: ["opus"] })); + } else { + loseAcknowledgment(new Error("lost acknowledgment")); + } }); - expect(button(card("opus"), "Add to combo").disabled).toBe(true); - expect(card("opus").textContent).toContain("ocx combo update opus --allow-metered-targets on"); - expect(card("opus").textContent).toContain("Vertex"); expect(reads).toBe(3); + await expectActionsDisabled(); + await act(async () => { + finishRead(ack === "lost with read failure" + ? new Response(null, { status: 500 }) + : Response.json({ excludedProviders: persistedExclusions, meteredComboIds: revoke ? [] : ["opus"] })); + }); + + if (ack === "lost with read failure") { + expect(host.querySelector('[role="alert"]')?.textContent).toContain("Could not load"); + expect(host.textContent).not.toContain("Add to combo"); + await act(async () => { button(host, "Retry").click(); }); + expect(isDisabled(button(card("opus"), "Add to combo"))).toBe(false); + expect(card("opus").textContent).not.toContain("Vertex"); + } else if (revoke) { + expect(button(card("opus"), "Add to combo").disabled).toBe(true); + expect(card("opus").textContent).toContain("ocx combo update opus --allow-metered-targets on"); + expect(card("opus").textContent).toContain("Vertex"); + } else { + expect(isDisabled(button(card("opus"), "Add to combo"))).toBe(false); + expect(isDisabled(save)).toBe(false); + expect(card("opus").textContent).not.toContain("Vertex"); + } } finally { globalThis.fetch = originalFetch; } diff --git a/structure/dashboard-and-usage.md b/structure/dashboard-and-usage.md index c7e13e9e69d..6287e7267d6 100644 --- a/structure/dashboard-and-usage.md +++ b/structure/dashboard-and-usage.md @@ -501,7 +501,7 @@ Dashboard overview polling observes authorization failures independently of stal The [explicit model-capability contract](config.md#explicit-per-model-capability-declarations) preserves operator declarations through provider storage and catalog capture; it does not infer upstream capability or change this surface's routing behavior. -Exact [model input declarations](config.md#explicit-per-model-capability-declarations) now feed text-only eligibility and catalog hints; existing image-description/omission handling consumes them before the main upstream send. The Combos page sends non-image members as the request-only `visionSidecarTargets` field on `PUT /api/combos` whenever the Image switch is enabled, so text-only enrollment needs no manual provider edit. The GUI classifies members from the authoritative `visionSidecarConsumer` flag served on `/api/models` rows, so a member covered only by legacy `noVisionModels` keeps its sidecar classification after reload. Members whose modalities are unknown or have no text input keep the switch unavailable and are named in the hint; a member later removed from the combo keeps its provider declaration until cleared in the provider editor. `gui/src/components/route-board/WorkspaceSuggestions.tsx` renders suggestion cards inside the Combos workspace. Generate opens a draft. Saving the draft and choosing Add to combo both use the dashboard-only `POST /api/combo-suggestions/save` endpoint. Extension is held while that combo has unsaved workspace edits. Dismissals are browser-local. Provider exclusions are persisted by the management API. The workspace gates cards on a successful persisted policy read for the current proxy and offers a retry on failure. The exclusion control remains available after the last card is dismissed. Generate shows an unchecked paid-target consent checkbox and disables saving until it is checked. Add to combo is disabled with an explanation until the existing combo permits paid targets. A save conflict triggers a fresh policy and combo read. A combo refresh re-reads paid-target consent granted by `ocx combo update --allow-metered-targets on`. An exclusion PUT acknowledges the write and triggers a policy GET. Actions are gated until the latest policy GET settles. The dedicated save route rechecks persisted exclusions and spend consent and marks all added targets metered. The [channel classifier](config.md) is used for placement preference. +Exact [model input declarations](config.md#explicit-per-model-capability-declarations) now feed text-only eligibility and catalog hints; existing image-description/omission handling consumes them before the main upstream send. The Combos page sends non-image members as the request-only `visionSidecarTargets` field on `PUT /api/combos` whenever the Image switch is enabled, so text-only enrollment needs no manual provider edit. The GUI classifies members from the authoritative `visionSidecarConsumer` flag served on `/api/models` rows, so a member covered only by legacy `noVisionModels` keeps its sidecar classification after reload. Members whose modalities are unknown or have no text input keep the switch unavailable and are named in the hint; a member later removed from the combo keeps its provider declaration until cleared in the provider editor. `gui/src/components/route-board/WorkspaceSuggestions.tsx` renders suggestion cards inside the Combos workspace. Generate opens a draft. Saving the draft and choosing Add to combo both use the dashboard-only `POST /api/combo-suggestions/save` endpoint. Extension is held while that combo has unsaved workspace edits. Dismissals are browser-local. Provider exclusions are persisted by the management API. The workspace gates cards on a successful persisted policy read for the current proxy and offers a retry on failure. The exclusion control remains available after the last card is dismissed. Generate shows an unchecked paid-target consent checkbox and disables saving until it is checked. Add to combo is disabled with an explanation until the existing combo permits paid targets. A save conflict triggers a fresh policy and combo read. A combo refresh re-reads paid-target consent granted by `ocx combo update --allow-metered-targets on`. An exclusion PUT disables suggestion actions immediately. Every PUT outcome triggers a fresh policy GET, including a lost acknowledgment. A successful read re-enables actions allowed by the persisted policy. A failed read offers a retry. The dedicated save route rechecks persisted exclusions and spend consent and marks all added targets metered. The [channel classifier](config.md) is used for placement preference. The raw provider editor round-trips `autoReviewModel` and `autoReviewModelOverrides` through editor-owned DTO fields. POST/PATCH/PUT share validation; PUT copies schema-normalized values into the persisted and live candidate before adoption. Canonical `openai` rejects these fields, including clear forms. Field-masked writes (PATCH, editor PUT, reload) pin every registry-seed key and ignore operator overlays the seed never defines, most commonly `selectedModels`; POST keeps the exact-key comparison. Canonical `openai` still rejects `allowPrivateNetwork`, which must not short-circuit destination DNS checks on the ChatGPT forward row. Existing authentication, origin checks and stale-baseline protection still govern the writes. See [reviewer projection](catalog.md#provider-scoped-approval-reviewer). Stored Direct substitution follows the [credential identity contract](providers/openai-accounts.md#sidecars-management-and-ui): both synchronous and asynchronous materializers discard the caller account header before applying the stored credential; ordinary native Direct passthrough is unchanged. From 8a3b3a99a7400399e583299cef29a79df454e42c Mon Sep 17 00:00:00 2001 From: JUN Date: Thu, 19 Nov 2026 04:01:53 +0900 Subject: [PATCH 21/23] Preserve current combo metering on ordinary dashboard saves Co-authored-by: Andrew (agent) --- gui/src/combo-workspace-data.ts | 1 - gui/tests/combo-suggestions.test.tsx | 9 ++++--- structure/dashboard-and-usage.md | 2 +- tests/cli/cli-combo-set-targets.test.ts | 32 ++++++++++++++++++++++++- tests/gui/combo-workspace-data.test.ts | 8 +++++++ 5 files changed, 44 insertions(+), 8 deletions(-) diff --git a/gui/src/combo-workspace-data.ts b/gui/src/combo-workspace-data.ts index 13c839916df..95bf17567f5 100644 --- a/gui/src/combo-workspace-data.ts +++ b/gui/src/combo-workspace-data.ts @@ -549,7 +549,6 @@ export function toPutBody( targets: item.targets.map((target) => ({ provider: target.provider.trim(), model: target.model.trim(), - ...(target.metered === true ? { metered: true } : {}), ...(weighted ? { weight: target.weight ?? 1 } : {}), ...(target.reasoningEfforts !== undefined ? { reasoningEfforts: [...target.reasoningEfforts] } diff --git a/gui/tests/combo-suggestions.test.tsx b/gui/tests/combo-suggestions.test.tsx index b048d219aca..4bb15cf0427 100644 --- a/gui/tests/combo-suggestions.test.tsx +++ b/gui/tests/combo-suggestions.test.tsx @@ -14,7 +14,7 @@ import { type SuggestionInput, type SuggestionProvider, } from "../src/combo-suggestions"; -import { isValidComboId, toPutBody, type ComboItem } from "../src/combo-workspace-data"; +import { isValidComboId, type ComboItem } from "../src/combo-workspace-data"; import { ComboSuggestions, type ComboSuggestionsProps } from "../src/components/route-board/ComboSuggestions"; import { useSuggestionExclusions } from "../src/components/route-board/use-suggestion-exclusions"; import { WorkspaceSuggestions } from "../src/components/route-board/WorkspaceSuggestions"; @@ -758,12 +758,11 @@ test("another model on the same provider does not hide a missing channel", () => expect(suggestion?.members.map(({ provider, model }) => [provider, model])).toEqual([["xai", name]]); }); -test("only consented extensions serialize paid targets, without writing consent", () => { +test("only consented extension previews mark added targets metered", () => { const member = { provider: "google-vertex", model: "kimi-k3-1-pro", tier: "vertex" } as const; expect(suggestionDraft("opus", [member])).toMatchObject({ allowMeteredTargets: true, targets: [{ metered: true }] }); const current = combo("opus", [["kimi", member.model]]); expect(extendedCombo(current, [member], () => "own-subscription").targets).toEqual(current.targets); - const body = toPutBody(extendedCombo({ ...current, allowMeteredTargets: true }, [member], () => "own-subscription")).combo; - expect(body.targets.map(({ metered }) => metered)).toEqual([undefined, true]); - expect(body).not.toHaveProperty("allowMeteredTargets"); + const extension = extendedCombo({ ...current, allowMeteredTargets: true }, [member], () => "own-subscription"); + expect(extension.targets.map(({ metered }) => metered)).toEqual([undefined, true]); }); diff --git a/structure/dashboard-and-usage.md b/structure/dashboard-and-usage.md index 6287e7267d6..8b724b073d6 100644 --- a/structure/dashboard-and-usage.md +++ b/structure/dashboard-and-usage.md @@ -501,7 +501,7 @@ Dashboard overview polling observes authorization failures independently of stal The [explicit model-capability contract](config.md#explicit-per-model-capability-declarations) preserves operator declarations through provider storage and catalog capture; it does not infer upstream capability or change this surface's routing behavior. -Exact [model input declarations](config.md#explicit-per-model-capability-declarations) now feed text-only eligibility and catalog hints; existing image-description/omission handling consumes them before the main upstream send. The Combos page sends non-image members as the request-only `visionSidecarTargets` field on `PUT /api/combos` whenever the Image switch is enabled, so text-only enrollment needs no manual provider edit. The GUI classifies members from the authoritative `visionSidecarConsumer` flag served on `/api/models` rows, so a member covered only by legacy `noVisionModels` keeps its sidecar classification after reload. Members whose modalities are unknown or have no text input keep the switch unavailable and are named in the hint; a member later removed from the combo keeps its provider declaration until cleared in the provider editor. `gui/src/components/route-board/WorkspaceSuggestions.tsx` renders suggestion cards inside the Combos workspace. Generate opens a draft. Saving the draft and choosing Add to combo both use the dashboard-only `POST /api/combo-suggestions/save` endpoint. Extension is held while that combo has unsaved workspace edits. Dismissals are browser-local. Provider exclusions are persisted by the management API. The workspace gates cards on a successful persisted policy read for the current proxy and offers a retry on failure. The exclusion control remains available after the last card is dismissed. Generate shows an unchecked paid-target consent checkbox and disables saving until it is checked. Add to combo is disabled with an explanation until the existing combo permits paid targets. A save conflict triggers a fresh policy and combo read. A combo refresh re-reads paid-target consent granted by `ocx combo update --allow-metered-targets on`. An exclusion PUT disables suggestion actions immediately. Every PUT outcome triggers a fresh policy GET, including a lost acknowledgment. A successful read re-enables actions allowed by the persisted policy. A failed read offers a retry. The dedicated save route rechecks persisted exclusions and spend consent and marks all added targets metered. The [channel classifier](config.md) is used for placement preference. +Exact [model input declarations](config.md#explicit-per-model-capability-declarations) now feed text-only eligibility and catalog hints; existing image-description/omission handling consumes them before the main upstream send. The Combos page sends non-image members as the request-only `visionSidecarTargets` field on `PUT /api/combos` whenever the Image switch is enabled, so text-only enrollment needs no manual provider edit. The GUI classifies members from the authoritative `visionSidecarConsumer` flag served on `/api/models` rows, so a member covered only by legacy `noVisionModels` keeps its sidecar classification after reload. Members whose modalities are unknown or have no text input keep the switch unavailable and are named in the hint; a member later removed from the combo keeps its provider declaration until cleared in the provider editor. `gui/src/components/route-board/WorkspaceSuggestions.tsx` renders suggestion cards inside the Combos workspace. Generate opens a draft. Saving the draft and choosing Add to combo both use the dashboard-only `POST /api/combo-suggestions/save` endpoint. Extension is held while that combo has unsaved workspace edits. Dismissals are browser-local. Provider exclusions are persisted by the management API. The workspace gates cards on a successful persisted policy read for the current proxy and offers a retry on failure. The exclusion control remains available after the last card is dismissed. Generate shows an unchecked paid-target consent checkbox and disables saving until it is checked. Add to combo is disabled with an explanation until the existing combo permits paid targets. A save conflict triggers a fresh policy and combo read. A combo refresh re-reads paid-target consent granted by `ocx combo update --allow-metered-targets on`. An exclusion PUT disables suggestion actions immediately. Every PUT outcome triggers a fresh policy GET, including a lost acknowledgment. A successful read re-enables actions allowed by the persisted policy. A failed read offers a retry. The dedicated save route rechecks persisted exclusions and spend consent and marks all added targets metered. Ordinary workspace saves omit target metering metadata so the server retains the current value for matching targets. The [channel classifier](config.md) is used for placement preference. The raw provider editor round-trips `autoReviewModel` and `autoReviewModelOverrides` through editor-owned DTO fields. POST/PATCH/PUT share validation; PUT copies schema-normalized values into the persisted and live candidate before adoption. Canonical `openai` rejects these fields, including clear forms. Field-masked writes (PATCH, editor PUT, reload) pin every registry-seed key and ignore operator overlays the seed never defines, most commonly `selectedModels`; POST keeps the exact-key comparison. Canonical `openai` still rejects `allowPrivateNetwork`, which must not short-circuit destination DNS checks on the ChatGPT forward row. Existing authentication, origin checks and stale-baseline protection still govern the writes. See [reviewer projection](catalog.md#provider-scoped-approval-reviewer). Stored Direct substitution follows the [credential identity contract](providers/openai-accounts.md#sidecars-management-and-ui): both synchronous and asynchronous materializers discard the caller account header before applying the stored credential; ordinary native Direct passthrough is unchanged. diff --git a/tests/cli/cli-combo-set-targets.test.ts b/tests/cli/cli-combo-set-targets.test.ts index 2de9d2ade1c..a24e328084e 100644 --- a/tests/cli/cli-combo-set-targets.test.ts +++ b/tests/cli/cli-combo-set-targets.test.ts @@ -1,5 +1,6 @@ +import { parseComboList, toPutBody } from "../../gui/src/combo-workspace-data"; import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; -import { readFileSync } from "node:fs"; +import { readFileSync, writeFileSync } from "node:fs"; import { getConfigPath, saveConfig } from "../../src/config"; import { handleComboCommand } from "../../src/cli/combo"; import type { RuntimeApiDeps } from "../../src/cli/runtime-api"; @@ -107,3 +108,32 @@ describe("ocx combo set --targets keeps the stored strategy (#7579)", () => { expect(stored().fresh).toMatchObject({ strategy: "failover", targets: [{ provider: "fixture", model: "m" }] }); }); }); + +test("an ordinary dashboard save preserves a metered flag cleared by the CLI", async () => { + config.combos!.chain = { + strategy: "failover", + targets: [{ provider: "fixture", model: "m", metered: true }], + }; + saveConfig(config); + const loaded = await deps.fetchImpl!("http://127.0.0.1/api/combos"); + const draft = parseComboList(await loaded.json()).find(combo => combo.id === "chain")!; + expect(draft.targets[0]?.metered).toBe(true); + + const targetsPath = getConfigPath() + ".targets.json"; + writeFileSync(targetsPath, JSON.stringify([{ provider: "fixture", model: "m", metered: false }])); + expect(await handleComboCommand(["set", "chain", "--targets-file", targetsPath, "--json"], deps)).toBe(0); + expect((stored().chain!.targets as unknown[])[0]).not.toHaveProperty("metered"); + expect(config.combos!.chain!.targets[0]?.metered).toBeFalsy(); + + const response = await deps.fetchImpl!("http://127.0.0.1/api/combos", { + method: "PUT", + body: JSON.stringify(toPutBody({ ...draft, displayName: "Renamed display" })), + }); + expect(response.status).toBe(200); + expect(stored().chain).toMatchObject({ + displayName: "Renamed display", + targets: [{ provider: "fixture", model: "m" }], + }); + expect((stored().chain!.targets as unknown[])[0]).not.toHaveProperty("metered"); + expect(config.combos!.chain!.targets[0]?.metered).toBeFalsy(); +}); diff --git a/tests/gui/combo-workspace-data.test.ts b/tests/gui/combo-workspace-data.test.ts index 9d1adfd2b89..884115184dd 100644 --- a/tests/gui/combo-workspace-data.test.ts +++ b/tests/gui/combo-workspace-data.test.ts @@ -21,6 +21,14 @@ import { } from "../../gui/src/combo-workspace-data"; import { comboImageBlockedTargets, comboImagesSupported, comboVisionSidecarTargets } from "../../gui/src/combo-capabilities"; +test("ordinary combo saves omit metered metadata from the loaded draft", () => { + const [draft] = parseComboList({ + combos: [{ id: "chain", targets: [{ provider: "a", model: "m", metered: true }] }], + }); + expect(draft!.targets[0]?.metered).toBe(true); + expect(toPutBody(draft!).combo.targets[0]).not.toHaveProperty("metered"); +}); + const configuredProviders = { a: {}, b: {}, From 9c597f3f8ba09bfe65933f9a4993db7a5d5477da Mon Sep 17 00:00:00 2001 From: JUN Date: Thu, 19 Nov 2026 10:12:05 +0900 Subject: [PATCH 22/23] docs(combos): document server-authoritative suggestion saves and 409 refresh recovery --- docs-site/src/content/docs/es/guides/combos.md | 2 ++ docs-site/src/content/docs/guides/combos.md | 2 ++ structure/dashboard-and-usage.md | 2 +- structure/gui-and-management-api.md | 2 +- 4 files changed, 6 insertions(+), 2 deletions(-) diff --git a/docs-site/src/content/docs/es/guides/combos.md b/docs-site/src/content/docs/es/guides/combos.md index 224c4d52792..7afa8a38843 100644 --- a/docs-site/src/content/docs/es/guides/combos.md +++ b/docs-site/src/content/docs/es/guides/combos.md @@ -792,4 +792,6 @@ Un rechazo estructurado de esfuerzo puede bajar una posición publicada cada vez Si los ajustes cambian antes de guardar una sugerencia, Combos actualiza las sugerencias y muestra un mensaje. Al guardar, se comprueban las exclusiones y el consentimiento de gasto vigentes. Al añadir sugerencias, el servidor aplica el nivel de mayor coste entre la configuración activa y la guardada. Trata los destinos existentes marcados explícitamente como medidos como destinos de pago por uso y conserva el orden relativo de los destinos existentes. +El proxy aplica estas reglas en cada guardado. El panel puede mostrar brevemente una acción que el proxy rechaza, por ejemplo justo después de cambiar los ajustes en otra pestaña o con la CLI. En ese caso, el proxy responde con HTTP 409 y el espacio de trabajo vuelve a cargar los ajustes guardados y los combos para que las tarjetas coincidan con lo que permite el proxy. + En el espacio de trabajo de combos, **Generar** abre un borrador de conmutación por error para un modelo disponible en varios proveedores. **Añadir al combo** ofrece destinos que faltan en un combo existente. Las tarjetas descartadas quedan ocultas en este navegador. Usa **Excluir un proveedor…** para filtrar ambos tipos de sugerencias. El proxy guarda la selección como `comboSuggestionExcludedProviders` en `config.json`. Los miembros existentes se conservan. Todos los destinos sugeridos pueden generar cargos, incluso los canales de suscripción, como Codex con créditos comprados, Grok con Extra Usage y Kimi Code con Extra Usage. Para guardar un borrador, marca **Permitir destinos de pago**. Para añadir destinos, habilita primero los destinos de pago en el combo existente. El proxy guarda todos los destinos sugeridos con `metered: true`. El control de exclusión sigue disponible tras descartar todas las tarjetas. Al cambiar una exclusión, las acciones de sugerencias quedan deshabilitadas hasta que el panel vuelva a cargar los ajustes guardados, aunque se pierda la respuesta del guardado. Si no se pueden cargar los ajustes de sugerencias, selecciona **Reintentar**. Si los ajustes guardados cambian antes de que guardes una sugerencia, el espacio de trabajo actualiza las tarjetas según las exclusiones y el permiso de pago vigentes. Si **Añadir al combo** está deshabilitado, ejecuta `ocx combo update --allow-metered-targets on` y sustituye `` por el identificador del combo guardado. La siguiente actualización del combo habilita la acción si hay destinos aptos para añadir. diff --git a/docs-site/src/content/docs/guides/combos.md b/docs-site/src/content/docs/guides/combos.md index 35fe814bb40..7a8ba582177 100644 --- a/docs-site/src/content/docs/guides/combos.md +++ b/docs-site/src/content/docs/guides/combos.md @@ -1218,4 +1218,6 @@ untried targets and newer failures keep their cooldowns. When settings change before a suggestion is saved, Combos refreshes the suggestions and displays a message. Saving checks the current exclusions and spend consent. +The proxy enforces these rules on every save. The dashboard can briefly show an action that the proxy then refuses, for example right after settings change in another tab or through the CLI. The proxy answers with HTTP 409, and the workspace reloads the saved settings and combos so the cards match what the proxy allows. + In the Combos workspace, **Generate** opens a failover draft for a model served by multiple providers. **Add to combo** offers missing targets for an existing combo. Dismissed cards stay hidden in this browser. Use **Exclude providers…** to filter both kinds of suggestions. The proxy stores your selection as `comboSuggestionExcludedProviders` in `config.json`. When appending suggestions, the server uses the more costly tier from the active and saved configurations. It treats existing targets explicitly marked as metered as pay-per-use and preserves the relative order of existing targets. Every suggested target can incur paid usage, including subscription channels such as Codex with purchased credits, Grok with Extra Usage, and Kimi Code with Extra Usage. To save a draft, check **Allow paid targets**. To append, first enable paid targets in the existing combo. The proxy saves every suggested target as `metered: true`. The exclusion control stays available after dismissing all cards. Changing an exclusion disables suggestion actions until the dashboard reloads the saved settings, even if the save response is lost. If suggestion settings fail to load, select **Retry**. If saved settings change before you save a suggestion, the workspace refreshes the cards using the current exclusions and paid-target consent. If **Add to combo** is disabled, run `ocx combo update --allow-metered-targets on`, replacing `` with the saved combo ID. The next combo refresh makes the action available when there are eligible targets to add. diff --git a/structure/dashboard-and-usage.md b/structure/dashboard-and-usage.md index 5aa57225b90..32e99eb4d27 100644 --- a/structure/dashboard-and-usage.md +++ b/structure/dashboard-and-usage.md @@ -501,7 +501,7 @@ Dashboard overview polling observes authorization failures independently of stal The [explicit model-capability contract](config.md#explicit-per-model-capability-declarations) preserves operator declarations through provider storage and catalog capture; it does not infer upstream capability or change this surface's routing behavior. -Exact [model input declarations](config.md#explicit-per-model-capability-declarations) now feed text-only eligibility and catalog hints; existing image-description/omission handling consumes them before the main upstream send. The Combos page sends non-image members as the request-only `visionSidecarTargets` field on `PUT /api/combos` whenever the Image switch is enabled, so text-only enrollment needs no manual provider edit. The GUI classifies members from the authoritative `visionSidecarConsumer` flag served on `/api/models` rows, so a member covered only by legacy `noVisionModels` keeps its sidecar classification after reload. Members whose modalities are unknown or have no text input keep the switch unavailable and are named in the hint; a member later removed from the combo keeps its provider declaration until cleared in the provider editor. `gui/src/components/route-board/WorkspaceSuggestions.tsx` renders suggestion cards inside the Combos workspace. Generate opens a draft. Saving the draft and choosing Add to combo both use the dashboard-only `POST /api/combo-suggestions/save` endpoint. Extension is held while that combo has unsaved workspace edits. Dismissals are browser-local. Provider exclusions are persisted by the management API. The workspace gates cards on a successful persisted policy read for the current proxy and offers a retry on failure. The exclusion control remains available after the last card is dismissed. Generate shows an unchecked paid-target consent checkbox and disables saving until it is checked. Add to combo is disabled with an explanation until the existing combo permits paid targets. A save conflict triggers a fresh policy and combo read. A combo refresh re-reads paid-target consent granted by `ocx combo update --allow-metered-targets on`. An exclusion PUT disables suggestion actions immediately. Every PUT outcome triggers a fresh policy GET, including a lost acknowledgment. A successful read re-enables actions allowed by the persisted policy. A failed read offers a retry. The dedicated save route rechecks persisted exclusions and spend consent and marks all added targets metered. Ordinary workspace saves omit target metering metadata so the server retains the current value for matching targets. The [channel classifier](config.md) is used for placement preference. +Exact [model input declarations](config.md#explicit-per-model-capability-declarations) now feed text-only eligibility and catalog hints; existing image-description/omission handling consumes them before the main upstream send. The Combos page sends non-image members as the request-only `visionSidecarTargets` field on `PUT /api/combos` whenever the Image switch is enabled, so text-only enrollment needs no manual provider edit. The GUI classifies members from the authoritative `visionSidecarConsumer` flag served on `/api/models` rows, so a member covered only by legacy `noVisionModels` keeps its sidecar classification after reload. Members whose modalities are unknown or have no text input keep the switch unavailable and are named in the hint; a member later removed from the combo keeps its provider declaration until cleared in the provider editor. `gui/src/components/route-board/WorkspaceSuggestions.tsx` renders suggestion cards inside the Combos workspace. Generate opens a draft. Saving the draft and choosing Add to combo both use the dashboard-only `POST /api/combo-suggestions/save` endpoint. Extension is held while that combo has unsaved workspace edits. Dismissals are browser-local. Provider exclusions are persisted by the management API. The workspace gates cards on a successful persisted policy read for the current proxy and offers a retry on failure. The exclusion control remains available after the last card is dismissed. Generate shows an unchecked paid-target consent checkbox and disables saving until it is checked. Add to combo is disabled with an explanation until the existing combo permits paid targets. A save conflict triggers a fresh policy and combo read. The server is authoritative for suggestion saves: `src/server/management/combo-suggestion-routes.ts` enforces the dashboard session, explicit Generate consent, stored consent for Add to combo, provider exclusions under the persisted-config lock, and `metered: true` on every suggested target. Workspace gating is advisory, so the workspace can briefly offer an action the server refuses, for example after a remount or a change made from another tab or the CLI. The 409 and the authoritative policy and combo refresh that follows are the recovery for that window. A combo refresh re-reads paid-target consent granted by `ocx combo update --allow-metered-targets on`. An exclusion PUT disables suggestion actions immediately. Every PUT outcome triggers a fresh policy GET, including a lost acknowledgment. A successful read re-enables actions allowed by the persisted policy. A failed read offers a retry. The dedicated save route rechecks persisted exclusions and spend consent and marks all added targets metered. Ordinary workspace saves omit target metering metadata so the server retains the current value for matching targets. The [channel classifier](config.md) is used for placement preference. The raw provider editor round-trips `autoReviewModel` and `autoReviewModelOverrides` through editor-owned DTO fields. POST/PATCH/PUT share validation; PUT copies schema-normalized values into the persisted and live candidate before adoption. Canonical `openai` rejects these fields, including clear forms. Field-masked writes (PATCH, editor PUT, reload) pin every registry-seed key and ignore operator overlays the seed never defines, most commonly `selectedModels`; POST keeps the exact-key comparison. Canonical `openai` still rejects `allowPrivateNetwork`, which must not short-circuit destination DNS checks on the ChatGPT forward row. Existing authentication, origin checks and stale-baseline protection still govern the writes. See [reviewer projection](catalog.md#provider-scoped-approval-reviewer). Stored Direct substitution follows the [credential identity contract](providers/openai-accounts.md#sidecars-management-and-ui): both synchronous and asynchronous materializers discard the caller account header before applying the stored credential; ordinary native Direct passthrough is unchanged. diff --git a/structure/gui-and-management-api.md b/structure/gui-and-management-api.md index e29c7706648..00ac51d2b25 100644 --- a/structure/gui-and-management-api.md +++ b/structure/gui-and-management-api.md @@ -311,7 +311,7 @@ after the save, and a non-retryable skip (no managed catalog) is a clean save. C | File-integration plans | `src/server/management/integration-routes.ts` and `aside-profile-routes.ts` — `POST /api/client-integrations/preview`, `POST /api/client-integrations/restore/preview`, and `POST /api/client-integrations/aside/profiles/{profileId}/preview`. Management-authenticated, declared non-mutating, and they write nothing: no snapshot, no lock, no maintenance, no recovery. They answer `409 integration_preview_unavailable` rather than gathering a model roster, because discovery refreshes credentials and writes the provider cache. Responses carry only declared managed schema paths, closed change kinds and an opaque fingerprint; no value, filesystem location or selected member identity appears. Mutation routes accept `operation` and `planFingerprint` together or not at all, reject a half-bound request and an operation that disagrees with the change, and answer `409 integration_preview_stale` with a freshly computed plan. Binding is an optimistic token, never authorization. [The integration contract](clients/integrations.md) owns the ordering. | | Grok reset coupons | `src/server/management/grok-coupon-routes.ts` — `GET /api/grok/reset-coupons`, `POST /api/grok/reset-coupons/consume`. The dashboard owner is `gui/src/hooks/useGrokResetCoupons.ts` with `gui/src/components/provider-workspace/GrokResetCoupons.tsx`, wired into the xAI OAuth rows of `ProviderAuthPanel`. Redemption truth is the settled ledger `code`, not the HTTP status: a replayed failure returns 200 with `replayed: true`. See [`providers/xai-grok.md`](providers/xai-grok.md). The route returns `ledger_unavailable` before dispatch when the shared ledger cannot be read or locked; stale uncertain attempts are inspected without another redemption or inferred success. A late inspection refusal or a lost claim replays an identity-matching definitive winner; otherwise it returns `operation_state_changed` (late refusal) or `attempt_in_progress` (lost claim) and never replaces an attempted or terminal record. Unknown-outcome responses include the effective operation ID; the CLI mints it before dispatch. Uncertain and pending attempts live in a module-level hold store shared by all hook instances and mirrored to `sessionStorage` (`ocx.grok-coupon-holds.v1`), so they survive modal close/reopen, remount, and reload for the tab session; the pending hold is written before the POST, only a definitive response for the same `operationId` clears it, and only GET refreshes are allowed after uncertainty. Every response that cannot prove settlement under a supplied operation ID, including pre-open refusals, carries that `operationId`. A definitive failure releases the matching speculative pending hold. Supplied token IDs must be non-empty strings before journal admission, and omitted account/token retries recover the operation’s durable identity within retention. Legacy version-one opens are quarantined rather than dispatched. After confirmed redemption, local settlement has five attempts and four 20 ms waits only for a `ConfigMutationLockError` caused by `SQLITE_BUSY`; any other error or changed claim stops without another redemption. | | Claude reset grants | `src/server/management/anthropic-reset-grant-routes.ts` — `GET /api/anthropic/reset-grants`, `POST /api/anthropic/reset-grants/consume` (lazy-loaded). Wire and fail-closed parsing live in `src/providers/anthropic-reset-grants.ts` (the Claude Code 2.1.278 `cedar_ember` contract, sent with `CLAUDE_CLI_USER_AGENT` from `src/providers/claude-cli-identity.ts`; every bearer request refuses redirects, and a refused claim redirect is an unknown outcome); the journal is `src/providers/anthropic-reset-grant-ledger.ts`: a cross-process `BEGIN IMMEDIATE` lock around every synchronous read-modify-write, a 90 s lease, the operation id reused as the upstream `request_id`, same-id retry only inside the vendor's ten-minute window, at most one unresolved operation per account and organization within each pool's journal and that ten-minute window, whatever grant it names (a new id gets `409 unresolved_prior_operation`), no settlement inferred from a re-read, and a fail-closed `500 journal_write_failed` when an answer cannot be recorded. Spending requires the `gui-session` principal. A journaled `reset`, including a same-id replay of that code, lifts that account cooldown only when it is a 429 quota refusal recorded before the operation was first journaled (the claim fence, `claimedAt`) and the journal's cleared windows cover every window the refusal named (both when it named none); it then drops the cached quota row and rereads usage with its own request rather than joining an older read. Model-family exclusions stay until the usage reread proves a family is no longer rejected. A failed reread leaves them in place. The HTTP result stays the journal answer if the reread fails. Other result codes do not admit. The dashboard owner is `gui/src/hooks/useAnthropicResetGrants.ts` with `gui/src/components/provider-workspace/AnthropicResetGrants.tsx` on the Anthropic OAuth rows of `ProviderAuthPanel`; the dialog re-reads the account when it opens, lets the user choose the grant (default: the selectable grant that expires first; the server re-gates the chosen `grantId`), and after an unknown outcome only retries the same id with no picker shown. Design and audit record: [`../devlog/_fin/260923_claude_reset_grants/010_plan.md`](../devlog/_fin/260923_claude_reset_grants/010_plan.md). | -| Combos | `src/server/management/combo-routes.ts` — `GET/PUT/DELETE /api/combos` own provider combination and failover definitions. `PUT` keeps a stored field the body omits (`cooldownMs`, `waitForCooldownMs`, `defaultEffortMode`, `reasoningEffortMode`, `imageInput`, `cooldownWaitPolicy`, per-target `lastResort`, JEV `decisionQuotaSignals`/`decisionQuotaTiers`/`jevEffortMode`/`sessionPin` on updates/rename); quota false/null clears sparsely and switching away removes quota policy under [the owning contract](providers/jev-decision.md#loaded-advisory-quota). Explicit values replace it and defaults are stored sparse. A combo validation 400 is `{ error, field? }`, where `field` is the top-level combo field of the first issue. `GET /api/combo-suggestions` and `PUT /api/combo-suggestions` use the dashboard-only route in `src/server/management/combo-suggestion-routes.ts`. All three suggestion operations require `hasHumanDashboardSession` before dispatch. Admin-token and remembered-admin callers receive 403. GET reads the saved policy and returns `{ excludedProviders: string[], meteredComboIds: string[] }`. PUT accepts `{ provider: string, excluded: boolean }`, changes only that provider in the locked persisted configuration, and returns the resulting policy. `POST /api/combo-suggestions/save` accepts a combo ID, a create or append mode, and provider/model pairs. The locked mutation validates persisted exclusions and spend consent. Create requires and stores explicit `allowMeteredTargets: true`. Append rejects request consent and requires stored consent. All new suggested targets have `metered: true`. Conflicts return a fixed reason code. When appending suggestions, the server uses the more costly tier from the active and saved configurations. It treats existing targets explicitly marked as metered as pay-per-use and preserves the relative order of existing targets. The dashboard and save route share the tier classifier. The config DTO carries the canonical forward and known OAuth subscription decisions computed before URL sanitization, so redaction cannot change gateway placement. | +| Combos | `src/server/management/combo-routes.ts` — `GET/PUT/DELETE /api/combos` own provider combination and failover definitions. `PUT` keeps a stored field the body omits (`cooldownMs`, `waitForCooldownMs`, `defaultEffortMode`, `reasoningEffortMode`, `imageInput`, `cooldownWaitPolicy`, per-target `lastResort`, JEV `decisionQuotaSignals`/`decisionQuotaTiers`/`jevEffortMode`/`sessionPin` on updates/rename); quota false/null clears sparsely and switching away removes quota policy under [the owning contract](providers/jev-decision.md#loaded-advisory-quota). Explicit values replace it and defaults are stored sparse. A combo validation 400 is `{ error, field? }`, where `field` is the top-level combo field of the first issue. `GET /api/combo-suggestions` and `PUT /api/combo-suggestions` use the dashboard-only route in `src/server/management/combo-suggestion-routes.ts`. All three suggestion operations require `hasHumanDashboardSession` before dispatch. Admin-token and remembered-admin callers receive 403. GET reads the saved policy and returns `{ excludedProviders: string[], meteredComboIds: string[] }`. PUT accepts `{ provider: string, excluded: boolean }`, changes only that provider in the locked persisted configuration, and returns the resulting policy. `POST /api/combo-suggestions/save` accepts a combo ID, a create or append mode, and provider/model pairs. The locked mutation validates persisted exclusions and spend consent. Create requires and stores explicit `allowMeteredTargets: true`. Append rejects request consent and requires stored consent. All new suggested targets have `metered: true`. Conflicts return a fixed reason code. These checks run only in the route, which is authoritative: the dashboard's gating is advisory and can briefly offer an action the route refuses, and the dashboard recovers from the 409 by re-reading the policy and combos. When appending suggestions, the server uses the more costly tier from the active and saved configurations. It treats existing targets explicitly marked as metered as pay-per-use and preserves the relative order of existing targets. The dashboard and save route share the tier classifier. The config DTO carries the canonical forward and known OAuth subscription decisions computed before URL sanitization, so redaction cannot change gateway placement. | | Protocol paths | `src/server/management/protocol-routes.ts` (lazy-loaded) — `GET /api/protocols` returns the contract version, the resolved API surfaces and protocol settings, the policy revision and the feature vocabulary; with `?provider=` (one non-empty name of at most 200 characters without control characters, else 400 `invalid_provider`; an unconfigured name is 404 `unknown_provider`, neither echoing the name) it adds a `provider` block from `src/protocols/provider-summary.ts` ([Protocol Paths](data-planes/protocol-paths.md#provider-wire-summary)); `POST /api/protocols/plan` takes `{ model, inbound, features? }` (model at most 200 characters, at most 24 features, any other key refused with 400) and returns a `ProtocolPlanV1` with `basis: "preview"` from `src/protocols/plan-snapshot.ts`. Both are read-only, never log their input, and send nothing upstream. `PATCH /api/protocols/settings` takes `{ messagesEnabled?, unrepresentable?, rollout? }` (strict: unknown keys and wrong types are 400), validates and applies through `src/server/management/protocol-settings-patch.ts`, persists with `saveConfigPreservingClaudeCode`, restores the live config if the save fails (409 on lock contention, 500 otherwise), and answers with the fresh `GET /api/protocols` body; closing Messages also writes `claudeCode.enabled = false` through `commitClaudeCodeBlock` ([Protocol Paths](data-planes/protocol-paths.md#settings)). The CLI drives all three through `ocx api protocols`, `ocx api explain` and `ocx api policy` ([Protocol Paths](data-planes/protocol-paths.md#cli)); none carries a route-registry exemption. | | Workflow budget | `src/server/management/workflow-budget-routes.ts` — `GET /api/workflow-budget` reads the tracked roots or one root, and `POST /api/workflow-budget/clear` clears exactly one. The clear moves the windowed send ring and the child map and nothing else: `active` belongs to turns still in flight, the spend ledger is a token budget an operator did not ask to forgive, and the lifetime send total survives so a clear cannot launder the record. A refusal event carries `spendScope` and `spendLimit` when a token ceiling fired, so the reason is readable without the config open beside it; no scope id is ever attached, because root ids are client thread headers and identity ids are credentials. Both are `deferred-verb` in the route registry — they are owed CLI verbs, and because the ledger is process memory there is no local projection the CLI could read instead. `GET`/`PUT /api/workflow-budget/settings` read and write the per-install count ceilings (`workflowBudget` in config: concurrent turns, sends and distinct children per window); the live config is bound in `src/lib/workflow-budget-config.ts` and read per decision by HTTP admission and the pre-dispatch send ceiling, so a write applies to the next request and never resets a root's usage. The window, interactive reserve and tracked-root bound stay fixed because a root's ring geometry is fixed when it first appears. The GET is `local-transport` (same block via `ocx config get`), the PUT `deferred-verb` with the other budget verbs. See [`../devlog/_fin/260915_workflow_budget_window/030_wfc_diff_plan.md`](../devlog/_fin/260915_workflow_budget_window/030_wfc_diff_plan.md). | | Codex accounts | `src/codex/auth-api/routes.ts` — `GET/POST/DELETE /api/codex-auth/accounts`, `PUT /api/codex-auth/accounts/alias`, `PUT /api/codex-auth/accounts/pause`, `PUT /api/codex-auth/accounts/pause-exhausted`, `POST /api/codex-auth/accounts/clear-cooldown`, `GET/PUT /api/codex-auth/active`, `PUT /api/codex-auth/auto-switch`, `PUT /api/codex-auth/pool-strategy`, `PUT /api/codex-auth/failover`, `GET /api/codex-auth/quota`, `GET /api/codex-auth/reset-credits` with `POST /api/codex-auth/reset-credits/consume`, and the login flow `POST /api/codex-auth/login`, `POST /api/codex-auth/login/code`, `POST /api/codex-auth/login/cancel`, `GET /api/codex-auth/login-status`. Pool login cancellation through `POST /api/codex-auth/login/cancel` addresses the flow id returned by the pool start route and follows the [pool publication contract](providers/openai-accounts.md#pool-login-policy-and-cancellation). Per-account quota activation uses the existing `GET/PUT /api/settings` surface and `src/codex/quota-auto-refresh.ts`, keeping scheduled spending separate from credential/authentication mutation. Account ids are opaque handles and are serialized so the GUI can address an account; emails are masked and tokens are never serialized. New-account config commits add UI-managed selector bindings in the same config save; deletion deliberately retains existing bindings for fail-closed exact routing and re-add stability. Account mutations request catalog convergence only after config durability and expose only the boolean `catalogRefreshPending` completion projection. `showCodexCredits` is a default-off boolean in settings GET and successful PUT; partial PUT accepts a boolean and rolls back on persistence failure. See [credits exposure](providers/openai-accounts.md#display-only-codex-credits). | From 16f9410023cf5ac579f5eb72acdb268d42a2df04 Mon Sep 17 00:00:00 2001 From: JUN Date: Thu, 19 Nov 2026 10:33:48 +0900 Subject: [PATCH 23/23] test(combos): refuse remembered-admin sessions on suggestion routes The dashboard-session denial test covered only the raw admin token. Add enrolled and resumed remembered-admin sessions, which derive from the admin token, and assert 403 with config.json unchanged for the exclusion PUT and both suggestion saves (append, create) plus the policy read. Co-authored-by: Andrew (agent) --- tests/server/combo-suggestion-routes.test.ts | 53 ++++++++++++++++---- 1 file changed, 44 insertions(+), 9 deletions(-) diff --git a/tests/server/combo-suggestion-routes.test.ts b/tests/server/combo-suggestion-routes.test.ts index 628c207a04a..11ad3245087 100644 --- a/tests/server/combo-suggestion-routes.test.ts +++ b/tests/server/combo-suggestion-routes.test.ts @@ -4,7 +4,7 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { handleManagementAPI } from "../../src/server/management-api"; import { - initializeManagementAuthState, issueGuiSession, managementPrincipal, + createManagementSessionControl, initializeManagementAuthState, issueGuiSession, managementPrincipal, managementSessionIssuance, requireManagementAuth, } from "../../src/server/management-auth"; import { loadConfig, saveConfig } from "../../src/config"; @@ -35,11 +35,44 @@ afterEach(() => { removeTreeWithRetry(home); }); -async function dispatch(config: OcxConfig, path: string, method: string, body?: unknown, adminOnly = false) { +type ManagementState = ReturnType; +type Remembered = { state: ManagementState; headers: Record }; +const ORIGIN = "http://localhost:10100"; +const USER_AGENT = "combo-suggestion-fixture"; + +/** A remembered-admin dashboard session, freshly enrolled or resumed from its device cookie after a restart. */ +async function rememberedSession(config: OcxConfig, resumed: boolean): Promise { + let state = initializeManagementAuthState(config); + const enroll = new ManagementRequest(ORIGIN + "/api/session/remember", { + method: "POST", headers: { Origin: ORIGIN, "User-Agent": USER_AGENT, "X-OpenCodex-API-Key": state.token! }, + }); + const response = (await handleManagementAPI(enroll, new URL(enroll.url), config, {}, managementPrincipal(enroll, state, config)!, + createManagementSessionControl(state), { trustedLoopback: true, guiSessionIssuance: managementSessionIssuance(enroll, state) }))!; + expect(response.status).toBe(200); + const enrolled = await response.json() as { session: ReturnType; device: { proof: string } }; + const cookie = response.headers.get("Set-Cookie")!.split(";")[0]!; + let session = enrolled.session; + if (resumed) { + state = initializeManagementAuthState(config); + session = issueGuiSession(new ManagementRequest(ORIGIN + "/opencodex-session", { headers: { + Host: new URL(ORIGIN).host, Origin: ORIGIN, "User-Agent": USER_AGENT, Cookie: cookie, + "X-OpenCodex-Device-Proof": enrolled.device.proof, + } }), config, state); + } + expect(session?.issuance).toBe("remembered-admin"); + return { state, headers: { + "User-Agent": USER_AGENT, Cookie: cookie, "X-OpenCodex-API-Key": session!.token, + "X-OpenCodex-GUI-Origin": session!.browserOrigin, "X-OpenCodex-CSRF-Token": session!.csrfToken, + } }; +} + +async function dispatch(config: OcxConfig, path: string, method: string, body?: unknown, auth: "session" | "admin" | Remembered = "session") { const url = new URL(path, "http://localhost:10100"); - const state = initializeManagementAuthState(config); + const state = typeof auth === "object" ? auth.state : initializeManagementAuthState(config); const headers = new Headers({ Origin: url.origin, "content-type": "application/json" }); - if (adminOnly) { + if (typeof auth === "object") { + for (const [name, value] of Object.entries(auth.headers)) headers.set(name, value); + } else if (auth === "admin") { headers.set("X-OpenCodex-API-Key", state.token!); } else { const session = issueGuiSession(new ManagementRequest(url, { headers }), config, state)!; @@ -158,13 +191,15 @@ test.each([ ["PUT", "/api/combo-suggestions", { provider: "other", excluded: true }], ["POST", "/api/combo-suggestions/save", { id: "mix", mode: "append", targets: [paidTarget] }], ["POST", "/api/combo-suggestions/save", { id: "draft", mode: "create", targets: [paidTarget], allowMeteredTargets: true }], -] as const)("%s %s requires a dashboard session", async (method, path, body) => { +] as const)("%s %s requires a dashboard session; admin tokens and remembered-admin sessions are refused", async (method, path, body) => { const live = seedPaidSuggestion(); const before = onDisk(); - const denied = await dispatch(live, path, method, body, true); - expect(denied.status).toBe(403); - expect(await denied.json()).toEqual({ error: "dashboard session required" }); - expect(onDisk()).toEqual(before); + for (const auth of ["admin", await rememberedSession(live, false), await rememberedSession(live, true)] as const) { + const denied = await dispatch(live, path, method, body, auth); + expect(denied.status).toBe(403); + expect(await denied.json()).toEqual({ error: "dashboard session required" }); + expect(onDisk()).toEqual(before); + } expect((await dispatch(live, path, method, body)).status).toBe(200); });