From c03f8ea3de4833c41544ea7ee109a1efde20bf9f Mon Sep 17 00:00:00 2001 From: "Andrew (agent)" Date: Thu, 12 Nov 2026 23:56:28 -0500 Subject: [PATCH 01/11] WIP feat(gui): combos overview (route board) with inline strategy, switch and channel editor --- gui/src/app-routing.ts | 3 + gui/src/components/ComboWorkspace.tsx | 7 + gui/src/components/combo-workspace-types.ts | 2 + .../components/route-board/ChannelEditor.tsx | 148 +++++++++ .../components/route-board/ModelRouteRow.tsx | 100 ++++++ gui/src/components/route-board/QuotaLine.tsx | 46 +++ gui/src/components/route-board/RouteBoard.tsx | 131 ++++++++ .../components/route-board/StrategyMenu.tsx | 37 +++ gui/src/design/pages/route-board.css | 133 ++++++++ gui/src/design/theme.css | 1 + gui/src/i18n/de.ts | 37 +++ gui/src/i18n/en.ts | 37 +++ gui/src/i18n/fr.ts | 37 +++ gui/src/i18n/ja.ts | 37 +++ gui/src/i18n/ko.ts | 37 +++ gui/src/i18n/pt.ts | 37 +++ gui/src/i18n/ru.ts | 37 +++ gui/src/i18n/tr.ts | 37 +++ gui/src/i18n/vi.ts | 37 +++ gui/src/i18n/zh-TW.ts | 37 +++ gui/src/i18n/zh.ts | 37 +++ gui/src/pages/Combos.tsx | 175 ++++++++++- gui/src/pages/combos-view.ts | 14 + gui/src/pages/models-tab.ts | 4 +- gui/src/route-board-model.ts | 284 ++++++++++++++++++ 25 files changed, 1474 insertions(+), 18 deletions(-) create mode 100644 gui/src/components/route-board/ChannelEditor.tsx create mode 100644 gui/src/components/route-board/ModelRouteRow.tsx create mode 100644 gui/src/components/route-board/QuotaLine.tsx create mode 100644 gui/src/components/route-board/RouteBoard.tsx create mode 100644 gui/src/components/route-board/StrategyMenu.tsx create mode 100644 gui/src/design/pages/route-board.css create mode 100644 gui/src/pages/combos-view.ts create mode 100644 gui/src/route-board-model.ts diff --git a/gui/src/app-routing.ts b/gui/src/app-routing.ts index 1a92cf20bfe..7977c9d512b 100644 --- a/gui/src/app-routing.ts +++ b/gui/src/app-routing.ts @@ -99,6 +99,8 @@ export const DASHBOARD_TAB_HASHES = ["dashboard/providers", "dashboard/models"] export const MODELS_TAB_HASHES = ["models/combos", "models/routing", "models/compatibility"] as const; /** Action deep link that opens the editable JEV Auto template in the Combos tab. */ export const JEV_AUTO_CREATE_HASH = "models/combos/jev-auto"; +/** The full combo workspace, behind the Combos overview's "Advanced" entry. */ +export const COMBOS_ADVANCED_HASH = "models/combos/advanced"; /** JEV Auto deep link; a self-hosted `jev-decision` row rides along as `?decisionProvider=`. */ export function jevAutoCreateHash(decisionProvider?: string | null): string { @@ -184,6 +186,7 @@ export function hashBelongsToPage(rawHash: string, page: Page): boolean { || (page === "models" && ( (MODELS_TAB_HASHES as readonly string[]).includes(rawHash) || rawHash === JEV_AUTO_CREATE_HASH + || rawHash === COMBOS_ADVANCED_HASH )) || (page === "dashboard" && (rawHash === DASHBOARD_UPDATE_HASH || (DASHBOARD_TAB_HASHES as readonly string[]).includes(rawHash))) diff --git a/gui/src/components/ComboWorkspace.tsx b/gui/src/components/ComboWorkspace.tsx index 32ac369178b..d047e6ffaf6 100644 --- a/gui/src/components/ComboWorkspace.tsx +++ b/gui/src/components/ComboWorkspace.tsx @@ -37,6 +37,7 @@ export default function ComboWorkspace({ addDecisionProvider, onCloseAdd, onCreated, + selectRequest, }: ComboWorkspaceProps) { const t = useT(); const providerMap = useMemo( @@ -109,6 +110,12 @@ export default function ComboWorkspace({ setPendingSelect(id); }, [activeId, detailDirty]); + const [seenSelectSeq, setSeenSelectSeq] = useState(selectRequest?.seq); + if (selectRequest && selectRequest.seq !== seenSelectSeq) { + setSeenSelectSeq(selectRequest.seq); + trySelect(selectRequest.id); + } + const confirmDiscard = () => { if (pendingSelect === undefined) return; setSelectedId(pendingSelect); diff --git a/gui/src/components/combo-workspace-types.ts b/gui/src/components/combo-workspace-types.ts index d2b613dd7f5..a0244bc5846 100644 --- a/gui/src/components/combo-workspace-types.ts +++ b/gui/src/components/combo-workspace-types.ts @@ -49,4 +49,6 @@ export interface ComboWorkspaceProps { addDecisionProvider?: string | null; onCloseAdd: () => void; onCreated: (id: string) => void; + /** Select this combo when `seq` changes (the overview's "open in Advanced"); dirty drafts still prompt. */ + selectRequest?: { id: string; seq: number }; } diff --git a/gui/src/components/route-board/ChannelEditor.tsx b/gui/src/components/route-board/ChannelEditor.tsx new file mode 100644 index 00000000000..cfb6ba8dc2c --- /dev/null +++ b/gui/src/components/route-board/ChannelEditor.tsx @@ -0,0 +1,148 @@ +import { useState, type DragEvent } from "react"; +import { COMBO_TARGETS_HINT_KEYS, type ComboStrategy } from "../../combo-workspace-data"; +import { useT } from "../../i18n/shared"; +import { formatProviderDisplayName } from "../../provider-icons"; +import { channelKey, moveChannel, type ChannelQuota, type RouteChannel } from "../../route-board-model"; +import { Select } from "../../ui"; +import { ProviderIcon } from "../provider-workspace/ProviderRail"; +import type { ModelOption, ProviderOption } from "../combo-workspace-types"; +import { QuotaLine } from "./QuotaLine"; + +export type EditableChannel = Pick; + +/** + * Inline channel editor under an expanded row: reorder (drag, or the move buttons from the + * keyboard), mark last resort, remove, add. Nothing is written until Save. + */ +export function ChannelEditor({ + comboModel, + strategy, + channels: initial, + quotaFor, + providers, + models, + lastResortActive, + saving, + onSave, + onCancel, + onOpenAdvanced, +}: { + comboModel: string; + strategy: ComboStrategy; + channels: readonly EditableChannel[]; + quotaFor: (provider: string) => ChannelQuota; + providers: readonly ProviderOption[]; + models: readonly ModelOption[]; + /** The combo defers last-resort channels (`cooldownWaitPolicy`); otherwise the mark is inert. */ + lastResortActive: boolean; + saving: boolean; + onSave: (channels: EditableChannel[]) => void; + onCancel: () => void; + onOpenAdvanced: () => void; +}) { + const t = useT(); + const [channels, setChannels] = useState(() => [...initial]); + const [dragIndex, setDragIndex] = useState(null); + const pickable = providers.filter((provider) => !provider.hiddenFromPicker); + const [addProvider, setAddProvider] = useState(() => pickable[0]?.name ?? ""); + const used = new Set(channels.map((channel) => channel.key)); + const addModels = models.filter((model) => model.provider === addProvider && !used.has(channelKey(model.provider, model.id))); + const [addModel, setAddModel] = useState(""); + const chosenModel = addModels.some((model) => model.id === addModel) ? addModel : addModels[0]?.id ?? ""; + const dirty = channels.length !== initial.length + || channels.some((channel, index) => channel.key !== initial[index]?.key || channel.lastResort !== initial[index]?.lastResort); + + const move = (from: number, to: number) => setChannels((list) => moveChannel(list, from, to)); + const onDrop = (event: DragEvent, to: number) => { + event.preventDefault(); + if (dragIndex !== null) move(dragIndex, to); + setDragIndex(null); + }; + const add = () => { + if (!addProvider || !chosenModel) return; + setChannels((list) => [...list, { key: channelKey(addProvider, chosenModel), provider: addProvider, model: chosenModel, lastResort: false }]); + }; + + return ( +
+
    + {channels.map((channel, index) => { + const name = `${formatProviderDisplayName(channel.provider, t)} ${channel.model}`; + return ( +
  1. setDragIndex(index)} + onDragEnd={() => setDragIndex(null)} + onDragOver={(event) => event.preventDefault()} + onDrop={(event) => onDrop(event, index)} + > + + {index + 1} + + + {formatProviderDisplayName(channel.provider, t)} + {channel.model} + + + + + + + + + + +
  2. + ); + })} +
+
+ 0 + ? addModels.map((model) => ({ value: model.id, label: model.id })) + : [{ value: "", label: t("routeBoard.edit.noModels"), disabled: true }]} + onChange={setAddModel} + /> + +
+

{t(COMBO_TARGETS_HINT_KEYS[strategy])}

+ {!lastResortActive && channels.some((channel) => channel.lastResort) && ( +

{t("routeBoard.edit.lastResortInert")}

+ )} +
+ + + {dirty && {t("routeBoard.edit.unsaved")}} + + +
+
+ ); +} diff --git a/gui/src/components/route-board/ModelRouteRow.tsx b/gui/src/components/route-board/ModelRouteRow.tsx new file mode 100644 index 00000000000..bc86883d965 --- /dev/null +++ b/gui/src/components/route-board/ModelRouteRow.tsx @@ -0,0 +1,100 @@ +import { useT } from "../../i18n/shared"; +import { formatProviderDisplayName } from "../../provider-icons"; +import { distinctProviderLabels, formatContextWindow, type RouteRow } from "../../route-board-model"; +import type { ComboStrategy } from "../../combo-workspace-data"; +import { Switch } from "../../ui"; +import { ProviderIcon } from "../provider-workspace/ProviderRail"; +import { QuotaLine } from "./QuotaLine"; +import { StrategyMenu } from "./StrategyMenu"; + +const MAX_STACKED_ICONS = 4; + +/** One combo: icons, name + public id, channel order, quota line, tags, context, strategy, switch. */ +export function ModelRouteRow({ + row, + expanded, + busy, + message, + onToggleExpanded, + onStrategy, + onEnabled, + children, +}: { + row: RouteRow; + expanded: boolean; + busy: boolean; + message: string | null; + onToggleExpanded: () => void; + onStrategy: (next: ComboStrategy) => void; + onEnabled: (next: boolean) => void; + children?: React.ReactNode; +}) { + const t = useT(); + const separator = row.combo.strategy === "failover" ? "→" : "·"; + const providers = [...new Set(row.channels.map((channel) => channel.provider))]; + const labels = distinctProviderLabels(providers, (provider) => formatProviderDisplayName(provider, t)); + const offChannels = row.channels.filter((channel) => channel.providerDisabled).length; + const panelId = `rb-panel-${row.combo.id}`; + return ( +
  • +
    + +
    + {offChannels > 0 && {t("routeBoard.tag.channelsOff", { count: offChannels })}} + {row.combo.strategy === "round-robin" && row.combo.stickyLimit > 1 && ( + {t("routeBoard.tag.sticky", { count: row.combo.stickyLimit })} + )} + {row.combo.imageInput === "disabled" && {t("routeBoard.tag.noImages")}} + {row.contextWindow !== undefined && ( + + {t("routeBoard.context", { size: formatContextWindow(row.contextWindow) })} + + )} + + onEnabled(!row.enabled)} + /> +
    +
    + {message &&

    {message}

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

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

    + ); +} diff --git a/gui/src/components/route-board/RouteBoard.tsx b/gui/src/components/route-board/RouteBoard.tsx new file mode 100644 index 00000000000..7113634d36a --- /dev/null +++ b/gui/src/components/route-board/RouteBoard.tsx @@ -0,0 +1,131 @@ +import { useState } from "react"; +import type { ComboDraftError, ComboItem, ComboStrategy } from "../../combo-workspace-data"; +import { useT } from "../../i18n/shared"; +import { + buildRouteRows, + channelQuota, + quotaWindowsByProvider, + planStrategyChange, + type ComboCatalogMeta, + type RouteBoardProvider, +} from "../../route-board-model"; +import type { ModelOption, ProviderOption } from "../combo-workspace-types"; +import { ChannelEditor, type EditableChannel } from "./ChannelEditor"; +import { ModelRouteRow } from "./ModelRouteRow"; + +type SaveResult = { ok: boolean; error?: string }; + +export interface RouteBoardProps { + combos: readonly ComboItem[]; + catalog: Readonly>; + lastResort: Readonly>; + /** Combo ids that defer last-resort channels (`cooldownWaitPolicy: "before-last-resort"`). */ + lastResortActive: ReadonlySet; + providers: readonly (ProviderOption & RouteBoardProvider)[]; + models: readonly ModelOption[]; + quotaReports: unknown; + validate: (item: ComboItem) => ComboDraftError | null; + errorText: (code: ComboDraftError, item: ComboItem) => string; + onSave: (item: ComboItem, channels?: readonly EditableChannel[]) => Promise; + onSetEnabled: (id: string, enabled: boolean) => Promise; + /** Open the full workspace, optionally on one combo. */ + onOpenAdvanced: (id?: string, reason?: "jev") => void; +} + +/** Combos overview: one row per combo, inline strategy and on/off, click a row to edit its channels. */ +export function RouteBoard(props: RouteBoardProps) { + const t = useT(); + const [expanded, setExpanded] = useState(null); + const [busy, setBusy] = useState(null); + const [messages, setMessages] = useState>({}); + const rows = buildRouteRows({ + combos: props.combos, + catalog: props.catalog, + lastResort: props.lastResort, + providers: props.providers, + quotaReports: props.quotaReports, + }); + const reported = quotaWindowsByProvider(props.quotaReports); + const providerByName = new Map(props.providers.map((provider) => [provider.name, provider])); + + const setMessage = (id: string, text: string | null) => setMessages((current) => { + const next = { ...current }; + if (text) next[id] = text; else delete next[id]; + return next; + }); + + const run = async (id: string, work: () => Promise): Promise => { + setBusy(id); + setMessage(id, null); + try { + const result = await work(); + if (!result.ok) setMessage(id, result.error ?? t("cws.saveFailed")); + return result.ok; + } finally { + setBusy(null); + } + }; + + const changeStrategy = (combo: ComboItem, next: ComboStrategy) => { + const plan = planStrategyChange(combo, next, props.validate); + if (plan.kind === "unchanged") return; + if (plan.kind === "open-advanced") return props.onOpenAdvanced(combo.id, "jev"); + if (plan.kind === "invalid") return setMessage(combo.id, t("routeBoard.notSaved", { reason: props.errorText(plan.error, plan.item) })); + void run(combo.id, () => props.onSave(plan.item)); + }; + + const saveChannels = async (combo: ComboItem, channels: EditableChannel[]) => { + const targets = channels.map((channel) => { + const existing = combo.targets.find((target) => target.provider === channel.provider && target.model === channel.model); + return existing ?? { provider: channel.provider, model: channel.model }; + }); + const item = { ...combo, targets }; + const error = props.validate(item); + if (error) return setMessage(combo.id, t("routeBoard.notSaved", { reason: props.errorText(error, item) })); + if (await run(combo.id, () => props.onSave(item, channels))) setExpanded(null); + }; + + if (rows.length === 0) { + return ( +
    +

    {t("routeBoard.empty")}

    + +
    + ); + } + + return ( +
      + {rows.map((row) => ( + setExpanded((current) => current === row.combo.id ? null : row.combo.id)} + onStrategy={(next) => changeStrategy(row.combo, next)} + onEnabled={(next) => void run(row.combo.id, () => props.onSetEnabled(row.combo.id, next))} + > + channelQuota( + providerByName.get(provider), + reported.get(provider), + row.channels.filter((channel) => channel.provider === provider).map((channel) => channel.model), + )} + providers={props.providers} + models={props.models} + lastResortActive={props.lastResortActive.has(row.combo.id)} + saving={busy === row.combo.id} + onSave={(channels) => void saveChannels(row.combo, channels)} + onCancel={() => setExpanded(null)} + onOpenAdvanced={() => props.onOpenAdvanced(row.combo.id)} + /> + + ))} +
    + ); +} diff --git a/gui/src/components/route-board/StrategyMenu.tsx b/gui/src/components/route-board/StrategyMenu.tsx new file mode 100644 index 00000000000..f297274071b --- /dev/null +++ b/gui/src/components/route-board/StrategyMenu.tsx @@ -0,0 +1,37 @@ +import { COMBO_STRATEGY_HINT_KEYS, COMBO_STRATEGY_LABEL_KEYS, type ComboStrategy } from "../../combo-workspace-data"; +import { useT } from "../../i18n/shared"; +import { ROUTE_BOARD_STRATEGIES } from "../../route-board-model"; +import { Select } from "../../ui"; + +/** Row strategy picker: every option carries its one-line explanation; the trigger shows the name. */ +export function StrategyMenu({ value, label, disabled, onChange }: { + value: ComboStrategy; + label: string; + disabled?: boolean; + onChange: (next: ComboStrategy) => void; +}) { + const t = useT(); + const options = ROUTE_BOARD_STRATEGIES.map((strategy) => ({ + value: strategy, + textValue: t(COMBO_STRATEGY_LABEL_KEYS[strategy]), + label: ( + + {t(COMBO_STRATEGY_LABEL_KEYS[strategy])} + {t(COMBO_STRATEGY_HINT_KEYS[strategy])} + + ), + })); + return ( + setCapability((current) => ({ ...current, capabilityPolicy: next as CapabilityPolicy }))} + /> + {capability.capabilityPolicy === "union" && ( + <> + {t("routeBoard.cap.unservable")} + setCapability((current) => ({ ...current, capabilityPolicy: next as CapabilityPolicy }))} - /> - {capability.capabilityPolicy === "union" && ( - <> - {t("routeBoard.cap.unservable")} - setCapability((current) => ({ ...current, capabilityPolicy: next as CapabilityPolicy }))} + /> + + {policy === "union" && ( +
    +
    + {t("routeBoard.cap.unservable")} + {t(capability.onUnservable === "reject" ? "routeBoard.cap.rejectHint" : "routeBoard.cap.degradeHint")} +
    + set({ context: event.target.value })} + /> + +
    + {t("routeBoard.members.input")} + + {MODALITIES.map((modality) => ( + + ))} + +
    +
    + {t("routeBoard.members.efforts")} + + {REASONING_EFFORT_LEVELS.map((level) => ( + + ))} + +
    +

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

    +

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

    + {editing.error &&

    {editing.error}

    } +
    + + {Object.keys(restore).length > 0 && ( + + )} + + + +
    +
    + + , + ]; + })} + + + + {t("routeBoard.members.combo")} + + {combo.context ? formatContextWindow(combo.context) : t("routeBoard.members.unknown")} + {combo.basis !== "catalog" && {t(combo.basis === "max" ? "routeBoard.contextBasis.max" : "routeBoard.contextBasis.min")}} + + {listText(combo.modalities, modalityWord)} + {listText(combo.efforts)} + + + + + ); +} diff --git a/gui/src/components/route-board/RouteBoard.tsx b/gui/src/components/route-board/RouteBoard.tsx index 819113126b9..4d56ef024b9 100644 --- a/gui/src/components/route-board/RouteBoard.tsx +++ b/gui/src/components/route-board/RouteBoard.tsx @@ -17,6 +17,7 @@ import { } from "../../route-board-model"; import type { ModelOption, ProviderOption } from "../combo-workspace-types"; import { ChannelEditor, type EditableChannel } from "./ChannelEditor"; +import type { SaveMemberModel } from "./MemberTable"; import { ModelRouteRow } from "./ModelRouteRow"; type SaveResult = { ok: boolean; error?: string }; @@ -44,6 +45,8 @@ export interface RouteBoardProps { onOpenAdvanced: (id?: string, reason?: "jev") => void; /** Combo with an unsaved draft in the advanced editor: read-only here until it is saved there. */ lockedId?: string | null; + /** Writes one member model's per-provider settings from the editor's member table. */ + onSaveModel?: SaveMemberModel; } /** Combos overview: one row per combo, inline strategy and on/off, click a row to edit its channels. */ @@ -148,6 +151,7 @@ export function RouteBoard(props: RouteBoardProps) { capability={props.capability?.[row.combo.id] ?? DEFAULT_CAPABILITY_SETTINGS} saving={busy === row.combo.id || props.lockedId === row.combo.id} onSave={(channels, settings) => void saveChannels(row.combo, channels, settings)} + onSaveModel={props.onSaveModel} onCancel={() => setExpanded(null)} /> diff --git a/gui/src/design/pages/route-board.css b/gui/src/design/pages/route-board.css index 052e721bab9..74c49de3671 100644 --- a/gui/src/design/pages/route-board.css +++ b/gui/src/design/pages/route-board.css @@ -162,3 +162,20 @@ .rb-members tbody th { color: var(--ocx-fg); } .rb-members tfoot th, .rb-members tfoot td { color: var(--ocx-fg); font-weight: 600; border-bottom: 0; } .rb-members-basis { color: var(--ocx-fg-subtle); font-weight: 400; } +.rb-members-model { display: block; font-size: 11.5px; color: var(--ocx-fg-subtle); font-weight: 400; } +.rb-members-actions { text-align: right; white-space: nowrap; } +.rb-src { display: inline-block; margin-left: 4px; padding: 0 5px; border-radius: 4px; font-size: 11px; line-height: 16px; color: var(--ocx-fg-subtle); background: var(--ocx-surface-2); } +.rb-src--manual { color: var(--ocx-accent); } +.rb-src--inferred { color: var(--ocx-warning); } +.rb-src--unknown { opacity: .7; } +.rb-members-editrow td { padding-top: 0; } +.rb-member-edit { display: flex; flex-direction: column; gap: 8px; padding: 10px 12px; border: 1px solid var(--ocx-line); border-radius: 8px; } +.rb-member-field { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; } +.rb-member-field > span:first-child { min-width: 84px; color: var(--ocx-fg-muted); font-size: 12.5px; } +.rb-member-field .input { max-width: 300px; } +.rb-chips { display: inline-flex; flex-wrap: wrap; gap: 6px; } +.rb-chip { padding: 2px 10px; border: 1px solid var(--ocx-line); border-radius: 999px; background: transparent; color: var(--ocx-fg-muted); font: inherit; font-size: 12.5px; cursor: pointer; } +.rb-chip[aria-pressed="true"] { border-color: var(--ocx-accent); color: var(--ocx-fg); background: var(--ocx-accent-soft); } +.rb-member-note { margin: 0; color: var(--ocx-fg-subtle); font-size: 12.5px; } +.rb-member-error { margin: 0; color: var(--ocx-danger); font-size: 12.5px; } +.rb-member-buttons { display: flex; align-items: center; gap: 8px; } diff --git a/gui/src/i18n/de.ts b/gui/src/i18n/de.ts index 82f76a264af..86e3b5ef15e 100644 --- a/gui/src/i18n/de.ts +++ b/gui/src/i18n/de.ts @@ -4553,4 +4553,18 @@ export const de: Record = { "routeBoard.members.combo": "Diese Combo", "routeBoard.contextBasis.min": "(kleinstes Mitglied)", "routeBoard.contextBasis.max": "(größtes Mitglied)", + "routeBoard.source.reported": "Anbieterangabe", + "routeBoard.source.inferred": "von gleichnamigem Modell abgeleitet", + "routeBoard.source.manual": "manuell", + "routeBoard.source.unknown": "unbekannt", + "routeBoard.members.actions": "Aktionen", + "routeBoard.members.edit": "Bearbeiten", + "routeBoard.members.editAria": "Bearbeiten, was {name} annimmt", + "routeBoard.members.contextPlaceholder": "z. B. 200K oder 1M; leer behält den Anbieterwert", + "routeBoard.members.contextInvalid": "Gib eine Tokenzahl ein, etwa 200000, 200K oder 1M.", + "routeBoard.members.scopeNote": "Wird bei {name} selbst gespeichert: Jede Kombination mit diesem Modell ändert sich mit.", + "routeBoard.members.restore": "Anbieterwerte verwenden", + "routeBoard.probe.run": "Testen", + "routeBoard.probe.note": "Der Test sendet diesem Anbieter eine kleine Anfrage; ein nutzungsbasierter Anbieter berechnet sie.", + "routeBoard.probe.pending": "Verfügbar, sobald die Backend-Prüfung ergänzt ist.", }; diff --git a/gui/src/i18n/en.ts b/gui/src/i18n/en.ts index e0bd5f05551..88f0e98122b 100644 --- a/gui/src/i18n/en.ts +++ b/gui/src/i18n/en.ts @@ -4587,6 +4587,20 @@ export const en = { "routeBoard.members.combo": "This combo", "routeBoard.contextBasis.min": "(smallest member)", "routeBoard.contextBasis.max": "(largest member)", + "routeBoard.source.reported": "provider report", + "routeBoard.source.inferred": "inferred from same-name model", + "routeBoard.source.manual": "manual", + "routeBoard.source.unknown": "unknown", + "routeBoard.members.actions": "Actions", + "routeBoard.members.edit": "Edit", + "routeBoard.members.editAria": "Edit what {name} can take", + "routeBoard.members.contextPlaceholder": "e.g. 200K or 1M; empty keeps the provider's value", + "routeBoard.members.contextInvalid": "Enter a token count such as 200000, 200K or 1M.", + "routeBoard.members.scopeNote": "Saved to {name} itself: every combo that uses this model changes too.", + "routeBoard.members.restore": "Use the provider's values", + "routeBoard.probe.run": "Test it", + "routeBoard.probe.note": "Testing sends this provider one small request; a pay-per-use provider bills it.", + "routeBoard.probe.pending": "Available once the backend probe is added.", } as const; export type TKey = keyof typeof en; diff --git a/gui/src/i18n/fr.ts b/gui/src/i18n/fr.ts index 735502c4895..22519aaf097 100644 --- a/gui/src/i18n/fr.ts +++ b/gui/src/i18n/fr.ts @@ -4542,4 +4542,18 @@ export const fr: Record = { "routeBoard.members.combo": "Cette combo", "routeBoard.contextBasis.min": "(plus petit membre)", "routeBoard.contextBasis.max": "(plus grand membre)", + "routeBoard.source.reported": "déclaré par le fournisseur", + "routeBoard.source.inferred": "déduit d'un modèle homonyme", + "routeBoard.source.manual": "saisi à la main", + "routeBoard.source.unknown": "inconnu", + "routeBoard.members.actions": "Actions possibles", + "routeBoard.members.edit": "Modifier", + "routeBoard.members.editAria": "Modifier ce que {name} accepte", + "routeBoard.members.contextPlaceholder": "ex. 200K ou 1M ; vide garde la valeur du fournisseur", + "routeBoard.members.contextInvalid": "Saisissez un nombre de jetons, par exemple 200000, 200K ou 1M.", + "routeBoard.members.scopeNote": "Enregistré sur {name} lui-même : chaque combo qui utilise ce modèle change aussi.", + "routeBoard.members.restore": "Reprendre les valeurs du fournisseur", + "routeBoard.probe.run": "Tester", + "routeBoard.probe.note": "Le test envoie une petite requête à ce fournisseur ; un fournisseur facturé à l'usage la facture.", + "routeBoard.probe.pending": "Disponible quand la sonde côté serveur sera ajoutée.", }; diff --git a/gui/src/i18n/ja.ts b/gui/src/i18n/ja.ts index fea6765fdd4..45c83c1dcbc 100644 --- a/gui/src/i18n/ja.ts +++ b/gui/src/i18n/ja.ts @@ -4575,4 +4575,18 @@ export const ja: Record = { "routeBoard.members.combo": "このコンボ", "routeBoard.contextBasis.min": "(最小メンバー)", "routeBoard.contextBasis.max": "(最大メンバー)", + "routeBoard.source.reported": "プロバイダー報告", + "routeBoard.source.inferred": "同名モデルから推定", + "routeBoard.source.manual": "手動", + "routeBoard.source.unknown": "不明", + "routeBoard.members.actions": "操作", + "routeBoard.members.edit": "編集", + "routeBoard.members.editAria": "{name} が受け付ける内容を編集", + "routeBoard.members.contextPlaceholder": "例: 200K、1M。空欄ならプロバイダーの値のまま", + "routeBoard.members.contextInvalid": "200000、200K、1M のようにトークン数を入力してください。", + "routeBoard.members.scopeNote": "{name} 自体に保存されます。このモデルを使うすべてのコンボが変わります。", + "routeBoard.members.restore": "プロバイダーの値に戻す", + "routeBoard.probe.run": "テストする", + "routeBoard.probe.note": "テストではこのプロバイダーに小さなリクエストを 1 回送ります。従量課金のプロバイダーでは課金されます。", + "routeBoard.probe.pending": "バックエンドの検出機能が追加されると使えます。", }; diff --git a/gui/src/i18n/ko.ts b/gui/src/i18n/ko.ts index 270362822eb..0dde629e714 100644 --- a/gui/src/i18n/ko.ts +++ b/gui/src/i18n/ko.ts @@ -4575,4 +4575,18 @@ export const ko: Record = { "routeBoard.members.combo": "이 콤보", "routeBoard.contextBasis.min": "(가장 작은 멤버)", "routeBoard.contextBasis.max": "(가장 큰 멤버)", + "routeBoard.source.reported": "제공자 보고", + "routeBoard.source.inferred": "같은 이름 모델에서 추정", + "routeBoard.source.manual": "수동", + "routeBoard.source.unknown": "알 수 없음", + "routeBoard.members.actions": "작업", + "routeBoard.members.edit": "편집", + "routeBoard.members.editAria": "{name}이(가) 받는 항목 편집", + "routeBoard.members.contextPlaceholder": "예: 200K, 1M. 비우면 제공자 값 유지", + "routeBoard.members.contextInvalid": "200000, 200K, 1M처럼 토큰 수를 입력하세요.", + "routeBoard.members.scopeNote": "{name} 자체에 저장됩니다. 이 모델을 쓰는 모든 콤보가 함께 바뀝니다.", + "routeBoard.members.restore": "제공자 값 사용", + "routeBoard.probe.run": "테스트", + "routeBoard.probe.note": "테스트는 이 제공자에 작은 요청을 한 번 보냅니다. 종량제 제공자는 요금이 부과됩니다.", + "routeBoard.probe.pending": "백엔드 탐지 기능이 추가되면 사용할 수 있습니다.", }; diff --git a/gui/src/i18n/pt.ts b/gui/src/i18n/pt.ts index fb05fd487b1..3978b9b912b 100644 --- a/gui/src/i18n/pt.ts +++ b/gui/src/i18n/pt.ts @@ -4548,4 +4548,18 @@ export const pt: Record = { "routeBoard.members.combo": "Esta combo", "routeBoard.contextBasis.min": "(menor membro)", "routeBoard.contextBasis.max": "(maior membro)", + "routeBoard.source.reported": "informado pelo provedor", + "routeBoard.source.inferred": "inferido de modelo homônimo", + "routeBoard.source.manual": "manual", + "routeBoard.source.unknown": "desconhecido", + "routeBoard.members.actions": "Ações", + "routeBoard.members.edit": "Editar", + "routeBoard.members.editAria": "Editar o que {name} aceita", + "routeBoard.members.contextPlaceholder": "ex.: 200K ou 1M; vazio mantém o valor do provedor", + "routeBoard.members.contextInvalid": "Informe uma contagem de tokens, como 200000, 200K ou 1M.", + "routeBoard.members.scopeNote": "Salvo no próprio {name}: todo combo que usa este modelo muda junto.", + "routeBoard.members.restore": "Usar os valores do provedor", + "routeBoard.probe.run": "Testar", + "routeBoard.probe.note": "O teste envia uma pequena solicitação a este provedor; um provedor pago por uso cobra por ela.", + "routeBoard.probe.pending": "Disponível quando a sondagem do backend for adicionada.", }; diff --git a/gui/src/i18n/ru.ts b/gui/src/i18n/ru.ts index 630d9f0f5d4..94cc4c9407d 100644 --- a/gui/src/i18n/ru.ts +++ b/gui/src/i18n/ru.ts @@ -4576,4 +4576,18 @@ export const ru: Record = { "routeBoard.members.combo": "Это комбо", "routeBoard.contextBasis.min": "(наименьший участник)", "routeBoard.contextBasis.max": "(наибольший участник)", + "routeBoard.source.reported": "данные провайдера", + "routeBoard.source.inferred": "выведено из одноимённой модели", + "routeBoard.source.manual": "вручную", + "routeBoard.source.unknown": "неизвестно", + "routeBoard.members.actions": "Действия", + "routeBoard.members.edit": "Изменить", + "routeBoard.members.editAria": "Изменить, что принимает {name}", + "routeBoard.members.contextPlaceholder": "напр. 200K или 1M; пусто — значение провайдера", + "routeBoard.members.contextInvalid": "Введите число токенов, например 200000, 200K или 1M.", + "routeBoard.members.scopeNote": "Сохраняется в самой модели {name}: меняются все комбо, где она используется.", + "routeBoard.members.restore": "Вернуть значения провайдера", + "routeBoard.probe.run": "Проверить", + "routeBoard.probe.note": "Проверка отправляет провайдеру один небольшой запрос; провайдер с оплатой за использование его тарифицирует.", + "routeBoard.probe.pending": "Станет доступно, когда появится проверка на сервере.", }; diff --git a/gui/src/i18n/tr.ts b/gui/src/i18n/tr.ts index 15dbe7648b9..1ae5b47e4b3 100644 --- a/gui/src/i18n/tr.ts +++ b/gui/src/i18n/tr.ts @@ -4576,4 +4576,18 @@ export const tr: Record = { "routeBoard.members.combo": "Bu kombo", "routeBoard.contextBasis.min": "(en küçük üye)", "routeBoard.contextBasis.max": "(en büyük üye)", + "routeBoard.source.reported": "sağlayıcı bildirdi", + "routeBoard.source.inferred": "aynı adlı modelden çıkarıldı", + "routeBoard.source.manual": "elle", + "routeBoard.source.unknown": "bilinmiyor", + "routeBoard.members.actions": "İşlemler", + "routeBoard.members.edit": "Düzenle", + "routeBoard.members.editAria": "{name} modelinin kabul ettiklerini düzenle", + "routeBoard.members.contextPlaceholder": "örn. 200K veya 1M; boş bırakılırsa sağlayıcı değeri kalır", + "routeBoard.members.contextInvalid": "200000, 200K veya 1M gibi bir token sayısı girin.", + "routeBoard.members.scopeNote": "{name} modelinin kendisine kaydedilir: bu modeli kullanan her kombo da değişir.", + "routeBoard.members.restore": "Sağlayıcı değerlerini kullan", + "routeBoard.probe.run": "Test et", + "routeBoard.probe.note": "Test bu sağlayıcıya küçük bir istek gönderir; kullanıma göre ücretlendiren sağlayıcı bunu faturalar.", + "routeBoard.probe.pending": "Arka uç yoklaması eklendiğinde kullanılabilir.", }; diff --git a/gui/src/i18n/vi.ts b/gui/src/i18n/vi.ts index 318bf66c8de..20489ba063d 100644 --- a/gui/src/i18n/vi.ts +++ b/gui/src/i18n/vi.ts @@ -4545,4 +4545,18 @@ export const vi: Record = { "routeBoard.members.combo": "Combo này", "routeBoard.contextBasis.min": "(thành viên nhỏ nhất)", "routeBoard.contextBasis.max": "(thành viên lớn nhất)", + "routeBoard.source.reported": "nhà cung cấp báo", + "routeBoard.source.inferred": "suy ra từ mô hình cùng tên", + "routeBoard.source.manual": "thủ công", + "routeBoard.source.unknown": "không rõ", + "routeBoard.members.actions": "Thao tác", + "routeBoard.members.edit": "Sửa", + "routeBoard.members.editAria": "Sửa những gì {name} nhận", + "routeBoard.members.contextPlaceholder": "vd. 200K hoặc 1M; để trống giữ giá trị của nhà cung cấp", + "routeBoard.members.contextInvalid": "Nhập số token, ví dụ 200000, 200K hoặc 1M.", + "routeBoard.members.scopeNote": "Lưu vào chính {name}: mọi combo dùng mô hình này đều thay đổi theo.", + "routeBoard.members.restore": "Dùng giá trị của nhà cung cấp", + "routeBoard.probe.run": "Kiểm tra", + "routeBoard.probe.note": "Kiểm tra gửi một yêu cầu nhỏ tới nhà cung cấp này; nhà cung cấp tính phí theo lượt sẽ tính phí.", + "routeBoard.probe.pending": "Dùng được khi phần dò ở máy chủ được thêm vào.", }; diff --git a/gui/src/i18n/zh-TW.ts b/gui/src/i18n/zh-TW.ts index 7e2413ad458..2eb456335ae 100644 --- a/gui/src/i18n/zh-TW.ts +++ b/gui/src/i18n/zh-TW.ts @@ -4539,4 +4539,18 @@ export const zhTW: Record = { "routeBoard.members.combo": "這個組合", "routeBoard.contextBasis.min": "(最小成員)", "routeBoard.contextBasis.max": "(最大成員)", + "routeBoard.source.reported": "提供方回報", + "routeBoard.source.inferred": "同名模型推斷", + "routeBoard.source.manual": "手動", + "routeBoard.source.unknown": "未知", + "routeBoard.members.actions": "操作", + "routeBoard.members.edit": "修改", + "routeBoard.members.editAria": "修改 {name} 能接收的內容", + "routeBoard.members.contextPlaceholder": "例如 200K、1M;留空則用提供方的值", + "routeBoard.members.contextInvalid": "請輸入 token 數,例如 200000、200K 或 1M。", + "routeBoard.members.scopeNote": "改的是 {name} 這個模型本身:所有用到它的組合都會跟著變。", + "routeBoard.members.restore": "恢復提供方的值", + "routeBoard.probe.run": "測一下", + "routeBoard.probe.note": "測一下會向這個提供方發一次很小的請求;按量計費的提供方會收這次的錢。", + "routeBoard.probe.pending": "後端探測介面上線後可用。", }; diff --git a/gui/src/i18n/zh.ts b/gui/src/i18n/zh.ts index d4de0ad4808..80607665076 100644 --- a/gui/src/i18n/zh.ts +++ b/gui/src/i18n/zh.ts @@ -4574,4 +4574,18 @@ export const zh: Record = { "routeBoard.members.combo": "这个组合", "routeBoard.contextBasis.min": "(最小成员)", "routeBoard.contextBasis.max": "(最大成员)", + "routeBoard.source.reported": "提供方报告", + "routeBoard.source.inferred": "同名模型推断", + "routeBoard.source.manual": "手动", + "routeBoard.source.unknown": "未知", + "routeBoard.members.actions": "操作", + "routeBoard.members.edit": "修改", + "routeBoard.members.editAria": "修改 {name} 能接收的内容", + "routeBoard.members.contextPlaceholder": "例如 200K、1M;留空则用提供方的值", + "routeBoard.members.contextInvalid": "请输入 token 数,例如 200000、200K 或 1M。", + "routeBoard.members.scopeNote": "改的是 {name} 这个模型本身:所有用到它的组合都会跟着变。", + "routeBoard.members.restore": "恢复提供方的值", + "routeBoard.probe.run": "测一下", + "routeBoard.probe.note": "测一下会向这个提供方发一次很小的请求;按量计费的提供方会收这次的钱。", + "routeBoard.probe.pending": "后端探测接口上线后可用。", }; diff --git a/gui/src/pages/Combos.tsx b/gui/src/pages/Combos.tsx index 1f7f6c8a860..047f2c95a54 100644 --- a/gui/src/pages/Combos.tsx +++ b/gui/src/pages/Combos.tsx @@ -29,10 +29,13 @@ import { accountCountFromList, channelKey, channelTargetsForPut, + capabilitySource, + configuredMemberModels, parseCapabilitySettings, type AccountCount, type ComboCapabilitySettings, type ComboCatalogMeta, + type MemberSources, type ComboSettingsPatch, } from "../route-board-model"; import { readCombosView, type CombosView } from "./combos-view"; @@ -56,6 +59,7 @@ type ModelOption = { inputModalitiesDeclared?: string[]; visionSidecarConsumer?: boolean; contextWindow?: number; + sources?: MemberSources; }; type ProviderDto = { adapter: string; @@ -77,6 +81,8 @@ type CachedCombosPage = { lastResort?: Record; lastResortActive?: string[]; capability?: Record; + /** Catalog models plus configured-only members, for the route board's member table. */ + memberModels?: ModelOption[]; }; type ProviderQuotasDto = { reports?: unknown }; @@ -252,6 +258,8 @@ export default function Combos({ })); const models: ModelOption[] = []; + /** Where each catalog member's capability values come from; only the route board reads it. */ + const sourcesByKey = new Map(); const capabilityModels: ModelOption[] = []; const catalogued = new Set(); const comboCatalog: Record = {}; @@ -276,6 +284,11 @@ export default function Combos({ inputModalities?: unknown; inputModalitiesDeclared?: unknown; visionSidecarConsumer?: unknown; + contextWindowDeclared?: unknown; + reasoningOverridden?: unknown; + contextWindowSource?: unknown; + inputModalitiesSource?: unknown; + reasoningEffortsSource?: unknown; }; if (typeof model.provider !== "string" || typeof model.id !== "string") continue; const provider = model.provider.trim(); @@ -309,6 +322,11 @@ export default function Combos({ visionSidecarConsumer: model.visionSidecarConsumer === true, ...(typeof model.contextWindow === "number" && model.contextWindow > 0 ? { contextWindow: model.contextWindow } : {}), }; + sourcesByKey.set(channelKey(provider, id), { + context: capabilitySource(typeof model.contextWindow === "number", typeof model.contextWindowDeclared === "number", model.contextWindowSource), + input: capabilitySource(Boolean(inputModalities?.length), Boolean(inputModalitiesDeclared?.length), model.inputModalitiesSource), + efforts: capabilitySource(reasoningEfforts !== undefined, model.reasoningOverridden === true, model.reasoningEffortsSource), + }); capabilityModels.push(option); models.push(option); // Catalog visibility does not restrict internal Combo selection. } @@ -322,7 +340,25 @@ export default function Combos({ } } - const next = { combos, providers, models, capabilityModels, cataloguedComboIds: [...catalogued], comboCatalog, lastResort, lastResortActive, capability } satisfies CachedCombosPage; + const catalogKeys = new Set(models.map((model) => channelKey(model.provider, model.id))); + const memberModels = [ + ...models.map((model) => { + const sources = sourcesByKey.get(channelKey(model.provider, model.id)); + return sources ? { ...model, sources } : model; + }), + ...configuredMemberModels(allProviders) + .filter((member) => !catalogKeys.has(channelKey(member.provider, member.id))) + .map((member): ModelOption => ({ + provider: member.provider, + id: member.id, + namespaced: `${member.provider}/${member.id}`, + ...(member.contextWindow ? { contextWindow: member.contextWindow } : {}), + ...(member.inputModalities ? { inputModalities: [...member.inputModalities] } : {}), + ...(member.reasoningEfforts ? { reasoningEfforts: [...member.reasoningEfforts] } : {}), + ...(member.sources ? { sources: member.sources } : {}), + })), + ]; + const next = { combos, providers, models, capabilityModels, cataloguedComboIds: [...catalogued], comboCatalog, lastResort, lastResortActive, capability, memberModels } satisfies CachedCombosPage; writeSessionListCacheEntry(cacheKey, next); // Retain the coherent payload here — one place, on the success path, never during // render. See the `retainedData` note below. @@ -502,6 +538,29 @@ export default function Combos({ } }; + /** + * One member model's per-provider settings (context, input, effort levels), the same write the + * Models page's settings dialog makes. Every combo using that model sees the change. + */ + const saveModelSettings = async (provider: string, modelId: string, patch: Record) => { + try { + const res = await fetch(`${apiBase}/api/model-settings`, { + method: "PUT", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ provider, modelId, ...patch }), + }); + const body = await res.json().catch(() => null) as unknown; + const receipt = body && typeof body === "object" ? body as { ok?: unknown; provider?: unknown; modelId?: unknown } : {}; + if (!res.ok || receipt.ok !== true || receipt.provider !== provider || receipt.modelId !== modelId) { + return responseError(body) || t("cws.saveFailed"); + } + resource.refresh(); + return null; + } catch { + return t("cws.saveFailed"); + } + }; + const setComboEnabled = async (id: string, enabled: boolean) => { try { const res = await putModelVisibility(apiBase, "models", "combo", [{ id }], enabled); @@ -613,7 +672,7 @@ export default function Combos({ lastResort={data?.lastResort ?? {}} lastResortActive={new Set(data?.lastResortActive ?? [])} providers={providers} - models={models} + models={data?.memberModels ?? models} quotaReports={quotaReports} validate={validateOverviewEdit} errorText={(code, item) => comboDraftErrorText(t, code, item, providerRows)} @@ -623,6 +682,7 @@ export default function Combos({ onSetEnabled={setComboEnabled} onOpenAdvanced={openAdvanced} lockedId={draftComboId} + onSaveModel={saveModelSettings} /> )} {workspaceMounted && ( diff --git a/gui/src/route-board-model.ts b/gui/src/route-board-model.ts index 4a07ab96299..bb0b44090a7 100644 --- a/gui/src/route-board-model.ts +++ b/gui/src/route-board-model.ts @@ -67,10 +67,117 @@ export interface ProviderQuotaLine { } /** What the catalog says one member can take. */ +/** + * Where a member capability value comes from: the provider's own report, a same-name model + * elsewhere in the catalog (T4c), the operator's per-model setting, or nowhere. + */ +export type CapabilitySource = "reported" | "inferred" | "manual" | "unknown"; + +export interface MemberSources { + context: CapabilitySource; + input: CapabilitySource; + efforts: CapabilitySource; +} + export interface MemberFacts { contextWindow?: number; inputModalities?: readonly string[]; reasoningEfforts?: readonly string[]; + sources?: MemberSources; +} + +/** + * Source of one capability field on a `/api/models` row. A manual flag wins; an explicit + * `inferred` source (the T4c backend names it) comes next; any other present value is the + * provider's report. + */ +export function capabilitySource(hasValue: boolean, manual: boolean, declaredSource?: unknown): CapabilitySource { + if (manual) return "manual"; + if (declaredSource === "inferred") return "inferred"; + return hasValue ? "reported" : "unknown"; +} + +/** + * Members the catalog has no row for (a provider whose model list was never fetched) still have + * whatever the operator set per model in config. Those values are manual by definition. + */ +export function configuredMemberModels(providers: Readonly>): MemberModel[] { + const out = new Map(); + const strings = (value: unknown) => Array.isArray(value) ? value.filter((v): v is string => typeof v === "string") : undefined; + const entry = (provider: string, id: string) => { + const key = channelKey(provider, id); + const found = out.get(key) ?? { provider, id, sources: { context: "unknown", input: "unknown", efforts: "unknown" } }; + out.set(key, found); + return found as MemberModel & { sources: MemberSources }; + }; + for (const [provider, raw] of Object.entries(providers)) { + if (!raw || typeof raw !== "object") continue; + const config = raw as { modelContextWindows?: unknown; modelReasoningEfforts?: unknown; modelCapabilities?: unknown }; + for (const [id, tokens] of Object.entries((config.modelContextWindows ?? {}) as Record)) { + if (typeof tokens !== "number" || tokens <= 0) continue; + const member = entry(provider, id); + member.contextWindow = tokens; + member.sources.context = "manual"; + } + for (const [id, ladder] of Object.entries((config.modelReasoningEfforts ?? {}) as Record)) { + const list = strings(ladder); + if (!list) continue; + const member = entry(provider, id); + member.reasoningEfforts = list; + member.sources.efforts = "manual"; + } + for (const [id, capabilities] of Object.entries((config.modelCapabilities ?? {}) as Record)) { + const list = strings((capabilities as { inputModalities?: unknown } | null)?.inputModalities); + if (!list) continue; + const member = entry(provider, id); + member.inputModalities = list; + member.sources.input = "manual"; + } + } + return [...out.values()]; +} + +/** Context typed by an operator: "200000", "200K", "1M", "1.5m". Undefined when it is not a positive whole token count. */ +export function parseContextInput(text: string): number | undefined { + const match = /^\s*(\d+(?:\.\d+)?)\s*([km]?)\s*$/i.exec(text.replace(/[,_]/g, "")); + if (!match) return undefined; + const unit = match[2]!.toLowerCase(); + const tokens = Math.round(Number(match[1]) * (unit === "m" ? 1_000_000 : unit === "k" ? 1_000 : 1)); + return Number.isSafeInteger(tokens) && tokens > 0 ? tokens : undefined; +} + +export interface MemberDraft { + context: string; + input: readonly string[]; + efforts: readonly string[]; +} + +/** Only the fields the operator changed, in the shape `PUT /api/model-settings` takes. */ +export function memberSettingsPatch(current: MemberFacts, draft: MemberDraft, order: readonly string[]): + { patch: Record; invalid?: "context" } { + const patch: Record = {}; + const contextText = draft.context.trim(); + if (contextText) { + const tokens = parseContextInput(contextText); + if (tokens === undefined) return { patch, invalid: "context" }; + if (tokens !== current.contextWindow) patch.contextWindow = tokens; + } + const same = (a: readonly string[] | undefined, b: readonly string[]) => + (a ?? []).length === b.length && b.every((value) => (a ?? []).includes(value)); + if (!same(current.inputModalities, draft.input)) patch.inputModalities = [...draft.input]; + if (!same(current.reasoningEfforts, draft.efforts)) { + patch.reasoningEfforts = order.filter((level) => draft.efforts.includes(level)); + } + return { patch }; +} + +/** Clears every per-model setting the operator made, so the provider's own values apply again. */ +export function memberRestorePatch(sources: MemberSources | undefined): Record { + return { + ...(sources?.context === "manual" ? { contextWindow: null } : {}), + ...(sources?.input === "manual" ? { inputModalities: null } : {}), + ...(sources?.efforts === "manual" ? { reasoningEfforts: null } : {}), + }; } export interface MemberModel extends MemberFacts { @@ -391,6 +498,26 @@ export function moveChannel(list: readonly T[], from: number, to: number): T[ return next; } +/** Pointer must pass a row's midpoint by this much before the drop slot changes. */ +export const DRAG_HYSTERESIS_PX = 8; + +/** + * Drop slot for a dragged row, from the pointer's Y against the rows' midpoints as they were when + * the drag started. The rows that make room move on screen, but these midpoints do not, so the + * slot cannot flip back and forth as rows slide under a still pointer. `current` adds hysteresis: + * the slot changes only once the pointer is clearly past the midpoint that separates the two. + */ +export function dragSlot(startMids: readonly number[], from: number, y: number, current: number): number { + const others = startMids.filter((_, index) => index !== from); + const slotAt = (pointer: number) => others.filter((mid) => mid < pointer).length; + const next = slotAt(y); + if (next === current) return current; + // Moving down past others[current], or up past others[current - 1]: require the margin. + const boundary = next > current ? others[current] : others[current - 1]; + if (boundary === undefined) return next; + return Math.abs(y - boundary) >= DRAG_HYSTERESIS_PX ? next : current; +} + /** `PUT /api/combos` target list for an edited channel list: `lastResort` sent explicitly. */ export function channelTargetsForPut( putTargets: readonly T[], diff --git a/gui/tests/route-board.test.tsx b/gui/tests/route-board.test.tsx index 03fff7486b1..ab98c29e24f 100644 --- a/gui/tests/route-board.test.tsx +++ b/gui/tests/route-board.test.tsx @@ -12,7 +12,13 @@ import { accountCountFromList, buildRouteRows, capabilityPatch, + capabilitySource, combineLists, + configuredMemberModels, + dragSlot, + memberRestorePatch, + memberSettingsPatch, + parseContextInput, comboContextWindow, parseCapabilitySettings, quotaFamilyWindow, @@ -235,6 +241,10 @@ function installFetch() { const method = init?.method ?? "GET"; if (method !== "GET") { calls.push({ url, method, body: init?.body ? JSON.parse(String(init.body)) : undefined }); + if (url.endsWith("/api/model-settings")) { + const sent = JSON.parse(String(init!.body)) as { provider: string; modelId: string }; + return Response.json({ ok: true, provider: sent.provider, modelId: sent.modelId, changed: true, hasOverrides: true, saved: true, catalogRefresh: { status: "skipped" } }); + } return Response.json(url.endsWith("/api/combos") ? { success: true } : { ok: true }); } if (url.endsWith("/api/combos")) return Response.json(combosPayload); @@ -249,7 +259,7 @@ function installFetch() { } if (url.endsWith("/api/models")) { return Response.json([ - { provider: "openai", id: "gpt-5" }, + { provider: "openai", id: "gpt-5", contextWindow: 400000, reasoningEfforts: ["low", "high"], reasoningOverridden: true }, { provider: "anthropic", id: "claude" }, { provider: "dead", id: "m" }, { provider: "combo", id: "alpha", displayName: "Alpha", displayNameSource: "provider", contextWindow: 200000, disabled: false }, @@ -395,18 +405,77 @@ describe("Combos overview page", () => { ]); }); - test("dragging reorders live, before the drop", async () => { + test("dragging moves the other rows aside from frozen midpoints and commits on drop", async () => { await renderPage(); await act(async () => { row("alpha").querySelector(".rb-row-toggle")!.click(); }); const editor = row("alpha").querySelector(".rb-editor")!; const names = () => [...editor.querySelectorAll(".rb-channel code")].map(node => node.textContent); const items = () => editor.querySelectorAll(".rb-channel"); + // Rows 40px tall at 0 and 40; the list starts at 0. Layout is frozen at drag start. + items().forEach((item, index) => { + item.getBoundingClientRect = () => ({ top: index * 40, height: 40, bottom: index * 40 + 40, left: 0, right: 0, width: 0, x: 0, y: index * 40, toJSON: () => ({}) }) as DOMRect; + }); + const over = (clientY: number) => { + const event = new testWindow.Event("dragover", { bubbles: true, cancelable: true }) as unknown as Event; + Object.defineProperty(event, "clientY", { value: clientY }); + editor.querySelector(".rb-channels")!.dispatchEvent(event); + }; await act(async () => { items()[0]!.dispatchEvent(new testWindow.Event("dragstart", { bubbles: true }) as unknown as Event); }); - await act(async () => { items()[1]!.dispatchEvent(new testWindow.Event("dragover", { bubbles: true, cancelable: true }) as unknown as Event); }); + await act(async () => { over(55); }); // short of the other row's midpoint (60): no move + expect(names()).toEqual(["gpt-5", "claude"]); + await act(async () => { over(70); }); + expect(names()).toEqual(["claude", "gpt-5"]); + await act(async () => { over(56); }); // back inside the hysteresis band: stays put + expect(names()).toEqual(["claude", "gpt-5"]); + expect(editor.textContent).not.toContain("Unsaved"); + await act(async () => { editor.querySelector(".rb-channels")!.dispatchEvent(new testWindow.Event("drop", { bubbles: true, cancelable: true }) as unknown as Event); }); expect(names()).toEqual(["claude", "gpt-5"]); expect(editor.textContent).toContain("Unsaved"); }); + test("member table: source tags per cell, and an in-place edit writes the provider's model settings", async () => { + await renderPage(); + await act(async () => { row("alpha").querySelector(".rb-tag--button")!.click(); }); + const editor = row("alpha").querySelector(".rb-editor")!; + const gpt = [...editor.querySelectorAll(".rb-members tbody tr")].find(tr => tr.textContent?.includes("gpt-5"))!; + expect([...gpt.querySelectorAll(".rb-src")].map(tag => tag.textContent)).toEqual(["provider report", "unknown", "manual"]); + expect(gpt.textContent).not.toContain("unknown unknown"); + await act(async () => { button(gpt, "Edit what OpenAI (Codex login) gpt-5 can take").click(); }); + const form = editor.querySelector(".rb-member-edit")!; + expect(form.textContent).toContain("every combo that uses this model changes too"); + expect(form.textContent).toContain("pay-per-use provider bills it"); + expect(button(form, "Test it").disabled).toBe(true); + const input = form.querySelector("input")!; + const setValue = Object.getOwnPropertyDescriptor(testWindow.HTMLInputElement.prototype, "value")!.set!; + await act(async () => { + setValue.call(input, "nonsense"); + input.dispatchEvent(new testWindow.Event("input", { bubbles: true }) as unknown as Event); + }); + await act(async () => { button(form, "Save").click(); }); + expect(form.querySelector("[role=alert]")?.textContent).toContain("200K"); + expect(calls).toEqual([]); + await act(async () => { + setValue.call(input, "1M"); + input.dispatchEvent(new testWindow.Event("input", { bubbles: true }) as unknown as Event); + }); + await act(async () => { button(form, "images").click(); }); + await act(async () => { button(form, "Save").click(); }); + await flush(); + expect(calls).toEqual([{ url: "/api/model-settings", method: "PUT", body: { provider: "openai", modelId: "gpt-5", contextWindow: 1000000, inputModalities: ["image"] } }]); + expect(editor.querySelector(".rb-member-edit")).toBeNull(); + }); + + test("restoring a member sends null only for the fields set by hand", async () => { + await renderPage(); + await act(async () => { row("alpha").querySelector(".rb-tag--button")!.click(); }); + const editor = row("alpha").querySelector(".rb-editor")!; + const gpt = [...editor.querySelectorAll(".rb-members tbody tr")].find(tr => tr.textContent?.includes("gpt-5"))!; + await act(async () => { button(gpt, "Edit what OpenAI (Codex login) gpt-5 can take").click(); }); + await act(async () => { button(editor.querySelector(".rb-member-edit")!, "Use the provider's values").click(); }); + await flush(); + expect(calls[0]!.body).toEqual({ provider: "openai", modelId: "gpt-5", reasoningEfforts: null }); + }); + test("the context tag opens More settings in place, with the members' numbers", async () => { await renderPage(); await act(async () => { row("alpha").querySelector(".rb-tag--button")!.click(); }); @@ -469,3 +538,87 @@ describe("Combos overview page", () => { expect(host.querySelector("#cwi-edit-alias")?.value).toBe("draft-alias"); }); }); + +describe("drag slot", () => { + const mids = (count: number) => Array.from({ length: count }, (_, index) => index * 40 + 20); + /** Runs a pointer path and returns every slot change, like dragover events would. */ + const sweep = (count: number, from: number, path: number[]) => { + const start = mids(count); + let slot = from; + const changes: number[] = []; + for (const y of path) { + const next = dragSlot(start, from, y, slot); + if (next !== slot) { changes.push(next); slot = next; } + } + return { slot, changes }; + }; + const range = (from: number, to: number, step: number) => { + const out: number[] = []; + for (let y = from; step > 0 ? y <= to : y >= to; y += step) out.push(y); + return out; + }; + + for (const count of [4, 6]) { + test(`${count} rows: a slow drag to the last place passes each slot once`, () => { + const result = sweep(count, 0, range(20, count * 40, 1)); + expect(result.slot).toBe(count - 1); + expect(result.changes).toEqual(Array.from({ length: count - 1 }, (_, index) => index + 1)); + }); + test(`${count} rows: a slow drag back to the first place passes each slot once`, () => { + const result = sweep(count, count - 1, range(count * 40 - 20, 0, -1)); + expect(result.slot).toBe(0); + expect(result.changes).toEqual(Array.from({ length: count - 1 }, (_, index) => count - 2 - index)); + }); + test(`${count} rows: a fast drag lands on the first and the last place`, () => { + expect(sweep(count, count - 1, [count * 40 - 20, -10]).slot).toBe(0); + expect(sweep(count, 0, [20, count * 40 + 30]).slot).toBe(count - 1); + }); + test(`${count} rows: a pointer jittering on a boundary changes the slot at most once`, () => { + const boundary = mids(count)[2]!; + const jitter = Array.from({ length: 40 }, (_, index) => boundary + (index % 2 === 0 ? 3 : -3)); + expect(sweep(count, 0, [20, boundary - 10, ...jitter]).changes.length).toBeLessThanOrEqual(2); + }); + } + + test("moving back past the start returns the row to its own place", () => { + expect(sweep(4, 1, [60, 140, 60]).slot).toBe(1); + }); +}); + +describe("member capability edits", () => { + test("context input accepts plain numbers and K/M suffixes", () => { + expect(parseContextInput("200000")).toBe(200000); + expect(parseContextInput("200K")).toBe(200000); + expect(parseContextInput("1m")).toBe(1000000); + expect(parseContextInput("1.5M")).toBe(1500000); + expect(parseContextInput("1,000,000")).toBe(1000000); + expect(parseContextInput("big")).toBeUndefined(); + expect(parseContextInput("0")).toBeUndefined(); + }); + + test("only changed fields are patched; unknown lists left empty stay unknown", () => { + const order = ["none", "minimal", "low", "medium", "high", "xhigh", "max"]; + expect(memberSettingsPatch({ contextWindow: 200000 }, { context: "200K", input: [], efforts: [] }, order)).toEqual({ patch: {} }); + expect(memberSettingsPatch({ reasoningEfforts: ["high"] }, { context: "", input: ["text"], efforts: ["high", "low"] }, order)) + .toEqual({ patch: { inputModalities: ["text"], reasoningEfforts: ["low", "high"] } }); + expect(memberSettingsPatch({}, { context: "lots", input: [], efforts: [] }, order).invalid).toBe("context"); + }); + + test("a member with no catalog row still shows its per-model config, tagged manual", () => { + expect(configuredMemberModels({ + zed: { modelContextWindows: { m: 400000 }, modelCapabilities: { m: { inputModalities: ["text"] } } }, + other: { modelReasoningEfforts: { n: ["low"] } }, + })).toEqual([ + { provider: "zed", id: "m", contextWindow: 400000, inputModalities: ["text"], sources: { context: "manual", input: "manual", efforts: "unknown" } }, + { provider: "other", id: "n", reasoningEfforts: ["low"], sources: { context: "unknown", input: "unknown", efforts: "manual" } }, + ]); + }); + + test("sources: manual wins, an explicit inferred source next, else the provider's report", () => { + expect(capabilitySource(true, true, "inferred")).toBe("manual"); + expect(capabilitySource(true, false, "inferred")).toBe("inferred"); + expect(capabilitySource(true, false)).toBe("reported"); + expect(capabilitySource(false, false)).toBe("unknown"); + expect(memberRestorePatch({ context: "manual", input: "reported", efforts: "manual" })).toEqual({ contextWindow: null, reasoningEfforts: null }); + }); +}); diff --git a/structure/dashboard-and-usage.md b/structure/dashboard-and-usage.md index e1e6e62b76c..5e5987912b7 100644 --- a/structure/dashboard-and-usage.md +++ b/structure/dashboard-and-usage.md @@ -126,7 +126,7 @@ The sidebar exposes eight rows (`gui/src/nav-groups.ts` `NAV_GROUPS`), in order: | API keys | Key table plus per-key detail (`gui/src/components/apikeys-workspace/`). The list payload carries masked prefixes only; each row deletes in place behind a two-step confirm, and clicking a key fetches the full value from `POST /api/keys/reveal`, which requires a current pairing or trusted Tailscale-identity session and answers `no-store`; automatic loopback sessions and raw admin tokens cannot reveal stored values, and a refusal there answers with the pairing surface — on the same-origin standalone transport the local pairing form, elsewhere the explanation alone — and requires a fresh reveal click after pairing. Displayed secrets and copy feedback are cleared on shared-session loss, pairing, inactive/hidden views, or a target change; stale asynchronous completions cannot restore them. | | Storage | Rail plus cleanup and trash detail (`gui/src/components/storage-workspace/`). | | Subagents | Featured-roster selection workspace (`gui/src/components/subagents-workspace/`). | -| Combos | `#models/combos` opens the overview (`gui/src/components/route-board/RouteBoard.tsx`, view model `gui/src/route-board-model.ts`): one row per combo with stacked provider icons, display name and public id, the channel order (`→` for failover, `·` otherwise, last-resort members marked), one quota line per provider from `/api/provider-quotas` (remaining percent, green above 50%, amber 20–50%, red below 20%; `key` providers read as pay per use), the catalog context window, an inline strategy menu and an on/off switch. Switched-off combos sort after the live ones. Antigravity pool windows read as family names (`Cla (Weekly)` → "Claude & GPT · weekly"). Account counts come from the report's `aggregation`, otherwise from `GET /api/oauth/accounts?provider=` for enabled OAuth providers (paused accounts listed separately). A strategy pick runs `validateComboDraft` and then the normal `PUT /api/combos`; JEV never saves from the row and opens the workspace on that combo instead, because an empty decision service means the hosted TypeSafe service. The switch writes the combo selector through `PUT /api/model-visibility` (`provider: "combo"`). Clicking a row opens the channel editor (reorder by drag, where the other rows make room live with a FLIP slide, or by move buttons; mark fallback only, i.e. `lastResort`; remove; add). Its "More settings" section opens in place: the capability policy, a "fallback channels wait their turn" switch that writes `cooldownWaitPolicy` (`"before-last-resort"` or `null`), and a read-only table of each member's context window, input modalities and effort levels with the combined row. The row's context tag opens that section and shows the smallest member under intersection and the largest under union (`comboContextWindow`); fallback-only marks render greyed with the reason while the combo has no `cooldownWaitPolicy`; only its save sends `lastResort` explicitly, every other save omits it so the server carries it over. Capability fields (`capabilityPolicy`, `onUnservable`) and `cooldownWaitPolicy` read absent as the defaults and are sent only when changed. "Advanced" opens the rail, detail panel and add flow (`gui/src/components/ComboWorkspace.tsx`) at `#models/combos/advanced`; `#models/combos/jev-auto` still lands there (`gui/src/pages/combos-view.ts`). The workspace stays mounted once opened, so an unsaved draft survives the overview, and the overview locks the strategy and channel save of the combo being drafted until the draft is saved or discarded. `gui/tests/route-board.test.tsx` covers the rows, PUT bodies, the JEV hand-off, validation, the switch selector, the channel save and the draft lock. | +| Combos | `#models/combos` opens the overview (`gui/src/components/route-board/RouteBoard.tsx`, view model `gui/src/route-board-model.ts`): one row per combo with stacked provider icons, display name and public id, the channel order (`→` for failover, `·` otherwise, last-resort members marked), one quota line per provider from `/api/provider-quotas` (remaining percent, green above 50%, amber 20–50%, red below 20%; `key` providers read as pay per use), the catalog context window, an inline strategy menu and an on/off switch. Switched-off combos sort after the live ones. Antigravity pool windows read as family names (`Cla (Weekly)` → "Claude & GPT · weekly"). Account counts come from the report's `aggregation`, otherwise from `GET /api/oauth/accounts?provider=` for enabled OAuth providers (paused accounts listed separately). A strategy pick runs `validateComboDraft` and then the normal `PUT /api/combos`; JEV never saves from the row and opens the workspace on that combo instead, because an empty decision service means the hosted TypeSafe service. The switch writes the combo selector through `PUT /api/model-visibility` (`provider: "combo"`). Clicking a row opens the channel editor (reorder by drag, where the other rows make room live with a FLIP slide, or by move buttons; mark fallback only, i.e. `lastResort`; remove; add). Its "More settings" section opens in place: the capability policy, a "fallback channels wait their turn" switch that writes `cooldownWaitPolicy` (`"before-last-resort"` or `null`), and a member table (`gui/src/components/route-board/MemberTable.tsx`) of each member's context window, input modalities and effort levels with the combined row. Every cell carries its source (`capabilitySource`: `contextWindowDeclared` / `inputModalitiesDeclared` / `reasoningOverridden` read as manual, an explicit `*Source: "inferred"` field as inferred, any other value as the provider's report, otherwise unknown); members with no `/api/models` row fall back to their per-model config (`configuredMemberModels`). A member edit sends only the changed fields to `PUT /api/model-settings` (`memberSettingsPatch`; restore sends `null` for the manual fields), validates the receipt, and refreshes the page; the probe button stays disabled until a backend probe exists. Drag reorder computes the drop slot from the row midpoints frozen at drag start with 8 px hysteresis (`dragSlot`) and commits on drop. The row's context tag opens that section and shows the smallest member under intersection and the largest under union (`comboContextWindow`); fallback-only marks render greyed with the reason while the combo has no `cooldownWaitPolicy`; only its save sends `lastResort` explicitly, every other save omits it so the server carries it over. Capability fields (`capabilityPolicy`, `onUnservable`) and `cooldownWaitPolicy` read absent as the defaults and are sent only when changed. "Advanced" opens the rail, detail panel and add flow (`gui/src/components/ComboWorkspace.tsx`) at `#models/combos/advanced`; `#models/combos/jev-auto` still lands there (`gui/src/pages/combos-view.ts`). The workspace stays mounted once opened, so an unsaved draft survives the overview, and the overview locks the strategy and channel save of the combo being drafted until the draft is saved or discarded. `gui/tests/route-board.test.tsx` covers the rows, PUT bodies, the JEV hand-off, validation, the switch selector, the channel save, drag sweeps over 4 and 6 rows, the member edit and restore bodies, and the draft lock. | | Add provider | Catalog browser plus form and OAuth panes (`gui/src/components/provider-catalog/`, `gui/src/components/AddProviderModal.tsx`). The catalog browses four tabs — Accounts, Free, Local, Paid — where Local is a catalog-only bucket peeled out of `bucketPresets` after `presetTier` has classified; the workspace `providerTier` stays three-way, so the rail, the free-paid sort and the Free count still treat a local runtime as free. Search sits above the tabs and reaches every tab at once: while a query is live the list renders all four groups with headings and the strip becomes jump chips with counts rather than a tablist, because moving the selected tab would change the row kind under the user (a preset-select button becomes a login row). ArrowDown from the search input focuses the first enabled result action; if none is available, focus stays in the input. The tab strip wraps within narrow modals. Every nonempty note has a full-text button so narrow rows never hide content permanently; the native note dialog closes during teardown and restores focus to its trigger. Provider notes clamp to two lines and open in full in a stacked native `` owned by `AddProviderModal`, which also owns the search text so its `window` Escape handler can unwind popup, then query, then dialog. | | Codex accounts | Account pool cards, add-account flow, switch and reset modals (`gui/src/components/CodexAccountPool.tsx`, `gui/src/components/AddCodexAccountModal.tsx`), plus the generic account-targeting picker opt-in on `gui/src/pages/codex-set-multiauth.tsx`. Add/delete/login completion is projected to one boolean before presentation; pending catalog work is a warning, not a failed account mutation. The main card's native-main device reauth (#3898) is owned by `gui/src/components/use-main-device-reauth.ts`: the dedicated `/api/codex-auth/main/reauth-device` namespace only — never the pool login route — with flowId-owned polling, an allowlisted verification URL, and no token fields accepted from payloads. The main-device reauth hook retains flow ownership from the Cancel click, while DELETE is unresolved and after retryable failure; polling normally continues. A concurrent GET HTTP error cannot expose a replacement login POST before DELETE settles. If a retryable DELETE failure races with a non-2xx GET while the flow is pending or committing, either response order preserves same-flow Cancel retry, restores the last server-provided device code, verification URL, and phase when needed, and keeps the existing poll cadence so a later terminal result remains observable. Outside same-flow cancellation ownership, a GET HTTP failure still stops polling without starting a second login POST. The cancellation-failure indication survives pending status updates until a trusted terminal result releases ownership. A successful DELETE with a terminal `failed` DTO releases it and uses the same closed failure-code mapping as polling; only `succeeded` notifies login completion. Unrecognized or nonterminal DTO status values remain retryable. A DELETE response with HTTP 404 and code `unknown_flow` releases the expired flow and shows the existing generic failure state so device re-login is available again; it claims neither login success nor confirmed cancellation. Confirmed cancellation also makes device re-login available. Start, polling and cancellation completions verify their controller or flow ownership after asynchronous response reads; replaced flows and unmounted hooks cannot update a newer flow or notify completion. Effect setup restores mounted state after the StrictMode development cleanup cycle. | | Dashboard overview | Overview, Providers, and Models tabs at the page level (`gui/src/pages/Dashboard.tsx`), the 30-day token and coverage stats in the overview head (`gui/src/pages/dashboard-overview-head.tsx`), and the effort-cap, injection, maintenance, sidecar, reasoning-retention, and memory panels below it (`gui/src/pages/dashboard-overview-panels.tsx`). The Reasoning retention controls (`gui/src/components/ReasoningRetentionPanel.tsx`) live in a collapsed Advanced settings disclosure at the end of Overview. They read and save `reasoningRetention` via GET/PUT `/api/settings` in `src/server/management/config-routes.ts`: only explicit `enabled: true` activates retention; absent, disabled, and legacy threshold-only settings remain off. The enable switch exposes numeric controls with defaults of 20% and 100000 tokens; disabling saves `enabled: false`, and null reset removes the setting and turns it off. Omission preserves it, validation precedes mutation, and save failure restores value and key presence. Copy warns that opt-in can preserve plaintext reasoning in local history/archive and that completed archives have no aggregate quota or expiry and require manual deletion. Loading disables writes, failures permit retry without losing edits, and stale responses cannot update a new API target. Its scope is the [routed v1/v2 compaction contract](transports/responses-failover.md#compaction-routing-overrides); opaque output stays unchanged. `tests/config/settings-reasoning-retention.test.ts` and `gui/tests/reasoning-retention-panel.test.tsx` cover the API and controls. Inputs expose invalid state and reference the validation alert only for the failing field. | From ce589968e5abe64f4eda81f466d7f45bfa47ddfa Mon Sep 17 00:00:00 2001 From: "Andrew (agent)" Date: Fri, 13 Nov 2026 03:16:12 -0500 Subject: [PATCH 09/11] feat(gui): route board round 4: server capability sources, inferred values with Adopt, live capability probe - Source tags read capabilitySources (manual / probed / reported / inferred / unknown) from /api/models, falling back to the manual flags on an older server. - A gap with an inferredCapabilities estimate shows the value and its basis, with Adopt writing it through PUT /api/model-settings. Estimates fill gaps only in the combined row, labelled. - Test it calls POST /api/providers/probe-capabilities with apply, confirms metered probes inline with the planned request count, and shows inapplicable reasons, 409, and an inconclusive baseline. Depends on #8674. --- docs-site/src/content/docs/guides/combos.md | 12 +- .../components/route-board/ChannelEditor.tsx | 16 +- .../components/route-board/MemberProbe.tsx | 93 +++++++ .../components/route-board/MemberTable.tsx | 245 +++++++++++++----- gui/src/components/route-board/RouteBoard.tsx | 3 + gui/src/design/pages/route-board.css | 5 + gui/src/i18n/de.ts | 35 ++- gui/src/i18n/en.ts | 35 ++- gui/src/i18n/fr.ts | 35 ++- gui/src/i18n/ja.ts | 35 ++- gui/src/i18n/ko.ts | 35 ++- gui/src/i18n/pt.ts | 35 ++- gui/src/i18n/ru.ts | 35 ++- gui/src/i18n/tr.ts | 35 ++- gui/src/i18n/vi.ts | 35 ++- gui/src/i18n/zh-TW.ts | 35 ++- gui/src/i18n/zh.ts | 35 ++- gui/src/pages/Combos.tsx | 50 +++- gui/src/route-board-model.ts | 123 ++++++++- gui/tests/route-board.test.tsx | 121 ++++++++- structure/dashboard-and-usage.md | 2 +- 21 files changed, 934 insertions(+), 121 deletions(-) create mode 100644 gui/src/components/route-board/MemberProbe.tsx diff --git a/docs-site/src/content/docs/guides/combos.md b/docs-site/src/content/docs/guides/combos.md index b973e094128..d0b12332cce 100644 --- a/docs-site/src/content/docs/guides/combos.md +++ b/docs-site/src/content/docs/guides/combos.md @@ -991,12 +991,16 @@ to clients. Click a row to reorder, add, remove, or mark channels fallback only **More settings** opens under the channels: the capability policy, a switch that makes fallback channels wait until nothing else works (`cooldownWaitPolicy: "before-last-resort"`), and each member's context window, input types and effort levels next to the combo's combined values. -Each value is tagged with where it comes from: the provider's report, a same-name model, a manual -setting, or unknown. **Edit** on a member changes that provider's per-model settings (the same +Each value is tagged with where it comes from: manual, probed, the provider's report, inferred from a +same-name model, or unknown. A missing value with a same-name estimate reads like "inferred 1M (based +on anthropic built-in table)"; **Adopt** saves it as a manual setting. Estimates never route: the +combined row counts them only when labelled "includes inferred". **Edit** on a member changes that provider's per-model settings (the same `PUT /api/model-settings` write as the Models page), so every combo using that model changes with it; context accepts `200000`, `200K` or `1M`. **Use the provider's values** clears what was set by -hand. **Test it** is reserved for a backend probe that sends one small request, which a pay-per-use -provider bills. Click the context tag on a row to open it directly. +hand. **Test it** calls `POST /api/providers/probe-capabilities` to check image input and effort levels +on that relay and saves conclusive results; for a pay-per-use provider it first asks, naming how many +small requests it will send. A failed plain request changes nothing. Context is inferred from the +model name, never probed. Click the context tag on a row to open it directly. **Advanced** opens the full workspace (`#models/combos/advanced`), which creates, edits, renames, and removes combos. Its model selectors include hidden models: catalog visibility only controls external model diff --git a/gui/src/components/route-board/ChannelEditor.tsx b/gui/src/components/route-board/ChannelEditor.tsx index 8015bdefbc3..7399a0b9301 100644 --- a/gui/src/components/route-board/ChannelEditor.tsx +++ b/gui/src/components/route-board/ChannelEditor.tsx @@ -8,6 +8,7 @@ import { combineLists, comboContextWindow, dragSlot, + withInferredGaps, memberFacts, moveChannel, type CapabilityPolicy, @@ -21,6 +22,7 @@ import { import { Select, Switch } from "../../ui"; import { ProviderIcon } from "../provider-workspace/ProviderRail"; import type { ModelOption, ProviderOption } from "../combo-workspace-types"; +import type { ProbeMemberModel } from "./MemberProbe"; import { MemberTable, type SaveMemberModel } from "./MemberTable"; import { QuotaLine } from "./QuotaLine"; @@ -86,6 +88,7 @@ export function ChannelEditor({ saving, onSave, onSaveModel, + onProbeModel, onCancel, }: { comboModel: string; @@ -107,6 +110,8 @@ export function ChannelEditor({ onSave: (channels: EditableChannel[], settings: ComboSettingsPatch) => void; /** Writes one member model's per-provider settings (shared by every combo using it). */ onSaveModel?: SaveMemberModel; + /** Probes what one member's relay accepts (image input, effort levels). */ + onProbeModel?: ProbeMemberModel; onCancel: () => void; }) { const t = useT(); @@ -180,9 +185,11 @@ export function ChannelEditor({ const facts = channels.map((channel) => memberFacts(models, channel.provider, channel.model)); const policy = capability.capabilityPolicy; - const context = comboContextWindow(facts, policy, catalogContext); - const modalities = combineLists(facts.map((fact) => fact.inputModalities), policy, MODALITY_ORDER); - const efforts = combineLists(facts.map((fact) => fact.reasoningEfforts), policy, COMBO_EFFORTS); + /** Estimates fill gaps in the combined row only, and the row says so; they never route. */ + const combined = withInferredGaps(facts); + const context = comboContextWindow(combined.members, policy, catalogContext); + const modalities = combineLists(combined.members.map((fact) => fact.inputModalities), policy, MODALITY_ORDER); + const efforts = combineLists(combined.members.map((fact) => fact.reasoningEfforts), policy, COMBO_EFFORTS); return (
    @@ -316,8 +323,9 @@ export function ChannelEditor({ channels={channels} facts={facts} labels={labels} - combo={{ context: context.tokens, basis: context.basis, modalities, efforts }} + combo={{ context: context.tokens, basis: context.basis, modalities, efforts, includesInferred: combined.used }} onSaveModel={onSaveModel} + onProbeModel={onProbeModel} />
    )} diff --git a/gui/src/components/route-board/MemberProbe.tsx b/gui/src/components/route-board/MemberProbe.tsx new file mode 100644 index 00000000000..a29b9ad1976 --- /dev/null +++ b/gui/src/components/route-board/MemberProbe.tsx @@ -0,0 +1,93 @@ +import { useEffect, useRef } from "react"; +import { useT } from "../../i18n/shared"; +import type { TKey } from "../../i18n/en"; +import type { ProbeOutcome } from "../../route-board-model"; + +/** Runs one capability probe; `confirmed` repeats it with the operator's consent to metered requests. */ +export type ProbeMemberModel = (provider: string, modelId: string, confirmed: boolean) => Promise; + +export type ProbeState = { phase: "running" } | { phase: "settled"; outcome: ProbeOutcome }; + +const REASON_KEYS: Record = { + disabled: "routeBoard.probe.reason.disabled", + forward_auth: "routeBoard.probe.reason.forward_auth", + oauth_auth: "routeBoard.probe.reason.oauth_auth", + unsupported_adapter: "routeBoard.probe.reason.unsupported_adapter", + unsupported_transport: "routeBoard.probe.reason.unsupported_transport", +}; + +const STATUS_KEYS: Record<"accepted" | "rejected" | "inconclusive", TKey> = { + accepted: "routeBoard.probe.accepted", + rejected: "routeBoard.probe.rejected", + inconclusive: "routeBoard.probe.inconclusive", +}; + +/** + * What a "Test it" press is doing or found, under the member's row. A metered provider asks first + * (with the number of requests), an inconclusive baseline changes nothing, and context is never + * probed: it comes from the model name. + */ +export function ProbeResult({ state, onConfirm, onDismiss }: { state: ProbeState; onConfirm: () => void; onDismiss: () => void }) { + const t = useT(); + const confirmRef = useRef(null); + const asking = state.phase === "settled" && state.outcome.kind === "confirm"; + useEffect(() => { if (asking) confirmRef.current?.focus(); }, [asking]); + + const body = (() => { + if (state.phase === "running") return

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

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

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

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

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

    ; + case "busy": + return

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

    ; + case "failed": + return

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

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

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

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

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

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

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

    -

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

    - {editing.error &&

    {editing.error}

    } -
    - - {Object.keys(restore).length > 0 && ( + const extra: ReactNode[] = []; + if (adoptError?.key === channel.key) { + extra.push( +

    {adoptError.message}

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

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

    + {editing.error &&

    {editing.error}

    } +
    + {Object.keys(restore).length > 0 && ( + + )} + - )} - - - + onClick={() => setEditing(null)}>{t("common.cancel")} + +
    - -
    {t("routeBoard.members.combo")} + {t("routeBoard.members.combo")} + {combo.includesInferred && {t("routeBoard.members.includesInferred")}} + {combo.context ? formatContextWindow(combo.context) : t("routeBoard.members.unknown")} {combo.basis !== "catalog" && {t(combo.basis === "max" ? "routeBoard.contextBasis.max" : "routeBoard.contextBasis.min")}} diff --git a/gui/src/components/route-board/RouteBoard.tsx b/gui/src/components/route-board/RouteBoard.tsx index 4d56ef024b9..7a8a22b656d 100644 --- a/gui/src/components/route-board/RouteBoard.tsx +++ b/gui/src/components/route-board/RouteBoard.tsx @@ -18,6 +18,7 @@ import { import type { ModelOption, ProviderOption } from "../combo-workspace-types"; import { ChannelEditor, type EditableChannel } from "./ChannelEditor"; import type { SaveMemberModel } from "./MemberTable"; +import type { ProbeMemberModel } from "./MemberProbe"; import { ModelRouteRow } from "./ModelRouteRow"; type SaveResult = { ok: boolean; error?: string }; @@ -47,6 +48,7 @@ export interface RouteBoardProps { lockedId?: string | null; /** Writes one member model's per-provider settings from the editor's member table. */ onSaveModel?: SaveMemberModel; + onProbeModel?: ProbeMemberModel; } /** Combos overview: one row per combo, inline strategy and on/off, click a row to edit its channels. */ @@ -152,6 +154,7 @@ export function RouteBoard(props: RouteBoardProps) { saving={busy === row.combo.id || props.lockedId === row.combo.id} onSave={(channels, settings) => void saveChannels(row.combo, channels, settings)} onSaveModel={props.onSaveModel} + onProbeModel={props.onProbeModel} onCancel={() => setExpanded(null)} /> diff --git a/gui/src/design/pages/route-board.css b/gui/src/design/pages/route-board.css index 74c49de3671..cc6ae92bbe2 100644 --- a/gui/src/design/pages/route-board.css +++ b/gui/src/design/pages/route-board.css @@ -179,3 +179,8 @@ .rb-member-note { margin: 0; color: var(--ocx-fg-subtle); font-size: 12.5px; } .rb-member-error { margin: 0; color: var(--ocx-danger); font-size: 12.5px; } .rb-member-buttons { display: flex; align-items: center; gap: 8px; } +.rb-inferred { color: var(--ocx-warning); font-size: 12.5px; } +.rb-adopt { margin-left: 4px; } +.rb-probe { display: flex; flex-direction: column; gap: 6px; padding: 8px 12px; border: 1px dashed var(--ocx-line); border-radius: 8px; } +.rb-probe-confirm { display: flex; flex-direction: column; gap: 6px; } +.rb-probe-results { margin: 0; padding-left: 18px; font-size: 12.5px; } diff --git a/gui/src/i18n/de.ts b/gui/src/i18n/de.ts index 86e3b5ef15e..c0233e60771 100644 --- a/gui/src/i18n/de.ts +++ b/gui/src/i18n/de.ts @@ -4565,6 +4565,37 @@ export const de: Record = { "routeBoard.members.scopeNote": "Wird bei {name} selbst gespeichert: Jede Kombination mit diesem Modell ändert sich mit.", "routeBoard.members.restore": "Anbieterwerte verwenden", "routeBoard.probe.run": "Testen", - "routeBoard.probe.note": "Der Test sendet diesem Anbieter eine kleine Anfrage; ein nutzungsbasierter Anbieter berechnet sie.", - "routeBoard.probe.pending": "Verfügbar, sobald die Backend-Prüfung ergänzt ist.", + "routeBoard.source.probed": "getestet", + "routeBoard.basis.registry": "integrierte Tabelle von {provider}", + "routeBoard.basis.vendor": "Modelldaten von {provider}", + "routeBoard.basis.provider": "konfigurierter Anbieter {provider}", + "routeBoard.basis.aggregator": "Katalog von {provider}", + "routeBoard.inferred.cell": "abgeleitet {value} (laut {basis})", + "routeBoard.inferred.adopt": "Übernehmen", + "routeBoard.inferred.adoptAria": "Abgeleiteten Wert {value} für {name} als manuelle Einstellung speichern", + "routeBoard.members.includesInferred": "enthält abgeleitete Werte", + "routeBoard.probe.runAria": "Testen, was {name} annimmt", + "routeBoard.probe.running": "Test läuft…", + "routeBoard.probe.confirmTitle": "Kostenpflichtigen Test bestätigen", + "routeBoard.probe.confirm": "Dieser Anbieter rechnet nach Nutzung ab: Der Test sendet {count} sehr kleine Anfragen. Fortfahren?", + "routeBoard.probe.confirmGo": "Test starten", + "routeBoard.probe.reason.disabled": "Kein Test möglich: Dieser Anbieter ist ausgeschaltet.", + "routeBoard.probe.reason.forward_auth": "Kein Test möglich: Dieser Anbieter leitet die Anmeldung des Clients weiter.", + "routeBoard.probe.reason.oauth_auth": "Kein Test möglich: Abo-Anmeldungen werden nicht getestet.", + "routeBoard.probe.reason.unsupported_adapter": "Kein Test möglich: Nur OpenAI-kompatible Endpunkte lassen sich testen.", + "routeBoard.probe.reason.unsupported_transport": "Kein Test möglich: Die Verbindungsart dieses Anbieters wird nicht unterstützt.", + "routeBoard.probe.reason.other": "Dieser Anbieter lässt sich nicht testen.", + "routeBoard.probe.busy": "Dieser Anbieter wird gerade getestet.", + "routeBoard.probe.failed": "Der Test wurde nicht abgeschlossen. Nichts wurde geändert.", + "routeBoard.probe.uncertain": "Unklar: Die einfache Anfrage kam nicht durch, daher wurde nichts geändert.", + "routeBoard.probe.image": "Bilder: {status}", + "routeBoard.probe.accepted": "angenommen", + "routeBoard.probe.rejected": "abgelehnt", + "routeBoard.probe.inconclusive": "unklar", + "routeBoard.probe.efforts": "Stufen angenommen: {accepted}; abgelehnt: {rejected}; unklar: {inconclusive}", + "routeBoard.probe.appliedInput": "gespeicherte Eingabe: {value}", + "routeBoard.probe.appliedEfforts": "gespeicherte Stufen: {value}", + "routeBoard.probe.nothingApplied": "Nichts eindeutig, daher nichts gespeichert.", + "routeBoard.probe.contextNote": "Der Kontext wird aus dem Modellnamen abgeleitet, nicht gemessen.", + "routeBoard.probe.close": "Schließen", }; diff --git a/gui/src/i18n/en.ts b/gui/src/i18n/en.ts index 88f0e98122b..45570e244f0 100644 --- a/gui/src/i18n/en.ts +++ b/gui/src/i18n/en.ts @@ -4599,8 +4599,39 @@ export const en = { "routeBoard.members.scopeNote": "Saved to {name} itself: every combo that uses this model changes too.", "routeBoard.members.restore": "Use the provider's values", "routeBoard.probe.run": "Test it", - "routeBoard.probe.note": "Testing sends this provider one small request; a pay-per-use provider bills it.", - "routeBoard.probe.pending": "Available once the backend probe is added.", + "routeBoard.source.probed": "probed", + "routeBoard.basis.registry": "{provider} built-in table", + "routeBoard.basis.vendor": "{provider} model metadata", + "routeBoard.basis.provider": "configured {provider}", + "routeBoard.basis.aggregator": "{provider} catalog", + "routeBoard.inferred.cell": "inferred {value} (based on {basis})", + "routeBoard.inferred.adopt": "Adopt", + "routeBoard.inferred.adoptAria": "Save the inferred {value} for {name} as a manual setting", + "routeBoard.members.includesInferred": "includes inferred", + "routeBoard.probe.runAria": "Test what {name} accepts", + "routeBoard.probe.running": "Testing…", + "routeBoard.probe.confirmTitle": "Confirm a paid test", + "routeBoard.probe.confirm": "This provider bills per use: the test sends {count} very small requests. Go ahead?", + "routeBoard.probe.confirmGo": "Run the test", + "routeBoard.probe.reason.disabled": "Can't test: this provider is turned off.", + "routeBoard.probe.reason.forward_auth": "Can't test: this provider forwards the client's own login.", + "routeBoard.probe.reason.oauth_auth": "Can't test: subscription logins are not probed.", + "routeBoard.probe.reason.unsupported_adapter": "Can't test: only OpenAI-compatible endpoints can be probed.", + "routeBoard.probe.reason.unsupported_transport": "Can't test: this provider's connection type is not supported.", + "routeBoard.probe.reason.other": "Can't test this provider.", + "routeBoard.probe.busy": "This provider is already being tested.", + "routeBoard.probe.failed": "The test did not finish. Nothing was changed.", + "routeBoard.probe.uncertain": "Inconclusive: the plain request did not go through, so nothing was changed.", + "routeBoard.probe.image": "Images: {status}", + "routeBoard.probe.accepted": "accepted", + "routeBoard.probe.rejected": "refused", + "routeBoard.probe.inconclusive": "unclear", + "routeBoard.probe.efforts": "Effort levels accepted: {accepted}; refused: {rejected}; unclear: {inconclusive}", + "routeBoard.probe.appliedInput": "saved input: {value}", + "routeBoard.probe.appliedEfforts": "saved effort levels: {value}", + "routeBoard.probe.nothingApplied": "Nothing conclusive, so nothing was saved.", + "routeBoard.probe.contextNote": "Context is inferred from the model name, not measured.", + "routeBoard.probe.close": "Close", } as const; export type TKey = keyof typeof en; diff --git a/gui/src/i18n/fr.ts b/gui/src/i18n/fr.ts index 22519aaf097..5b73c393ab8 100644 --- a/gui/src/i18n/fr.ts +++ b/gui/src/i18n/fr.ts @@ -4554,6 +4554,37 @@ export const fr: Record = { "routeBoard.members.scopeNote": "Enregistré sur {name} lui-même : chaque combo qui utilise ce modèle change aussi.", "routeBoard.members.restore": "Reprendre les valeurs du fournisseur", "routeBoard.probe.run": "Tester", - "routeBoard.probe.note": "Le test envoie une petite requête à ce fournisseur ; un fournisseur facturé à l'usage la facture.", - "routeBoard.probe.pending": "Disponible quand la sonde côté serveur sera ajoutée.", + "routeBoard.source.probed": "testé", + "routeBoard.basis.registry": "table intégrée de {provider}", + "routeBoard.basis.vendor": "métadonnées de {provider}", + "routeBoard.basis.provider": "fournisseur configuré {provider}", + "routeBoard.basis.aggregator": "catalogue de {provider}", + "routeBoard.inferred.cell": "déduit {value} (d'après {basis})", + "routeBoard.inferred.adopt": "Adopter", + "routeBoard.inferred.adoptAria": "Enregistrer la valeur déduite {value} pour {name} comme réglage manuel", + "routeBoard.members.includesInferred": "inclut des valeurs déduites", + "routeBoard.probe.runAria": "Tester ce que {name} accepte", + "routeBoard.probe.running": "Test en cours…", + "routeBoard.probe.confirmTitle": "Confirmer un test payant", + "routeBoard.probe.confirm": "Ce fournisseur facture à l'usage : le test envoie {count} toutes petites requêtes. Continuer ?", + "routeBoard.probe.confirmGo": "Lancer le test", + "routeBoard.probe.reason.disabled": "Test impossible : ce fournisseur est désactivé.", + "routeBoard.probe.reason.forward_auth": "Test impossible : ce fournisseur relaie la connexion du client.", + "routeBoard.probe.reason.oauth_auth": "Test impossible : les connexions par abonnement ne sont pas testées.", + "routeBoard.probe.reason.unsupported_adapter": "Test impossible : seuls les points d'accès compatibles OpenAI se testent.", + "routeBoard.probe.reason.unsupported_transport": "Test impossible : le type de connexion de ce fournisseur n'est pas pris en charge.", + "routeBoard.probe.reason.other": "Ce fournisseur ne peut pas être testé.", + "routeBoard.probe.busy": "Ce fournisseur est déjà en cours de test.", + "routeBoard.probe.failed": "Le test n'a pas abouti. Rien n'a été modifié.", + "routeBoard.probe.uncertain": "Résultat incertain : la requête simple n'est pas passée, rien n'a été modifié.", + "routeBoard.probe.image": "Images : {status}", + "routeBoard.probe.accepted": "acceptées", + "routeBoard.probe.rejected": "refusées", + "routeBoard.probe.inconclusive": "incertain", + "routeBoard.probe.efforts": "Niveaux acceptés : {accepted} ; refusés : {rejected} ; incertains : {inconclusive}", + "routeBoard.probe.appliedInput": "entrée enregistrée : {value}", + "routeBoard.probe.appliedEfforts": "niveaux enregistrés : {value}", + "routeBoard.probe.nothingApplied": "Rien de concluant, donc rien n'a été enregistré.", + "routeBoard.probe.contextNote": "Le contexte est déduit du nom du modèle, pas mesuré.", + "routeBoard.probe.close": "Fermer", }; diff --git a/gui/src/i18n/ja.ts b/gui/src/i18n/ja.ts index 45c83c1dcbc..59fcb80d7a4 100644 --- a/gui/src/i18n/ja.ts +++ b/gui/src/i18n/ja.ts @@ -4587,6 +4587,37 @@ export const ja: Record = { "routeBoard.members.scopeNote": "{name} 自体に保存されます。このモデルを使うすべてのコンボが変わります。", "routeBoard.members.restore": "プロバイダーの値に戻す", "routeBoard.probe.run": "テストする", - "routeBoard.probe.note": "テストではこのプロバイダーに小さなリクエストを 1 回送ります。従量課金のプロバイダーでは課金されます。", - "routeBoard.probe.pending": "バックエンドの検出機能が追加されると使えます。", + "routeBoard.source.probed": "実測", + "routeBoard.basis.registry": "{provider} の内蔵表", + "routeBoard.basis.vendor": "{provider} のモデル情報", + "routeBoard.basis.provider": "設定済みの {provider}", + "routeBoard.basis.aggregator": "{provider} のカタログ", + "routeBoard.inferred.cell": "推定 {value}(根拠: {basis})", + "routeBoard.inferred.adopt": "採用", + "routeBoard.inferred.adoptAria": "{name} の推定値 {value} を手動設定として保存", + "routeBoard.members.includesInferred": "推定値を含む", + "routeBoard.probe.runAria": "{name} が受け付けるものをテスト", + "routeBoard.probe.running": "テスト中…", + "routeBoard.probe.confirmTitle": "有料テストの確認", + "routeBoard.probe.confirm": "このプロバイダーは従量課金です。テストではごく小さなリクエストを {count} 回送ります。続けますか?", + "routeBoard.probe.confirmGo": "テストする", + "routeBoard.probe.reason.disabled": "テストできません: このプロバイダーはオフです。", + "routeBoard.probe.reason.forward_auth": "テストできません: このプロバイダーはクライアントのログインを転送します。", + "routeBoard.probe.reason.oauth_auth": "テストできません: サブスクリプションのログインはテストしません。", + "routeBoard.probe.reason.unsupported_adapter": "テストできません: OpenAI 互換のエンドポイントだけがテストできます。", + "routeBoard.probe.reason.unsupported_transport": "テストできません: このプロバイダーの接続方式には対応していません。", + "routeBoard.probe.reason.other": "このプロバイダーはテストできません。", + "routeBoard.probe.busy": "このプロバイダーはテスト中です。", + "routeBoard.probe.failed": "テストが完了しませんでした。何も変更していません。", + "routeBoard.probe.uncertain": "判定できません: 通常のリクエストが通らなかったため、何も変更していません。", + "routeBoard.probe.image": "画像: {status}", + "routeBoard.probe.accepted": "受け付け", + "routeBoard.probe.rejected": "拒否", + "routeBoard.probe.inconclusive": "不明", + "routeBoard.probe.efforts": "推論レベル 受け付け: {accepted}、拒否: {rejected}、不明: {inconclusive}", + "routeBoard.probe.appliedInput": "入力を保存: {value}", + "routeBoard.probe.appliedEfforts": "推論レベルを保存: {value}", + "routeBoard.probe.nothingApplied": "確かな結果がないため、何も保存していません。", + "routeBoard.probe.contextNote": "コンテキストはモデル名から推定し、実測しません。", + "routeBoard.probe.close": "閉じる", }; diff --git a/gui/src/i18n/ko.ts b/gui/src/i18n/ko.ts index 0dde629e714..5a75534040d 100644 --- a/gui/src/i18n/ko.ts +++ b/gui/src/i18n/ko.ts @@ -4587,6 +4587,37 @@ export const ko: Record = { "routeBoard.members.scopeNote": "{name} 자체에 저장됩니다. 이 모델을 쓰는 모든 콤보가 함께 바뀝니다.", "routeBoard.members.restore": "제공자 값 사용", "routeBoard.probe.run": "테스트", - "routeBoard.probe.note": "테스트는 이 제공자에 작은 요청을 한 번 보냅니다. 종량제 제공자는 요금이 부과됩니다.", - "routeBoard.probe.pending": "백엔드 탐지 기능이 추가되면 사용할 수 있습니다.", + "routeBoard.source.probed": "실측", + "routeBoard.basis.registry": "{provider} 내장 표", + "routeBoard.basis.vendor": "{provider} 모델 정보", + "routeBoard.basis.provider": "설정된 {provider}", + "routeBoard.basis.aggregator": "{provider} 카탈로그", + "routeBoard.inferred.cell": "추정 {value}(근거: {basis})", + "routeBoard.inferred.adopt": "채택", + "routeBoard.inferred.adoptAria": "{name}의 추정값 {value}을(를) 수동 설정으로 저장", + "routeBoard.members.includesInferred": "추정값 포함", + "routeBoard.probe.runAria": "{name}이(가) 받는 항목 테스트", + "routeBoard.probe.running": "테스트 중…", + "routeBoard.probe.confirmTitle": "유료 테스트 확인", + "routeBoard.probe.confirm": "이 제공자는 종량제입니다. 테스트는 아주 작은 요청을 {count}번 보냅니다. 계속할까요?", + "routeBoard.probe.confirmGo": "테스트 실행", + "routeBoard.probe.reason.disabled": "테스트 불가: 이 제공자는 꺼져 있습니다.", + "routeBoard.probe.reason.forward_auth": "테스트 불가: 이 제공자는 클라이언트 로그인을 그대로 전달합니다.", + "routeBoard.probe.reason.oauth_auth": "테스트 불가: 구독 로그인은 테스트하지 않습니다.", + "routeBoard.probe.reason.unsupported_adapter": "테스트 불가: OpenAI 호환 엔드포인트만 테스트할 수 있습니다.", + "routeBoard.probe.reason.unsupported_transport": "테스트 불가: 이 제공자의 연결 방식은 지원하지 않습니다.", + "routeBoard.probe.reason.other": "이 제공자는 테스트할 수 없습니다.", + "routeBoard.probe.busy": "이 제공자는 이미 테스트 중입니다.", + "routeBoard.probe.failed": "테스트가 끝나지 않았습니다. 아무것도 바꾸지 않았습니다.", + "routeBoard.probe.uncertain": "판단 불가: 기본 요청이 통과하지 못해 아무것도 바꾸지 않았습니다.", + "routeBoard.probe.image": "이미지: {status}", + "routeBoard.probe.accepted": "수락", + "routeBoard.probe.rejected": "거부", + "routeBoard.probe.inconclusive": "불확실", + "routeBoard.probe.efforts": "추론 단계 수락: {accepted}; 거부: {rejected}; 불확실: {inconclusive}", + "routeBoard.probe.appliedInput": "입력 저장: {value}", + "routeBoard.probe.appliedEfforts": "추론 단계 저장: {value}", + "routeBoard.probe.nothingApplied": "확실한 결과가 없어 아무것도 저장하지 않았습니다.", + "routeBoard.probe.contextNote": "컨텍스트는 모델 이름으로 추정하며 실측하지 않습니다.", + "routeBoard.probe.close": "닫기", }; diff --git a/gui/src/i18n/pt.ts b/gui/src/i18n/pt.ts index 3978b9b912b..c1eaa5af072 100644 --- a/gui/src/i18n/pt.ts +++ b/gui/src/i18n/pt.ts @@ -4560,6 +4560,37 @@ export const pt: Record = { "routeBoard.members.scopeNote": "Salvo no próprio {name}: todo combo que usa este modelo muda junto.", "routeBoard.members.restore": "Usar os valores do provedor", "routeBoard.probe.run": "Testar", - "routeBoard.probe.note": "O teste envia uma pequena solicitação a este provedor; um provedor pago por uso cobra por ela.", - "routeBoard.probe.pending": "Disponível quando a sondagem do backend for adicionada.", + "routeBoard.source.probed": "testado", + "routeBoard.basis.registry": "tabela integrada de {provider}", + "routeBoard.basis.vendor": "metadados de {provider}", + "routeBoard.basis.provider": "provedor configurado {provider}", + "routeBoard.basis.aggregator": "catálogo de {provider}", + "routeBoard.inferred.cell": "inferido {value} (com base em {basis})", + "routeBoard.inferred.adopt": "Adotar", + "routeBoard.inferred.adoptAria": "Salvar o valor inferido {value} de {name} como configuração manual", + "routeBoard.members.includesInferred": "inclui valores inferidos", + "routeBoard.probe.runAria": "Testar o que {name} aceita", + "routeBoard.probe.running": "Testando…", + "routeBoard.probe.confirmTitle": "Confirmar um teste pago", + "routeBoard.probe.confirm": "Este provedor cobra por uso: o teste envia {count} solicitações bem pequenas. Continuar?", + "routeBoard.probe.confirmGo": "Executar o teste", + "routeBoard.probe.reason.disabled": "Não dá para testar: este provedor está desligado.", + "routeBoard.probe.reason.forward_auth": "Não dá para testar: este provedor repassa o login do cliente.", + "routeBoard.probe.reason.oauth_auth": "Não dá para testar: logins de assinatura não são testados.", + "routeBoard.probe.reason.unsupported_adapter": "Não dá para testar: só endpoints compatíveis com OpenAI podem ser testados.", + "routeBoard.probe.reason.unsupported_transport": "Não dá para testar: o tipo de conexão deste provedor não é suportado.", + "routeBoard.probe.reason.other": "Este provedor não pode ser testado.", + "routeBoard.probe.busy": "Este provedor já está sendo testado.", + "routeBoard.probe.failed": "O teste não terminou. Nada foi alterado.", + "routeBoard.probe.uncertain": "Inconclusivo: a solicitação simples não passou, então nada foi alterado.", + "routeBoard.probe.image": "Imagens: {status}", + "routeBoard.probe.accepted": "aceitas", + "routeBoard.probe.rejected": "recusadas", + "routeBoard.probe.inconclusive": "incerto", + "routeBoard.probe.efforts": "Níveis aceitos: {accepted}; recusados: {rejected}; incertos: {inconclusive}", + "routeBoard.probe.appliedInput": "entrada salva: {value}", + "routeBoard.probe.appliedEfforts": "níveis salvos: {value}", + "routeBoard.probe.nothingApplied": "Nada conclusivo, então nada foi salvo.", + "routeBoard.probe.contextNote": "O contexto é inferido do nome do modelo, não medido.", + "routeBoard.probe.close": "Fechar", }; diff --git a/gui/src/i18n/ru.ts b/gui/src/i18n/ru.ts index 94cc4c9407d..34589594b8c 100644 --- a/gui/src/i18n/ru.ts +++ b/gui/src/i18n/ru.ts @@ -4588,6 +4588,37 @@ export const ru: Record = { "routeBoard.members.scopeNote": "Сохраняется в самой модели {name}: меняются все комбо, где она используется.", "routeBoard.members.restore": "Вернуть значения провайдера", "routeBoard.probe.run": "Проверить", - "routeBoard.probe.note": "Проверка отправляет провайдеру один небольшой запрос; провайдер с оплатой за использование его тарифицирует.", - "routeBoard.probe.pending": "Станет доступно, когда появится проверка на сервере.", + "routeBoard.source.probed": "проверено", + "routeBoard.basis.registry": "встроенная таблица {provider}", + "routeBoard.basis.vendor": "данные моделей {provider}", + "routeBoard.basis.provider": "настроенный провайдер {provider}", + "routeBoard.basis.aggregator": "каталог {provider}", + "routeBoard.inferred.cell": "предположительно {value} (по данным: {basis})", + "routeBoard.inferred.adopt": "Принять", + "routeBoard.inferred.adoptAria": "Сохранить предполагаемое значение {value} для {name} как ручную настройку", + "routeBoard.members.includesInferred": "с предполагаемыми значениями", + "routeBoard.probe.runAria": "Проверить, что принимает {name}", + "routeBoard.probe.running": "Проверка…", + "routeBoard.probe.confirmTitle": "Подтвердите платную проверку", + "routeBoard.probe.confirm": "Этот провайдер берёт плату за использование: проверка отправит {count} очень маленьких запросов. Продолжить?", + "routeBoard.probe.confirmGo": "Проверить", + "routeBoard.probe.reason.disabled": "Проверить нельзя: провайдер выключен.", + "routeBoard.probe.reason.forward_auth": "Проверить нельзя: провайдер передаёт вход клиента.", + "routeBoard.probe.reason.oauth_auth": "Проверить нельзя: входы по подписке не проверяются.", + "routeBoard.probe.reason.unsupported_adapter": "Проверить нельзя: проверяются только OpenAI-совместимые адреса.", + "routeBoard.probe.reason.unsupported_transport": "Проверить нельзя: тип подключения провайдера не поддерживается.", + "routeBoard.probe.reason.other": "Этот провайдер нельзя проверить.", + "routeBoard.probe.busy": "Этот провайдер уже проверяется.", + "routeBoard.probe.failed": "Проверка не завершилась. Ничего не изменено.", + "routeBoard.probe.uncertain": "Неясно: обычный запрос не прошёл, поэтому ничего не изменено.", + "routeBoard.probe.image": "Изображения: {status}", + "routeBoard.probe.accepted": "принимаются", + "routeBoard.probe.rejected": "отклоняются", + "routeBoard.probe.inconclusive": "неясно", + "routeBoard.probe.efforts": "Уровни приняты: {accepted}; отклонены: {rejected}; неясно: {inconclusive}", + "routeBoard.probe.appliedInput": "сохранён ввод: {value}", + "routeBoard.probe.appliedEfforts": "сохранены уровни: {value}", + "routeBoard.probe.nothingApplied": "Ничего определённого, поэтому ничего не сохранено.", + "routeBoard.probe.contextNote": "Контекст определяется по имени модели и не измеряется.", + "routeBoard.probe.close": "Закрыть", }; diff --git a/gui/src/i18n/tr.ts b/gui/src/i18n/tr.ts index 1ae5b47e4b3..e8dd5008177 100644 --- a/gui/src/i18n/tr.ts +++ b/gui/src/i18n/tr.ts @@ -4588,6 +4588,37 @@ export const tr: Record = { "routeBoard.members.scopeNote": "{name} modelinin kendisine kaydedilir: bu modeli kullanan her kombo da değişir.", "routeBoard.members.restore": "Sağlayıcı değerlerini kullan", "routeBoard.probe.run": "Test et", - "routeBoard.probe.note": "Test bu sağlayıcıya küçük bir istek gönderir; kullanıma göre ücretlendiren sağlayıcı bunu faturalar.", - "routeBoard.probe.pending": "Arka uç yoklaması eklendiğinde kullanılabilir.", + "routeBoard.source.probed": "test edildi", + "routeBoard.basis.registry": "{provider} yerleşik tablosu", + "routeBoard.basis.vendor": "{provider} model bilgileri", + "routeBoard.basis.provider": "yapılandırılmış {provider}", + "routeBoard.basis.aggregator": "{provider} kataloğu", + "routeBoard.inferred.cell": "tahmini {value} (dayanak: {basis})", + "routeBoard.inferred.adopt": "Benimse", + "routeBoard.inferred.adoptAria": "{name} için tahmini {value} değerini elle ayar olarak kaydet", + "routeBoard.members.includesInferred": "tahmini değerler içerir", + "routeBoard.probe.runAria": "{name} modelinin kabul ettiklerini test et", + "routeBoard.probe.running": "Test ediliyor…", + "routeBoard.probe.confirmTitle": "Ücretli testi onayla", + "routeBoard.probe.confirm": "Bu sağlayıcı kullanıma göre ücretlendirir: test {count} çok küçük istek gönderir. Devam edilsin mi?", + "routeBoard.probe.confirmGo": "Testi çalıştır", + "routeBoard.probe.reason.disabled": "Test edilemez: bu sağlayıcı kapalı.", + "routeBoard.probe.reason.forward_auth": "Test edilemez: bu sağlayıcı istemcinin oturumunu iletir.", + "routeBoard.probe.reason.oauth_auth": "Test edilemez: abonelik oturumları test edilmez.", + "routeBoard.probe.reason.unsupported_adapter": "Test edilemez: yalnızca OpenAI uyumlu uç noktalar test edilebilir.", + "routeBoard.probe.reason.unsupported_transport": "Test edilemez: bu sağlayıcının bağlantı türü desteklenmiyor.", + "routeBoard.probe.reason.other": "Bu sağlayıcı test edilemez.", + "routeBoard.probe.busy": "Bu sağlayıcı zaten test ediliyor.", + "routeBoard.probe.failed": "Test tamamlanmadı. Hiçbir şey değiştirilmedi.", + "routeBoard.probe.uncertain": "Belirsiz: düz istek geçmedi, bu yüzden hiçbir şey değiştirilmedi.", + "routeBoard.probe.image": "Görseller: {status}", + "routeBoard.probe.accepted": "kabul edildi", + "routeBoard.probe.rejected": "reddedildi", + "routeBoard.probe.inconclusive": "belirsiz", + "routeBoard.probe.efforts": "Düzeyler kabul: {accepted}; ret: {rejected}; belirsiz: {inconclusive}", + "routeBoard.probe.appliedInput": "kaydedilen giriş: {value}", + "routeBoard.probe.appliedEfforts": "kaydedilen düzeyler: {value}", + "routeBoard.probe.nothingApplied": "Kesin sonuç yok, bu yüzden hiçbir şey kaydedilmedi.", + "routeBoard.probe.contextNote": "Bağlam model adından tahmin edilir, ölçülmez.", + "routeBoard.probe.close": "Kapat", }; diff --git a/gui/src/i18n/vi.ts b/gui/src/i18n/vi.ts index 20489ba063d..ce7374dfb62 100644 --- a/gui/src/i18n/vi.ts +++ b/gui/src/i18n/vi.ts @@ -4557,6 +4557,37 @@ export const vi: Record = { "routeBoard.members.scopeNote": "Lưu vào chính {name}: mọi combo dùng mô hình này đều thay đổi theo.", "routeBoard.members.restore": "Dùng giá trị của nhà cung cấp", "routeBoard.probe.run": "Kiểm tra", - "routeBoard.probe.note": "Kiểm tra gửi một yêu cầu nhỏ tới nhà cung cấp này; nhà cung cấp tính phí theo lượt sẽ tính phí.", - "routeBoard.probe.pending": "Dùng được khi phần dò ở máy chủ được thêm vào.", + "routeBoard.source.probed": "đã đo", + "routeBoard.basis.registry": "bảng tích hợp của {provider}", + "routeBoard.basis.vendor": "dữ liệu mô hình của {provider}", + "routeBoard.basis.provider": "{provider} đã cấu hình", + "routeBoard.basis.aggregator": "danh mục của {provider}", + "routeBoard.inferred.cell": "suy ra {value} (dựa trên {basis})", + "routeBoard.inferred.adopt": "Áp dụng", + "routeBoard.inferred.adoptAria": "Lưu giá trị suy ra {value} của {name} thành thiết lập thủ công", + "routeBoard.members.includesInferred": "có giá trị suy ra", + "routeBoard.probe.runAria": "Kiểm tra những gì {name} nhận", + "routeBoard.probe.running": "Đang kiểm tra…", + "routeBoard.probe.confirmTitle": "Xác nhận kiểm tra có tính phí", + "routeBoard.probe.confirm": "Nhà cung cấp này tính phí theo lượt: phép kiểm tra gửi {count} yêu cầu rất nhỏ. Tiếp tục?", + "routeBoard.probe.confirmGo": "Chạy kiểm tra", + "routeBoard.probe.reason.disabled": "Không kiểm tra được: nhà cung cấp này đang tắt.", + "routeBoard.probe.reason.forward_auth": "Không kiểm tra được: nhà cung cấp này chuyển tiếp đăng nhập của máy khách.", + "routeBoard.probe.reason.oauth_auth": "Không kiểm tra được: đăng nhập theo gói thuê bao không được kiểm tra.", + "routeBoard.probe.reason.unsupported_adapter": "Không kiểm tra được: chỉ kiểm tra được điểm cuối tương thích OpenAI.", + "routeBoard.probe.reason.unsupported_transport": "Không kiểm tra được: kiểu kết nối của nhà cung cấp này chưa được hỗ trợ.", + "routeBoard.probe.reason.other": "Không kiểm tra được nhà cung cấp này.", + "routeBoard.probe.busy": "Nhà cung cấp này đang được kiểm tra.", + "routeBoard.probe.failed": "Phép kiểm tra chưa xong. Không có gì thay đổi.", + "routeBoard.probe.uncertain": "Không chắc chắn: yêu cầu thường không qua được nên không có gì thay đổi.", + "routeBoard.probe.image": "Hình ảnh: {status}", + "routeBoard.probe.accepted": "chấp nhận", + "routeBoard.probe.rejected": "từ chối", + "routeBoard.probe.inconclusive": "không rõ", + "routeBoard.probe.efforts": "Mức suy luận chấp nhận: {accepted}; từ chối: {rejected}; không rõ: {inconclusive}", + "routeBoard.probe.appliedInput": "đã lưu đầu vào: {value}", + "routeBoard.probe.appliedEfforts": "đã lưu mức suy luận: {value}", + "routeBoard.probe.nothingApplied": "Không có kết quả chắc chắn nên không lưu gì.", + "routeBoard.probe.contextNote": "Ngữ cảnh được suy ra từ tên mô hình, không đo thực tế.", + "routeBoard.probe.close": "Đóng", }; diff --git a/gui/src/i18n/zh-TW.ts b/gui/src/i18n/zh-TW.ts index 2eb456335ae..c3ae4462260 100644 --- a/gui/src/i18n/zh-TW.ts +++ b/gui/src/i18n/zh-TW.ts @@ -4551,6 +4551,37 @@ export const zhTW: Record = { "routeBoard.members.scopeNote": "改的是 {name} 這個模型本身:所有用到它的組合都會跟著變。", "routeBoard.members.restore": "恢復提供方的值", "routeBoard.probe.run": "測一下", - "routeBoard.probe.note": "測一下會向這個提供方發一次很小的請求;按量計費的提供方會收這次的錢。", - "routeBoard.probe.pending": "後端探測介面上線後可用。", + "routeBoard.source.probed": "實測", + "routeBoard.basis.registry": "{provider} 內建表", + "routeBoard.basis.vendor": "{provider} 模型資料", + "routeBoard.basis.provider": "已設定的 {provider}", + "routeBoard.basis.aggregator": "{provider} 目錄", + "routeBoard.inferred.cell": "推斷 {value}(依據 {basis})", + "routeBoard.inferred.adopt": "採用", + "routeBoard.inferred.adoptAria": "把 {name} 的推斷值 {value} 存成手動設定", + "routeBoard.members.includesInferred": "含推斷", + "routeBoard.probe.runAria": "測一下 {name} 能接收什麼", + "routeBoard.probe.running": "正在測…", + "routeBoard.probe.confirmTitle": "確認付費測試", + "routeBoard.probe.confirm": "這家按量計費,會發 {count} 個很小的請求。繼續嗎?", + "routeBoard.probe.confirmGo": "繼續測", + "routeBoard.probe.reason.disabled": "測不了:這家提供方已關閉。", + "routeBoard.probe.reason.forward_auth": "測不了:這家提供方轉發的是用戶端自己的登入。", + "routeBoard.probe.reason.oauth_auth": "測不了:訂閱登入的提供方不做探測。", + "routeBoard.probe.reason.unsupported_adapter": "測不了:只能探測 OpenAI 相容的介面。", + "routeBoard.probe.reason.unsupported_transport": "測不了:不支援這家提供方的連線方式。", + "routeBoard.probe.reason.other": "這家提供方測不了。", + "routeBoard.probe.busy": "這家正在探測。", + "routeBoard.probe.failed": "測試沒跑完,沒有改任何值。", + "routeBoard.probe.uncertain": "探測不確定:一般請求沒通過,沒有改任何值。", + "routeBoard.probe.image": "圖片:{status}", + "routeBoard.probe.accepted": "接受", + "routeBoard.probe.rejected": "拒絕", + "routeBoard.probe.inconclusive": "不確定", + "routeBoard.probe.efforts": "推理檔位 接受:{accepted};拒絕:{rejected};不確定:{inconclusive}", + "routeBoard.probe.appliedInput": "已寫入輸入:{value}", + "routeBoard.probe.appliedEfforts": "已寫入檔位:{value}", + "routeBoard.probe.nothingApplied": "沒有確定的結果,沒有寫入任何值。", + "routeBoard.probe.contextNote": "上下文從名字推斷,不實測。", + "routeBoard.probe.close": "關閉", }; diff --git a/gui/src/i18n/zh.ts b/gui/src/i18n/zh.ts index 80607665076..84423a59829 100644 --- a/gui/src/i18n/zh.ts +++ b/gui/src/i18n/zh.ts @@ -4586,6 +4586,37 @@ export const zh: Record = { "routeBoard.members.scopeNote": "改的是 {name} 这个模型本身:所有用到它的组合都会跟着变。", "routeBoard.members.restore": "恢复提供方的值", "routeBoard.probe.run": "测一下", - "routeBoard.probe.note": "测一下会向这个提供方发一次很小的请求;按量计费的提供方会收这次的钱。", - "routeBoard.probe.pending": "后端探测接口上线后可用。", + "routeBoard.source.probed": "实测", + "routeBoard.basis.registry": "{provider} 内置表", + "routeBoard.basis.vendor": "{provider} 模型资料", + "routeBoard.basis.provider": "已配置的 {provider}", + "routeBoard.basis.aggregator": "{provider} 目录", + "routeBoard.inferred.cell": "推断 {value}(依据 {basis})", + "routeBoard.inferred.adopt": "采用", + "routeBoard.inferred.adoptAria": "把 {name} 的推断值 {value} 存成手动设置", + "routeBoard.members.includesInferred": "含推断", + "routeBoard.probe.runAria": "测一下 {name} 能接收什么", + "routeBoard.probe.running": "正在测…", + "routeBoard.probe.confirmTitle": "确认付费测试", + "routeBoard.probe.confirm": "这家按量计费,会发 {count} 个很小的请求。继续吗?", + "routeBoard.probe.confirmGo": "继续测", + "routeBoard.probe.reason.disabled": "测不了:这家提供方已关闭。", + "routeBoard.probe.reason.forward_auth": "测不了:这家提供方转发的是客户端自己的登录。", + "routeBoard.probe.reason.oauth_auth": "测不了:订阅登录的提供方不做探测。", + "routeBoard.probe.reason.unsupported_adapter": "测不了:只能探测 OpenAI 兼容的接口。", + "routeBoard.probe.reason.unsupported_transport": "测不了:不支持这家提供方的连接方式。", + "routeBoard.probe.reason.other": "这家提供方测不了。", + "routeBoard.probe.busy": "这家正在探测。", + "routeBoard.probe.failed": "测试没跑完,没有改任何值。", + "routeBoard.probe.uncertain": "探测不确定:普通请求没通过,没有改任何值。", + "routeBoard.probe.image": "图片:{status}", + "routeBoard.probe.accepted": "接受", + "routeBoard.probe.rejected": "拒绝", + "routeBoard.probe.inconclusive": "不确定", + "routeBoard.probe.efforts": "推理档位 接受:{accepted};拒绝:{rejected};不确定:{inconclusive}", + "routeBoard.probe.appliedInput": "已写入输入:{value}", + "routeBoard.probe.appliedEfforts": "已写入档位:{value}", + "routeBoard.probe.nothingApplied": "没有确定的结果,没有写入任何值。", + "routeBoard.probe.contextNote": "上下文从名字推断,不实测。", + "routeBoard.probe.close": "关闭", }; diff --git a/gui/src/pages/Combos.tsx b/gui/src/pages/Combos.tsx index 047f2c95a54..785ddf14b12 100644 --- a/gui/src/pages/Combos.tsx +++ b/gui/src/pages/Combos.tsx @@ -30,6 +30,11 @@ import { channelKey, channelTargetsForPut, capabilitySource, + parseCapabilitySources, + parseInferredCapabilities, + parseProbeResponse, + type MemberInferred, + type ProbeOutcome, configuredMemberModels, parseCapabilitySettings, type AccountCount, @@ -60,6 +65,7 @@ type ModelOption = { visionSidecarConsumer?: boolean; contextWindow?: number; sources?: MemberSources; + inferred?: MemberInferred; }; type ProviderDto = { adapter: string; @@ -260,6 +266,7 @@ export default function Combos({ const models: ModelOption[] = []; /** Where each catalog member's capability values come from; only the route board reads it. */ const sourcesByKey = new Map(); + const inferredByKey = new Map(); const capabilityModels: ModelOption[] = []; const catalogued = new Set(); const comboCatalog: Record = {}; @@ -286,9 +293,8 @@ export default function Combos({ visionSidecarConsumer?: unknown; contextWindowDeclared?: unknown; reasoningOverridden?: unknown; - contextWindowSource?: unknown; - inputModalitiesSource?: unknown; - reasoningEffortsSource?: unknown; + capabilitySources?: unknown; + inferredCapabilities?: unknown; }; if (typeof model.provider !== "string" || typeof model.id !== "string") continue; const provider = model.provider.trim(); @@ -322,11 +328,15 @@ export default function Combos({ visionSidecarConsumer: model.visionSidecarConsumer === true, ...(typeof model.contextWindow === "number" && model.contextWindow > 0 ? { contextWindow: model.contextWindow } : {}), }; - sourcesByKey.set(channelKey(provider, id), { - context: capabilitySource(typeof model.contextWindow === "number", typeof model.contextWindowDeclared === "number", model.contextWindowSource), - input: capabilitySource(Boolean(inputModalities?.length), Boolean(inputModalitiesDeclared?.length), model.inputModalitiesSource), - efforts: capabilitySource(reasoningEfforts !== undefined, model.reasoningOverridden === true, model.reasoningEffortsSource), + // The server labels each axis (`capabilitySources`); an older server does not, so fall back + // to the manual flags it does send. + sourcesByKey.set(channelKey(provider, id), parseCapabilitySources(model.capabilitySources) ?? { + context: capabilitySource(typeof model.contextWindow === "number", typeof model.contextWindowDeclared === "number"), + input: capabilitySource(Boolean(inputModalities?.length), Boolean(inputModalitiesDeclared?.length)), + efforts: capabilitySource(reasoningEfforts !== undefined, model.reasoningOverridden === true), }); + const inferred = parseInferredCapabilities(model.inferredCapabilities); + if (inferred) inferredByKey.set(channelKey(provider, id), inferred); capabilityModels.push(option); models.push(option); // Catalog visibility does not restrict internal Combo selection. } @@ -343,8 +353,10 @@ export default function Combos({ const catalogKeys = new Set(models.map((model) => channelKey(model.provider, model.id))); const memberModels = [ ...models.map((model) => { - const sources = sourcesByKey.get(channelKey(model.provider, model.id)); - return sources ? { ...model, sources } : model; + const key = channelKey(model.provider, model.id); + const sources = sourcesByKey.get(key); + const inferred = inferredByKey.get(key); + return { ...model, ...(sources ? { sources } : {}), ...(inferred ? { inferred } : {}) }; }), ...configuredMemberModels(allProviders) .filter((member) => !catalogKeys.has(channelKey(member.provider, member.id))) @@ -561,6 +573,25 @@ export default function Combos({ } }; + /** + * `POST /api/providers/probe-capabilities` for one member, applying conclusive results. A metered + * provider answers `requiresConfirmation` first; the repeat carries the operator's consent. + */ + const probeModel = async (provider: string, modelId: string, confirmed: boolean): Promise => { + try { + const res = await fetch(`${apiBase}/api/providers/probe-capabilities`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ name: provider, model: modelId, apply: true, ...(confirmed ? { confirmMetered: true } : {}) }), + }); + const outcome = parseProbeResponse(res.status, await res.json().catch(() => null)); + if (outcome.kind === "done" && Object.keys(outcome.applied).length > 0) resource.refresh(); + return outcome; + } catch { + return { kind: "failed" }; + } + }; + const setComboEnabled = async (id: string, enabled: boolean) => { try { const res = await putModelVisibility(apiBase, "models", "combo", [{ id }], enabled); @@ -683,6 +714,7 @@ export default function Combos({ onOpenAdvanced={openAdvanced} lockedId={draftComboId} onSaveModel={saveModelSettings} + onProbeModel={probeModel} /> )} {workspaceMounted && ( diff --git a/gui/src/route-board-model.ts b/gui/src/route-board-model.ts index bb0b44090a7..13b39dc6c82 100644 --- a/gui/src/route-board-model.ts +++ b/gui/src/route-board-model.ts @@ -68,10 +68,119 @@ export interface ProviderQuotaLine { /** What the catalog says one member can take. */ /** - * Where a member capability value comes from: the provider's own report, a same-name model - * elsewhere in the catalog (T4c), the operator's per-model setting, or nowhere. + * Where a member capability value comes from, as `/api/models` labels it per axis + * (`capabilitySources`): the operator's declaration, a declaration a capability probe wrote, the + * provider's own report, a same-name estimate, or nowhere. */ -export type CapabilitySource = "reported" | "inferred" | "manual" | "unknown"; +export type CapabilitySource = "manual" | "probed" | "reported" | "inferred" | "unknown"; +const CAPABILITY_SOURCES: ReadonlySet = new Set(["manual", "probed", "reported", "inferred", "unknown"]); + +/** A same-name estimate and what it rests on. Display data only: it never routes. */ +export interface InferredValue { + value: T; + basis: { source: "registry" | "vendor" | "provider" | "aggregator"; provider: string; modelId: string }; +} + +export interface MemberInferred { + context?: InferredValue; + input?: InferredValue; + efforts?: InferredValue; +} + +/** `capabilitySources` from a `/api/models` row; undefined from a backend that does not send it. */ +export function parseCapabilitySources(raw: unknown): MemberSources | undefined { + if (!raw || typeof raw !== "object") return undefined; + const axes = raw as { contextWindow?: unknown; inputModalities?: unknown; reasoningEfforts?: unknown }; + const read = (value: unknown): CapabilitySource => typeof value === "string" && CAPABILITY_SOURCES.has(value) ? value as CapabilitySource : "unknown"; + return { context: read(axes.contextWindow), input: read(axes.inputModalities), efforts: read(axes.reasoningEfforts) }; +} + +/** `inferredCapabilities` from a `/api/models` row: only well-formed axes survive. */ +export function parseInferredCapabilities(raw: unknown): MemberInferred | undefined { + if (!raw || typeof raw !== "object") return undefined; + const basisOf = (value: unknown): InferredValue["basis"] | undefined => { + if (!value || typeof value !== "object") return undefined; + const basis = value as { source?: unknown; provider?: unknown; modelId?: unknown }; + return ["registry", "vendor", "provider", "aggregator"].includes(String(basis.source)) + && typeof basis.provider === "string" && typeof basis.modelId === "string" + ? { source: basis.source as InferredValue["basis"]["source"], provider: basis.provider, modelId: basis.modelId } + : undefined; + }; + const axis = (value: unknown, valid: (candidate: unknown) => candidate is T): InferredValue | undefined => { + if (!value || typeof value !== "object") return undefined; + const entry = value as { value?: unknown; basis?: unknown }; + const basis = basisOf(entry.basis); + return basis && valid(entry.value) ? { value: entry.value, basis } : undefined; + }; + const isTokens = (value: unknown): value is number => typeof value === "number" && Number.isSafeInteger(value) && value > 0; + const isList = (value: unknown): value is string[] => Array.isArray(value) && value.length > 0 && value.every((item) => typeof item === "string"); + const axes = raw as { contextWindow?: unknown; inputModalities?: unknown; reasoningEfforts?: unknown }; + const out: MemberInferred = { + ...(axis(axes.contextWindow, isTokens) ? { context: axis(axes.contextWindow, isTokens)! } : {}), + ...(axis(axes.inputModalities, isList) ? { input: axis(axes.inputModalities, isList)! } : {}), + ...(axis(axes.reasoningEfforts, isList) ? { efforts: axis(axes.reasoningEfforts, isList)! } : {}), + }; + return Object.keys(out).length > 0 ? out : undefined; +} + +/** + * Members with estimates filled into the gaps, for the combo's combined row only. `used` says + * whether any estimate went in, so the combined values can be labelled as including one. + */ +export function withInferredGaps(members: readonly MemberFacts[]): { members: MemberFacts[]; used: boolean } { + let used = false; + const filled = members.map((member) => { + const next: MemberFacts = { ...member }; + if (next.contextWindow === undefined && member.inferred?.context) { next.contextWindow = member.inferred.context.value; used = true; } + if (next.inputModalities === undefined && member.inferred?.input) { next.inputModalities = member.inferred.input.value; used = true; } + if (next.reasoningEfforts === undefined && member.inferred?.efforts) { next.reasoningEfforts = member.inferred.efforts.value; used = true; } + return next; + }); + return { members: filled, used }; +} + +/** What `POST /api/providers/probe-capabilities` answered, reduced to what the table shows. */ +export type ProbeOutcome = + | { kind: "confirm"; planned: number } + | { kind: "inapplicable"; reason: string } + | { kind: "busy" } + | { kind: "failed" } + | { + kind: "done"; + baselineOk: boolean; + image?: "accepted" | "rejected" | "inconclusive"; + accepted: string[]; + rejected: string[]; + inconclusive: string[]; + applied: { inputModalities?: string[]; reasoningEfforts?: string[] }; + }; + +export function parseProbeResponse(status: number, body: unknown): ProbeOutcome { + if (status === 409) return { kind: "busy" }; + if (status < 200 || status >= 300 || !body || typeof body !== "object") return { kind: "failed" }; + const raw = body as Record; + if (raw.applicable === false) return { kind: "inapplicable", reason: typeof raw.reason === "string" ? raw.reason : "unknown" }; + if (raw.requiresConfirmation === true) { + return { kind: "confirm", planned: typeof raw.plannedRequests === "number" && raw.plannedRequests > 0 ? raw.plannedRequests : 1 }; + } + if (raw.sent !== true || !raw.baseline || typeof raw.baseline !== "object") return { kind: "failed" }; + const list = (value: unknown) => Array.isArray(value) ? value.filter((item): item is string => typeof item === "string") : []; + const reasoning = (raw.reasoning ?? {}) as Record; + const imageStatus = (raw.image as { status?: unknown } | undefined)?.status; + const applied = (raw.applied ?? {}) as Record; + return { + kind: "done", + baselineOk: (raw.baseline as { status?: unknown }).status === "accepted", + ...(imageStatus === "accepted" || imageStatus === "rejected" || imageStatus === "inconclusive" ? { image: imageStatus } : {}), + accepted: list(reasoning.accepted), + rejected: list(reasoning.rejected), + inconclusive: list(reasoning.inconclusive), + applied: { + ...(Array.isArray(applied.inputModalities) ? { inputModalities: list(applied.inputModalities) } : {}), + ...(Array.isArray(applied.reasoningEfforts) ? { reasoningEfforts: list(applied.reasoningEfforts) } : {}), + }, + }; +} export interface MemberSources { context: CapabilitySource; @@ -84,6 +193,7 @@ export interface MemberFacts { inputModalities?: readonly string[]; reasoningEfforts?: readonly string[]; sources?: MemberSources; + inferred?: MemberInferred; } /** @@ -173,10 +283,11 @@ export function memberSettingsPatch(current: MemberFacts, draft: MemberDraft, or /** Clears every per-model setting the operator made, so the provider's own values apply again. */ export function memberRestorePatch(sources: MemberSources | undefined): Record { + const declared = (source: CapabilitySource | undefined) => source === "manual" || source === "probed"; return { - ...(sources?.context === "manual" ? { contextWindow: null } : {}), - ...(sources?.input === "manual" ? { inputModalities: null } : {}), - ...(sources?.efforts === "manual" ? { reasoningEfforts: null } : {}), + ...(declared(sources?.context) ? { contextWindow: null } : {}), + ...(declared(sources?.input) ? { inputModalities: null } : {}), + ...(declared(sources?.efforts) ? { reasoningEfforts: null } : {}), }; } diff --git a/gui/tests/route-board.test.tsx b/gui/tests/route-board.test.tsx index ab98c29e24f..b6793eec006 100644 --- a/gui/tests/route-board.test.tsx +++ b/gui/tests/route-board.test.tsx @@ -14,6 +14,10 @@ import { capabilityPatch, capabilitySource, combineLists, + parseCapabilitySources, + parseInferredCapabilities, + parseProbeResponse, + withInferredGaps, configuredMemberModels, dragSlot, memberRestorePatch, @@ -215,6 +219,7 @@ let host: HTMLElement; type Call = { url: string; method: string; body: unknown }; let calls: Call[]; +let probeReply: "ok" | "baseline" | "busy" | "blocked" = "ok"; let combosPayload: unknown; const alpha = combo("alpha", [["openai", "gpt-5"], ["anthropic", "claude"]]); @@ -241,6 +246,20 @@ function installFetch() { const method = init?.method ?? "GET"; if (method !== "GET") { calls.push({ url, method, body: init?.body ? JSON.parse(String(init.body)) : undefined }); + if (url.endsWith("/api/providers/probe-capabilities")) { + const sent = JSON.parse(String(init!.body)) as { confirmMetered?: boolean }; + if (probeReply === "busy") return Response.json({ error: "busy" }, { status: 409 }); + if (probeReply === "blocked") return Response.json({ applicable: false, reason: "unsupported_adapter", sent: false }); + if (!sent.confirmMetered) return Response.json({ applicable: true, sent: false, requiresConfirmation: true, metered: true, plannedRequests: 4 }); + if (probeReply === "baseline") { + return Response.json({ applicable: true, sent: true, baseline: { status: "inconclusive" }, reasoning: { accepted: [], rejected: [], inconclusive: ["low"] }, applied: {} }); + } + return Response.json({ + applicable: true, sent: true, baseline: { status: "accepted" }, image: { status: "accepted" }, + reasoning: { accepted: ["low", "high"], rejected: ["max"], inconclusive: [] }, + applied: { inputModalities: ["text", "image"], reasoningEfforts: ["low", "high"] }, + }); + } if (url.endsWith("/api/model-settings")) { const sent = JSON.parse(String(init!.body)) as { provider: string; modelId: string }; return Response.json({ ok: true, provider: sent.provider, modelId: sent.modelId, changed: true, hasOverrides: true, saved: true, catalogRefresh: { status: "skipped" } }); @@ -260,7 +279,12 @@ function installFetch() { if (url.endsWith("/api/models")) { return Response.json([ { provider: "openai", id: "gpt-5", contextWindow: 400000, reasoningEfforts: ["low", "high"], reasoningOverridden: true }, - { provider: "anthropic", id: "claude" }, + { + provider: "anthropic", id: "claude", + capabilitySources: { contextWindow: "unknown", inputModalities: "probed", reasoningEfforts: "unknown" }, + inputModalities: ["text"], + inferredCapabilities: { contextWindow: { value: 1000000, basis: { source: "registry", provider: "anthropic", modelId: "claude" } } }, + }, { provider: "dead", id: "m" }, { provider: "combo", id: "alpha", displayName: "Alpha", displayNameSource: "provider", contextWindow: 200000, disabled: false }, { provider: "combo", id: "offline", disabled: false }, @@ -287,6 +311,7 @@ beforeEach(() => { }); (globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; root = null; + probeReply = "ok"; installFetch(); }); @@ -443,8 +468,6 @@ describe("Combos overview page", () => { await act(async () => { button(gpt, "Edit what OpenAI (Codex login) gpt-5 can take").click(); }); const form = editor.querySelector(".rb-member-edit")!; expect(form.textContent).toContain("every combo that uses this model changes too"); - expect(form.textContent).toContain("pay-per-use provider bills it"); - expect(button(form, "Test it").disabled).toBe(true); const input = form.querySelector("input")!; const setValue = Object.getOwnPropertyDescriptor(testWindow.HTMLInputElement.prototype, "value")!.set!; await act(async () => { @@ -465,6 +488,64 @@ describe("Combos overview page", () => { expect(editor.querySelector(".rb-member-edit")).toBeNull(); }); + test("a gap with a same-name estimate shows it, and Adopt saves it as a manual setting", async () => { + await renderPage(); + await act(async () => { row("alpha").querySelector(".rb-tag--button")!.click(); }); + const editor = row("alpha").querySelector(".rb-editor")!; + const claude = [...editor.querySelectorAll(".rb-members tbody tr")].find(tr => tr.textContent?.includes("claude"))!; + expect(claude.textContent).toContain("inferred 1M (based on anthropic built-in table)"); + expect(claude.textContent).toContain("probed"); + expect(editor.querySelector(".rb-members tfoot")?.textContent).toContain("includes inferred"); + await act(async () => { claude.querySelector(".rb-adopt")!.click(); }); + await flush(); + expect(calls).toEqual([{ url: "/api/model-settings", method: "PUT", body: { provider: "anthropic", modelId: "claude", contextWindow: 1000000 } }]); + }); + + test("Test it asks before a metered probe, then repeats with consent and lists the results", async () => { + await renderPage(); + await act(async () => { row("alpha").querySelector(".rb-tag--button")!.click(); }); + const editor = row("alpha").querySelector(".rb-editor")!; + const gpt = () => [...editor.querySelectorAll(".rb-members tbody tr")].find(tr => tr.querySelector("th")?.textContent?.includes("gpt-5"))!; + await act(async () => { button(gpt(), "Test what OpenAI (Codex login) gpt-5 accepts").click(); }); + await flush(); + const dialog = editor.querySelector("[role=alertdialog]")!; + expect(dialog.textContent).toContain("sends 4 very small requests"); + expect(editor.textContent).toContain("Context is inferred from the model name, not measured."); + await act(async () => { button(dialog, "Run the test").click(); }); + await flush(); + expect(calls.map(call => call.body)).toEqual([ + { name: "openai", model: "gpt-5", apply: true }, + { name: "openai", model: "gpt-5", apply: true, confirmMetered: true }, + ]); + const results = editor.querySelector(".rb-probe")!.textContent!; + expect(results).toContain("Images: accepted"); + expect(results).toContain("accepted: low · high; refused: max"); + expect(results).toContain("saved effort levels: low · high"); + }); + + test("Test it: a failed baseline changes nothing, a busy provider says so, an inapplicable one greys the button", async () => { + await renderPage(); + await act(async () => { row("alpha").querySelector(".rb-tag--button")!.click(); }); + const editor = row("alpha").querySelector(".rb-editor")!; + const gpt = () => [...editor.querySelectorAll(".rb-members tbody tr")].find(tr => tr.querySelector("th")?.textContent?.includes("gpt-5"))!; + const test = () => button(gpt(), "Test what OpenAI (Codex login) gpt-5 accepts"); + probeReply = "baseline"; + await act(async () => { test().click(); }); + await flush(); + await act(async () => { button(editor.querySelector("[role=alertdialog]")!, "Run the test").click(); }); + await flush(); + expect(editor.querySelector(".rb-probe")!.textContent).toContain("Inconclusive"); + probeReply = "busy"; + await act(async () => { test().click(); }); + await flush(); + expect(editor.querySelector(".rb-probe")!.textContent).toContain("already being tested"); + probeReply = "blocked"; + await act(async () => { test().click(); }); + await flush(); + expect(editor.querySelector(".rb-probe")!.textContent).toContain("only OpenAI-compatible endpoints"); + expect(test().disabled).toBe(true); + }); + test("restoring a member sends null only for the fields set by hand", async () => { await renderPage(); await act(async () => { row("alpha").querySelector(".rb-tag--button")!.click(); }); @@ -622,3 +703,37 @@ describe("member capability edits", () => { expect(memberRestorePatch({ context: "manual", input: "reported", efforts: "manual" })).toEqual({ contextWindow: null, reasoningEfforts: null }); }); }); + +describe("capability sources, estimates and probe replies", () => { + test("sources come from the server's per-axis labels; junk reads as unknown", () => { + expect(parseCapabilitySources({ contextWindow: "probed", inputModalities: "inferred", reasoningEfforts: "nonsense" })) + .toEqual({ context: "probed", input: "inferred", efforts: "unknown" }); + expect(parseCapabilitySources(undefined)).toBeUndefined(); + }); + + test("estimates keep only well-formed axes, and fill gaps only in the combined row", () => { + const inferred = parseInferredCapabilities({ + contextWindow: { value: 1000000, basis: { source: "registry", provider: "anthropic", modelId: "m" } }, + inputModalities: { value: [], basis: { source: "vendor", provider: "x", modelId: "m" } }, + reasoningEfforts: { value: ["low"], basis: { source: "nowhere", provider: "x", modelId: "m" } }, + }); + expect(inferred).toEqual({ context: { value: 1000000, basis: { source: "registry", provider: "anthropic", modelId: "m" } } }); + expect(withInferredGaps([{ contextWindow: 200000, inferred }, { inferred }])).toEqual({ + members: [{ contextWindow: 200000, inferred }, { contextWindow: 1000000, inferred }], + used: true, + }); + expect(withInferredGaps([{ contextWindow: 200000 }]).used).toBe(false); + }); + + test("probe replies map to confirm, inapplicable, busy, done and failed", () => { + expect(parseProbeResponse(200, { requiresConfirmation: true, plannedRequests: 5 })).toEqual({ kind: "confirm", planned: 5 }); + expect(parseProbeResponse(200, { applicable: false, reason: "oauth_auth" })).toEqual({ kind: "inapplicable", reason: "oauth_auth" }); + expect(parseProbeResponse(409, { error: "busy" })).toEqual({ kind: "busy" }); + expect(parseProbeResponse(500, { error: "x" })).toEqual({ kind: "failed" }); + expect(parseProbeResponse(200, { sent: true, baseline: { status: "inconclusive" } })).toMatchObject({ kind: "done", baselineOk: false }); + }); + + test("restore clears probed declarations too", () => { + expect(memberRestorePatch({ context: "reported", input: "probed", efforts: "manual" })).toEqual({ inputModalities: null, reasoningEfforts: null }); + }); +}); diff --git a/structure/dashboard-and-usage.md b/structure/dashboard-and-usage.md index 5e5987912b7..cbf67ee270c 100644 --- a/structure/dashboard-and-usage.md +++ b/structure/dashboard-and-usage.md @@ -126,7 +126,7 @@ The sidebar exposes eight rows (`gui/src/nav-groups.ts` `NAV_GROUPS`), in order: | API keys | Key table plus per-key detail (`gui/src/components/apikeys-workspace/`). The list payload carries masked prefixes only; each row deletes in place behind a two-step confirm, and clicking a key fetches the full value from `POST /api/keys/reveal`, which requires a current pairing or trusted Tailscale-identity session and answers `no-store`; automatic loopback sessions and raw admin tokens cannot reveal stored values, and a refusal there answers with the pairing surface — on the same-origin standalone transport the local pairing form, elsewhere the explanation alone — and requires a fresh reveal click after pairing. Displayed secrets and copy feedback are cleared on shared-session loss, pairing, inactive/hidden views, or a target change; stale asynchronous completions cannot restore them. | | Storage | Rail plus cleanup and trash detail (`gui/src/components/storage-workspace/`). | | Subagents | Featured-roster selection workspace (`gui/src/components/subagents-workspace/`). | -| Combos | `#models/combos` opens the overview (`gui/src/components/route-board/RouteBoard.tsx`, view model `gui/src/route-board-model.ts`): one row per combo with stacked provider icons, display name and public id, the channel order (`→` for failover, `·` otherwise, last-resort members marked), one quota line per provider from `/api/provider-quotas` (remaining percent, green above 50%, amber 20–50%, red below 20%; `key` providers read as pay per use), the catalog context window, an inline strategy menu and an on/off switch. Switched-off combos sort after the live ones. Antigravity pool windows read as family names (`Cla (Weekly)` → "Claude & GPT · weekly"). Account counts come from the report's `aggregation`, otherwise from `GET /api/oauth/accounts?provider=` for enabled OAuth providers (paused accounts listed separately). A strategy pick runs `validateComboDraft` and then the normal `PUT /api/combos`; JEV never saves from the row and opens the workspace on that combo instead, because an empty decision service means the hosted TypeSafe service. The switch writes the combo selector through `PUT /api/model-visibility` (`provider: "combo"`). Clicking a row opens the channel editor (reorder by drag, where the other rows make room live with a FLIP slide, or by move buttons; mark fallback only, i.e. `lastResort`; remove; add). Its "More settings" section opens in place: the capability policy, a "fallback channels wait their turn" switch that writes `cooldownWaitPolicy` (`"before-last-resort"` or `null`), and a member table (`gui/src/components/route-board/MemberTable.tsx`) of each member's context window, input modalities and effort levels with the combined row. Every cell carries its source (`capabilitySource`: `contextWindowDeclared` / `inputModalitiesDeclared` / `reasoningOverridden` read as manual, an explicit `*Source: "inferred"` field as inferred, any other value as the provider's report, otherwise unknown); members with no `/api/models` row fall back to their per-model config (`configuredMemberModels`). A member edit sends only the changed fields to `PUT /api/model-settings` (`memberSettingsPatch`; restore sends `null` for the manual fields), validates the receipt, and refreshes the page; the probe button stays disabled until a backend probe exists. Drag reorder computes the drop slot from the row midpoints frozen at drag start with 8 px hysteresis (`dragSlot`) and commits on drop. The row's context tag opens that section and shows the smallest member under intersection and the largest under union (`comboContextWindow`); fallback-only marks render greyed with the reason while the combo has no `cooldownWaitPolicy`; only its save sends `lastResort` explicitly, every other save omits it so the server carries it over. Capability fields (`capabilityPolicy`, `onUnservable`) and `cooldownWaitPolicy` read absent as the defaults and are sent only when changed. "Advanced" opens the rail, detail panel and add flow (`gui/src/components/ComboWorkspace.tsx`) at `#models/combos/advanced`; `#models/combos/jev-auto` still lands there (`gui/src/pages/combos-view.ts`). The workspace stays mounted once opened, so an unsaved draft survives the overview, and the overview locks the strategy and channel save of the combo being drafted until the draft is saved or discarded. `gui/tests/route-board.test.tsx` covers the rows, PUT bodies, the JEV hand-off, validation, the switch selector, the channel save, drag sweeps over 4 and 6 rows, the member edit and restore bodies, and the draft lock. | +| Combos | `#models/combos` opens the overview (`gui/src/components/route-board/RouteBoard.tsx`, view model `gui/src/route-board-model.ts`): one row per combo with stacked provider icons, display name and public id, the channel order (`→` for failover, `·` otherwise, last-resort members marked), one quota line per provider from `/api/provider-quotas` (remaining percent, green above 50%, amber 20–50%, red below 20%; `key` providers read as pay per use), the catalog context window, an inline strategy menu and an on/off switch. Switched-off combos sort after the live ones. Antigravity pool windows read as family names (`Cla (Weekly)` → "Claude & GPT · weekly"). Account counts come from the report's `aggregation`, otherwise from `GET /api/oauth/accounts?provider=` for enabled OAuth providers (paused accounts listed separately). A strategy pick runs `validateComboDraft` and then the normal `PUT /api/combos`; JEV never saves from the row and opens the workspace on that combo instead, because an empty decision service means the hosted TypeSafe service. The switch writes the combo selector through `PUT /api/model-visibility` (`provider: "combo"`). Clicking a row opens the channel editor (reorder by drag, where the other rows make room live with a FLIP slide, or by move buttons; mark fallback only, i.e. `lastResort`; remove; add). Its "More settings" section opens in place: the capability policy, a "fallback channels wait their turn" switch that writes `cooldownWaitPolicy` (`"before-last-resort"` or `null`), and a member table (`gui/src/components/route-board/MemberTable.tsx`) of each member's context window, input modalities and effort levels with the combined row. Every cell carries its source from the row's `capabilitySources` (`parseCapabilitySources`; an older server without it falls back to the `*Declared` / `reasoningOverridden` flags via `capabilitySource`); members with no `/api/models` row fall back to their per-model config (`configuredMemberModels`). A gap with an `inferredCapabilities` estimate shows the value and its basis with an Adopt button that writes it through `PUT /api/model-settings`; estimates fill gaps only in the combined row, labelled (`withInferredGaps`), never in routing. A member edit sends only the changed fields to `PUT /api/model-settings` (`memberSettingsPatch`; restore sends `null` for the manual fields), validates the receipt, and refreshes the page; "Test it" (`gui/src/components/route-board/MemberProbe.tsx`) posts `POST /api/providers/probe-capabilities` with `apply: true`, repeats with `confirmMetered: true` after an inline confirmation naming `plannedRequests`, and shows `applicable: false` reasons (button greyed), a 409 as already running, and a failed baseline as inconclusive (`parseProbeResponse`). Drag reorder computes the drop slot from the row midpoints frozen at drag start with 8 px hysteresis (`dragSlot`) and commits on drop. The row's context tag opens that section and shows the smallest member under intersection and the largest under union (`comboContextWindow`); fallback-only marks render greyed with the reason while the combo has no `cooldownWaitPolicy`; only its save sends `lastResort` explicitly, every other save omits it so the server carries it over. Capability fields (`capabilityPolicy`, `onUnservable`) and `cooldownWaitPolicy` read absent as the defaults and are sent only when changed. "Advanced" opens the rail, detail panel and add flow (`gui/src/components/ComboWorkspace.tsx`) at `#models/combos/advanced`; `#models/combos/jev-auto` still lands there (`gui/src/pages/combos-view.ts`). The workspace stays mounted once opened, so an unsaved draft survives the overview, and the overview locks the strategy and channel save of the combo being drafted until the draft is saved or discarded. `gui/tests/route-board.test.tsx` covers the rows, PUT bodies, the JEV hand-off, validation, the switch selector, the channel save, drag sweeps over 4 and 6 rows, the member edit and restore bodies, and the draft lock. | | Add provider | Catalog browser plus form and OAuth panes (`gui/src/components/provider-catalog/`, `gui/src/components/AddProviderModal.tsx`). The catalog browses four tabs — Accounts, Free, Local, Paid — where Local is a catalog-only bucket peeled out of `bucketPresets` after `presetTier` has classified; the workspace `providerTier` stays three-way, so the rail, the free-paid sort and the Free count still treat a local runtime as free. Search sits above the tabs and reaches every tab at once: while a query is live the list renders all four groups with headings and the strip becomes jump chips with counts rather than a tablist, because moving the selected tab would change the row kind under the user (a preset-select button becomes a login row). ArrowDown from the search input focuses the first enabled result action; if none is available, focus stays in the input. The tab strip wraps within narrow modals. Every nonempty note has a full-text button so narrow rows never hide content permanently; the native note dialog closes during teardown and restores focus to its trigger. Provider notes clamp to two lines and open in full in a stacked native `` owned by `AddProviderModal`, which also owns the search text so its `window` Escape handler can unwind popup, then query, then dialog. | | Codex accounts | Account pool cards, add-account flow, switch and reset modals (`gui/src/components/CodexAccountPool.tsx`, `gui/src/components/AddCodexAccountModal.tsx`), plus the generic account-targeting picker opt-in on `gui/src/pages/codex-set-multiauth.tsx`. Add/delete/login completion is projected to one boolean before presentation; pending catalog work is a warning, not a failed account mutation. The main card's native-main device reauth (#3898) is owned by `gui/src/components/use-main-device-reauth.ts`: the dedicated `/api/codex-auth/main/reauth-device` namespace only — never the pool login route — with flowId-owned polling, an allowlisted verification URL, and no token fields accepted from payloads. The main-device reauth hook retains flow ownership from the Cancel click, while DELETE is unresolved and after retryable failure; polling normally continues. A concurrent GET HTTP error cannot expose a replacement login POST before DELETE settles. If a retryable DELETE failure races with a non-2xx GET while the flow is pending or committing, either response order preserves same-flow Cancel retry, restores the last server-provided device code, verification URL, and phase when needed, and keeps the existing poll cadence so a later terminal result remains observable. Outside same-flow cancellation ownership, a GET HTTP failure still stops polling without starting a second login POST. The cancellation-failure indication survives pending status updates until a trusted terminal result releases ownership. A successful DELETE with a terminal `failed` DTO releases it and uses the same closed failure-code mapping as polling; only `succeeded` notifies login completion. Unrecognized or nonterminal DTO status values remain retryable. A DELETE response with HTTP 404 and code `unknown_flow` releases the expired flow and shows the existing generic failure state so device re-login is available again; it claims neither login success nor confirmed cancellation. Confirmed cancellation also makes device re-login available. Start, polling and cancellation completions verify their controller or flow ownership after asynchronous response reads; replaced flows and unmounted hooks cannot update a newer flow or notify completion. Effect setup restores mounted state after the StrictMode development cleanup cycle. | | Dashboard overview | Overview, Providers, and Models tabs at the page level (`gui/src/pages/Dashboard.tsx`), the 30-day token and coverage stats in the overview head (`gui/src/pages/dashboard-overview-head.tsx`), and the effort-cap, injection, maintenance, sidecar, reasoning-retention, and memory panels below it (`gui/src/pages/dashboard-overview-panels.tsx`). The Reasoning retention controls (`gui/src/components/ReasoningRetentionPanel.tsx`) live in a collapsed Advanced settings disclosure at the end of Overview. They read and save `reasoningRetention` via GET/PUT `/api/settings` in `src/server/management/config-routes.ts`: only explicit `enabled: true` activates retention; absent, disabled, and legacy threshold-only settings remain off. The enable switch exposes numeric controls with defaults of 20% and 100000 tokens; disabling saves `enabled: false`, and null reset removes the setting and turns it off. Omission preserves it, validation precedes mutation, and save failure restores value and key presence. Copy warns that opt-in can preserve plaintext reasoning in local history/archive and that completed archives have no aggregate quota or expiry and require manual deletion. Loading disables writes, failures permit retry without losing edits, and stale responses cannot update a new API target. Its scope is the [routed v1/v2 compaction contract](transports/responses-failover.md#compaction-routing-overrides); opaque output stays unchanged. `tests/config/settings-reasoning-retention.test.ts` and `gui/tests/reasoning-retention-panel.test.tsx` cover the API and controls. Inputs expose invalid state and reference the validation alert only for the failing field. | From 0b26e115d2611791ad779c4a40e914b631708493 Mon Sep 17 00:00:00 2001 From: "Andrew (agent)" Date: Fri, 13 Nov 2026 03:30:26 -0500 Subject: [PATCH 10/11] feat(gui): route board drag follows Magpie's pointer sorter: the row itself moves, no ghost copy Ports Magpie's dragRows (MIT, Copyright (c) 2026 yetone; notice kept in drag-rows.ts): pointer events with capture, the dragged row lifted and moved by a transform, the rows it passes sliding a row's height aside, Escape/blur/resize cancel, one commit on release. The slot still comes from the layout midpoints with 8 px hysteresis (dragSlot). Replaces HTML5 drag-and-drop, whose drag image drew a translucent second copy over a translucent original. Provider icons no longer start the browser's own image drag. Move buttons and their FLIP slide are unchanged. --- .../components/route-board/ChannelEditor.tsx | 77 +++----- gui/src/components/route-board/drag-rows.ts | 171 ++++++++++++++++++ gui/src/design/pages/route-board.css | 12 +- gui/tests/route-board.test.tsx | 61 +++++-- structure/dashboard-and-usage.md | 2 +- 5 files changed, 253 insertions(+), 70 deletions(-) create mode 100644 gui/src/components/route-board/drag-rows.ts diff --git a/gui/src/components/route-board/ChannelEditor.tsx b/gui/src/components/route-board/ChannelEditor.tsx index 7399a0b9301..e00ccd1f47a 100644 --- a/gui/src/components/route-board/ChannelEditor.tsx +++ b/gui/src/components/route-board/ChannelEditor.tsx @@ -1,4 +1,5 @@ -import { useEffect, useLayoutEffect, useRef, useState, type DragEvent } from "react"; +import { useEffect, useLayoutEffect, useRef, useState, type PointerEvent as ReactPointerEvent } from "react"; +import { flushSync } from "react-dom"; import { COMBO_EFFORTS, COMBO_TARGETS_HINT_KEYS, type ComboStrategy } from "../../combo-workspace-data"; import { useT } from "../../i18n/shared"; import { formatProviderDisplayName } from "../../provider-icons"; @@ -7,7 +8,6 @@ import { channelKey, combineLists, comboContextWindow, - dragSlot, withInferredGaps, memberFacts, moveChannel, @@ -25,6 +25,7 @@ import type { ModelOption, ProviderOption } from "../combo-workspace-types"; import type { ProbeMemberModel } from "./MemberProbe"; import { MemberTable, type SaveMemberModel } from "./MemberTable"; import { QuotaLine } from "./QuotaLine"; +import { dragRows } from "./drag-rows"; export type EditableChannel = Pick; @@ -39,13 +40,17 @@ const MODALITY_ORDER = ["text", "image"]; function useSlideOnReorder(order: readonly string[]) { const nodes = useRef(new Map()); const previous = useRef(new Map()); + /** Set by a drag commit: the rows are already drawn where they land, so nothing slides. */ + const still = useRef(false); useLayoutEffect(() => { const next = new Map(); + const skip = still.current; + still.current = false; for (const [key, node] of nodes.current) { const top = node.getBoundingClientRect().top; next.set(key, top); const before = previous.current.get(key); - if (before === undefined || before === top || typeof node.animate !== "function") continue; + if (skip || before === undefined || before === top || typeof node.animate !== "function") continue; node.animate([{ transform: `translateY(${before - top}px)` }, { transform: "translateY(0)" }], { duration: SLIDE_MS, easing: "ease-out", @@ -56,17 +61,9 @@ function useSlideOnReorder(order: readonly string[]) { const ref = (key: string) => (node: HTMLElement | null) => { if (node) nodes.current.set(key, node); else nodes.current.delete(key); }; - return { ref, nodes }; + return { ref, still }; } -/** A drag in progress: the order and the row midpoints (relative to the list) frozen at drag start. */ -interface DragState { - key: string; - from: number; - start: EditableChannel[]; - mids: number[]; - slot: number; -} /** * Inline channel editor under an expanded row: reorder (drag, with the other rows making room @@ -116,14 +113,10 @@ export function ChannelEditor({ }) { const t = useT(); const [channels, setChannels] = useState(() => [...initial]); - const [drag, setDrag] = useState(null); - const dropped = useRef(false); const listRef = useRef(null); const [moreOpen, setMoreOpen] = useState(moreOpenInitially); const moreRef = useRef(null); - /** While dragging, the list shows the would-be order; `channels` changes only on drop. */ - const view = drag ? moveChannel(drag.start, drag.from, drag.slot) : channels; - const slide = useSlideOnReorder(view.map((channel) => channel.key)); + const slide = useSlideOnReorder(channels.map((channel) => channel.key)); const pickable = providers.filter((provider) => !provider.hiddenFromPicker); const [addProvider, setAddProvider] = useState(() => pickable[0]?.name ?? ""); const used = new Set(channels.map((channel) => channel.key)); @@ -150,33 +143,21 @@ export function ChannelEditor({ }, [moreOpenInitially]); const move = (from: number, to: number) => setChannels((list) => moveChannel(list, from, to)); - const listTop = () => listRef.current?.getBoundingClientRect().top ?? 0; - const startDrag = (event: DragEvent, key: string, from: number) => { - event.dataTransfer?.setData("text/plain", key); - // A slide still running from the last drop would skew the measurement: settle it first. - for (const node of slide.nodes.current.values()) node.getAnimations?.().forEach((animation) => animation.finish()); - const top = listTop(); - const mids = channels.map((channel) => { - const rect = slide.nodes.current.get(channel.key)?.getBoundingClientRect(); - return rect ? rect.top - top + rect.height / 2 : 0; - }); - dropped.current = false; - setDrag({ key, from, start: [...channels], mids, slot: from }); - }; - /* - * The slot comes from where the pointer is against the rows' midpoints as they stood when the - * drag began, never against rows that are mid-slide, with a few pixels of hysteresis at each - * boundary. Reading the moving rows made the order flip back and forth under a still pointer. + /** + * The row itself follows the pointer and the others slide aside (Magpie's sorter, `drag-rows.ts`); + * the order changes once, on release. Presses on the row's own controls stay clicks. */ - const onListDragOver = (event: DragEvent) => { - if (!drag) return; - event.preventDefault(); - const slot = dragSlot(drag.mids, drag.from, event.clientY - listTop(), drag.slot); - if (slot !== drag.slot) setDrag({ ...drag, slot }); - }; - const finishDrag = (commit: boolean) => { - if (drag && commit) setChannels(moveChannel(drag.start, drag.from, drag.slot)); - setDrag(null); + const startDrag = (event: ReactPointerEvent, from: number) => { + const list = listRef.current; + const target = event.target as Element; + if (!list || target.closest("button, input, a, [role=combobox]")) return; + // On touch only the grip drags, so the rest of the row still scrolls the page. + if (event.pointerType === "touch" && !target.closest(".rb-channel-grip")) return; + const rows = Array.from(list.children) as HTMLElement[]; + dragRows(event.nativeEvent, event.currentTarget, event.currentTarget, list, rows, (to) => { + slide.still.current = true; + flushSync(() => setChannels((current) => moveChannel(current, from, to))); + }); }; const add = () => { if (!addProvider || !chosenModel) return; @@ -196,20 +177,16 @@ export function ChannelEditor({
      { event.preventDefault(); dropped.current = true; finishDrag(true); }} > - {view.map((channel, index) => { + {channels.map((channel, index) => { const providerName = labels?.get(channel.provider) ?? formatProviderDisplayName(channel.provider, t); const name = `${providerName} ${channel.model}`; return (
    1. startDrag(event, channel.key, index)} - onDragEnd={() => { if (!dropped.current) finishDrag(false); }} + className="rb-channel" + onPointerDown={(event) => startDrag(event, index)} > {index + 1} diff --git a/gui/src/components/route-board/drag-rows.ts b/gui/src/components/route-board/drag-rows.ts new file mode 100644 index 00000000000..28b72724cae --- /dev/null +++ b/gui/src/components/route-board/drag-rows.ts @@ -0,0 +1,171 @@ +/* + * Pointer row sorter, adapted from Magpie's `dragRows`, `dragScroll`, `dragListen` and `tapLike` + * (internal/gui/assets/app.js in https://github.com/yetone/magpie). + * + * MIT License + * + * Copyright (c) 2026 yetone + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + * Changes from the original: TypeScript; the target slot goes through `dragSlot` (the row + * midpoints from layout, plus a few pixels of hysteresis at each boundary) instead of the plain + * midpoint walk, so a pointer resting on a boundary cannot make the rows flip back and forth. + */ +import { dragSlot } from "../../route-board-model"; + +/** The box a drag scrolls, and how fast a pointer at y scrolls it. */ +function dragScroll(list: HTMLElement) { + let scroll: HTMLElement | null = list.parentElement; + while (scroll && !/(auto|scroll)/.test(window.getComputedStyle(scroll).overflowY)) scroll = scroll.parentElement; + const box = scroll ?? (document.scrollingElement as HTMLElement | null) ?? document.documentElement; + const bounds = box.getBoundingClientRect(); + const edge = 36; + return { + scroll: box, + speedAt: (y: number) => y < bounds.top + edge ? -Math.min(1, (bounds.top + edge - y) / edge) + : y > bounds.bottom - edge ? Math.min(1, (y - bounds.bottom + edge) / edge) : 0, + }; +} + +/** A drag's listeners: letting go saves; Escape, blur, resize and a lost capture cancel. */ +function dragListen(handle: HTMLElement, move: (ev: PointerEvent) => void, finish: (save: boolean, ev?: PointerEvent) => void) { + const cancel = (ev: Event) => finish(false, ev as PointerEvent); + const on: Array<[EventTarget, string, EventListener, AddEventListenerOptions | boolean | undefined]> = [ + [document, "pointermove", move as EventListener, { passive: false }], + [document, "pointerup", ((ev: PointerEvent) => finish(true, ev)) as EventListener, undefined], + [document, "pointercancel", cancel, undefined], + [handle, "lostpointercapture", cancel, undefined], + [window, "blur", cancel, undefined], + [window, "resize", cancel, undefined], + [document, "keydown", ((ev: KeyboardEvent) => { + if (ev.key === "Escape") { ev.preventDefault(); ev.stopImmediatePropagation(); finish(false); } + }) as EventListener, true], + ]; + for (const [target, name, listener, options] of on) target.addEventListener(name, listener, options); + return () => { for (const [target, name, listener, options] of on) target.removeEventListener(name, listener, options); }; +} + +/** + * A tap on a trackpad can slide a few pixels between press and lift: let go within 300ms and + * under 12px from where it came down is a click, not a drag. + */ +const tapLike = (t0: number, x0: number, y0: number, ev?: PointerEvent) => + ev?.type === "pointerup" && performance.now() - t0 < 300 && Math.hypot(ev.clientX - x0, ev.clientY - y0) < 12; + +const frameRequest = (callback: FrameRequestCallback) => + typeof requestAnimationFrame === "function" ? requestAnimationFrame(callback) : setTimeout(() => callback(performance.now()), 16) as unknown as number; +const frameCancel = (id: number) => { + if (typeof cancelAnimationFrame === "function") cancelAnimationFrame(id); else clearTimeout(id); +}; + +/** + * The row itself follows the pointer (a transform, no copy and no placeholder); the rows it + * passes slide a row's height out of the way; one `commit(to)` on release. Returns false when the + * press does not start a drag. + */ +export function dragRows( + e: PointerEvent, + handle: HTMLElement, + row: HTMLElement, + list: HTMLElement, + rows: HTMLElement[], + commit: (to: number) => void, +): boolean { + if (e.button !== 0 || e.isPrimary === false || rows.length < 2) return false; + const from = rows.indexOf(row); + if (from < 0) return false; + const base = () => list.getBoundingClientRect().top - list.scrollTop - rows[0]!.offsetTop; + const lift = rows[0]!.getBoundingClientRect().top - base() - rows[0]!.offsetTop; + const grab = e.clientY - row.getBoundingClientRect().top; + const { scroll, speedAt } = dragScroll(list); + let dragging = false; + let ended = false; + let to = from; + let y = e.clientY; + let frame = 0; + let lastTime = 0; + const y0 = y; + const x0 = e.clientX; + const t0 = performance.now(); + const pointer = e.pointerId; + + const paint = (time: number) => { + frame = 0; + if (!rows.every((r) => r.isConnected)) { finish(false); return; } + if (!dragging) return; + const dt = Math.min(32, lastTime ? time - lastTime : 16); + lastTime = time; + const speed = speedAt(y); + if (speed) scroll.scrollTop += speed * dt * 0.6; + const b = base() + lift; + const tops = rows.map((r) => b + r.offsetTop); + const heights = rows.map((r) => r.offsetHeight); + const h = heights[from]!; + const lo = tops[0]! - tops[from]!; + const hi = tops.at(-1)! + heights.at(-1)! - h - tops[from]!; + const d = Math.max(lo, Math.min(hi, y - grab - tops[from]!)); + Object.assign(row.style, { transform: `translateY(${d}px)` }); + to = dragSlot(tops.map((top, i) => top + heights[i]! / 2), from, tops[from]! + d + h / 2, to); + // Held at the top or the foot, it goes there even if the end row's middle is out of reach. + if (d <= lo && from > 0) to = 0; + else if (d >= hi && from < rows.length - 1) to = rows.length - 1; + rows.forEach((r, i) => { + if (i === from) return; + const shift = i > from && i <= to ? -h : i < from && i >= to ? h : 0; + Object.assign(r.style, { transform: shift ? `translateY(${shift}px)` : "" }); + }); + frame = frameRequest(paint); + }; + const move = (ev: PointerEvent) => { + if (ev.pointerId !== pointer) return; + if (!row.isConnected || !handle.isConnected) { finish(false, ev); return; } + y = ev.clientY; + if (!dragging) { + if (Math.abs(y - y0) < 4) return; + dragging = true; + list.classList.add("sorting"); + row.classList.add("dragging"); + window.getSelection()?.removeAllRanges(); + handle.setPointerCapture?.(pointer); + } + ev.preventDefault(); + if (!frame) frame = frameRequest(paint); + }; + const finish = (save: boolean, ev?: PointerEvent) => { + if (ended || (ev?.pointerId != null && ev.pointerId !== pointer)) return; + if (save && dragging && tapLike(t0, x0, y0, ev)) save = false; + if (save && dragging && ev) { + y = ev.clientY; + frameCancel(frame); + paint(performance.now()); + } + if (ended) return; + ended = true; + frameCancel(frame); + off(); + if (handle.hasPointerCapture?.(pointer)) handle.releasePointerCapture(pointer); + list.classList.remove("sorting"); + row.classList.remove("dragging"); + rows.forEach((r) => { r.style.transform = ""; }); + if (save && dragging && to !== from) commit(to); + }; + const off = dragListen(handle, move, finish); + return true; +} diff --git a/gui/src/design/pages/route-board.css b/gui/src/design/pages/route-board.css index cc6ae92bbe2..915a808edad 100644 --- a/gui/src/design/pages/route-board.css +++ b/gui/src/design/pages/route-board.css @@ -107,7 +107,6 @@ background: var(--ocx-bg); box-shadow: inset 0 0 0 1px var(--ocx-line); } -.rb-channel--dragging { opacity: 0.5; } .rb-channel-grip { color: var(--ocx-fg-subtle); cursor: grab; letter-spacing: -2px; } .rb-channel-index { color: var(--ocx-fg-subtle); font-variant-numeric: tabular-nums; text-align: right; } .rb-channel-name { display: flex; flex-direction: column; min-width: 0; } @@ -139,9 +138,7 @@ .rb-tag--button:hover { color: var(--ocx-fg); box-shadow: inset 0 0 0 1px var(--ocx-line-strong); } .rb-tag--button:focus-visible { outline: 2px solid var(--ocx-highlight); outline-offset: 1px; } .rb-tag-basis { color: var(--ocx-fg-subtle); } -.rb-channel { cursor: grab; } .rb-channel:active { cursor: grabbing; } -.rb-channel--dragging { opacity: 0.45; box-shadow: inset 0 0 0 1px var(--ocx-highlight); } .rb-more { margin-top: 10px; border-top: 1px solid var(--ocx-line); padding-top: 8px; } .rb-more-toggle { @@ -184,3 +181,12 @@ .rb-probe { display: flex; flex-direction: column; gap: 6px; padding: 8px 12px; border: 1px dashed var(--ocx-line); border-radius: 8px; } .rb-probe-confirm { display: flex; flex-direction: column; gap: 6px; } .rb-probe-results { margin: 0; padding-left: 18px; font-size: 12.5px; } +/* Pointer sorting, after Magpie's routing page: the row itself is lifted, the others slide aside. */ +.rb-channels.sorting { user-select: none; -webkit-user-select: none; } +.rb-channels.sorting > .rb-channel { transition: transform .22s cubic-bezier(.22, 1, .36, 1); } +.rb-channels > .rb-channel.dragging { position: relative; z-index: 2; background: var(--ocx-surface-2); cursor: grabbing; transition: none; will-change: transform; + box-shadow: 0 6px 18px rgba(0, 0, 0, .28), 0 0 0 1px var(--ocx-line); } +.rb-channel-grip { touch-action: none; } +.rb-channel :is(button, input, [role=combobox]) { cursor: pointer; } +/* A press on the provider icon must start the row drag, not the browser's own image drag. */ +.rb-channel img, .rb-channel svg { pointer-events: none; -webkit-user-drag: none; user-select: none; } diff --git a/gui/tests/route-board.test.tsx b/gui/tests/route-board.test.tsx index b6793eec006..56e3248c2f8 100644 --- a/gui/tests/route-board.test.tsx +++ b/gui/tests/route-board.test.tsx @@ -430,34 +430,63 @@ describe("Combos overview page", () => { ]); }); - test("dragging moves the other rows aside from frozen midpoints and commits on drop", async () => { + test("pointer drag: the row itself follows, the others slide aside, one commit on release", async () => { await renderPage(); await act(async () => { row("alpha").querySelector(".rb-row-toggle")!.click(); }); const editor = row("alpha").querySelector(".rb-editor")!; + const list = editor.querySelector(".rb-channels")!; const names = () => [...editor.querySelectorAll(".rb-channel code")].map(node => node.textContent); - const items = () => editor.querySelectorAll(".rb-channel"); - // Rows 40px tall at 0 and 40; the list starts at 0. Layout is frozen at drag start. + const items = () => [...editor.querySelectorAll(".rb-channel")]; + // Rows 40px tall at 0 and 40 in a list at 0 (happy-dom has no layout). items().forEach((item, index) => { + Object.defineProperty(item, "offsetTop", { configurable: true, value: index * 40 }); + Object.defineProperty(item, "offsetHeight", { configurable: true, value: 40 }); item.getBoundingClientRect = () => ({ top: index * 40, height: 40, bottom: index * 40 + 40, left: 0, right: 0, width: 0, x: 0, y: index * 40, toJSON: () => ({}) }) as DOMRect; }); - const over = (clientY: number) => { - const event = new testWindow.Event("dragover", { bubbles: true, cancelable: true }) as unknown as Event; - Object.defineProperty(event, "clientY", { value: clientY }); - editor.querySelector(".rb-channels")!.dispatchEvent(event); + const pointer = (target: EventTarget, type: string, clientY: number) => { + const event = new testWindow.Event(type, { bubbles: true, cancelable: true }) as unknown as Event; + Object.defineProperties(event, { clientY: { value: clientY }, clientX: { value: 0 }, pointerId: { value: 1 }, button: { value: 0 }, isPrimary: { value: true }, pointerType: { value: "mouse" } }); + target.dispatchEvent(event); }; - await act(async () => { items()[0]!.dispatchEvent(new testWindow.Event("dragstart", { bubbles: true }) as unknown as Event); }); - await act(async () => { over(55); }); // short of the other row's midpoint (60): no move - expect(names()).toEqual(["gpt-5", "claude"]); - await act(async () => { over(70); }); - expect(names()).toEqual(["claude", "gpt-5"]); - await act(async () => { over(56); }); // back inside the hysteresis band: stays put - expect(names()).toEqual(["claude", "gpt-5"]); - expect(editor.textContent).not.toContain("Unsaved"); - await act(async () => { editor.querySelector(".rb-channels")!.dispatchEvent(new testWindow.Event("drop", { bubbles: true, cancelable: true }) as unknown as Event); }); + const first = items()[0]!; + await act(async () => { pointer(first, "pointerdown", 20); }); + await act(async () => { pointer(document, "pointermove", 30); }); + expect(list.classList.contains("sorting")).toBe(true); + expect(first.classList.contains("dragging")).toBe(true); + expect(editor.querySelectorAll(".rb-channel").length).toBe(2); // no copy of the dragged row + expect(names()).toEqual(["gpt-5", "claude"]); // nothing reorders before the release + await new Promise(resolve => setTimeout(resolve, 400)); // past the tap window + await act(async () => { pointer(document, "pointerup", 75); }); expect(names()).toEqual(["claude", "gpt-5"]); + expect(list.classList.contains("sorting")).toBe(false); + expect(items().every(item => item.style.transform === "")).toBe(true); expect(editor.textContent).toContain("Unsaved"); }); + test("pointer drag: a press on a row's button stays a click, and Escape cancels a drag", async () => { + await renderPage(); + await act(async () => { row("alpha").querySelector(".rb-row-toggle")!.click(); }); + const editor = row("alpha").querySelector(".rb-editor")!; + const list = editor.querySelector(".rb-channels")!; + const names = () => [...editor.querySelectorAll(".rb-channel code")].map(node => node.textContent); + const pointer = (target: EventTarget, type: string, clientY: number) => { + const event = new testWindow.Event(type, { bubbles: true, cancelable: true }) as unknown as Event; + Object.defineProperties(event, { clientY: { value: clientY }, clientX: { value: 0 }, pointerId: { value: 1 }, button: { value: 0 }, isPrimary: { value: true }, pointerType: { value: "mouse" } }); + target.dispatchEvent(event); + }; + await act(async () => { pointer(editor.querySelector(".rb-remove")!, "pointerdown", 20); }); + await act(async () => { pointer(document, "pointermove", 60); }); + expect(list.classList.contains("sorting")).toBe(false); + await act(async () => { pointer(document, "pointerup", 60); }); + await act(async () => { pointer(editor.querySelector(".rb-channel")!, "pointerdown", 20); }); + await act(async () => { pointer(document, "pointermove", 60); }); + expect(list.classList.contains("sorting")).toBe(true); + await act(async () => { document.dispatchEvent(new testWindow.KeyboardEvent("keydown", { key: "Escape", bubbles: true, cancelable: true }) as unknown as Event); }); + expect(list.classList.contains("sorting")).toBe(false); + await act(async () => { pointer(document, "pointerup", 75); }); + expect(names()).toEqual(["gpt-5", "claude"]); + }); + test("member table: source tags per cell, and an in-place edit writes the provider's model settings", async () => { await renderPage(); await act(async () => { row("alpha").querySelector(".rb-tag--button")!.click(); }); diff --git a/structure/dashboard-and-usage.md b/structure/dashboard-and-usage.md index cbf67ee270c..76bbfe8c027 100644 --- a/structure/dashboard-and-usage.md +++ b/structure/dashboard-and-usage.md @@ -126,7 +126,7 @@ The sidebar exposes eight rows (`gui/src/nav-groups.ts` `NAV_GROUPS`), in order: | API keys | Key table plus per-key detail (`gui/src/components/apikeys-workspace/`). The list payload carries masked prefixes only; each row deletes in place behind a two-step confirm, and clicking a key fetches the full value from `POST /api/keys/reveal`, which requires a current pairing or trusted Tailscale-identity session and answers `no-store`; automatic loopback sessions and raw admin tokens cannot reveal stored values, and a refusal there answers with the pairing surface — on the same-origin standalone transport the local pairing form, elsewhere the explanation alone — and requires a fresh reveal click after pairing. Displayed secrets and copy feedback are cleared on shared-session loss, pairing, inactive/hidden views, or a target change; stale asynchronous completions cannot restore them. | | Storage | Rail plus cleanup and trash detail (`gui/src/components/storage-workspace/`). | | Subagents | Featured-roster selection workspace (`gui/src/components/subagents-workspace/`). | -| Combos | `#models/combos` opens the overview (`gui/src/components/route-board/RouteBoard.tsx`, view model `gui/src/route-board-model.ts`): one row per combo with stacked provider icons, display name and public id, the channel order (`→` for failover, `·` otherwise, last-resort members marked), one quota line per provider from `/api/provider-quotas` (remaining percent, green above 50%, amber 20–50%, red below 20%; `key` providers read as pay per use), the catalog context window, an inline strategy menu and an on/off switch. Switched-off combos sort after the live ones. Antigravity pool windows read as family names (`Cla (Weekly)` → "Claude & GPT · weekly"). Account counts come from the report's `aggregation`, otherwise from `GET /api/oauth/accounts?provider=` for enabled OAuth providers (paused accounts listed separately). A strategy pick runs `validateComboDraft` and then the normal `PUT /api/combos`; JEV never saves from the row and opens the workspace on that combo instead, because an empty decision service means the hosted TypeSafe service. The switch writes the combo selector through `PUT /api/model-visibility` (`provider: "combo"`). Clicking a row opens the channel editor (reorder by drag, where the other rows make room live with a FLIP slide, or by move buttons; mark fallback only, i.e. `lastResort`; remove; add). Its "More settings" section opens in place: the capability policy, a "fallback channels wait their turn" switch that writes `cooldownWaitPolicy` (`"before-last-resort"` or `null`), and a member table (`gui/src/components/route-board/MemberTable.tsx`) of each member's context window, input modalities and effort levels with the combined row. Every cell carries its source from the row's `capabilitySources` (`parseCapabilitySources`; an older server without it falls back to the `*Declared` / `reasoningOverridden` flags via `capabilitySource`); members with no `/api/models` row fall back to their per-model config (`configuredMemberModels`). A gap with an `inferredCapabilities` estimate shows the value and its basis with an Adopt button that writes it through `PUT /api/model-settings`; estimates fill gaps only in the combined row, labelled (`withInferredGaps`), never in routing. A member edit sends only the changed fields to `PUT /api/model-settings` (`memberSettingsPatch`; restore sends `null` for the manual fields), validates the receipt, and refreshes the page; "Test it" (`gui/src/components/route-board/MemberProbe.tsx`) posts `POST /api/providers/probe-capabilities` with `apply: true`, repeats with `confirmMetered: true` after an inline confirmation naming `plannedRequests`, and shows `applicable: false` reasons (button greyed), a 409 as already running, and a failed baseline as inconclusive (`parseProbeResponse`). Drag reorder computes the drop slot from the row midpoints frozen at drag start with 8 px hysteresis (`dragSlot`) and commits on drop. The row's context tag opens that section and shows the smallest member under intersection and the largest under union (`comboContextWindow`); fallback-only marks render greyed with the reason while the combo has no `cooldownWaitPolicy`; only its save sends `lastResort` explicitly, every other save omits it so the server carries it over. Capability fields (`capabilityPolicy`, `onUnservable`) and `cooldownWaitPolicy` read absent as the defaults and are sent only when changed. "Advanced" opens the rail, detail panel and add flow (`gui/src/components/ComboWorkspace.tsx`) at `#models/combos/advanced`; `#models/combos/jev-auto` still lands there (`gui/src/pages/combos-view.ts`). The workspace stays mounted once opened, so an unsaved draft survives the overview, and the overview locks the strategy and channel save of the combo being drafted until the draft is saved or discarded. `gui/tests/route-board.test.tsx` covers the rows, PUT bodies, the JEV hand-off, validation, the switch selector, the channel save, drag sweeps over 4 and 6 rows, the member edit and restore bodies, and the draft lock. | +| Combos | `#models/combos` opens the overview (`gui/src/components/route-board/RouteBoard.tsx`, view model `gui/src/route-board-model.ts`): one row per combo with stacked provider icons, display name and public id, the channel order (`→` for failover, `·` otherwise, last-resort members marked), one quota line per provider from `/api/provider-quotas` (remaining percent, green above 50%, amber 20–50%, red below 20%; `key` providers read as pay per use), the catalog context window, an inline strategy menu and an on/off switch. Switched-off combos sort after the live ones. Antigravity pool windows read as family names (`Cla (Weekly)` → "Claude & GPT · weekly"). Account counts come from the report's `aggregation`, otherwise from `GET /api/oauth/accounts?provider=` for enabled OAuth providers (paused accounts listed separately). A strategy pick runs `validateComboDraft` and then the normal `PUT /api/combos`; JEV never saves from the row and opens the workspace on that combo instead, because an empty decision service means the hosted TypeSafe service. The switch writes the combo selector through `PUT /api/model-visibility` (`provider: "combo"`). Clicking a row opens the channel editor (reorder by pointer drag or by move buttons (which slide with FLIP); mark fallback only, i.e. `lastResort`; remove; add). Its "More settings" section opens in place: the capability policy, a "fallback channels wait their turn" switch that writes `cooldownWaitPolicy` (`"before-last-resort"` or `null`), and a member table (`gui/src/components/route-board/MemberTable.tsx`) of each member's context window, input modalities and effort levels with the combined row. Every cell carries its source from the row's `capabilitySources` (`parseCapabilitySources`; an older server without it falls back to the `*Declared` / `reasoningOverridden` flags via `capabilitySource`); members with no `/api/models` row fall back to their per-model config (`configuredMemberModels`). A gap with an `inferredCapabilities` estimate shows the value and its basis with an Adopt button that writes it through `PUT /api/model-settings`; estimates fill gaps only in the combined row, labelled (`withInferredGaps`), never in routing. A member edit sends only the changed fields to `PUT /api/model-settings` (`memberSettingsPatch`; restore sends `null` for the manual fields), validates the receipt, and refreshes the page; "Test it" (`gui/src/components/route-board/MemberProbe.tsx`) posts `POST /api/providers/probe-capabilities` with `apply: true`, repeats with `confirmMetered: true` after an inline confirmation naming `plannedRequests`, and shows `applicable: false` reasons (button greyed), a 409 as already running, and a failed baseline as inconclusive (`parseProbeResponse`). Pointer drag is Magpie's row sorter (`gui/src/components/route-board/drag-rows.ts`, MIT, © yetone): the row itself follows the pointer by a transform with no copy or placeholder, the rows it passes slide a row's height aside, Escape cancels, and the order changes once on release; the slot comes from the layout midpoints with 8 px hysteresis (`dragSlot`), and presses on the row's own controls (or anywhere but the grip on touch) stay clicks. The row's context tag opens that section and shows the smallest member under intersection and the largest under union (`comboContextWindow`); fallback-only marks render greyed with the reason while the combo has no `cooldownWaitPolicy`; only its save sends `lastResort` explicitly, every other save omits it so the server carries it over. Capability fields (`capabilityPolicy`, `onUnservable`) and `cooldownWaitPolicy` read absent as the defaults and are sent only when changed. "Advanced" opens the rail, detail panel and add flow (`gui/src/components/ComboWorkspace.tsx`) at `#models/combos/advanced`; `#models/combos/jev-auto` still lands there (`gui/src/pages/combos-view.ts`). The workspace stays mounted once opened, so an unsaved draft survives the overview, and the overview locks the strategy and channel save of the combo being drafted until the draft is saved or discarded. `gui/tests/route-board.test.tsx` covers the rows, PUT bodies, the JEV hand-off, validation, the switch selector, the channel save, drag sweeps over 4 and 6 rows, the member edit and restore bodies, and the draft lock. | | Add provider | Catalog browser plus form and OAuth panes (`gui/src/components/provider-catalog/`, `gui/src/components/AddProviderModal.tsx`). The catalog browses four tabs — Accounts, Free, Local, Paid — where Local is a catalog-only bucket peeled out of `bucketPresets` after `presetTier` has classified; the workspace `providerTier` stays three-way, so the rail, the free-paid sort and the Free count still treat a local runtime as free. Search sits above the tabs and reaches every tab at once: while a query is live the list renders all four groups with headings and the strip becomes jump chips with counts rather than a tablist, because moving the selected tab would change the row kind under the user (a preset-select button becomes a login row). ArrowDown from the search input focuses the first enabled result action; if none is available, focus stays in the input. The tab strip wraps within narrow modals. Every nonempty note has a full-text button so narrow rows never hide content permanently; the native note dialog closes during teardown and restores focus to its trigger. Provider notes clamp to two lines and open in full in a stacked native `` owned by `AddProviderModal`, which also owns the search text so its `window` Escape handler can unwind popup, then query, then dialog. | | Codex accounts | Account pool cards, add-account flow, switch and reset modals (`gui/src/components/CodexAccountPool.tsx`, `gui/src/components/AddCodexAccountModal.tsx`), plus the generic account-targeting picker opt-in on `gui/src/pages/codex-set-multiauth.tsx`. Add/delete/login completion is projected to one boolean before presentation; pending catalog work is a warning, not a failed account mutation. The main card's native-main device reauth (#3898) is owned by `gui/src/components/use-main-device-reauth.ts`: the dedicated `/api/codex-auth/main/reauth-device` namespace only — never the pool login route — with flowId-owned polling, an allowlisted verification URL, and no token fields accepted from payloads. The main-device reauth hook retains flow ownership from the Cancel click, while DELETE is unresolved and after retryable failure; polling normally continues. A concurrent GET HTTP error cannot expose a replacement login POST before DELETE settles. If a retryable DELETE failure races with a non-2xx GET while the flow is pending or committing, either response order preserves same-flow Cancel retry, restores the last server-provided device code, verification URL, and phase when needed, and keeps the existing poll cadence so a later terminal result remains observable. Outside same-flow cancellation ownership, a GET HTTP failure still stops polling without starting a second login POST. The cancellation-failure indication survives pending status updates until a trusted terminal result releases ownership. A successful DELETE with a terminal `failed` DTO releases it and uses the same closed failure-code mapping as polling; only `succeeded` notifies login completion. Unrecognized or nonterminal DTO status values remain retryable. A DELETE response with HTTP 404 and code `unknown_flow` releases the expired flow and shows the existing generic failure state so device re-login is available again; it claims neither login success nor confirmed cancellation. Confirmed cancellation also makes device re-login available. Start, polling and cancellation completions verify their controller or flow ownership after asynchronous response reads; replaced flows and unmounted hooks cannot update a newer flow or notify completion. Effect setup restores mounted state after the StrictMode development cleanup cycle. | | Dashboard overview | Overview, Providers, and Models tabs at the page level (`gui/src/pages/Dashboard.tsx`), the 30-day token and coverage stats in the overview head (`gui/src/pages/dashboard-overview-head.tsx`), and the effort-cap, injection, maintenance, sidecar, reasoning-retention, and memory panels below it (`gui/src/pages/dashboard-overview-panels.tsx`). The Reasoning retention controls (`gui/src/components/ReasoningRetentionPanel.tsx`) live in a collapsed Advanced settings disclosure at the end of Overview. They read and save `reasoningRetention` via GET/PUT `/api/settings` in `src/server/management/config-routes.ts`: only explicit `enabled: true` activates retention; absent, disabled, and legacy threshold-only settings remain off. The enable switch exposes numeric controls with defaults of 20% and 100000 tokens; disabling saves `enabled: false`, and null reset removes the setting and turns it off. Omission preserves it, validation precedes mutation, and save failure restores value and key presence. Copy warns that opt-in can preserve plaintext reasoning in local history/archive and that completed archives have no aggregate quota or expiry and require manual deletion. Loading disables writes, failures permit retry without losing edits, and stale responses cannot update a new API target. Its scope is the [routed v1/v2 compaction contract](transports/responses-failover.md#compaction-routing-overrides); opaque output stays unchanged. `tests/config/settings-reasoning-retention.test.ts` and `gui/tests/reasoning-retention-panel.test.tsx` cover the API and controls. Inputs expose invalid state and reference the validation alert only for the failing field. | From 67cf25dc8a8eb5853b637e8c72a8ee8cd5edf8c1 Mon Sep 17 00:00:00 2001 From: "Andrew (agent)" Date: Fri, 13 Nov 2026 12:09:40 -0500 Subject: [PATCH 11/11] feat(gui): suggested combos on the Combos overview Models that two or more enabled providers serve under one normalized name (prefix, case, gaps, version dots and a trailing effort suffix folded; snapshot dates kept) show as suggestions above the combo rows. Generate opens a failover draft ordered maker's subscription, other subscriptions, Vertex, then keys and relays (more quota left first within a tier) and saves through the existing PUT /api/combos. A combo that already covers the name gets an "add to combo" hint for missing providers instead, inserted ahead of its first lower-tier member. Dismissals stay in localStorage. The grouping idea follows Magpie's found groups (MIT, (c) yetone); no code is taken from it. --- docs-site/src/content/docs/guides/combos.md | 8 + .../src/content/docs/zh-cn/guides/combos.md | 2 +- gui/src/combo-suggestions.ts | 254 +++++++++++++++ .../route-board/ComboSuggestions.tsx | 269 ++++++++++++++++ gui/src/design/pages/route-board.css | 51 +++ gui/src/i18n/de.ts | 23 ++ gui/src/i18n/en.ts | 23 ++ gui/src/i18n/fr.ts | 23 ++ gui/src/i18n/ja.ts | 23 ++ gui/src/i18n/ko.ts | 23 ++ gui/src/i18n/pt.ts | 23 ++ gui/src/i18n/ru.ts | 23 ++ gui/src/i18n/tr.ts | 23 ++ gui/src/i18n/vi.ts | 23 ++ gui/src/i18n/zh-TW.ts | 23 ++ gui/src/i18n/zh.ts | 23 ++ gui/src/pages/Combos.tsx | 38 ++- gui/tests/combo-suggestions.test.tsx | 297 ++++++++++++++++++ structure/dashboard-and-usage.md | 2 +- 19 files changed, 1171 insertions(+), 3 deletions(-) create mode 100644 gui/src/combo-suggestions.ts create mode 100644 gui/src/components/route-board/ComboSuggestions.tsx create mode 100644 gui/tests/combo-suggestions.test.tsx diff --git a/docs-site/src/content/docs/guides/combos.md b/docs-site/src/content/docs/guides/combos.md index d0b12332cce..fbe53c32db7 100644 --- a/docs-site/src/content/docs/guides/combos.md +++ b/docs-site/src/content/docs/guides/combos.md @@ -1002,6 +1002,14 @@ on that relay and saves conclusive results; for a pay-per-use provider it first small requests it will send. A failed plain request changes nothing. Context is inferred from the model name, never probed. Click the context tag on a row to open it directly. +**Suggested combos** sits above the rows when two or more of your providers serve a model under the +same name (`claude-opus-5.5` and `claude-opus-5-5`, or `gpt-6.1-sol-high` and `gpt-6.1-sol`, count as +one; snapshot dates do not). **Generate** opens a failover draft with subscriptions from the model's +maker first, then other subscriptions, Vertex credit, and pay-per-use keys and relays last; rename, +reorder, or drop members, then **Save combo**. When an existing combo for that model is missing a +provider that serves it, the card offers **Add to combo** instead. **Dismiss** hides a suggestion in this +browser only; nothing is written to the config. + **Advanced** opens the full workspace (`#models/combos/advanced`), which creates, edits, renames, and removes combos. Its model selectors include hidden models: catalog visibility only controls external model lists, not internal Combo selection, and selecting a hidden model does not make it visible externally. 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 ad51add3845..0a9975f9206 100644 --- a/docs-site/src/content/docs/zh-cn/guides/combos.md +++ b/docs-site/src/content/docs/zh-cn/guides/combos.md @@ -222,7 +222,7 @@ combo 失败分为 **跳转** 失败和 **终止** 失败。 ### Dashboard -**模型 → 组合** 默认先打开总览:每个组合一行,显示通道顺序、各供应商剩余额度、上下文窗口、策略下拉和开关。点 **高级** 打开下面介绍的完整工作区。 +**模型 → 组合** 默认先打开总览:每个组合一行,显示通道顺序、各供应商剩余额度、上下文窗口、策略下拉和开关。点 **高级** 打开下面介绍的完整工作区。总览上方的 **推荐组合** 会列出两家以上提供方都提供的同名模型:**生成** 打开一个故障转移草稿(原厂订阅在前,其次其他订阅、Vertex 赠金,按量 key 和中转站最后),确认后保存;已有组合缺某一家时显示 **加进组合**;**忽略** 只记在本浏览器里,不写配置。 打开本地 dashboard 并选择 **Models → Combos**。该工作区可以创建、编辑、重命名和删除 combo。模型选择器使用包含隐藏模型的完整目录:显示/隐藏设置只影响对外模型列表,不影响 Combo 内部选择,选中隐藏模型也不会将其对外显示。目标选择器仍排除已禁用的提供方、嵌套 combo 和仅用于决策服务的 JEV 提供方。 diff --git a/gui/src/combo-suggestions.ts b/gui/src/combo-suggestions.ts new file mode 100644 index 00000000000..d635cbcf76a --- /dev/null +++ b/gui/src/combo-suggestions.ts @@ -0,0 +1,254 @@ +/** + * Combo suggestions for the Combos overview: models that two or more providers serve under the + * same name, offered as a ready-made failover combo, and existing combos that a provider serving + * their model is missing from. Pure: no React, no fetch, no storage. + * + * The idea of merging one model across providers by a normalized name follows Magpie's found + * groups (`internal/catalog/samemodel.go`, MIT, Copyright (c) 2026 yetone). No code is taken + * from it. Unlike Magpie, a snapshot date stays part of the name (two snapshots can differ in + * capability) and a trailing reasoning-effort suffix is dropped. + */ +import { COMBO_ID_RE, emptyDraft, newComboTarget, type ComboItem } from "./combo-workspace-data"; + +export interface SuggestionProvider { + name: string; + disabled?: boolean; + hiddenFromPicker?: boolean; + authMode?: string; + adapter?: string; + baseUrl?: string; +} + +export interface SuggestionModel { + provider: string; + id: string; +} + +/** + * Order members are suggested in: a subscription from the model's own maker, any other + * subscription, Vertex credit, then pay-per-use keys and relays. + */ +export type ChannelTier = "own-subscription" | "subscription" | "vertex" | "metered"; +const TIER_RANK: Record = { "own-subscription": 0, subscription: 1, vertex: 2, metered: 3 }; + +export interface SuggestedMember { + provider: string; + model: string; + tier: ChannelTier; + /** Lowest remaining percent across the provider's reported windows for this model. */ + remainingPercent?: number; +} + +export type ComboSuggestion = + | { + kind: "create"; + /** Dismissal key, stable across reloads. */ + key: string; + /** Normalized model name the members share. */ + model: string; + /** Free combo id for the draft. */ + comboId: string; + members: SuggestedMember[]; + /** At least one member is listed in the model catalog rather than hidden from it. */ + listed: boolean; + } + | { + kind: "extend"; + key: string; + model: string; + comboId: string; + /** Providers serving the combo's model that the combo does not route to yet. */ + members: SuggestedMember[]; + }; + +const EFFORT_SUFFIX = /-(?:minimal|low|medium|high|xhigh|max)$/; + +/** + * One model's name across providers: no `provider/` prefix, lowercase, runs of spaces, + * underscores and dashes as one dash, a version dot as a dash (`claude-opus-5.5` is + * `claude-opus-5-5`), and no trailing effort suffix (`gpt-6.1-sol-high` is `gpt-6-1-sol`). + */ +export function normalizeModelName(id: string): string { + let name = id.trim().toLowerCase(); + name = name.slice(name.lastIndexOf("/") + 1); + name = name.replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, ""); + name = name.replace(/(\d)\.(?=\d)/g, "$1-"); + return name.replace(EFFORT_SUFFIX, ""); +} + +/** The id spelled as the provider writes it, minus prefix and effort suffix: the combo id candidate. */ +function spelling(id: string): string { + const bare = id.trim().slice(id.trim().lastIndexOf("/") + 1).toLowerCase(); + return bare.replace(EFFORT_SUFFIX, ""); +} + +const MODEL_MAKERS: ReadonlyArray<[RegExp, string]> = [ + [/^claude/, "anthropic"], + [/^(?:gpt|o\d|codex|chatgpt)/, "openai"], + [/^(?:gemini|gemma)/, "google"], + [/^grok/, "xai"], + [/^deepseek/, "deepseek"], +]; + +const PROVIDER_MAKERS: ReadonlyArray<[RegExp, string]> = [ + [/(?:^|\.)anthropic\.com$/, "anthropic"], + [/(?:^|\.)(?:openai\.com|chatgpt\.com)$/, "openai"], + [/(?:^|\.)googleapis\.com$/, "google"], + [/(?:^|\.)x\.ai$/, "xai"], + [/(?:^|\.)deepseek\.com$/, "deepseek"], +]; + +function hostOf(baseUrl: string | undefined): string { + if (!baseUrl) return ""; + try { + return new URL(baseUrl).hostname.toLowerCase(); + } catch { + return ""; + } +} + +export function channelTier(provider: SuggestionProvider, model: string): ChannelTier { + const host = hostOf(provider.baseUrl); + if (host.startsWith("aiplatform.") || /vertex/i.test(provider.name)) return "vertex"; + if (provider.authMode !== "oauth" && provider.authMode !== "forward") return "metered"; + const modelMaker = MODEL_MAKERS.find(([re]) => re.test(normalizeModelName(model)))?.[1]; + const providerMaker = PROVIDER_MAKERS.find(([re]) => re.test(host))?.[1]; + return modelMaker !== undefined && modelMaker === providerMaker ? "own-subscription" : "subscription"; +} + +/** Tier first; within a tier more quota left first, unknown quota after; then catalog order. */ +export function orderMembers(members: readonly SuggestedMember[]): SuggestedMember[] { + return members + .map((member, index) => ({ member, index })) + .sort((a, b) => { + const tier = TIER_RANK[a.member.tier] - TIER_RANK[b.member.tier]; + if (tier !== 0) return tier; + const left = a.member.remainingPercent ?? -1; + const right = b.member.remainingPercent ?? -1; + return right - left || a.index - b.index; + }) + .map(({ member }) => member); +} + +/** The combo is about one model: its id names it, or every member serves it. */ +function comboModel(combo: ComboItem): string | undefined { + const byId = normalizeModelName(combo.id); + const names = new Set(combo.targets.map((target) => normalizeModelName(target.model))); + if (names.size === 1) return [...names][0]; + return names.has(byId) ? byId : undefined; +} + +/** `base`, else `base-2`, `base-3`, … that no combo id or alias already takes (case-insensitive). */ +export function freeComboId(base: string, combos: readonly ComboItem[]): string { + const taken = new Set(combos.flatMap((combo) => [combo.id, combo.alias ?? ""]).map((id) => id.toLowerCase())); + if (!taken.has(base.toLowerCase())) return base; + for (let n = 2; ; n++) { + const candidate = `${base}-${n}`; + if (!taken.has(candidate.toLowerCase())) return candidate; + } +} + +export interface SuggestionInput { + combos: readonly ComboItem[]; + /** Catalog rows, combos excluded, hidden rows included: hiding a model only hides it from pickers. */ + models: readonly SuggestionModel[]; + /** `provider/model` keys hidden from the model catalog (`disabledModels`). */ + hiddenModels?: ReadonlySet; + providers: readonly SuggestionProvider[]; + remainingPercent?: (provider: string, model: string) => number | undefined; + dismissed?: ReadonlySet; +} + +export function suggestionKey(kind: ComboSuggestion["kind"], model: string, comboId?: string): string { + return kind === "create" ? `create:${model}` : `extend:${comboId}:${model}`; +} + +export function buildComboSuggestions(input: SuggestionInput): ComboSuggestion[] { + const providers = new Map(input.providers.map((provider) => [provider.name, provider])); + /** model name → provider → that provider's id for it (the shortest spelling wins). */ + const byModel = new Map>(); + for (const row of input.models) { + const provider = providers.get(row.provider); + if (!provider || provider.disabled || provider.hiddenFromPicker) continue; + const name = normalizeModelName(row.id); + if (!name) continue; + const served = byModel.get(name) ?? new Map(); + const current = served.get(row.provider); + if (current === undefined || row.id.length < current.length) served.set(row.provider, row.id); + byModel.set(name, served); + } + + const member = (provider: string, model: string): SuggestedMember => { + const remaining = input.remainingPercent?.(provider, model); + return { + provider, + model, + tier: channelTier(providers.get(provider)!, model), + ...(remaining !== undefined ? { remainingPercent: remaining } : {}), + }; + }; + + const covering = new Map(); + for (const combo of input.combos) { + const name = comboModel(combo); + if (name !== undefined && !covering.has(name)) covering.set(name, combo); + } + + const creates: Array = []; + const extends_: Array = []; + for (const [name, served] of byModel) { + if (served.size < 2) continue; + const combo = covering.get(name); + if (combo) { + const routed = new Set(combo.targets.map((target) => target.provider)); + const missing = [...served].filter(([provider]) => !routed.has(provider)); + const key = suggestionKey("extend", name, combo.id); + if (missing.length === 0 || input.dismissed?.has(key)) continue; + extends_.push({ kind: "extend", key, model: name, comboId: combo.id, members: orderMembers(missing.map(([p, m]) => member(p, m))) }); + continue; + } + const key = suggestionKey("create", name); + if (input.dismissed?.has(key)) continue; + const spellings = [...served.values()].map(spelling); + const counts = new Map(); + for (const value of spellings) counts.set(value, (counts.get(value) ?? 0) + 1); + const preferred = spellings.reduce((best, value) => (counts.get(value)! > counts.get(best)! ? value : best)); + creates.push({ + kind: "create", + key, + model: name, + comboId: freeComboId(COMBO_ID_RE.test(preferred) ? preferred : name, input.combos), + members: orderMembers([...served].map(([p, m]) => member(p, m))), + listed: [...served].some(([provider, model]) => !input.hiddenModels?.has(`${provider}/${model}`)), + }); + } + creates.sort((a, b) => Number(b.listed) - Number(a.listed) || b.members.length - a.members.length || a.model.localeCompare(b.model)); + extends_.sort((a, b) => a.comboId.localeCompare(b.comboId)); + // A model nobody lists in the catalog is usually an older version: after the hints for live combos. + return [...creates.filter((s) => s.listed), ...extends_, ...creates.filter((s) => !s.listed)]; +} + +/** The failover combo a create suggestion saves, members in the order given. */ +export function suggestionDraft(comboId: string, members: readonly SuggestedMember[]): ComboItem { + return { + ...emptyDraft(comboId), + targets: members.map((entry) => newComboTarget({ provider: entry.provider, model: entry.model })), + }; +} + +/** + * The combo with each suggested member placed before the first of its own members in a lower + * tier (a subscription goes ahead of pay-per-use keys), else last. Its own members keep their order. + */ +export function extendedCombo( + combo: ComboItem, + members: readonly SuggestedMember[], + tierOf: (provider: string, model: string) => ChannelTier, +): ComboItem { + const targets = [...combo.targets]; + for (const entry of members) { + const at = targets.findIndex((target) => TIER_RANK[tierOf(target.provider, target.model)] > TIER_RANK[entry.tier]); + targets.splice(at < 0 ? targets.length : at, 0, newComboTarget({ provider: entry.provider, model: entry.model })); + } + return { ...combo, targets }; +} diff --git a/gui/src/components/route-board/ComboSuggestions.tsx b/gui/src/components/route-board/ComboSuggestions.tsx new file mode 100644 index 00000000000..e76fa42e170 --- /dev/null +++ b/gui/src/components/route-board/ComboSuggestions.tsx @@ -0,0 +1,269 @@ +import { useState } from "react"; +import { + buildComboSuggestions, + channelTier, + extendedCombo, + suggestionDraft, + type ChannelTier, + type ComboSuggestion, + type SuggestedMember, + type SuggestionModel, + type SuggestionProvider, +} from "../../combo-suggestions"; +import { isValidComboId, type ComboDraftError, type ComboItem } from "../../combo-workspace-data"; +import { useT, type TKey } from "../../i18n/shared"; +import { makeCollapseStore } from "../../pages/collapse-store"; +import { formatProviderDisplayName } from "../../provider-icons"; +import { moveChannel } from "../../route-board-model"; +import { ProviderIcon } from "../provider-workspace/ProviderRail"; + +type SaveResult = { ok: boolean; error?: string }; + +const dismissedStore = makeCollapseStore("ocx.combos.suggestions.dismissed.v1"); +const COLLAPSED_COUNT = 3; + +const TIER_LABEL: Record = { + "own-subscription": "comboSuggest.tier.ownSubscription", + subscription: "comboSuggest.tier.subscription", + vertex: "comboSuggest.tier.vertex", + metered: "comboSuggest.tier.metered", +}; + +export interface ComboSuggestionsProps { + combos: readonly ComboItem[]; + models: readonly SuggestionModel[]; + hiddenModels: ReadonlySet; + providers: readonly SuggestionProvider[]; + remainingPercent: (provider: string, model: string) => number | undefined; + validate: (item: ComboItem, isCreate: boolean) => ComboDraftError | null; + errorText: (code: ComboDraftError, item: ComboItem) => string; + onCreate: (item: ComboItem) => Promise; + onExtend: (item: ComboItem) => Promise; +} + +/** Suggested combos above the overview: same-name models across providers, one click to a draft. */ +export function ComboSuggestions(props: ComboSuggestionsProps) { + const t = useT(); + const [dismissed, setDismissed] = useState>(() => dismissedStore.read() ?? new Set()); + const [showAll, setShowAll] = useState(false); + const [draftKey, setDraftKey] = useState(null); + const suggestions = buildComboSuggestions({ ...props, dismissed }); + if (suggestions.length === 0) return null; + + const dismiss = (key: string) => { + const next = new Set(dismissed).add(key); + dismissedStore.write(next); + setDismissed(next); + if (draftKey === key) setDraftKey(null); + }; + const providerByName = new Map(props.providers.map((provider) => [provider.name, provider])); + const tierOf = (provider: string, model: string): ChannelTier => { + const known = providerByName.get(provider); + return known ? channelTier(known, model) : "metered"; + }; + const shown = showAll ? suggestions : suggestions.slice(0, COLLAPSED_COUNT); + + return ( +
      +
      + {t("comboSuggest.title")} + {t("comboSuggest.lede")} +
      +
        + {shown.map((suggestion) => ( + setDraftKey(open ? suggestion.key : null)} + onDismiss={() => dismiss(suggestion.key)} + /> + ))} +
      + {suggestions.length > COLLAPSED_COUNT && ( + + )} +
      + ); +} + +function MemberChips({ members }: { members: readonly SuggestedMember[] }) { + const t = useT(); + return ( + + {members.map((member, index) => ( + + {index > 0 && } + {formatProviderDisplayName(member.provider, t)} + {t(TIER_LABEL[member.tier])} + + ))} + + ); +} + +function SuggestionCard({ + suggestion, + drafting, + combos, + tierOf, + validate, + errorText, + onCreate, + onExtend, + onDraft, + onDismiss, +}: { + suggestion: ComboSuggestion; + drafting: boolean; + combos: readonly ComboItem[]; + tierOf: (provider: string, model: string) => ChannelTier; + validate: ComboSuggestionsProps["validate"]; + errorText: ComboSuggestionsProps["errorText"]; + onCreate: ComboSuggestionsProps["onCreate"]; + onExtend: ComboSuggestionsProps["onExtend"]; + onDraft: (open: boolean) => void; + onDismiss: () => void; +}) { + const t = useT(); + const [busy, setBusy] = useState(false); + const [message, setMessage] = useState(null); + + const save = async (item: ComboItem, isCreate: boolean) => { + const error = validate(item, isCreate); + if (error) return setMessage(errorText(error, item)); + setBusy(true); + setMessage(null); + try { + const result = await (isCreate ? onCreate(item) : onExtend(item)); + if (!result.ok) setMessage(result.error ?? t("cws.saveFailed")); + else if (isCreate) onDraft(false); + } finally { + setBusy(false); + } + }; + + const providers = [...new Set(suggestion.members.map((member) => member.provider))]; + const target = suggestion.kind === "extend" ? combos.find((combo) => combo.id === suggestion.comboId) : undefined; + return ( +
    2. +
      + + + {suggestion.kind === "create" ? ( + <> + + {suggestion.comboId} + {t("comboSuggest.servedBy", { count: suggestion.members.length })} + + + + ) : ( + <> + + {suggestion.comboId} + + {t("comboSuggest.canAdd", { providers: providers.map((provider) => formatProviderDisplayName(provider, t)).join(", ") })} + + + + + )} + + + {suggestion.kind === "create" ? ( + + ) : ( + + )} + + +
      + {message &&

      {message}

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

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

      +
        + {members.map((member, index) => ( +
      1. + + {formatProviderDisplayName(member.provider, t)} + {member.model} + {t(TIER_LABEL[member.tier])} + {member.remainingPercent !== undefined && ( + {t("comboSuggest.draft.left", { percent: Math.round(member.remainingPercent) })} + )} + + + + + +
      2. + ))} +
      +
      + {t("comboSuggest.draft.strategy")} + + +
      +
      + ); +} diff --git a/gui/src/design/pages/route-board.css b/gui/src/design/pages/route-board.css index 915a808edad..a3bedb8698f 100644 --- a/gui/src/design/pages/route-board.css +++ b/gui/src/design/pages/route-board.css @@ -190,3 +190,54 @@ .rb-channel :is(button, input, [role=combobox]) { cursor: pointer; } /* A press on the provider icon must start the row drag, not the browser's own image drag. */ .rb-channel img, .rb-channel svg { pointer-events: none; -webkit-user-drag: none; user-select: none; } + +/* Suggested combos: same-name models across providers (T2c). Grey, above the combo list. */ +.rb-suggest { + margin-bottom: 16px; + padding: 12px 0 4px; + border-radius: 12px; + background: light-dark(var(--ocx-raised), var(--ocx-surface-2)); + box-shadow: inset 0 0 0 1px var(--ocx-line); +} +.rb-suggest-head { display: flex; flex-wrap: wrap; align-items: baseline; gap: 4px 10px; padding: 0 16px 6px; } +.rb-suggest-head strong { color: var(--ocx-fg); font-size: 14px; font-weight: 600; } +.rb-suggest-head span { color: var(--ocx-fg-subtle); font-size: 12.5px; } +.rb-suggest-list { list-style: none; margin: 0; padding: 0; } +.rb-suggest-card + .rb-suggest-card { border-top: 1px dashed var(--ocx-line); } +.rb-suggest-actions { display: inline-flex; flex: none; gap: 6px; } +.rb-suggest-note { color: var(--ocx-fg-subtle); font-size: 12.5px; } +.rb-suggest-tier { + padding: 0 5px; + border-radius: 999px; + background: var(--ocx-accent-soft); + color: var(--ocx-fg-subtle); + font-size: 11px; +} +.rb-suggest-tier--own-subscription { background: var(--ocx-success-soft); color: var(--ocx-success); } +.rb-suggest-tier--subscription { background: var(--ocx-highlight-soft); color: var(--ocx-highlight); } +.rb-suggest-more { margin: 2px 12px 6px; } +.rb-suggest-draft { display: flex; flex-direction: column; gap: 8px; padding: 0 16px 14px 100px; } +.rb-suggest-field { display: inline-flex; align-items: center; gap: 8px; color: var(--ocx-fg-muted); font-size: 13px; } +.rb-suggest-id { width: 260px; font-family: var(--font-code); } +.rb-suggest-hint { margin: 0; color: var(--ocx-fg-subtle); font-size: 12.5px; } +.rb-suggest-members { display: flex; flex-direction: column; gap: 4px; margin: 0; padding: 0; list-style: none; counter-reset: rb-member; } +.rb-suggest-members li { + display: flex; + align-items: center; + gap: 8px; + padding: 4px 8px; + border-radius: 8px; + background: var(--ocx-surface); + box-shadow: inset 0 0 0 1px var(--ocx-line); + font-size: 13px; + counter-increment: rb-member; +} +.rb-suggest-members li::before { content: counter(rb-member); width: 14px; color: var(--ocx-fg-subtle); font-size: 12px; text-align: right; } +.rb-suggest-member-name { color: var(--ocx-fg); } +.rb-suggest-members code { color: var(--ocx-fg-muted); font-family: var(--font-code); font-size: 12px; } +.rb-suggest-move { display: inline-flex; gap: 2px; margin-left: auto; } +.rb-suggest-icon-btn { min-width: 28px; padding-inline: 6px; } +.rb-suggest-draft-actions { display: flex; align-items: center; justify-content: flex-end; gap: 8px; } +.rb-suggest-draft-actions .rb-suggest-note { margin-right: auto; } +@media (max-width: 760px) { .rb-suggest-draft { padding-left: 16px; } } +.rb-suggest-card .rb-row-body { flex: 1 1 auto; } diff --git a/gui/src/i18n/de.ts b/gui/src/i18n/de.ts index c0233e60771..4cda039a8b9 100644 --- a/gui/src/i18n/de.ts +++ b/gui/src/i18n/de.ts @@ -4598,4 +4598,27 @@ export const de: Record = { "routeBoard.probe.nothingApplied": "Nichts eindeutig, daher nichts gespeichert.", "routeBoard.probe.contextNote": "Der Kontext wird aus dem Modellnamen abgeleitet, nicht gemessen.", "routeBoard.probe.close": "Schließen", + "comboSuggest.title": "Vorgeschlagene Combos", + "comboSuggest.lede": "Modelle, die mehr als einer Ihrer Anbieter unter demselben Namen bereitstellt. Erstellen Sie eine Combo, um einen Modellnamen über alle diese Anbieter zu routen.", + "comboSuggest.servedBy": "bereitgestellt von {count} Anbietern", + "comboSuggest.canAdd": "kann auch {providers} nutzen", + "comboSuggest.generate": "Erstellen", + "comboSuggest.addTo": "Zur Combo hinzufügen", + "comboSuggest.dismiss": "Ausblenden", + "comboSuggest.showAll": "Alle {count} anzeigen", + "comboSuggest.showFewer": "Weniger anzeigen", + "comboSuggest.tier.ownSubscription": "Abo des Herstellers", + "comboSuggest.tier.subscription": "Abo", + "comboSuggest.tier.vertex": "Vertex-Guthaben", + "comboSuggest.tier.metered": "nutzungsabhängig", + "comboSuggest.draft.id": "Combo-ID", + "comboSuggest.draft.orderHint": "Die Reihenfolge von oben nach unten: zuerst Abos, dann Vertex-Guthaben, zuletzt Keys mit nutzungsabhängiger Abrechnung und Relays. Vor dem Speichern umsortieren oder entfernen.", + "comboSuggest.draft.left": "{percent}% übrig", + "comboSuggest.draft.up": "Nach oben", + "comboSuggest.draft.down": "Nach unten", + "comboSuggest.draft.remove": "Entfernen", + "comboSuggest.draft.strategy": "Strategie: Failover. Nach dem Speichern in der Zeile ändern.", + "comboSuggest.draft.cancel": "Abbrechen", + "comboSuggest.draft.save": "Combo speichern", + "comboSuggest.draft.saving": "Wird gespeichert…", }; diff --git a/gui/src/i18n/en.ts b/gui/src/i18n/en.ts index 45570e244f0..08dac5d156d 100644 --- a/gui/src/i18n/en.ts +++ b/gui/src/i18n/en.ts @@ -4632,6 +4632,29 @@ export const en = { "routeBoard.probe.nothingApplied": "Nothing conclusive, so nothing was saved.", "routeBoard.probe.contextNote": "Context is inferred from the model name, not measured.", "routeBoard.probe.close": "Close", + "comboSuggest.title": "Suggested combos", + "comboSuggest.lede": "Models that more than one of your providers serve under the same name. Generate a combo to route one model name across all of them.", + "comboSuggest.servedBy": "served by {count} providers", + "comboSuggest.canAdd": "can also use {providers}", + "comboSuggest.generate": "Generate", + "comboSuggest.addTo": "Add to combo", + "comboSuggest.dismiss": "Dismiss", + "comboSuggest.showAll": "Show all {count}", + "comboSuggest.showFewer": "Show fewer", + "comboSuggest.tier.ownSubscription": "maker's subscription", + "comboSuggest.tier.subscription": "subscription", + "comboSuggest.tier.vertex": "Vertex credit", + "comboSuggest.tier.metered": "pay per use", + "comboSuggest.draft.id": "Combo id", + "comboSuggest.draft.orderHint": "Tried top to bottom: subscriptions first, then Vertex credit, pay-per-use keys and relays last. Reorder or remove before saving.", + "comboSuggest.draft.left": "{percent}% left", + "comboSuggest.draft.up": "Move up", + "comboSuggest.draft.down": "Move down", + "comboSuggest.draft.remove": "Remove", + "comboSuggest.draft.strategy": "Strategy: failover. Change it in the row after saving.", + "comboSuggest.draft.cancel": "Cancel", + "comboSuggest.draft.save": "Save combo", + "comboSuggest.draft.saving": "Saving…", } as const; export type TKey = keyof typeof en; diff --git a/gui/src/i18n/fr.ts b/gui/src/i18n/fr.ts index 5b73c393ab8..fdf43b06c54 100644 --- a/gui/src/i18n/fr.ts +++ b/gui/src/i18n/fr.ts @@ -4587,4 +4587,27 @@ export const fr: Record = { "routeBoard.probe.nothingApplied": "Rien de concluant, donc rien n'a été enregistré.", "routeBoard.probe.contextNote": "Le contexte est déduit du nom du modèle, pas mesuré.", "routeBoard.probe.close": "Fermer", + "comboSuggest.title": "Combinaisons suggérées", + "comboSuggest.lede": "Modèles que plusieurs de vos fournisseurs proposent sous le même nom. Générez une combinaison pour router un seul nom de modèle vers tous ces fournisseurs.", + "comboSuggest.servedBy": "proposé par {count} fournisseurs", + "comboSuggest.canAdd": "peut aussi utiliser {providers}", + "comboSuggest.generate": "Générer", + "comboSuggest.addTo": "Ajouter à la combinaison", + "comboSuggest.dismiss": "Ignorer", + "comboSuggest.showAll": "Afficher les {count}", + "comboSuggest.showFewer": "Afficher moins", + "comboSuggest.tier.ownSubscription": "abonnement de l’éditeur", + "comboSuggest.tier.subscription": "abonnement", + "comboSuggest.tier.vertex": "crédit Vertex", + "comboSuggest.tier.metered": "paiement à l’usage", + "comboSuggest.draft.id": "Identifiant de la combinaison", + "comboSuggest.draft.orderHint": "Testés de haut en bas : les abonnements d’abord, puis le crédit Vertex, les clés à l’usage et les relais en dernier. Réordonnez ou retirez des éléments avant d’enregistrer.", + "comboSuggest.draft.left": "{percent} % restants", + "comboSuggest.draft.up": "Monter", + "comboSuggest.draft.down": "Descendre", + "comboSuggest.draft.remove": "Retirer", + "comboSuggest.draft.strategy": "Stratégie : basculement. Modifiez-la dans la ligne après l’enregistrement.", + "comboSuggest.draft.cancel": "Annuler", + "comboSuggest.draft.save": "Enregistrer la combinaison", + "comboSuggest.draft.saving": "Enregistrement…", }; diff --git a/gui/src/i18n/ja.ts b/gui/src/i18n/ja.ts index 59fcb80d7a4..3bd397e5ae3 100644 --- a/gui/src/i18n/ja.ts +++ b/gui/src/i18n/ja.ts @@ -4620,4 +4620,27 @@ export const ja: Record = { "routeBoard.probe.nothingApplied": "確かな結果がないため、何も保存していません。", "routeBoard.probe.contextNote": "コンテキストはモデル名から推定し、実測しません。", "routeBoard.probe.close": "閉じる", + "comboSuggest.title": "おすすめのコンボ", + "comboSuggest.lede": "複数のプロバイダーが同じ名前で提供しているモデルです。コンボを生成すると、1 つのモデル名ですべてのプロバイダーにルーティングできます。", + "comboSuggest.servedBy": "{count} 社のプロバイダーが提供", + "comboSuggest.canAdd": "{providers} も利用可能", + "comboSuggest.generate": "生成", + "comboSuggest.addTo": "コンボに追加", + "comboSuggest.dismiss": "非表示", + "comboSuggest.showAll": "すべて表示({count} 件)", + "comboSuggest.showFewer": "折りたたむ", + "comboSuggest.tier.ownSubscription": "提供元のサブスクリプション", + "comboSuggest.tier.subscription": "サブスクリプション", + "comboSuggest.tier.vertex": "Vertex クレジット", + "comboSuggest.tier.metered": "従量課金", + "comboSuggest.draft.id": "コンボ ID", + "comboSuggest.draft.orderHint": "上から順に試行されます。サブスクリプションが先、次に Vertex クレジット、従量課金の API キーとリレーは最後です。保存前に並べ替えや削除ができます。", + "comboSuggest.draft.left": "残り {percent}%", + "comboSuggest.draft.up": "上へ", + "comboSuggest.draft.down": "下へ", + "comboSuggest.draft.remove": "削除", + "comboSuggest.draft.strategy": "戦略:フェイルオーバー。保存後に行内で変更できます。", + "comboSuggest.draft.cancel": "キャンセル", + "comboSuggest.draft.save": "コンボを保存", + "comboSuggest.draft.saving": "保存中…", }; diff --git a/gui/src/i18n/ko.ts b/gui/src/i18n/ko.ts index 5a75534040d..7d61796bcf8 100644 --- a/gui/src/i18n/ko.ts +++ b/gui/src/i18n/ko.ts @@ -4620,4 +4620,27 @@ export const ko: Record = { "routeBoard.probe.nothingApplied": "확실한 결과가 없어 아무것도 저장하지 않았습니다.", "routeBoard.probe.contextNote": "컨텍스트는 모델 이름으로 추정하며 실측하지 않습니다.", "routeBoard.probe.close": "닫기", + "comboSuggest.title": "추천 콤보", + "comboSuggest.lede": "둘 이상의 프로바이더가 같은 이름으로 제공하는 모델입니다. 콤보를 생성하면 하나의 모델 이름으로 이들 모두에 라우팅할 수 있습니다.", + "comboSuggest.servedBy": "{count}개 프로바이더가 제공", + "comboSuggest.canAdd": "{providers}도 사용할 수 있음", + "comboSuggest.generate": "생성", + "comboSuggest.addTo": "콤보에 추가", + "comboSuggest.dismiss": "무시", + "comboSuggest.showAll": "전체 {count}개 보기", + "comboSuggest.showFewer": "접기", + "comboSuggest.tier.ownSubscription": "제작사 구독", + "comboSuggest.tier.subscription": "구독", + "comboSuggest.tier.vertex": "Vertex 크레딧", + "comboSuggest.tier.metered": "종량제", + "comboSuggest.draft.id": "콤보 ID", + "comboSuggest.draft.orderHint": "위에서 아래 순서로 시도합니다. 구독이 먼저, 그다음 Vertex 크레딧, 종량제 키와 릴레이는 마지막입니다. 저장하기 전에 순서를 바꾸거나 삭제할 수 있습니다.", + "comboSuggest.draft.left": "{percent}% 남음", + "comboSuggest.draft.up": "위로", + "comboSuggest.draft.down": "아래로", + "comboSuggest.draft.remove": "삭제", + "comboSuggest.draft.strategy": "전략: 장애 조치(failover). 저장 후 행에서 바꿀 수 있습니다.", + "comboSuggest.draft.cancel": "취소", + "comboSuggest.draft.save": "콤보 저장", + "comboSuggest.draft.saving": "저장 중…", }; diff --git a/gui/src/i18n/pt.ts b/gui/src/i18n/pt.ts index c1eaa5af072..2a4e78e7aee 100644 --- a/gui/src/i18n/pt.ts +++ b/gui/src/i18n/pt.ts @@ -4593,4 +4593,27 @@ export const pt: Record = { "routeBoard.probe.nothingApplied": "Nada conclusivo, então nada foi salvo.", "routeBoard.probe.contextNote": "O contexto é inferido do nome do modelo, não medido.", "routeBoard.probe.close": "Fechar", + "comboSuggest.title": "Combos sugeridos", + "comboSuggest.lede": "Modelos que mais de um dos seus provedores oferece com o mesmo nome. Gere um combo para rotear um único nome de modelo entre todos eles.", + "comboSuggest.servedBy": "oferecido por {count} provedores", + "comboSuggest.canAdd": "também pode usar {providers}", + "comboSuggest.generate": "Gerar", + "comboSuggest.addTo": "Adicionar ao combo", + "comboSuggest.dismiss": "Dispensar", + "comboSuggest.showAll": "Mostrar todos ({count})", + "comboSuggest.showFewer": "Mostrar menos", + "comboSuggest.tier.ownSubscription": "assinatura do criador", + "comboSuggest.tier.subscription": "assinatura", + "comboSuggest.tier.vertex": "crédito Vertex", + "comboSuggest.tier.metered": "pago por uso", + "comboSuggest.draft.id": "ID do combo", + "comboSuggest.draft.orderHint": "Testados de cima para baixo: assinaturas primeiro, depois crédito Vertex; chaves de pagamento por uso e relays por último. Reordene ou remova antes de salvar.", + "comboSuggest.draft.left": "{percent}% restante", + "comboSuggest.draft.up": "Mover para cima", + "comboSuggest.draft.down": "Mover para baixo", + "comboSuggest.draft.remove": "Remover", + "comboSuggest.draft.strategy": "Estratégia: failover. Altere-a na linha depois de salvar.", + "comboSuggest.draft.cancel": "Cancelar", + "comboSuggest.draft.save": "Salvar combo", + "comboSuggest.draft.saving": "Salvando…", }; diff --git a/gui/src/i18n/ru.ts b/gui/src/i18n/ru.ts index 34589594b8c..16c3c5d20a9 100644 --- a/gui/src/i18n/ru.ts +++ b/gui/src/i18n/ru.ts @@ -4621,4 +4621,27 @@ export const ru: Record = { "routeBoard.probe.nothingApplied": "Ничего определённого, поэтому ничего не сохранено.", "routeBoard.probe.contextNote": "Контекст определяется по имени модели и не измеряется.", "routeBoard.probe.close": "Закрыть", + "comboSuggest.title": "Рекомендуемые комбо", + "comboSuggest.lede": "Модели, которые несколько ваших провайдеров предлагают под одним именем. Создайте комбо, чтобы направлять одно имя модели на все они сразу.", + "comboSuggest.servedBy": "доступна у {count} провайдеров", + "comboSuggest.canAdd": "также может использовать {providers}", + "comboSuggest.generate": "Создать", + "comboSuggest.addTo": "Добавить в комбо", + "comboSuggest.dismiss": "Скрыть", + "comboSuggest.showAll": "Показать все ({count})", + "comboSuggest.showFewer": "Свернуть", + "comboSuggest.tier.ownSubscription": "подписка создателя модели", + "comboSuggest.tier.subscription": "подписка", + "comboSuggest.tier.vertex": "кредит Vertex", + "comboSuggest.tier.metered": "оплата по факту", + "comboSuggest.draft.id": "ID комбо", + "comboSuggest.draft.orderHint": "Пробуются сверху вниз: сначала подписки, затем кредит Vertex, а ключи с оплатой по факту и ретрансляторы — в конце. Измените порядок или удалите лишнее перед сохранением.", + "comboSuggest.draft.left": "осталось {percent}%", + "comboSuggest.draft.up": "Вверх", + "comboSuggest.draft.down": "Вниз", + "comboSuggest.draft.remove": "Удалить", + "comboSuggest.draft.strategy": "Стратегия: Failover. Изменить можно в строке после сохранения.", + "comboSuggest.draft.cancel": "Отмена", + "comboSuggest.draft.save": "Сохранить комбо", + "comboSuggest.draft.saving": "Сохранение…", }; diff --git a/gui/src/i18n/tr.ts b/gui/src/i18n/tr.ts index e8dd5008177..aed159cb8ef 100644 --- a/gui/src/i18n/tr.ts +++ b/gui/src/i18n/tr.ts @@ -4621,4 +4621,27 @@ export const tr: Record = { "routeBoard.probe.nothingApplied": "Kesin sonuç yok, bu yüzden hiçbir şey kaydedilmedi.", "routeBoard.probe.contextNote": "Bağlam model adından tahmin edilir, ölçülmez.", "routeBoard.probe.close": "Kapat", + "comboSuggest.title": "Önerilen kombolar", + "comboSuggest.lede": "Birden fazla sağlayıcınızın aynı adla sunduğu modeller. Tüm bu sağlayıcılar üzerinde tek bir model adını yönlendirmek için kombo oluşturun.", + "comboSuggest.servedBy": "{count} sağlayıcı sunuyor", + "comboSuggest.canAdd": "{providers} da kullanabilir", + "comboSuggest.generate": "Oluştur", + "comboSuggest.addTo": "Komboya ekle", + "comboSuggest.dismiss": "Kapat", + "comboSuggest.showAll": "Tümünü göster ({count})", + "comboSuggest.showFewer": "Daha azını göster", + "comboSuggest.tier.ownSubscription": "üreticinin aboneliği", + "comboSuggest.tier.subscription": "abonelik", + "comboSuggest.tier.vertex": "Vertex kredisi", + "comboSuggest.tier.metered": "kullandıkça öde", + "comboSuggest.draft.id": "Kombo kimliği", + "comboSuggest.draft.orderHint": "Yukarıdan aşağıya denenir: önce abonelikler, sonra Vertex kredisi, kullandıkça ödemeli anahtarlar ve röleler en sonda. Kaydetmeden önce sırayı değiştirin ya da kaldırın.", + "comboSuggest.draft.left": "%{percent} kaldı", + "comboSuggest.draft.up": "Yukarı taşı", + "comboSuggest.draft.down": "Aşağı taşı", + "comboSuggest.draft.remove": "Kaldır", + "comboSuggest.draft.strategy": "Strateji: failover. Kaydettikten sonra satırda değiştirin.", + "comboSuggest.draft.cancel": "İptal", + "comboSuggest.draft.save": "Komboyu kaydet", + "comboSuggest.draft.saving": "Kaydediliyor…", }; diff --git a/gui/src/i18n/vi.ts b/gui/src/i18n/vi.ts index ce7374dfb62..30eca42de5f 100644 --- a/gui/src/i18n/vi.ts +++ b/gui/src/i18n/vi.ts @@ -4590,4 +4590,27 @@ export const vi: Record = { "routeBoard.probe.nothingApplied": "Không có kết quả chắc chắn nên không lưu gì.", "routeBoard.probe.contextNote": "Ngữ cảnh được suy ra từ tên mô hình, không đo thực tế.", "routeBoard.probe.close": "Đóng", + "comboSuggest.title": "Combo gợi ý", + "comboSuggest.lede": "Các model mà nhiều provider của bạn cùng phục vụ dưới một tên. Tạo combo để định tuyến một tên model qua tất cả chúng.", + "comboSuggest.servedBy": "được {count} provider phục vụ", + "comboSuggest.canAdd": "cũng có thể dùng {providers}", + "comboSuggest.generate": "Tạo", + "comboSuggest.addTo": "Thêm vào combo", + "comboSuggest.dismiss": "Bỏ qua", + "comboSuggest.showAll": "Hiện tất cả {count}", + "comboSuggest.showFewer": "Thu gọn", + "comboSuggest.tier.ownSubscription": "gói đăng ký của nhà phát triển", + "comboSuggest.tier.subscription": "gói đăng ký", + "comboSuggest.tier.vertex": "credit Vertex", + "comboSuggest.tier.metered": "trả theo lượt dùng", + "comboSuggest.draft.id": "ID combo", + "comboSuggest.draft.orderHint": "Thử từ trên xuống: gói đăng ký trước, rồi credit Vertex, key trả theo lượt dùng và relay ở cuối. Sắp xếp lại hoặc xóa trước khi lưu.", + "comboSuggest.draft.left": "còn {percent}%", + "comboSuggest.draft.up": "Lên", + "comboSuggest.draft.down": "Xuống", + "comboSuggest.draft.remove": "Xóa", + "comboSuggest.draft.strategy": "Chiến lược: failover. Đổi trong hàng sau khi lưu.", + "comboSuggest.draft.cancel": "Hủy", + "comboSuggest.draft.save": "Lưu combo", + "comboSuggest.draft.saving": "Đang lưu…", }; diff --git a/gui/src/i18n/zh-TW.ts b/gui/src/i18n/zh-TW.ts index c3ae4462260..651410b94ce 100644 --- a/gui/src/i18n/zh-TW.ts +++ b/gui/src/i18n/zh-TW.ts @@ -4584,4 +4584,27 @@ export const zhTW: Record = { "routeBoard.probe.nothingApplied": "沒有確定的結果,沒有寫入任何值。", "routeBoard.probe.contextNote": "上下文從名字推斷,不實測。", "routeBoard.probe.close": "關閉", + "comboSuggest.title": "推薦組合", + "comboSuggest.lede": "多家供應商都以同一名稱提供的模型。生成一個組合,就能用一個模型名在這幾家之間路由。", + "comboSuggest.servedBy": "{count} 家供應商都有", + "comboSuggest.canAdd": "還可以加進 {providers}", + "comboSuggest.generate": "生成", + "comboSuggest.addTo": "加進組合", + "comboSuggest.dismiss": "忽略", + "comboSuggest.showAll": "顯示全部 {count} 條", + "comboSuggest.showFewer": "收起", + "comboSuggest.tier.ownSubscription": "原廠訂閱", + "comboSuggest.tier.subscription": "訂閱", + "comboSuggest.tier.vertex": "Vertex 贈金", + "comboSuggest.tier.metered": "按量計費", + "comboSuggest.draft.id": "組合 ID", + "comboSuggest.draft.orderHint": "從上往下依次嘗試:訂閱在前,其次 Vertex 贈金,按量 API key 和中轉站最後。儲存前可以調整順序或刪掉某一家。", + "comboSuggest.draft.left": "剩 {percent}%", + "comboSuggest.draft.up": "上移", + "comboSuggest.draft.down": "下移", + "comboSuggest.draft.remove": "刪掉", + "comboSuggest.draft.strategy": "策略:容錯移轉。儲存後可以在列中改。", + "comboSuggest.draft.cancel": "取消", + "comboSuggest.draft.save": "儲存組合", + "comboSuggest.draft.saving": "正在儲存…", }; diff --git a/gui/src/i18n/zh.ts b/gui/src/i18n/zh.ts index 84423a59829..9453d5a97b5 100644 --- a/gui/src/i18n/zh.ts +++ b/gui/src/i18n/zh.ts @@ -4619,4 +4619,27 @@ export const zh: Record = { "routeBoard.probe.nothingApplied": "没有确定的结果,没有写入任何值。", "routeBoard.probe.contextNote": "上下文从名字推断,不实测。", "routeBoard.probe.close": "关闭", + "comboSuggest.title": "推荐组合", + "comboSuggest.lede": "你有两家以上提供方都提供同名的模型。生成一个组合,就能用一个模型名在这几家之间路由。", + "comboSuggest.servedBy": "{count} 家提供方都有", + "comboSuggest.canAdd": "还可以加进 {providers}", + "comboSuggest.generate": "生成", + "comboSuggest.addTo": "加进组合", + "comboSuggest.dismiss": "忽略", + "comboSuggest.showAll": "显示全部 {count} 条", + "comboSuggest.showFewer": "收起", + "comboSuggest.tier.ownSubscription": "原厂订阅", + "comboSuggest.tier.subscription": "订阅", + "comboSuggest.tier.vertex": "Vertex 赠金", + "comboSuggest.tier.metered": "按量计费", + "comboSuggest.draft.id": "组合 ID", + "comboSuggest.draft.orderHint": "从上往下依次尝试:订阅在前,其次 Vertex 赠金,按量 API key 和中转站最后。保存前可以调整顺序或删掉某一家。", + "comboSuggest.draft.left": "剩 {percent}%", + "comboSuggest.draft.up": "上移", + "comboSuggest.draft.down": "下移", + "comboSuggest.draft.remove": "删掉", + "comboSuggest.draft.strategy": "策略:故障转移。保存后可以在行里改。", + "comboSuggest.draft.cancel": "取消", + "comboSuggest.draft.save": "保存组合", + "comboSuggest.draft.saving": "正在保存…", }; diff --git a/gui/src/pages/Combos.tsx b/gui/src/pages/Combos.tsx index 785ddf14b12..79b57c7f23b 100644 --- a/gui/src/pages/Combos.tsx +++ b/gui/src/pages/Combos.tsx @@ -22,12 +22,15 @@ import { jevAutoCreateDecisionProvider } from "../app-routing"; import { COMBOS_ADVANCED_HASH } from "./combos-advanced-hash"; import type { ComboAddIntent } from "../components/combo-workspace-types"; import { RouteBoard } from "../components/route-board/RouteBoard"; +import { ComboSuggestions } from "../components/route-board/ComboSuggestions"; import type { EditableChannel } from "../components/route-board/ChannelEditor"; import { comboDraftErrorText } from "../components/combo-workspace-utils"; import { putModelVisibility } from "../model-visibility"; import { accountCountFromList, channelKey, + channelQuota, + quotaWindowsByProvider, channelTargetsForPut, capabilitySource, parseCapabilitySources, @@ -89,6 +92,8 @@ type CachedCombosPage = { capability?: Record; /** Catalog models plus configured-only members, for the route board's member table. */ memberModels?: ModelOption[]; + /** `provider/model` rows hidden from the catalog; suggestions rank combos with a listed member first. */ + hiddenModels?: string[]; }; type ProviderQuotasDto = { reports?: unknown }; @@ -270,6 +275,7 @@ export default function Combos({ const capabilityModels: ModelOption[] = []; const catalogued = new Set(); const comboCatalog: Record = {}; + const hiddenModels: string[] = []; const parseModalities = (raw: unknown): string[] | undefined => Array.isArray(raw) ? raw.flatMap((modality) => { @@ -335,6 +341,7 @@ export default function Combos({ input: capabilitySource(Boolean(inputModalities?.length), Boolean(inputModalitiesDeclared?.length)), efforts: capabilitySource(reasoningEfforts !== undefined, model.reasoningOverridden === true), }); + if (model.disabled === true) hiddenModels.push(`${provider}/${id}`); const inferred = parseInferredCapabilities(model.inferredCapabilities); if (inferred) inferredByKey.set(channelKey(provider, id), inferred); capabilityModels.push(option); @@ -370,7 +377,7 @@ export default function Combos({ ...(member.sources ? { sources: member.sources } : {}), })), ]; - const next = { combos, providers, models, capabilityModels, cataloguedComboIds: [...catalogued], comboCatalog, lastResort, lastResortActive, capability, memberModels } satisfies CachedCombosPage; + const next = { combos, providers, models, capabilityModels, cataloguedComboIds: [...catalogued], comboCatalog, lastResort, lastResortActive, capability, memberModels, hiddenModels } satisfies CachedCombosPage; writeSessionListCacheEntry(cacheKey, next); // Retain the coherent payload here — one place, on the success path, never during // render. See the `retainedData` note below. @@ -622,6 +629,22 @@ export default function Combos({ providers: providerRows, }); + const validateSuggested = (item: ComboItem, isCreate: boolean) => isCreate + ? validateComboDraft(item, { + existingIds: combos.map((combo) => combo.id), + existingAliases: combos.flatMap((combo) => combo.alias ? [combo.alias] : []), + combos, + isCreate: true, + providers: providerRows, + }) + : validateOverviewEdit(item); + const quotaByProvider = quotaWindowsByProvider(quotaReports); + const providerByName = new Map(providers.map((provider) => [provider.name, provider])); + const remainingPercent = (provider: string, model: string) => { + const quota = channelQuota(providerByName.get(provider), quotaByProvider.get(provider), [model]); + return quota.kind === "windows" ? Math.min(...quota.windows.map((window) => window.remainingPercent)) : undefined; + }; + const removeCombo = async (id: string) => { try { const res = await fetch(`${apiBase}/api/combos?id=${encodeURIComponent(id)}`, { method: "DELETE" }); @@ -696,6 +719,19 @@ export default function Combos({ {state.refreshing ? t("common.loading") : ""} + {view === "overview" && ( + comboDraftErrorText(t, code, item, providerRows)} + onCreate={(item) => saveCombo(item, true, undefined, {})} + onExtend={(item) => saveCombo(item, false, undefined, {})} + /> + )} {view === "overview" && ( , extra: Partial = {}): ComboItem => ({ + id, + model: `combo/${id}`, + alias: null, + nativeAlias: false, + displayName: null, + strategy: "failover", + stickyLimit: 1, + defaultEffort: null, + imageInput: "auto", + reasoningEffortMode: "strict", + targets: targets.map(([provider, model]) => ({ provider, model })), + ...extra, +}); + +const PROVIDERS: SuggestionProvider[] = [ + { name: "anthropic-apikey", authMode: "key", baseUrl: "https://api.anthropic.com" }, + { name: "cursor", authMode: "oauth", baseUrl: "https://api2.cursor.sh" }, + { name: "anthropic", authMode: "oauth", baseUrl: "https://api.anthropic.com" }, + { name: "google-vertex", baseUrl: "https://aiplatform.googleapis.com" }, + { name: "google-antigravity", authMode: "oauth", baseUrl: "https://daily-cloudcode-pa.googleapis.com" }, + { name: "openai", authMode: "forward", baseUrl: "https://chatgpt.com/backend-api/codex" }, + { name: "zayu-claude", authMode: "key", baseUrl: "https://relay.example" }, + { name: "qoder", authMode: "key", disabled: true }, + { name: "jev", authMode: "key", hiddenFromPicker: true }, +]; + +const models = (rows: Array<[string, string]>) => rows.map(([provider, id]) => ({ provider, id })); +const suggest = (input: Partial & Pick) => + buildComboSuggestions({ combos: [], providers: PROVIDERS, ...input }); +const summary = (input: Partial & Pick) => + suggest(input).map((s) => `${s.kind} ${s.comboId}: ${s.members.map((m) => m.provider).join(" > ")}`); + +describe("normalizeModelName", () => { + test("folds case, provider prefix, version dots, gaps and a trailing effort suffix", () => { + expect(normalizeModelName("Claude-Opus-5.5")).toBe("claude-opus-5-5"); + expect(normalizeModelName("anthropic/claude-opus-5-5")).toBe("claude-opus-5-5"); + expect(normalizeModelName("deepseek-ai/DeepSeek-V4.1-Flash")).toBe("deepseek-v4-1-flash"); + expect(normalizeModelName("GPT 6.1 Sol")).toBe("gpt-6-1-sol"); + expect(normalizeModelName("gpt-6.1-sol-xhigh")).toBe("gpt-6-1-sol"); + expect(normalizeModelName("gemini_3.8__flash-low")).toBe("gemini-3-8-flash"); + }); + + test("keeps snapshot dates and other variants apart", () => { + expect(normalizeModelName("claude-opus-5-5-20260801")).not.toBe(normalizeModelName("claude-opus-5-5")); + expect(normalizeModelName("gemini-3.8-flash-thinking")).toBe("gemini-3-8-flash-thinking"); + }); +}); + +describe("buildComboSuggestions", () => { + test("suggests a model two providers serve under different spellings, once per provider", () => { + expect(summary({ + models: models([ + ["cursor", "Gemini-3.8-Flash"], + ["google-antigravity", "gemini-3.8-flash"], + ["google-antigravity", "gemini-3.8-flash-high"], + ["openai", "gpt-6-luna"], + ]), + })).toEqual(["create gemini-3.8-flash: google-antigravity > cursor"]); + }); + + test("a model only one provider serves is no suggestion", () => { + expect(suggest({ models: models([["openai", "gpt-6-luna"], ["openai", "gpt-6-luna-high"]]) })).toEqual([]); + }); + + test("disabled and picker-hidden providers do not count", () => { + expect(suggest({ models: models([["anthropic", "claude-x"], ["qoder", "claude-x"], ["jev", "claude-x"]]) })).toEqual([]); + }); + + test("models hidden from the catalog still count, but suggestions with a listed member come first", () => { + const hiddenModels = new Set(["openai/gpt-5.5", "cursor/gpt-5.5", "cursor/gpt-5.6-luna"]); + const result = suggest({ + models: models([["openai", "gpt-5.5"], ["cursor", "gpt-5.5"], ["openai", "gpt-5.6-luna"], ["cursor", "gpt-5.6-luna"]]), + hiddenModels, + }); + expect(result.map((s) => [s.comboId, s.kind === "create" && s.listed])).toEqual([["gpt-5.6-luna", true], ["gpt-5.5", false]]); + }); + + test("orders members: maker's subscription, other subscriptions, Vertex, then keys and relays", () => { + expect(summary({ + models: models([ + ["zayu-claude", "claude-opus-5-5"], + ["anthropic-apikey", "claude-opus-5-5"], + ["google-vertex", "claude-opus-5-5"], + ["cursor", "claude-opus-5.5"], + ["anthropic", "claude-opus-5-5"], + ]), + })).toEqual(["create claude-opus-5-5: anthropic > cursor > google-vertex > zayu-claude > anthropic-apikey"]); + }); + + test("within a tier, more quota left goes first and unknown quota last", () => { + const remaining: Record = { anthropic: 10, "google-antigravity": 80 }; + const result = suggest({ + models: models([["cursor", "claude-sonnet-5-5"], ["anthropic", "claude-sonnet-5-5"], ["google-antigravity", "claude-sonnet-5-5"]]), + remainingPercent: (provider) => remaining[provider], + }); + // anthropic is the maker's own subscription, so it leads despite its lower quota. + expect(result[0]!.members.map((m) => [m.provider, m.remainingPercent])).toEqual([ + ["anthropic", 10], ["google-antigravity", 80], ["cursor", undefined], + ]); + }); + + test("a combo already about the model is not suggested again; a missing provider becomes an extend hint", () => { + const combos = [combo("claude-opus-5-5", [["anthropic", "claude-opus-5-5"], ["zayu-claude", "claude-opus-5-5"]])]; + const rows = models([["anthropic", "claude-opus-5-5"], ["zayu-claude", "claude-opus-5-5"], ["cursor", "claude-opus-5.5"]]); + expect(summary({ combos, models: rows })).toEqual(["extend claude-opus-5-5: cursor"]); + expect(summary({ combos, models: rows.slice(0, 2) })).toEqual([]); + }); + + test("hints for existing combos come before suggestions whose members are all hidden", () => { + const combos = [combo("gemini", [["google-antigravity", "gemini-3.8-flash"]])]; + const result = suggest({ + combos, + models: models([["google-antigravity", "gemini-3.8-flash"], ["cursor", "gemini-3.8-flash"], ["openai", "gpt-5.5"], ["cursor", "gpt-5.5"], ["openai", "gpt-6-luna"], ["cursor", "gpt-6-luna"]]), + hiddenModels: new Set(["openai/gpt-5.5", "cursor/gpt-5.5"]), + }); + expect(result.map((s) => `${s.kind} ${s.comboId}`)).toEqual(["create gpt-6-luna", "extend gemini", "create gpt-5.5"]); + }); + + test("a combo whose members all serve the model covers it whatever its id", () => { + const combos = [combo("opus", [["anthropic", "claude-opus-5-5"], ["cursor", "claude-opus-5.5"]])]; + expect(suggest({ combos, models: models([["anthropic", "claude-opus-5-5"], ["cursor", "claude-opus-5.5"]]) })).toEqual([]); + }); + + test("a mixed combo that does not name the model does not cover it", () => { + const combos = [combo("Reviewer", [["anthropic", "claude-sonnet-5-5"], ["google-antigravity", "gemini-3.8-flash"]])]; + expect(summary({ combos, models: models([["google-antigravity", "gemini-3.8-flash"], ["cursor", "gemini-3.8-flash"]]) })) + .toEqual(["create gemini-3.8-flash: google-antigravity > cursor"]); + }); + + test("a taken combo id or alias gets -2, -3", () => { + const combos = [combo("gpt-5.5", [["openai", "gpt-6-luna"], ["anthropic", "claude-x"]]), combo("other", [["openai", "x"]], { alias: "gpt-5.5-2" })]; + expect(freeComboId("gpt-5.5", combos)).toBe("gpt-5.5-3"); + expect(freeComboId("GPT-5.5", [])).toBe("GPT-5.5"); + expect(suggest({ combos, models: models([["openai", "gpt-5.5"], ["cursor", "gpt-5.5"]]) })[0]!.comboId).toBe("gpt-5.5-3"); + }); + + test("dismissed suggestions stay out, other ones stay in", () => { + const rows = models([["openai", "gpt-5.5"], ["cursor", "gpt-5.5"], ["openai", "gpt-5.6-sol"], ["cursor", "gpt-5.6-sol"]]); + const all = suggest({ models: rows }); + expect(all.map((s) => s.key)).toEqual(["create:gpt-5-5", "create:gpt-5-6-sol"]); + expect(suggest({ models: rows, dismissed: new Set(["create:gpt-5-5"]) }).map((s) => s.comboId)).toEqual(["gpt-5.6-sol"]); + }); +}); + +describe("drafts", () => { + test("a create draft is a failover combo with the members in the order given", () => { + const members = orderMembers([ + { provider: "cursor", model: "gpt-5.5", tier: "subscription" }, + { provider: "openai", model: "gpt-5.5", tier: "own-subscription" }, + ]); + const draft = suggestionDraft("gpt-5.5", members); + expect([draft.id, draft.model, draft.strategy]).toEqual(["gpt-5.5", "combo/gpt-5.5", "failover"]); + expect(draft.targets.map((t) => `${t.provider}/${t.model}`)).toEqual(["openai/gpt-5.5", "cursor/gpt-5.5"]); + }); + + test("extending puts a member ahead of the first lower-tier one and keeps the combo's own order", () => { + const tiers: Record = { anthropic: "own-subscription", "anthropic-apikey": "metered", "zayu-claude": "metered" }; + const tierOf = (provider: string) => tiers[provider]!; + const base = combo("opus", [["anthropic", "claude-opus-5-5"], ["zayu-claude", "claude-opus-5-5"], ["anthropic-apikey", "claude-opus-5-5"]]); + const next = extendedCombo(base, [ + { provider: "cursor", model: "claude-opus-5.5", tier: "subscription" }, + { provider: "relay-2", model: "claude-opus-5-5", tier: "metered" }, + ], tierOf); + expect(next.targets.map((t) => t.provider)).toEqual(["anthropic", "cursor", "zayu-claude", "anthropic-apikey", "relay-2"]); + const relayFirst = combo("opus", [["zayu-claude", "claude-opus-5-5"], ["anthropic", "claude-opus-5-5"]]); + expect(extendedCombo(relayFirst, [{ provider: "cursor", model: "claude-opus-5.5", tier: "subscription" }], tierOf).targets.map((t) => t.provider)) + .toEqual(["cursor", "zayu-claude", "anthropic"]); + }); + + test("tiers read the provider, not its name", () => { + expect(channelTier({ name: "my-vertex-2", baseUrl: "https://x.example" }, "gemini-4-argon")).toBe("vertex"); + expect(channelTier({ name: "anything", authMode: "forward", baseUrl: "https://chatgpt.com" }, "gpt-6-luna")).toBe("own-subscription"); + expect(channelTier({ name: "xai", authMode: "oauth", baseUrl: "https://api.x.ai/v1" }, "grok-4.7")).toBe("own-subscription"); + expect(channelTier({ name: "zed", authMode: "oauth", baseUrl: "https://cloud.zed.dev" }, "grok-4.7")).toBe("subscription"); + expect(channelTier({ name: "ollama", baseUrl: "http://localhost:11434" }, "llama")).toBe("metered"); + }); +}); + +describe("ComboSuggestions card", () => { + let testWindow: Window; + let root: Root | null = null; + let host: HTMLElement; + const globals = ["document", "window", "navigator", "localStorage"] as const; + let previous: Record<(typeof globals)[number], unknown>; + + beforeEach(() => { + previous = Object.fromEntries(globals.map((key) => [key, Reflect.get(globalThis, key)])) as typeof previous; + testWindow = new Window({ url: "http://localhost/#models/combos" }); + Object.defineProperty(testWindow.navigator, "language", { configurable: true, value: "en-US" }); + Object.defineProperties(globalThis, { + document: { configurable: true, value: testWindow.document }, + window: { configurable: true, value: testWindow }, + navigator: { configurable: true, value: testWindow.navigator }, + localStorage: { configurable: true, value: testWindow.localStorage }, + }); + (globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + }); + + afterEach(async () => { + if (root) await act(async () => { root?.unmount(); }); + root = null; + testWindow.close(); + for (const key of globals) Object.defineProperty(globalThis, key, { configurable: true, value: previous[key] }); + }); + + const saved: Array<{ kind: string; item: ComboItem }> = []; + async function render(combos: ComboItem[] = []) { + saved.length = 0; + const { createRoot } = await import("react-dom/client"); + host = document.createElement("div"); + document.body.append(host); + root = createRoot(host); + await act(async () => { + root!.render( + + undefined} + validate={() => null} + errorText={() => "bad"} + onCreate={async (item) => { saved.push({ kind: "create", item }); return { ok: true }; }} + onExtend={async (item) => { saved.push({ kind: "extend", item }); return { ok: true }; }} + /> + , + ); + }); + } + const button = (scope: ParentNode, name: string) => { + const found = [...scope.querySelectorAll("button")] + .find((item) => item.textContent?.trim() === name || item.getAttribute("aria-label") === name); + if (!found) throw new Error(`button not found: ${name}`); + return found; + }; + const card = (title: string) => { + const found = [...host.querySelectorAll(".rb-suggest-card")].find((item) => item.querySelector("strong")?.textContent === title); + if (!found) throw new Error(`card not found: ${title}`); + return found; + }; + + test("generate opens a draft; reordering and saving sends that order", async () => { + await render(); + expect(host.querySelector(".rb-suggest-head strong")?.textContent).toBe("Suggested combos"); + const gemini = card("gemini-3.8-flash"); + expect(gemini.querySelector(".rb-order")?.textContent).toContain("→"); + await act(async () => { button(gemini, "Generate").click(); }); + const draft = gemini.querySelector(".rb-suggest-draft")!; + await act(async () => { button(draft.querySelectorAll("li")[0]!, "Move down").click(); }); + await act(async () => { button(draft, "Save combo").click(); }); + expect(saved.map(({ kind, item }) => [kind, item.id, item.strategy, item.targets.map((t) => t.provider)])).toEqual([ + ["create", "gemini-3.8-flash", "failover", ["cursor", "google-antigravity"]], + ]); + }); + + test("dismiss hides the card and the choice survives a remount", async () => { + await render(); + await act(async () => { button(card("claude-opus-5-5"), "Dismiss").click(); }); + expect(() => card("claude-opus-5-5")).toThrow(); + await act(async () => { root?.unmount(); }); + await render(); + expect(() => card("claude-opus-5-5")).toThrow(); + expect(card("gemini-3.8-flash")).toBeTruthy(); + }); + + test("an existing combo missing a provider offers to add it", async () => { + await render([combo("gemini", [["google-antigravity", "gemini-3.8-flash"]])]); + const extend = card("gemini"); + expect(extend.textContent).toContain("can also use"); + await act(async () => { button(extend, "Add to combo").click(); }); + expect(saved.map(({ kind, item }) => [kind, item.id, item.targets.map((t) => t.provider)])).toEqual([ + ["extend", "gemini", ["google-antigravity", "cursor"]], + ]); + }); +}); diff --git a/structure/dashboard-and-usage.md b/structure/dashboard-and-usage.md index 76bbfe8c027..9665eed3834 100644 --- a/structure/dashboard-and-usage.md +++ b/structure/dashboard-and-usage.md @@ -126,7 +126,7 @@ The sidebar exposes eight rows (`gui/src/nav-groups.ts` `NAV_GROUPS`), in order: | API keys | Key table plus per-key detail (`gui/src/components/apikeys-workspace/`). The list payload carries masked prefixes only; each row deletes in place behind a two-step confirm, and clicking a key fetches the full value from `POST /api/keys/reveal`, which requires a current pairing or trusted Tailscale-identity session and answers `no-store`; automatic loopback sessions and raw admin tokens cannot reveal stored values, and a refusal there answers with the pairing surface — on the same-origin standalone transport the local pairing form, elsewhere the explanation alone — and requires a fresh reveal click after pairing. Displayed secrets and copy feedback are cleared on shared-session loss, pairing, inactive/hidden views, or a target change; stale asynchronous completions cannot restore them. | | Storage | Rail plus cleanup and trash detail (`gui/src/components/storage-workspace/`). | | Subagents | Featured-roster selection workspace (`gui/src/components/subagents-workspace/`). | -| Combos | `#models/combos` opens the overview (`gui/src/components/route-board/RouteBoard.tsx`, view model `gui/src/route-board-model.ts`): one row per combo with stacked provider icons, display name and public id, the channel order (`→` for failover, `·` otherwise, last-resort members marked), one quota line per provider from `/api/provider-quotas` (remaining percent, green above 50%, amber 20–50%, red below 20%; `key` providers read as pay per use), the catalog context window, an inline strategy menu and an on/off switch. Switched-off combos sort after the live ones. Antigravity pool windows read as family names (`Cla (Weekly)` → "Claude & GPT · weekly"). Account counts come from the report's `aggregation`, otherwise from `GET /api/oauth/accounts?provider=` for enabled OAuth providers (paused accounts listed separately). A strategy pick runs `validateComboDraft` and then the normal `PUT /api/combos`; JEV never saves from the row and opens the workspace on that combo instead, because an empty decision service means the hosted TypeSafe service. The switch writes the combo selector through `PUT /api/model-visibility` (`provider: "combo"`). Clicking a row opens the channel editor (reorder by pointer drag or by move buttons (which slide with FLIP); mark fallback only, i.e. `lastResort`; remove; add). Its "More settings" section opens in place: the capability policy, a "fallback channels wait their turn" switch that writes `cooldownWaitPolicy` (`"before-last-resort"` or `null`), and a member table (`gui/src/components/route-board/MemberTable.tsx`) of each member's context window, input modalities and effort levels with the combined row. Every cell carries its source from the row's `capabilitySources` (`parseCapabilitySources`; an older server without it falls back to the `*Declared` / `reasoningOverridden` flags via `capabilitySource`); members with no `/api/models` row fall back to their per-model config (`configuredMemberModels`). A gap with an `inferredCapabilities` estimate shows the value and its basis with an Adopt button that writes it through `PUT /api/model-settings`; estimates fill gaps only in the combined row, labelled (`withInferredGaps`), never in routing. A member edit sends only the changed fields to `PUT /api/model-settings` (`memberSettingsPatch`; restore sends `null` for the manual fields), validates the receipt, and refreshes the page; "Test it" (`gui/src/components/route-board/MemberProbe.tsx`) posts `POST /api/providers/probe-capabilities` with `apply: true`, repeats with `confirmMetered: true` after an inline confirmation naming `plannedRequests`, and shows `applicable: false` reasons (button greyed), a 409 as already running, and a failed baseline as inconclusive (`parseProbeResponse`). Pointer drag is Magpie's row sorter (`gui/src/components/route-board/drag-rows.ts`, MIT, © yetone): the row itself follows the pointer by a transform with no copy or placeholder, the rows it passes slide a row's height aside, Escape cancels, and the order changes once on release; the slot comes from the layout midpoints with 8 px hysteresis (`dragSlot`), and presses on the row's own controls (or anywhere but the grip on touch) stay clicks. The row's context tag opens that section and shows the smallest member under intersection and the largest under union (`comboContextWindow`); fallback-only marks render greyed with the reason while the combo has no `cooldownWaitPolicy`; only its save sends `lastResort` explicitly, every other save omits it so the server carries it over. Capability fields (`capabilityPolicy`, `onUnservable`) and `cooldownWaitPolicy` read absent as the defaults and are sent only when changed. "Advanced" opens the rail, detail panel and add flow (`gui/src/components/ComboWorkspace.tsx`) at `#models/combos/advanced`; `#models/combos/jev-auto` still lands there (`gui/src/pages/combos-view.ts`). The workspace stays mounted once opened, so an unsaved draft survives the overview, and the overview locks the strategy and channel save of the combo being drafted until the draft is saved or discarded. `gui/tests/route-board.test.tsx` covers the rows, PUT bodies, the JEV hand-off, validation, the switch selector, the channel save, drag sweeps over 4 and 6 rows, the member edit and restore bodies, and the draft lock. | +| Combos | `#models/combos` opens the overview (`gui/src/components/route-board/RouteBoard.tsx`, view model `gui/src/route-board-model.ts`): one row per combo with stacked provider icons, display name and public id, the channel order (`→` for failover, `·` otherwise, last-resort members marked), one quota line per provider from `/api/provider-quotas` (remaining percent, green above 50%, amber 20–50%, red below 20%; `key` providers read as pay per use), the catalog context window, an inline strategy menu and an on/off switch. Switched-off combos sort after the live ones. Antigravity pool windows read as family names (`Cla (Weekly)` → "Claude & GPT · weekly"). Account counts come from the report's `aggregation`, otherwise from `GET /api/oauth/accounts?provider=` for enabled OAuth providers (paused accounts listed separately). A strategy pick runs `validateComboDraft` and then the normal `PUT /api/combos`; JEV never saves from the row and opens the workspace on that combo instead, because an empty decision service means the hosted TypeSafe service. The switch writes the combo selector through `PUT /api/model-visibility` (`provider: "combo"`). Clicking a row opens the channel editor (reorder by pointer drag or by move buttons (which slide with FLIP); mark fallback only, i.e. `lastResort`; remove; add). Its "More settings" section opens in place: the capability policy, a "fallback channels wait their turn" switch that writes `cooldownWaitPolicy` (`"before-last-resort"` or `null`), and a member table (`gui/src/components/route-board/MemberTable.tsx`) of each member's context window, input modalities and effort levels with the combined row. Every cell carries its source from the row's `capabilitySources` (`parseCapabilitySources`; an older server without it falls back to the `*Declared` / `reasoningOverridden` flags via `capabilitySource`); members with no `/api/models` row fall back to their per-model config (`configuredMemberModels`). A gap with an `inferredCapabilities` estimate shows the value and its basis with an Adopt button that writes it through `PUT /api/model-settings`; estimates fill gaps only in the combined row, labelled (`withInferredGaps`), never in routing. A member edit sends only the changed fields to `PUT /api/model-settings` (`memberSettingsPatch`; restore sends `null` for the manual fields), validates the receipt, and refreshes the page; "Test it" (`gui/src/components/route-board/MemberProbe.tsx`) posts `POST /api/providers/probe-capabilities` with `apply: true`, repeats with `confirmMetered: true` after an inline confirmation naming `plannedRequests`, and shows `applicable: false` reasons (button greyed), a 409 as already running, and a failed baseline as inconclusive (`parseProbeResponse`). Pointer drag is Magpie's row sorter (`gui/src/components/route-board/drag-rows.ts`, MIT, © yetone): the row itself follows the pointer by a transform with no copy or placeholder, the rows it passes slide a row's height aside, Escape cancels, and the order changes once on release; the slot comes from the layout midpoints with 8 px hysteresis (`dragSlot`), and presses on the row's own controls (or anywhere but the grip on touch) stay clicks. The row's context tag opens that section and shows the smallest member under intersection and the largest under union (`comboContextWindow`); fallback-only marks render greyed with the reason while the combo has no `cooldownWaitPolicy`; only its save sends `lastResort` explicitly, every other save omits it so the server carries it over. Capability fields (`capabilityPolicy`, `onUnservable`) and `cooldownWaitPolicy` read absent as the defaults and are sent only when changed. "Advanced" opens the rail, detail panel and add flow (`gui/src/components/ComboWorkspace.tsx`) at `#models/combos/advanced`; `#models/combos/jev-auto` still lands there (`gui/src/pages/combos-view.ts`). The workspace stays mounted once opened, so an unsaved draft survives the overview, and the overview locks the strategy and channel save of the combo being drafted until the draft is saved or discarded. Above the rows, suggested combos (`gui/src/components/route-board/ComboSuggestions.tsx`, pure model `gui/src/combo-suggestions.ts`) group catalog models of enabled, picker-visible providers by a normalized name (prefix, case, gaps, version dots and a trailing effort suffix folded; snapshot dates kept). Hidden catalog rows count, because hiding only affects external lists, but a suggestion with a listed member ranks first. A name served by two or more providers and not yet covered by a combo (one whose id names it or whose members all serve it) becomes a draft: members ordered maker's subscription, other subscriptions, Vertex, then keys and relays, by remaining quota within a tier; the operator can rename, reorder or drop members before the normal create `PUT /api/combos` (strategy failover, id made free with `-2`, `-3`). A covered name whose combo lacks a serving provider becomes an add hint that inserts the member ahead of the combo's first lower-tier member. Dismissals live in `localStorage` (`ocx.combos.suggestions.dismissed.v1`), never in config. `gui/tests/combo-suggestions.test.tsx` covers normalization, coverage, ordering, id collisions, dismissal and the draft save. `gui/tests/route-board.test.tsx` covers the rows, PUT bodies, the JEV hand-off, validation, the switch selector, the channel save, drag sweeps over 4 and 6 rows, the member edit and restore bodies, and the draft lock. | | Add provider | Catalog browser plus form and OAuth panes (`gui/src/components/provider-catalog/`, `gui/src/components/AddProviderModal.tsx`). The catalog browses four tabs — Accounts, Free, Local, Paid — where Local is a catalog-only bucket peeled out of `bucketPresets` after `presetTier` has classified; the workspace `providerTier` stays three-way, so the rail, the free-paid sort and the Free count still treat a local runtime as free. Search sits above the tabs and reaches every tab at once: while a query is live the list renders all four groups with headings and the strip becomes jump chips with counts rather than a tablist, because moving the selected tab would change the row kind under the user (a preset-select button becomes a login row). ArrowDown from the search input focuses the first enabled result action; if none is available, focus stays in the input. The tab strip wraps within narrow modals. Every nonempty note has a full-text button so narrow rows never hide content permanently; the native note dialog closes during teardown and restores focus to its trigger. Provider notes clamp to two lines and open in full in a stacked native `` owned by `AddProviderModal`, which also owns the search text so its `window` Escape handler can unwind popup, then query, then dialog. | | Codex accounts | Account pool cards, add-account flow, switch and reset modals (`gui/src/components/CodexAccountPool.tsx`, `gui/src/components/AddCodexAccountModal.tsx`), plus the generic account-targeting picker opt-in on `gui/src/pages/codex-set-multiauth.tsx`. Add/delete/login completion is projected to one boolean before presentation; pending catalog work is a warning, not a failed account mutation. The main card's native-main device reauth (#3898) is owned by `gui/src/components/use-main-device-reauth.ts`: the dedicated `/api/codex-auth/main/reauth-device` namespace only — never the pool login route — with flowId-owned polling, an allowlisted verification URL, and no token fields accepted from payloads. The main-device reauth hook retains flow ownership from the Cancel click, while DELETE is unresolved and after retryable failure; polling normally continues. A concurrent GET HTTP error cannot expose a replacement login POST before DELETE settles. If a retryable DELETE failure races with a non-2xx GET while the flow is pending or committing, either response order preserves same-flow Cancel retry, restores the last server-provided device code, verification URL, and phase when needed, and keeps the existing poll cadence so a later terminal result remains observable. Outside same-flow cancellation ownership, a GET HTTP failure still stops polling without starting a second login POST. The cancellation-failure indication survives pending status updates until a trusted terminal result releases ownership. A successful DELETE with a terminal `failed` DTO releases it and uses the same closed failure-code mapping as polling; only `succeeded` notifies login completion. Unrecognized or nonterminal DTO status values remain retryable. A DELETE response with HTTP 404 and code `unknown_flow` releases the expired flow and shows the existing generic failure state so device re-login is available again; it claims neither login success nor confirmed cancellation. Confirmed cancellation also makes device re-login available. Start, polling and cancellation completions verify their controller or flow ownership after asynchronous response reads; replaced flows and unmounted hooks cannot update a newer flow or notify completion. Effect setup restores mounted state after the StrictMode development cleanup cycle. | | Dashboard overview | Overview, Providers, and Models tabs at the page level (`gui/src/pages/Dashboard.tsx`), the 30-day token and coverage stats in the overview head (`gui/src/pages/dashboard-overview-head.tsx`), and the effort-cap, injection, maintenance, sidecar, reasoning-retention, and memory panels below it (`gui/src/pages/dashboard-overview-panels.tsx`). The Reasoning retention controls (`gui/src/components/ReasoningRetentionPanel.tsx`) live in a collapsed Advanced settings disclosure at the end of Overview. They read and save `reasoningRetention` via GET/PUT `/api/settings` in `src/server/management/config-routes.ts`: only explicit `enabled: true` activates retention; absent, disabled, and legacy threshold-only settings remain off. The enable switch exposes numeric controls with defaults of 20% and 100000 tokens; disabling saves `enabled: false`, and null reset removes the setting and turns it off. Omission preserves it, validation precedes mutation, and save failure restores value and key presence. Copy warns that opt-in can preserve plaintext reasoning in local history/archive and that completed archives have no aggregate quota or expiry and require manual deletion. Loading disables writes, failures permit retry without losing edits, and stale responses cannot update a new API target. Its scope is the [routed v1/v2 compaction contract](transports/responses-failover.md#compaction-routing-overrides); opaque output stays unchanged. `tests/config/settings-reasoning-retention.test.ts` and `gui/tests/reasoning-retention-panel.test.tsx` cover the API and controls. Inputs expose invalid state and reference the validation alert only for the failing field. |