Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

feat(models): add the hosted Tools tab and Source capability chips (#2559)

Call White7010fc27e48f
diff --git a/tests/scenarios/INDEX.yaml b/tests/scenarios/INDEX.yaml
index c784871ef..43104cebf 100644
--- a/tests/scenarios/INDEX.yaml
+++ b/tests/scenarios/INDEX.yaml
@@ -118,6 +118,10 @@ capabilities:
- ui/src/components/settings/models/BackendModelCatalogDialog.test.tsx
- ui/src/components/settings/models/AgentCard.test.tsx
- ui/src/components/workbench/HostedToolRow.test.tsx
+ - ui/src/components/settings/models/ToolsTab.test.tsx
+ - ui/src/components/settings/models/hostedTools.test.ts
+ - ui/src/components/settings/models/useHostedTools.test.tsx
+ - ui/src/components/settings/models/SourceDetailPanel.test.tsx
- ui/src/components/settings/models/MigrationDialog.test.tsx
- ui/src/components/settings/models/migrationScan.test.ts
- ui/src/components/onboarding/providers/providerStage.test.ts
diff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yaml
index f146d8239..85e711db0 100644
--- a/tests/scenarios/model_hub/catalog.yaml
+++ b/tests/scenarios/model_hub/catalog.yaml
@@ -64,6 +64,11 @@ capability:
- ui/src/components/settings/models/RouteChainDialog.test.tsx
- ui/src/components/settings/models/BackendModelCatalogDialog.test.tsx
- ui/src/components/settings/models/AgentCard.test.tsx
+ # Hosted tools: the Tools tab, its evidence projection, and the Source chips.
+ - ui/src/components/settings/models/ToolsTab.test.tsx
+ - ui/src/components/settings/models/hostedTools.test.ts
+ - ui/src/components/settings/models/useHostedTools.test.tsx
+ - ui/src/components/settings/models/SourceDetailPanel.test.tsx
# Migration: the setup key-import entry and the broader settings dialog it
# narrows, plus the one predicate that separates them.
- ui/src/components/settings/models/MigrationDialog.test.tsx
@@ -407,6 +412,120 @@ scenarios:
- tests/test_vibey_agent.py::test_a_generated_image_is_kept_as_an_immutable_file_its_bytes_name_and_type
- tests/test_vibey_agent.py::test_a_proxied_image_that_was_not_saved_is_a_failed_call_with_its_code
- tests/test_agent_transcript.py::test_the_media_sweep_keeps_every_file_a_row_registers_and_takes_only_stale_orphans
+ - id: MH-HOSTED-UI-001
+ name: A Tools-tab toggle or executor pick writes the tool's whole setting with an executor the server accepts; the picker offers only verified pairs
+ status: covered
+ kind: contract
+ layer: unit
+ test:
+ - 'ui/src/components/settings/models/ToolsTab.test.tsx::MH-HOSTED-UI-001: a toggle replaces the whole setting and keeps the saved executor'
+ - 'ui/src/components/settings/models/ToolsTab.test.tsx::MH-HOSTED-UI-001: writes a saved executor back only while the server would still accept it'
+ - 'ui/src/components/settings/models/ToolsTab.test.tsx::MH-HOSTED-UI-001: the executor picker offers only verified pairs, and a pick keeps the toggle'
+ - 'ui/src/components/settings/models/ToolsTab.test.tsx::MH-HOSTED-UI-001: a saved executor that is no longer verified stays visible as itself'
+ - 'ui/src/components/settings/models/ToolsTab.test.tsx::MH-HOSTED-UI-001: keeps a saved executor visible as itself when nothing is verified any more'
+ - 'ui/src/components/settings/models/ToolsTab.test.tsx::MH-HOSTED-UI-001: holds a tool''s controls while its write is in flight'
+ - id: MH-HOSTED-UI-002
+ name: Every hosted-tool evidence shape maps to the chip it owes the user, including wire-stale records that route as unknown
+ status: covered
+ kind: observation
+ layer: unit
+ test:
+ - 'ui/src/components/settings/models/hostedTools.test.ts::MH-HOSTED-UI-002: gives every evidence shape the chip it owes the user'
+ - id: MH-HOSTED-UI-003
+ name: The Tools tab states a cost only where one is known; an image is never priced and unknown is never shown as zero
+ status: covered
+ kind: observation
+ layer: unit
+ test:
+ - 'ui/src/components/settings/models/ToolsTab.test.tsx::MH-HOSTED-UI-003: states a cost only where one is known, and never prices an image'
+ - 'ui/src/components/settings/models/ToolsTab.test.tsx::MH-HOSTED-UI-003: the image cost copy is the orchestrator-decided Chinese line'
+ - 'ui/src/components/settings/models/ToolsTab.test.tsx::MH-HOSTED-UI-003: lets the locale compose a price with its extras'
+ - 'ui/src/components/settings/models/ToolsTab.test.tsx::MH-HOSTED-UI-003: says a check''s cost is unknown before it runs, when no estimate is known'
+ - 'ui/src/components/settings/models/SourceDetailPanel.test.tsx::MH-HOSTED-UI-003: says a re-check''s cost is unknown when no estimate is known'
+ - 'ui/src/components/settings/models/hostedTools.test.ts::MH-HOSTED-UI-003: totals a check only from what the server estimates, and never counts unknown as zero'
+ - 'ui/src/components/settings/models/format.test.ts::MH-HOSTED-UI-003: keeps the first significant digits of a per-call price, and never shows a nonzero price as zero'
+ - id: MH-HOSTED-UI-004
+ name: The Tools tab says how many checks an engine upgrade made stale, and nothing when none did
+ status: covered
+ kind: observation
+ layer: unit
+ test:
+ - 'ui/src/components/settings/models/ToolsTab.test.tsx::MH-HOSTED-UI-004: says how many checks an engine upgrade made stale, and nothing when none did'
+ - id: MH-HOSTED-UI-005
+ name: The hosted-tools report stays unread until the Tools tab opens, then re-reads on every open
+ status: covered
+ kind: observation
+ layer: unit
+ test:
+ - 'ui/src/components/settings/models/SettingsModelsPage.render.test.tsx::MH-HOSTED-UI-005: leaves the hosted-tools report unread until its tab opens, then re-reads on every open'
+ - id: MH-HOSTED-UI-006
+ name: A Source model shows one chip per tool with evidence; a refused tool reads via proxy only while the server binds one for it, and unchecked draws nothing
+ status: covered
+ kind: observation
+ layer: unit
+ test:
+ - 'ui/src/components/settings/models/ToolsTab.test.tsx::MH-HOSTED-UI-006: names the Sources that have no native pair for a tool'
+ - 'ui/src/components/settings/models/SourceDetailPanel.test.tsx::MH-HOSTED-UI-006: draws evidence per model, and says "via proxy" only while a proxy is bound for the tool'
+ - 'ui/src/components/settings/models/SourceDetailPanel.test.tsx::MH-HOSTED-UI-006: draws a chip for each reasoning effort the Source refused, even with no tool evidence'
+ - 'ui/src/components/settings/models/SourceDetailPanel.test.tsx::MH-HOSTED-UI-006: says when the capability read failed instead of drawing a Source with no evidence'
+ - 'ui/src/components/settings/models/SourceDetailPanel.test.tsx::MH-HOSTED-UI-006: adds no capability column when no model has evidence'
+ - 'ui/src/components/settings/models/hostedTools.test.ts::MH-HOSTED-UI-006: gives a Source model one capability per tool with evidence, in catalog order'
+ - id: MH-HOSTED-UI-007
+ name: Hosted-tool writes run one at a time and a read never overlaps one, so the screen holds the newest committed state
+ status: covered
+ kind: concurrency
+ layer: unit
+ test:
+ - 'ui/src/components/settings/models/useHostedTools.test.tsx::MH-HOSTED-UI-007: a read asked for during a write waits, so it cannot paint the pre-write state over the write'
+ - 'ui/src/components/settings/models/useHostedTools.test.tsx::MH-HOSTED-UI-007: runs writes one at a time, so each answer lands in the order the server committed them'
+ - 'ui/src/components/settings/models/useHostedTools.test.tsx::MH-HOSTED-UI-007: drops a read that was already out when a write started'
+ - 'ui/src/components/settings/models/useHostedTools.test.tsx::MH-HOSTED-UI-007: re-reads after the newest write fails, because a lost answer may have committed'
+ - 'ui/src/components/settings/models/useHostedTools.test.tsx::MH-HOSTED-UI-007: re-reads when the open Source changes, since an edit can drop its evidence'
+ - 'ui/src/components/settings/models/useHostedTools.test.tsx::MH-HOSTED-UI-007: keeps the status a probe answered with when the read after it fails'
+ - 'ui/src/components/settings/models/useHostedTools.test.tsx::MH-HOSTED-UI-007: lands the status read for a lost probe answer, even when the read after it fails'
+ - 'ui/src/components/settings/models/useHostedTools.test.tsx::MH-HOSTED-UI-007: shows no status of the previous Source identity while the new identity''s read fails'
+ - 'ui/src/components/settings/models/useHostedTools.test.tsx::MH-HOSTED-UI-007: keeps a tool pending until the read reconciling its lost write lands'
+ - 'ui/src/components/settings/models/useHostedTools.test.tsx::MH-HOSTED-UI-007: drops a write answer asked under another Source identity'
+ - id: MH-HOSTED-UI-013
+ name: A hosted-tool check runs only on the user's ask with its estimated cost shown first, and an answer that is not evidence reads as not verified with a retry
+ status: covered
+ kind: contract
+ layer: unit
+ test:
+ - 'ui/src/components/settings/models/ToolsTab.test.tsx::MH-HOSTED-UI-013: checks one row with its cost on the button, and says when the answer was not evidence'
+ - 'ui/src/components/settings/models/ToolsTab.test.tsx::MH-HOSTED-UI-013: runs the header check only after the dialog shows what it sends and costs'
+ - 'ui/src/components/settings/models/ToolsTab.test.tsx::MH-HOSTED-UI-013: says why a failed check failed, and never shows the server''s key as text'
+ - 'ui/src/components/settings/models/SourceDetailPanel.test.tsx::MH-HOSTED-UI-013: checks a tool again from its chip, with the cost on the action, and answers there when the check is not evidence'
+ - 'ui/src/components/settings/models/useHostedTools.test.tsx::MH-HOSTED-UI-013: reads the record before calling a probe unanswered when its answer was lost'
+ - 'ui/src/components/settings/models/useHostedTools.test.tsx::MH-HOSTED-UI-013: reads a verdict the status does not carry as not verified, with why'
+ - 'ui/src/components/settings/models/hostedTools.test.ts::MH-HOSTED-UI-013: offers to check every pair with no current answer, and never an image'
+ - id: MH-HOSTED-UI-016
+ name: A hosted-tool check is a real call on exactly one Source, so the Models page reads its Sources again after one, and a Source the probe verified shows as verified
+ status: covered
+ kind: contract
+ layer: unit
+ test:
+ - 'ui/src/components/settings/models/SettingsModelsPage.render.test.tsx::MH-HOSTED-UI-016: reads the hosted-tools report again after a committed Source change, since its models decide which pairs could run a tool'
+ - 'ui/src/components/settings/models/SettingsModelsPage.render.test.tsx::MH-HOSTED-UI-016: reads the Sources again after a check, since a probe can verify its Source'
+ - id: MH-HOSTED-UI-018
+ name: The Tools tab never enables a tool that cannot run. It stays off until the server binds an executor, says whether a check or an executor pick is missing or checks are not available yet, and an enabled tool with nothing verified says its calls fail
+ status: covered
+ kind: contract
+ layer: unit
+ test:
+ - 'ui/src/components/settings/models/ToolsTab.test.tsx::MH-HOSTED-UI-018: cannot turn a tool on until a pair is verified to run it, but can always turn it off'
+ - 'ui/src/components/settings/models/ToolsTab.test.tsx::MH-HOSTED-UI-018: keeps a tool off while the server binds no executor for it, and says to choose one when a verified pair exists'
+ - 'ui/src/components/settings/models/ToolsTab.test.tsx::MH-HOSTED-UI-018: claims routing only while the tool is on, and shows an off tool''s executor as a saved preference'
+ - 'ui/src/components/settings/models/ToolsTab.test.tsx::MH-HOSTED-UI-018: says plainly when a tool cannot be checked yet, instead of asking for a check it cannot run'
+ - 'ui/src/components/settings/models/ToolsTab.test.tsx::MH-HOSTED-UI-018: says an enabled tool with nothing verified fails its calls, instead of naming a proxy'
+ - id: MH-HOSTED-UI-017
+ name: A Source's capability chip is usable without a mouse. Its spoken name is the locale's composition of the label, explanation and facts, it announces the detail it opens, and Enter moves focus to the detail's paid re-check
+ status: covered
+ kind: contract
+ layer: unit
+ test:
+ - 'ui/src/components/settings/models/SourceDetailPanel.test.tsx::MH-HOSTED-UI-017: names the record time, how it was learned, the reason, and until when it holds'
+ - 'ui/src/components/settings/models/SourceDetailPanel.test.tsx::MH-HOSTED-UI-017: moves keyboard focus into the detail on Enter, so its paid re-check can be reached'
- id: MH-VIBEY-007
name: Vibey starts once with the user's Sources and built-in Agent models, seeded when its first Source exists
status: covered
diff --git a/ui/src/components/settings/models/HostedCapabilityChips.tsx b/ui/src/components/settings/models/HostedCapabilityChips.tsx
new file mode 100644
index 000000000..b3155738f
--- /dev/null
+++ b/ui/src/components/settings/models/HostedCapabilityChips.tsx
@@ -0,0 +1,276 @@
+// A Source model's capability chips (`vibey-hosted-tools.md` §6.2, design.pen
+// frame FB4vC): one per hosted tool with evidence, and one per reasoning effort
+// the Source refused. No record draws nothing, because unchecked is the normal
+// state rather than a problem.
+//
+// The hover/focus/tap detail follows TimeHint: a phone has no hover, so a tap
+// toggles it, and the chip's accessible name carries the same facts. The detail
+// stays open while the pointer is on it, so its check action can be reached.
+import * as React from 'react';
+import { useTranslation } from 'react-i18next';
+import { AtSign, Ban, Check, Gauge, Globe, Image as ImageIcon, Loader2, Radar, RotateCw, TriangleAlert, Waypoints } from 'lucide-react';
+
+import { Button } from '@/components/ui/button';
+import { Popover, PopoverAnchor, PopoverContent } from '@/components/ui/popover';
+import { cn } from '@/lib/utils';
+import { formatDayTime, formatMonthDay, formatSentences } from './format';
+import { probeableTool, probeKey, type ModelCapability, type ProbeTarget } from './hostedTools';
+import type { HostedToolName, HostedToolProbeResult, RefusedEffort } from './types';
+import { ProbeAnswerNote } from './HostedProbeDialog';
+import { useEstimateLabel } from './useEstimateLabel';
+
+const TOOL_ICON: Record<HostedToolName, React.ComponentType<{ className?: string }>> = {
+ web_search: Globe,
+ x_search: AtSign,
+ image_generation: ImageIcon,
+};
+
+/**
+ * The chip's state. A probe record older than 30 days, either way, asks for a new
+ * check. A refused tool reads "via proxy" only while the server binds a proxy
+ * executor for it (`bound`); otherwise it is simply not supported here.
+ */
+const chipState = ({ chip, proxied }: ModelCapability) => {
+ if (chip.kind === 'engineUpgraded') return 'engineUpgraded' as const;
+ if (chip.kind === 'native') return chip.aged ? 'reverify' as const : 'native' as const;
+ if (proxied) return chip.aged ? 'viaProxyAged' as const : 'viaProxy' as const;
+ return chip.aged ? 'unsupportedAged' as const : 'unsupported' as const;
+};
+type ChipState = ReturnType<typeof chipState>;
+
+const STATE_CLASS: Record<ChipState, string> = {
+ native: 'model-hub-status-mint',
+ reverify: 'model-hub-status-gold',
+ engineUpgraded: 'model-hub-status-gold',
+ viaProxy: 'model-hub-accent-pill--cyan',
+ viaProxyAged: 'model-hub-status-gold',
+ unsupported: 'model-hub-fill-0a border-border text-muted',
+ unsupportedAged: 'model-hub-status-gold',
+};
+
+const STATE_ICON: Record<ChipState, React.ComponentType<{ className?: string }>> = {
+ native: Check,
+ reverify: RotateCw,
+ engineUpgraded: TriangleAlert,
+ viaProxy: Waypoints,
+ viaProxyAged: RotateCw,
+ unsupported: Ban,
+ unsupportedAged: RotateCw,
+};
+
+type Fact = { term: string; value: string; mono?: boolean };
+
+/** The facts every evidence record states: when and how it was learned, why, and until when. */
+const useEvidenceFacts = () => {
+ const { t, i18n } = useTranslation();
+ return (record: { basis: 'probe' | 'observed' | null; observed_at: string | null; detail: string | null; changes_at: string | null }): Fact[] => {
+ const facts: Fact[] = [];
+ if (record.observed_at) {
+ facts.push({
+ term: t('settings.models.capability.recorded') as string,
+ value: t('settings.models.capability.recordedValue', {
+ time: formatDayTime(record.observed_at, i18n.language),
+ basis: t(`settings.models.capability.basis.${record.basis === 'observed' ? 'observed' : 'probe'}`),
+ }) as string,
+ });
+ }
+ if (record.detail) facts.push({ term: t('settings.models.capability.reason') as string, value: record.detail, mono: true });
+ if (record.changes_at) {
+ facts.push({
+ term: t('settings.models.capability.expiry') as string,
+ value: t(record.basis === 'observed' ? 'settings.models.capability.expiryObserved' : 'settings.models.capability.expiryProbe', {
+ date: formatMonthDay(record.changes_at),
+ }) as string,
+ });
+ }
+ return facts;
+ };
+};
+
+const EvidenceChip: React.FC<{
+ data: string;
+ label: string;
+ explanation: string;
+ facts: Fact[];
+ className: string;
+ Icon: React.ComponentType<{ className?: string }>;
+ TitleIcon: React.ComponentType<{ className?: string }>;
+ action?: React.ReactNode;
+}> = ({ data, label, explanation, facts, className, Icon, TitleIcon, action }) => {
+ const { t, i18n } = useTranslation();
+ const [open, setOpen] = React.useState(false);
+ const detailId = React.useId();
+ // The whole spoken name is the locale's composition, as the detail shows it.
+ const accessibleName = facts.length === 0
+ ? t('settings.models.capability.accessibleName', { label, explanation })
+ : t('settings.models.capability.accessibleNameFacts', {
+ label,
+ explanation,
+ facts: formatSentences(
+ facts.map((fact) => t('settings.models.capability.accessibleFact', { term: fact.term, value: fact.value }) as string),
+ i18n.language,
+ ),
+ });
+ const anchor = React.useRef<HTMLButtonElement>(null);
+ const pointer = React.useRef<string | null>(null);
+ const closing = React.useRef<number | null>(null);
+ const keepOpen = () => {
+ if (closing.current !== null) window.clearTimeout(closing.current);
+ closing.current = null;
+ setOpen(true);
+ };
+ // Leaving the chip for its detail must not close the detail on the way.
+ const closeSoon = () => {
+ closing.current = window.setTimeout(() => setOpen(false), 120);
+ };
+ React.useEffect(() => () => { if (closing.current !== null) window.clearTimeout(closing.current); }, []);
+ // Enter or Space moves keyboard focus into the detail, where its action is; a
+ // hover or a focus that only passes by leaves focus where it is.
+ const enterDetail = React.useRef(false);
+ const focusDetail = () => {
+ enterDetail.current = false;
+ const detail = document.getElementById(detailId);
+ const target = detail?.querySelector<HTMLElement>('button, [href], [tabindex]:not([tabindex="-1"])') ?? detail;
+ if (target && !target.hasAttribute('tabindex') && target === detail) target.setAttribute('tabindex', '-1');
+ target?.focus();
+ };
+ return (
+ <Popover open={open} onOpenChange={setOpen}>
+ <PopoverAnchor asChild>
+ <button
+ ref={anchor}
+ type="button"
+ data-capability={data}
+ aria-label={accessibleName as string}
+ // It opens a detail that may hold a paid re-check: say so.
+ aria-haspopup="dialog"
+ aria-expanded={open}
+ aria-controls={open ? detailId : undefined}
+ // Shrinks inside its column and truncates; the detail always has the whole label.
+ className={cn('model-hub-pill min-w-0 max-w-full flex-initial gap-1 border', className)}
+ onPointerDown={(event) => { pointer.current = event.pointerType; }}
+ onPointerEnter={(event) => { if (event.pointerType === 'mouse') keepOpen(); }}
+ onPointerLeave={(event) => { if (event.pointerType === 'mouse') closeSoon(); }}
+ onFocus={() => { if (pointer.current === null) keepOpen(); }}
+ onBlur={() => { pointer.current = null; closeSoon(); }}
+ onKeyDown={(event) => {
+ if (event.key !== 'Enter' && event.key !== ' ') return;
+ event.preventDefault();
+ enterDetail.current = true;
+ if (open) focusDetail();
+ else keepOpen();
+ }}
+ onClick={() => {
+ if (pointer.current === 'mouse') setOpen(true);
+ else setOpen((previous) => !previous);
+ }}
+ >
+ <Icon className="size-3 shrink-0" aria-hidden />
+ <span className="truncate">{label}</span>
+ </button>
+ </PopoverAnchor>
+ <PopoverContent
+ id={detailId}
+ side="bottom"
+ align="start"
+ sideOffset={6}
+ onOpenAutoFocus={(event) => {
+ event.preventDefault();
+ if (enterDetail.current) focusDetail();
+ }}
+ onInteractOutside={(event) => { if (anchor.current?.contains(event.target as Node)) event.preventDefault(); }}
+ onPointerEnter={(event) => { if (event.pointerType === 'mouse') keepOpen(); }}
+ onPointerLeave={(event) => { if (event.pointerType === 'mouse') closeSoon(); }}
+ onFocusCapture={keepOpen}
+ className="model-hub-capability-detail flex w-[320px] max-w-[calc(100vw-24px)] flex-col gap-2.5 text-foreground"
+ >
+ <span className="flex items-center gap-1.5 font-bold"><TitleIcon className="model-hub-ink-mint size-3.5" aria-hidden />{label}</span>
+ <span className="model-hub-capability-explain">{explanation}</span>
+ {facts.length > 0 && (
+ <dl className="model-hub-capability-facts grid gap-x-3 gap-y-1 rounded-lg">
+ {facts.map((fact) => (
+ <React.Fragment key={fact.term}><dt>{fact.term}</dt><dd className={cn(fact.mono && 'font-mono')}>{fact.value}</dd></React.Fragment>
+ ))}
+ </dl>
+ )}
+ {action}
+ </PopoverContent>
+ </Popover>
+ );
+};
+
+const CapabilityChip: React.FC<{
+ capability: ModelCapability;
+ probing: ReadonlySet<string>;
+ onProbe?: (target: ProbeTarget) => Promise<HostedToolProbeResult | null>;
+}> = ({ capability, probing, onProbe }) => {
+ const { t } = useTranslation();
+ const facts = useEvidenceFacts()(capability.evidence);
+ const estimate = useEstimateLabel()(capability.candidate.probe_estimate);
+ const state = chipState(capability);
+ const tool = t(`settings.models.tools.tool.${capability.tool}.name`) as string;
+ const target: ProbeTarget = { tool: capability.tool, candidate: capability.candidate };
+ const running = probing.has(probeKey(target));
+ // The last answer from this chip's check, so one that became no evidence still answers here.
+ const [last, setLast] = React.useState<HostedToolProbeResult | null | undefined>(undefined);
+ const label = t(`settings.models.capability.chip.${state}`, {
+ tool,
+ date: capability.evidence.observed_at ? formatMonthDay(capability.evidence.observed_at) : '',
+ }) as string;
+ const explanation = t(`settings.models.capability.explain.${state}`, {
+ tool,
+ toolInline: t(`settings.models.tools.tool.${capability.tool}.inline`),
+ }) as string;
+ const action = onProbe && probeableTool(capability.tool)
+ ? (
+ <span className="flex flex-col items-end gap-1">
+ {last !== undefined && <ProbeAnswerNote result={last} />}
+ <Button variant="outline" size="xs" disabled={running || probing.size > 0} aria-busy={running} onClick={() => void onProbe(target).then(setLast)}>
+ {running ? <Loader2 className="animate-spin" aria-hidden /> : <Radar aria-hidden />}
+ {t('settings.models.capability.recheckCost', { cost: estimate ?? t('settings.models.tools.probe.unknown') })}
+ </Button>
+ </span>
+ )
+ : undefined;
+ return (
+ <EvidenceChip
+ data={`${capability.tool}:${state}`}
+ label={label}
+ explanation={explanation}
+ facts={facts}
+ className={STATE_CLASS[state]}
+ Icon={STATE_ICON[state]}
+ TitleIcon={TOOL_ICON[capability.tool]}
+ action={action}
+ />
+ );
+};
+
+const EffortChip: React.FC<{ refused: RefusedEffort }> = ({ refused }) => {
+ const { t } = useTranslation();
+ const facts = useEvidenceFacts()(refused);
+ const effort = t(`chat.picker.effortOptions.${refused.effort}`, { defaultValue: refused.effort }) as string;
+ return (
+ <EvidenceChip
+ data={`effort:${refused.effort}`}
+ label={t('settings.models.capability.effort.unsupported', { effort }) as string}
+ explanation={t('settings.models.capability.effort.explain') as string}
+ facts={facts}
+ className="model-hub-fill-0a border-border text-muted"
+ Icon={Ban}
+ TitleIcon={Gauge}
+ />
+ );
+};
+
+export const HostedCapabilityChips: React.FC<{
+ capabilities: readonly ModelCapability[];
+ refusedEfforts?: readonly RefusedEffort[];
+ probing: ReadonlySet<string>;
+ onProbe?: (target: ProbeTarget) => Promise<HostedToolProbeResult | null>;
+}> = ({ capabilities, refusedEfforts = [], probing, onProbe }) => (
+ <span className="flex min-w-0 flex-wrap items-center gap-1.5">
+ {capabilities.map((capability) => <CapabilityChip key={capability.tool} capability={capability} probing={probing} onProbe={onProbe} />)}
+ {refusedEfforts.map((refused) => <EffortChip key={refused.effort} refused={refused} />)}
+ </span>
+);
diff --git a/ui/src/components/settings/models/HostedProbeDialog.tsx b/ui/src/components/settings/models/HostedProbeDialog.tsx
new file mode 100644
index 000000000..87c9f163f
--- /dev/null
+++ b/ui/src/components/settings/models/HostedProbeDialog.tsx
@@ -0,0 +1,220 @@
+// 检测可用工具 — the confirm and result dialogs (design.pen frame vQPXo).
+//
+// A check sends real, cost-bearing requests, so it runs only after the user has
+// seen what will be sent and what it is estimated to cost. Probes run one at a
+// time; only verified and unsupported become evidence, so a probe that did not
+// get an answer is reported as "not verified", never as "not supported".
+import * as React from 'react';
+import { Trans, useTranslation } from 'react-i18next';
+import { AlertCircle, AtSign, Check, Globe, Image as ImageIcon, Loader2, RotateCw, ShieldCheck } from 'lucide-react';
+
+import { Button } from '@/components/ui/button';
+import { Dialog, DialogContent, DialogDescription, DialogTitle } from '@/components/ui/dialog';
+import { cn } from '@/lib/utils';
+import { probeKey, probeTotal, probeUnanswered, type ProbeTarget } from './hostedTools';
+import { serverText } from './serverCopy';
+import type { HostedToolName, HostedToolProbeResult, Source } from './types';
+import { useEstimateLabel } from './useEstimateLabel';
+
+const TOOL_ICON: Record<HostedToolName, React.ComponentType<{ className?: string }>> = {
+ web_search: Globe,
+ x_search: AtSign,
+ image_generation: ImageIcon,
+};
+
+type Outcome = HostedToolProbeResult['call']['outcome'] | 'failed';
+
+const outcomeOf = (result: HostedToolProbeResult | null): Outcome => result?.call.outcome ?? 'failed';
+
+const TargetLine: React.FC<{ target: ProbeTarget; sources: ReadonlyMap<string, Source>; trailing: React.ReactNode }> = ({ target, sources, trailing }) => {
+ const { t } = useTranslation();
+ const Icon = TOOL_ICON[target.tool];
+ return (
+ <li className="model-hub-probe-row flex items-center gap-2.5 rounded-lg border border-border bg-background" data-probe={probeKey(target)}>
+ <Icon className="model-hub-ink-mint size-[14px] shrink-0" aria-hidden />
+ {/* The pair reads as the locale composes it; each part keeps its own style. */}
+ <Trans
+ i18nKey="settings.models.tools.dialog.pair"
+ values={{
+ tool: t(`settings.models.tools.tool.${target.tool}.name`),
+ source: sources.get(target.candidate.source_id)?.display_name ?? target.candidate.source_id,
+ model: target.candidate.model_id,
+ }}
+ components={{
+ tool: <span className="shrink-0 font-semibold text-foreground" />,
+ source: <span className="min-w-0 truncate text-foreground" />,
+ model: <span className="min-w-0 truncate font-mono text-muted" />,
+ muted: <span className="text-muted" />,
+ }}
+ />
+ <span className="ml-auto shrink-0">{trailing}</span>
+ </li>
+ );
+};
+
+const OutcomeChip: React.FC<{ outcome: Outcome }> = ({ outcome }) => {
+ const { t } = useTranslation();
+ if (outcome === 'verified') {
+ return <span className="model-hub-pill model-hub-status-mint gap-1 border"><Check className="size-3" aria-hidden />{t('settings.models.tools.result.outcome.verified')}</span>;
+ }
+ if (outcome === 'unsupported') {
+ return <span className="model-hub-pill model-hub-fill-0a gap-1 border border-border text-muted">{t('settings.models.tools.result.outcome.unsupported')}</span>;
+ }
+ return <span className="model-hub-pill model-hub-status-gold gap-1 border"><AlertCircle className="size-3" aria-hidden />{t('settings.models.tools.result.outcome.unverified')}</span>;
+};
+
+/**
+ * What a probe that became no evidence says where it was asked (a Tools row, a
+ * Source chip): a request that failed says why, and one that completed without
+ * the tool says that. Nothing for an answer that is evidence.
+ */
+export const ProbeAnswerNote: React.FC<{ result: HostedToolProbeResult | null }> = ({ result }) => {
+ const { t } = useTranslation();
+ if (!probeUnanswered(result)) return null;
+ const failure = serverText(t, result?.call.error);
+ return (
+ <span className="model-hub-tool-cost-note flex items-center gap-1 model-hub-ink-gold" role="status">
+ <AlertCircle className="size-3 shrink-0" aria-hidden />
+ {failure
+ ? t('settings.models.tools.probe.outcome.transientReason', { reason: failure })
+ : result?.call.outcome === 'inconclusive'
+ ? t('settings.models.tools.probe.outcome.inconclusive')
+ : t('settings.models.tools.probe.outcome.transient')}
+ </span>
+ );
+};
+
+/** Mounted for one check: the set it shows is the one it was opened with. */
+export const HostedProbeDialog: React.FC<{
+ targets: readonly ProbeTarget[];
+ sources: ReadonlyMap<string, Source>;
+ onRun: (target: ProbeTarget) => Promise<HostedToolProbeResult | null>;
+ onClose: () => void;
+}> = ({ targets, sources, onRun, onClose }) => {
+ const { t } = useTranslation();
+ const estimateLabel = useEstimateLabel();
+ // The set is fixed when the dialog opens: the read refreshes under it as probes land.
+ const [planned, setPlanned] = React.useState<readonly ProbeTarget[]>(targets);
+ const [phase, setPhase] = React.useState<'confirm' | 'running' | 'result'>('confirm');
+ const [results, setResults] = React.useState<ReadonlyMap<string, HostedToolProbeResult | null>>(() => new Map());
+
+ const run = async (batch: readonly ProbeTarget[]) => {
+ setPhase('running');
+ for (const target of batch) {
+ const result = await onRun(target);
+ setResults((previous) => new Map(previous).set(probeKey(target), result));
+ }
+ setPhase('result');
+ };
+
+ const total = probeTotal(planned);
+ const totalLabel = estimateLabel(total);
+ const outcomes = planned.map((target) => outcomeOf(results.get(probeKey(target)) ?? null));
+ const unverified = planned.filter((target) => results.has(probeKey(target)) && probeUnanswered(results.get(probeKey(target)) ?? null));
+ const count = (wanted: (outcome: Outcome) => boolean) => outcomes.filter(wanted).length;
+ // A retry is as paid as the first run, so it says its cost the same way.
+ const retryLabel = estimateLabel(probeTotal(unverified));
+ const done = results.size;
+
+ return (
+ <Dialog open onOpenChange={(next) => { if (!next && phase !== 'running') onClose(); }}>
+ <DialogContent className="model-hub-probe-dialog flex max-h-[calc(100dvh-2rem)] flex-col gap-0 overflow-hidden p-0 sm:max-w-[560px]">
+ <div className="model-hub-probe-head border-b border-border">
+ <DialogTitle className="font-bold text-foreground">
+ {t(phase === 'result' ? 'settings.models.tools.result.title' : 'settings.models.tools.dialog.title')}
+ </DialogTitle>
+ <DialogDescription className="text-muted">{t('settings.models.tools.dialog.subtitle')}</DialogDescription>
+ </div>
+ <div className="model-hub-probe-body flex min-h-0 flex-1 flex-col gap-3 overflow-y-auto">
+ {phase === 'confirm' && (
+ <>
+ <p className="text-foreground">{t('settings.models.tools.dialog.body', { count: planned.length })}</p>
+ <p className="model-hub-probe-privacy flex items-start gap-2 rounded-lg">
+ <ShieldCheck className="model-hub-ink-mint mt-px size-[14px] shrink-0" aria-hidden />
+ <span>{t('settings.models.tools.dialog.privacy')}</span>
+ </p>
+ <span className="model-hub-probe-label">{t('settings.models.tools.dialog.listTitle')}</span>
+ <ul className="flex flex-col gap-1.5">
+ {planned.map((target) => (
+ <TargetLine key={probeKey(target)} target={target} sources={sources} trailing={<span className="font-semibold text-foreground">{estimateLabel(target.candidate.probe_estimate) ?? t('settings.models.tools.probe.unknown')}</span>} />
+ ))}
+ </ul>
+ <div className="model-hub-probe-total flex items-center justify-between gap-3">
+ <span className="flex flex-col">
+ <span className="font-semibold text-foreground">{t('settings.models.tools.dialog.total')}</span>
+ <span className="text-muted">{t('settings.models.tools.dialog.totalNote')}</span>
+ </span>
+ <span className="font-bold text-foreground">{totalLabel ?? t('settings.models.tools.probe.unknown')}</span>
+ </div>
+ </>
+ )}
+ {phase !== 'confirm' && (
+ <>
+ {phase === 'result' && (
+ <span className="flex flex-wrap gap-1.5" role="status">
+ {count((outcome) => outcome === 'verified') > 0 && <span className="model-hub-pill model-hub-status-mint gap-1 border"><Check className="size-3" aria-hidden />{t('settings.models.tools.result.verified', { count: count((outcome) => outcome === 'verified') })}</span>}
+ {count((outcome) => outcome === 'unsupported') > 0 && <span className="model-hub-pill model-hub-fill-0a border border-border text-muted">{t('settings.models.tools.result.unsupported', { count: count((outcome) => outcome === 'unsupported') })}</span>}
+ {unverified.length > 0 && <span className="model-hub-pill model-hub-status-gold gap-1 border"><AlertCircle className="size-3" aria-hidden />{t('settings.models.tools.result.unverified', { count: unverified.length })}</span>}
+ </span>
+ )}
+ {phase === 'running' && <p className="flex items-center gap-2 text-muted" role="status"><Loader2 className="size-3.5 animate-spin" aria-hidden />{t('settings.models.tools.dialog.running', { done, count: planned.length })}</p>}
+ <ul className="flex flex-col gap-1.5">
+ {planned.map((target, index) => {
+ const key = probeKey(target);
+ const result = results.get(key);
+ // A request that failed says why; one that completed without the tool says that.
+ const failure = serverText(t, result?.call.error);
+ const reason = outcomes[index] === 'verified' || outcomes[index] === 'unsupported'
+ ? null
+ : outcomes[index] === 'inconclusive' && !failure
+ ? t('settings.models.tools.result.reason.inconclusive')
+ : failure
+ ? t('settings.models.tools.result.reason.transientReason', { reason: failure })
+ : t('settings.models.tools.result.reason.transient');
+ return (
+ <React.Fragment key={key}>
+ <TargetLine
+ target={target}
+ sources={sources}
+ trailing={results.has(key)
+ ? <OutcomeChip outcome={outcomes[index]} />
+ : <Loader2 className="size-3.5 animate-spin text-muted" aria-label={t('settings.models.tools.probe.running') as string} />}
+ />
+ {results.has(key) && reason && <p className="model-hub-probe-reason">{reason}</p>}
+ </React.Fragment>
+ );
+ })}
+ </ul>
+ {phase === 'result' && <p className="text-muted">{t('settings.models.tools.result.note')}</p>}
+ </>
+ )}
+ </div>
+ <div className={cn('model-hub-probe-foot flex items-center gap-2 border-t border-border', phase === 'result' && unverified.length > 0 ? 'justify-between' : 'justify-end')}>
+ {phase === 'confirm' && (
+ <>
+ <Button variant="outline" size="sm" onClick={onClose}>{t('settings.models.tools.dialog.cancel')}</Button>
+ <Button size="sm" disabled={planned.length === 0} onClick={() => void run(planned)}>
+ {totalLabel ? t('settings.models.tools.dialog.startCost', { cost: totalLabel }) : t('settings.models.tools.dialog.start')}
+ </Button>
+ </>
+ )}
+ {phase === 'result' && (
+ <>
+ {unverified.length > 0 && (
+ <Button variant="outline" size="sm" onClick={() => {
+ setPlanned(unverified);
+ setResults(new Map());
+ void run(unverified);
+ }}>
+ <RotateCw className="size-3.5" aria-hidden />
+ {t('settings.models.tools.result.retryCost', { count: unverified.length, cost: retryLabel ?? t('settings.models.tools.probe.unknown') })}
+ </Button>
+ )}
+ <Button size="sm" onClick={onClose}>{t('settings.models.tools.result.done')}</Button>
+ </>
+ )}
+ </div>
+ </DialogContent>
+ </Dialog>
+ );
+};
diff --git a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
index e7b3661da..61160660b 100644
--- a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
+++ b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
@@ -16,7 +16,7 @@ import type { ModelsSurfaceKind } from './modelHubSurfaceState';
import { ApiCallError, modelsApi } from './modelsApi';
import { QUOTA_PENDING_REREADS, QUOTA_PENDING_REREAD_MS, SettingsModelsPage as SettingsModelsRoute } from './SettingsModelsPage';
import { hasNativeSubscriptionCustody, SUBSCRIPTION_VENDORS } from './subscriptionOptions';
-import { CONTRACT_VERSION, type AgentBackend, type AgentChain, type AgentSupply, type BackendModel, type MigrationItem, type RuntimeDependency, type RuntimeManifest, type QuotaSummary, type Source, type UsageReport } from './types';
+import { CONTRACT_VERSION, type AgentBackend, type AgentChain, type AgentSupply, type BackendModel, type HostedToolsStatus, type MigrationItem, type RuntimeDependency, type RuntimeManifest, type QuotaSummary, type Source, type UsageReport } from './types';
// The page navigates to Agents when the user clicks an Agent that needs
// attention, so it needs a router in scope. Every render site wants the same
@@ -249,6 +249,15 @@ const routedImpact = {
interrupted: [{ backend: 'claude' as const, model_id: routedModelId, agents: ['Release bot'] }],
};
+const hostedToolsStatus: HostedToolsStatus = {
+ tools: [
+ { name: 'web_search', enabled: false, executor: null, bound: null, candidates: [] },
+ { name: 'x_search', enabled: false, executor: null, bound: null, candidates: [] },
+ { name: 'image_generation', enabled: false, executor: null, bound: null, candidates: [] },
+ ],
+ reverify: { engine_upgraded: 0, aged: 0 },
+};
+
const deferred = <T,>() => {
let resolve!: (value: T) => void;
const promise = new Promise<T>((done) => {
@@ -274,6 +283,7 @@ const renderPage = (
vi.spyOn(modelsApi, 'getUsageSummary').mockResolvedValue(usageSummary);
vi.spyOn(modelsApi, 'getQuota').mockResolvedValue(quotaSummary);
vi.spyOn(modelsApi, 'refreshQuota').mockResolvedValue(quotaSummary);
+ vi.spyOn(modelsApi, 'getHostedTools').mockResolvedValue(hostedToolsStatus);
return render(
<ToastProvider>
<I18nextProvider i18n={i18n}>
@@ -689,7 +699,7 @@ describe('SettingsModelsPage surface branches', () => {
// Frame 09 is what the `sources` tab shows here — not what the Hub shows
// instead of its tabs. It is still Frame 09's body: none of the gateway
// overview leaks in beside it.
- expect(screen.getAllByRole('tab')).toHaveLength(4);
+ expect(screen.getAllByRole('tab')).toHaveLength(5);
expect(screen.queryByText(/^Recent switches$|^最近切换$/i)).toBeNull();
});
@@ -839,7 +849,7 @@ describe('SettingsModelsPage surface branches', () => {
await userEvent.click(toggle);
await waitFor(() => expect(start).toHaveBeenCalledOnce());
- expect(await screen.findAllByRole('tab')).toHaveLength(4);
+ expect(await screen.findAllByRole('tab')).toHaveLength(5);
});
it('keeps routing controls available while an enabled gateway process is unavailable', async () => {
@@ -866,7 +876,7 @@ describe('SettingsModelsPage surface branches', () => {
expect((toggle as HTMLButtonElement).disabled).toBe(true);
expect(await screen.findByText('Retained source')).toBeTruthy();
expect(screen.getByRole('button', { name: /Runtime mode:|运行模式[::]/i })).toBeTruthy();
- expect(screen.queryAllByRole('tab')).toHaveLength(4);
+ expect(screen.queryAllByRole('tab')).toHaveLength(5);
});
it('still allows persisted enablement to be turned off on an unsupported host', async () => {
@@ -976,7 +986,7 @@ describe('SettingsModelsPage surface branches', () => {
renderPage([retainedSource]);
expect(await screen.findByText('Retained source')).toBeTruthy();
- expect(screen.getAllByRole('tab')).toHaveLength(4);
+ expect(screen.getAllByRole('tab')).toHaveLength(5);
expect(screen.queryByText(/^Switch to the gateway and you gain three things$|^切换到模型网关,有三大益处$/i)).toBeNull();
});
@@ -2516,7 +2526,7 @@ describe('SettingsModelsPage usage region', () => {
vi.restoreAllMocks();
renderPage(sources);
- await waitFor(() => expect(screen.getAllByRole('tab'), landing).toHaveLength(4));
+ await waitFor(() => expect(screen.getAllByRole('tab'), landing).toHaveLength(5));
await openUsage();
await waitFor(() => expect(vi.mocked(modelsApi.getUsageSummary), landing).toHaveBeenCalledWith('24h'));
}
@@ -2833,3 +2843,69 @@ describe('SettingsModelsPage quota region', () => {
await waitFor(() => expect(document.activeElement).toBe(screen.getByRole('tab', { name: /^Subscription quota$|^订阅额度$/ })));
});
});
+
+// How the Tools tab is READ. What it says once read is `ToolsTab.test.tsx`'s
+// subject; here the read is the tab's own, off the landing's first paint.
+describe('SettingsModelsPage tools region', () => {
+ it('MH-HOSTED-UI-005: leaves the hosted-tools report unread until its tab opens, then re-reads on every open', async () => {
+ renderPage([retainedSource]);
+ await screen.findByText('Retained source');
+ const read = vi.mocked(modelsApi.getHostedTools);
+ expect(read).not.toHaveBeenCalled();
+
+ await userEvent.click(screen.getByRole('tab', { name: /^Tools$|^工具$/ }));
+ await screen.findByRole('region', { name: /^Web search$|^网页搜索$/ });
+ expect(read).toHaveBeenCalledTimes(1);
+
+ await userEvent.click(screen.getByRole('tab', { name: /^Sources & gateway$|^供应商与路由$/ }));
+ await userEvent.click(screen.getByRole('tab', { name: /^Tools$|^工具$/ }));
+ await waitFor(() => expect(read).toHaveBeenCalledTimes(2));
+ });
+
+ it('MH-HOSTED-UI-016: reads the hosted-tools report again after a committed Source change, since its models decide which pairs could run a tool', async () => {
+ renderPage([retainedSource]);
+ const updatedSource = { ...retainedSource, display_name: 'Updated source' };
+ vi.spyOn(modelsApi, 'patchSource').mockResolvedValueOnce({ source: updatedSource, removed_hops: [], interrupted: [] });
+ await userEvent.click((await screen.findByText('Retained source')).closest('button') as HTMLButtonElement);
+ await screen.findByRole('dialog', { name: 'Retained source' });
+ const read = vi.mocked(modelsApi.getHostedTools);
+ await waitFor(() => expect(read).toHaveBeenCalled());
+ const readsBefore = read.mock.calls.length;
+ vi.mocked(modelsApi.listSources).mockResolvedValue([updatedSource]);
+
+ // A change that keeps the Source's identity (here its name) still commits a new Source row.
+ await userEvent.click(screen.getByRole('button', { name: /Manage Retained source|管理 Retained source/i }));
+ await userEvent.click(screen.getByRole('menuitem', { name: /^Edit source$|^编辑供应商$/i }));
+ const name = screen.getByLabelText(/^Display name$|^显示名称$/i);
+ await userEvent.clear(name);
+ await userEvent.type(name, updatedSource.display_name);
+ await userEvent.click(screen.getByRole('button', { name: /^Save$|^保存$/i }));
+ await screen.findByText(/^The source was updated$|^供应商已更新$/);
+
+ await waitFor(() => expect(read.mock.calls.length).toBeGreaterThan(readsBefore));
+ });
+
+ it('MH-HOSTED-UI-016: reads the Sources again after a check, since a probe can verify its Source', async () => {
+ const unknown = { status: 'unknown' as const, stale: null, basis: null, observed_at: null, detail: null, changes_at: null };
+ const withCandidate: HostedToolsStatus = {
+ ...hostedToolsStatus,
+ tools: hostedToolsStatus.tools.map((tool) => tool.name === 'web_search'
+ ? { ...tool, candidates: [{ source_id: retainedSource.id, model_id: 'claude-opus-5-5', call: unknown, replay: unknown, billing: 'metered' as const, price: null, probe_estimate: null }] }
+ : tool),
+ };
+ renderPage([retainedSource]);
+ vi.mocked(modelsApi.getHostedTools).mockResolvedValue(withCandidate);
+ const probe = vi.spyOn(modelsApi, 'probeHostedTool').mockResolvedValue({
+ probe: { tool: 'web_search', source_id: retainedSource.id, model_id: 'claude-opus-5-5', call: { outcome: 'verified', error: null }, replay: null },
+ hosted_tools: withCandidate,
+ });
+ await screen.findByText('Retained source');
+ await userEvent.click(screen.getByRole('tab', { name: /^Tools$|^工具$/ }));
+ const card = await screen.findByRole('region', { name: /^Web search$|^网页搜索$/ });
+ const sourceReads = vi.mocked(modelsApi.listSources).mock.calls.length;
+
+ await userEvent.click(within(card).getByRole('button', { name: /^Check · cost unknown$|^检测 · 费用未知$/ }));
+ expect(probe).toHaveBeenCalledTimes(1);
+ await waitFor(() => expect(vi.mocked(modelsApi.listSources).mock.calls.length).toBeGreaterThan(sourceReads));
+ });
+});
diff --git a/ui/src/components/settings/models/SettingsModelsPage.tsx b/ui/src/components/settings/models/SettingsModelsPage.tsx
index 4a112e322..9fa369015 100644
--- a/ui/src/components/settings/models/SettingsModelsPage.tsx
+++ b/ui/src/components/settings/models/SettingsModelsPage.tsx
@@ -1,5 +1,5 @@
import * as React from 'react';
-import { ArrowDownToLine, Activity, Gauge, LoaderCircle, Power, RefreshCw, Route, ScrollText } from 'lucide-react';
+import { ArrowDownToLine, Activity, Gauge, LoaderCircle, Power, RefreshCw, Route, ScrollText, Wrench } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { useLocation, useNavigate, useSearchParams } from 'react-router-dom';
@@ -35,7 +35,10 @@ import {
} from './suspendedRouteAttempts';
import { SupplyGraph, SupplyLegend } from './SupplyGraph';
import { QuotaTab } from './QuotaTab';
+import { ToolsTab } from './ToolsTab';
import { UsageTab } from './UsageTab';
+import { useHostedTools } from './useHostedTools';
+import type { ProbeTarget } from './hostedTools';
import './modelHubSurface.css';
import { agentsWithEcho, createLatestAsyncAuthority, createLatestAsyncAuthorityByKeySet, createLatestEntityAuthorityByKey, createPendingWrites, mapWithConcurrency } from './asyncLifetime';
import { createAgentCollectionReadAuthority, createSourceCollectionReadAuthority } from './collectionReadAuthority';
@@ -329,15 +332,15 @@ function usePendingRereads(active: boolean, pendingKey: string | null, settled:
const focusQuotaOpener = (opener: HTMLElement) =>
(opener.isConnected ? opener : document.querySelector<HTMLElement>('[role="tab"][aria-selected="true"]'))?.focus();
-type HubTab = 'sources' | 'quota' | 'usage' | 'logs';
+type HubTab = 'sources' | 'tools' | 'quota' | 'usage' | 'logs';
const HubTabs: React.FC<{ tab: HubTab; onChange: (tab: HubTab) => void }> = ({ tab, onChange }) => {
const { t } = useModelsTranslation();
return (
<div role="tablist" className="flex h-[39px] items-end gap-1 border-b border-border">
- {(['sources', 'quota', 'usage', 'logs'] as const).map((id) => (
+ {(['sources', 'tools', 'quota', 'usage', 'logs'] as const).map((id) => (
<button key={id} type="button" role="tab" aria-selected={tab === id} onClick={() => onChange(id)} className={cn('flex h-[41px] items-center gap-[7px] border-b-2 px-3.5 text-[13px] transition-colors', tab === id ? 'border-mint font-semibold text-foreground' : 'border-transparent font-normal text-muted hover:text-foreground')}>
- {id === 'sources' ? <Route className="size-3.5" /> : id === 'quota' ? <Gauge className="size-3.5" /> : id === 'usage' ? <Activity className="size-3.5" /> : <ScrollText className="size-3.5" />}
+ {id === 'sources' ? <Route className="size-3.5" /> : id === 'tools' ? <Wrench className="size-3.5" /> : id === 'quota' ? <Gauge className="size-3.5" /> : id === 'usage' ? <Activity className="size-3.5" /> : <ScrollText className="size-3.5" />}
{t(`settings.models.shell.tab.${id === 'sources' ? 'hub' : id}`)}
</button>
))}
@@ -1241,6 +1244,31 @@ export const SettingsModelsPage: React.FC = () => {
}
}, [selectSource, showToast, t]);
const selectedSource = sources.find((source) => source.id === selectedSourceId) ?? null;
+ // Read while the tab is open, or while a Source's detail shows its capability
+ // chips, and again when that Source changes: an edit can change its identity,
+ // which drops its evidence on the server.
+ // The open Source's identity as evidence follows it (`retry.source_identity`).
+ const selectedSourceIdentity = selectedSource
+ ? JSON.stringify([
+ selectedSource.id, selectedSource.kind, selectedSource.vendor, selectedSource.protocol, selectedSource.supply_channel,
+ selectedSource.base_url ?? null, selectedSource.credential_ref ?? null, selectedSource.verification_pending ?? null,
+ ])
+ : null;
+ const hostedTools = useHostedTools(tab === 'tools' || selectedSource !== null, selectedSourceIdentity);
+ // A probe is a real call on exactly one Source, and a successful one verifies
+ // that Source (a pending credential check clears), so the Sources read follows it.
+ // A committed Source change (a model added, removed or refetched, or its
+ // identity) changes which pairs could run a tool and what binds, so the
+ // hosted-tools report follows it once the Sources settle.
+ const presentSourceMutationAndTools = React.useCallback<PresentSourceMutationCommit>(async (commit) => {
+ await presentSourceMutation(commit);
+ void hostedTools.refresh();
+ }, [presentSourceMutation, hostedTools.refresh]);
+ const probeHostedTool = React.useCallback(async (target: ProbeTarget) => {
+ const result = await hostedTools.probe(target);
+ void refresh();
+ return result;
+ }, [hostedTools.probe, refresh]);
const sourceDetailOpen = selectedSourceId !== null && subscriptionVendor === null;
const orderAgent = agents.find((agent) => agent.backend === orderBackend && agent.mode === 'hub') ?? null;
const menuAgent = agents.find((agent) => agent.backend === menuBackend && agent.mode === 'hub') ?? null;
@@ -1619,6 +1647,7 @@ export const SettingsModelsPage: React.FC = () => {
selectSource({ sourceId, returnFocus: () => opener });
}}
/>
+ : tab === 'tools' ? <ToolsTab read={hostedTools.read} sources={sources} pending={hostedTools.pending} probing={hostedTools.probing} onChange={(tool, body) => void hostedTools.save(tool, body)} onProbe={probeHostedTool} onRetry={() => void hostedTools.refresh()} />
: tab === 'usage' ? <UsageTab usage={usageRead} windowKey={usageWindow} onWindowChange={setUsageWindow} onRetry={retryUsage} />
: tab === 'logs' ? <RecentSwitchesCard events={eventsRead} sources={sourcesRead} onRetry={retryEvents} loadingMore={loadingEvents} onLoadMore={loadOlderEvents} />
: directEmpty ? <DirectHome agents={installedNativeAgents} switchFailures={switchFailures} connectingBackend={adoptAgent?.backend ?? null} onSwitch={switchToGateway} />
@@ -1764,11 +1793,15 @@ export const SettingsModelsPage: React.FC = () => {
? <SourceDetailPanel
key={selectedSource.id}
source={selectedSource}
+ hostedTools={hostedTools.read}
+ onRetryHostedTools={() => void hostedTools.refresh()}
+ hostedProbing={hostedTools.probing}
+ onProbeHostedTool={probeHostedTool}
activeBackends={activeBackends}
headingRef={sourceDetailHeadingRef}
trackMutation={trackSourceMutation(selectedSource.id)}
onReauth={setReauthSource}
- onMutationCommitted={presentSourceMutation}
+ onMutationCommitted={presentSourceMutationAndTools}
/>
: <section className="grid min-h-0 flex-1 place-items-center px-5 py-12 text-center text-[12px] text-muted">{t('settings.models.sourceDetail.gone')}</section>}
</DialogContent>
diff --git a/ui/src/components/settings/models/SourceDetailPanel.test.tsx b/ui/src/components/settings/models/SourceDetailPanel.test.tsx
index c34a689e2..ccd2382aa 100644
--- a/ui/src/components/settings/models/SourceDetailPanel.test.tsx
+++ b/ui/src/components/settings/models/SourceDetailPanel.test.tsx
@@ -11,6 +11,7 @@ import { ToastProvider } from '@/context/ToastProvider';
import i18n from '@/i18n';
import { classifyModelHubFailure, createPendingWrites } from './asyncLifetime';
import { MANAGE_DESTINATION, type ManageKind } from './manage';
+import { readyRegion, unreadRegion } from './regionRead';
import { ApiCallError, modelsApi } from './modelsApi';
import type {
PresentSourceMutationCommit,
@@ -29,7 +30,7 @@ import {
NEEDS_ACTION_DETAIL_KEYS,
SOURCE_STATUSES,
} from './types';
-import type { Source, SourceDetailKey, SourceKind, SourceProtocol, SupplyChannel } from './types';
+import type { HostedEvidence, HostedToolCandidate, HostedToolProbeResult, HostedToolsStatus, Source, SourceDetailKey, SourceKind, SourceProtocol, SupplyChannel } from './types';
const source: Source = {
id: 'src_detail',
@@ -1379,3 +1380,143 @@ describe('SourceDetailPanel', () => {
});
});
+
+// What a Source's model rows say about hosted tools (§6.2, frame FB4vC). The
+// projection's states are `hostedTools.test.ts`'s subject; what is proved here is
+// what a Source row adds: a refused tool reads "via proxy" only while the server
+// binds a proxy for it, unchecked draws nothing, refused efforts get their own
+// chip, and the detail carries the record's facts and its check.
+describe('SourceDetailPanel hosted-tool capability chips', () => {
+ const twoModels: Source = {
+ ...source,
+ models: [
+ { id: 'model-a', display_name: null, origin: 'discovered', reasoning_efforts: [], reasoning_efforts_source: null },
+ { id: 'model-b', display_name: null, origin: 'discovered', reasoning_efforts: [], reasoning_efforts_source: null },
+ ],
+ };
+ const at = '2026-10-13T10:20:00Z';
+ const verified: HostedEvidence = {
+ status: 'verified', stale: null, basis: 'probe', observed_at: at, detail: null, changes_at: '2026-11-12T10:20:00Z',
+ };
+ const refused: HostedEvidence = {
+ status: 'unsupported', stale: null, basis: 'observed', observed_at: at, detail: '400 · unsupported_tool_type', changes_at: '2026-10-20T10:20:00Z',
+ };
+ const unknown: HostedEvidence = { status: 'unknown', stale: null, basis: null, observed_at: null, detail: null, changes_at: null };
+ const candidate = (model_id: string, call: HostedEvidence): HostedToolCandidate => ({
+ source_id: source.id, model_id, call, replay: unknown, billing: 'metered', price: null, probe_estimate: { basis: 'list', usd: 0.02 },
+ });
+ const executor = { source_id: 'src_grok0001', model_id: 'grok-4.6' };
+ const status = (xSearch: { enabled: boolean; bound: typeof executor | null }): HostedToolsStatus => ({
+ tools: [
+ { name: 'web_search', enabled: true, executor: null, bound: null, candidates: [candidate('model-a', verified), candidate('model-b', unknown)] },
+ { name: 'x_search', ...xSearch, executor: null, candidates: [candidate('model-a', refused)] },
+ { name: 'image_generation', enabled: false, executor: null, bound: null, candidates: [] },
+ ],
+ reverify: { engine_upgraded: 0, aged: 0 },
+ });
+ const renderChips = (
+ hostedTools: HostedToolsStatus,
+ { models = twoModels.models, onProbe }: { models?: Source['models']; onProbe?: React.ComponentProps<typeof SourceDetailPanel>['onProbeHostedTool'] } = {},
+ ) => render(
+ <I18nextProvider i18n={i18n}>
+ <CommittedPanel source={{ ...twoModels, models }} hostedTools={readyRegion(hostedTools)} onProbeHostedTool={onProbe} trackMutation={immediateTrack} onReauth={noReauth} />
+ </I18nextProvider>,
+ );
+ const chips = (modelId: string) => [...(screen.getByTitle(modelId).closest('.model-hub-source-table-row') as HTMLElement)
+ .querySelectorAll('[data-capability]')].map((chip) => chip.getAttribute('data-capability'));
+
+ it('MH-HOSTED-UI-006: draws evidence per model, and says "via proxy" only while a proxy is bound for the tool', () => {
+ renderChips(status({ enabled: true, bound: executor }));
+ expect(chips('model-a')).toEqual(['web_search:native', 'x_search:viaProxy']);
+ // Unchecked is the normal state, not a problem: no chip at all.
+ expect(chips('model-b')).toEqual([]);
+ cleanup();
+
+ // Off, or on with nothing bound: no call goes anywhere, so it is just unsupported here.
+ renderChips(status({ enabled: false, bound: executor }));
+ expect(chips('model-a')).toEqual(['web_search:native', 'x_search:unsupported']);
+ cleanup();
+ renderChips(status({ enabled: true, bound: null }));
+ expect(chips('model-a')).toEqual(['web_search:native', 'x_search:unsupported']);
+ });
+
+ it('MH-HOSTED-UI-017: names the record time, how it was learned, the reason, and until when it holds', async () => {
+ renderChips(status({ enabled: false, bound: null }));
+ const chip = screen.getByRole('button', { name: /X search · not supported on this Source|X 搜索 · 此供应商不支持/ });
+ // The accessible name carries the same facts as the hover detail, each with
+ // its term, composed by the locale.
+ expect(chip.getAttribute('aria-label')).toMatch(/(Reason: |原因:)400 · unsupported_tool_type/);
+ // And it says it opens a detail, which may hold a paid re-check.
+ expect(chip.getAttribute('aria-haspopup')).toBe('dialog');
+ expect(chip.getAttribute('aria-expanded')).toBe('false');
+ await userEvent.hover(chip);
+ const detail = await screen.findByRole('dialog');
+ expect(chip.getAttribute('aria-expanded')).toBe('true');
+ expect(chip.getAttribute('aria-controls')).toBe(detail.id);
+ within(detail).getByText(/a real request|一次真实请求/);
+ within(detail).getByText('400 · unsupported_tool_type');
+ within(detail).getByText(/until 10-20, then the default applies|到 10-20,过期后按默认判断/);
+ });
+
+ it('MH-HOSTED-UI-013: checks a tool again from its chip, with the cost on the action, and answers there when the check is not evidence', async () => {
+ const onProbe = vi.fn(async (): Promise<HostedToolProbeResult> => ({
+ tool: 'x_search', source_id: source.id, model_id: 'model-a', call: { outcome: 'inconclusive', error: null }, replay: null,
+ }));
+ renderChips(status({ enabled: false, bound: null }), { onProbe });
+ await userEvent.hover(screen.getByRole('button', { name: /X search · not supported on this Source|X 搜索 · 此供应商不支持/ }));
+ const detail = await screen.findByRole('dialog');
+ await userEvent.click(within(detail).getByRole('button', { name: /Check again · about \$0\.02|重新检测 · 约 \$0\.02/ }));
+ expect(onProbe).toHaveBeenCalledWith({ tool: 'x_search', candidate: expect.objectContaining({ source_id: source.id, model_id: 'model-a' }) });
+ // Nothing was recorded, so the chip still reads as before; the detail says why.
+ await within(detail).findByText(/the model didn't use the tool|模型没有调用工具/);
+ });
+
+ it('MH-HOSTED-UI-017: moves keyboard focus into the detail on Enter, so its paid re-check can be reached', async () => {
+ renderChips(status({ enabled: false, bound: null }), { onProbe: vi.fn(async () => null) });
+ const chip = screen.getByRole('button', { name: /X search · not supported on this Source|X 搜索 · 此供应商不支持/ });
+ chip.focus();
+ await userEvent.keyboard('{Enter}');
+ const detail = await screen.findByRole('dialog');
+ await waitFor(() => expect(document.activeElement).toBe(
+ within(detail).getByRole('button', { name: /Check again · about \$0\.02|重新检测 · 约 \$0\.02/ }),
+ ));
+ });
+
+ it('MH-HOSTED-UI-003: says a re-check\'s cost is unknown when no estimate is known', async () => {
+ const read = status({ enabled: false, bound: null });
+ const unpriced = { ...read, tools: read.tools.map((tool) => ({ ...tool, candidates: tool.candidates.map((candidate) => ({ ...candidate, probe_estimate: null })) })) };
+ renderChips(unpriced, { onProbe: vi.fn(async () => null) });
+ await userEvent.hover(screen.getByRole('button', { name: /X search · not supported on this Source|X 搜索 · 此供应商不支持/ }));
+ const detail = await screen.findByRole('dialog');
+ within(detail).getByRole('button', { name: /Check again · cost unknown|重新检测 · 费用未知/ });
+ });
+
+ it('MH-HOSTED-UI-006: draws a chip for each reasoning effort the Source refused, even with no tool evidence', () => {
+ const models = twoModels.models.map((model) => model.id === 'model-b'
+ ? { ...model, refused_efforts: [{ effort: 'xhigh', basis: 'observed' as const, observed_at: at, detail: '400 · unsupported reasoning effort', changes_at: null }] }
+ : model);
+ renderChips({ ...status({ enabled: false, bound: null }), tools: [] }, { models });
+ expect(chips('model-a')).toEqual([]);
+ expect(chips('model-b')).toEqual(['effort:xhigh']);
+ });
+
+ it('MH-HOSTED-UI-006: says when the capability read failed instead of drawing a Source with no evidence', async () => {
+ const retry = vi.fn();
+ render(
+ <I18nextProvider i18n={i18n}>
+ <CommittedPanel source={twoModels} hostedTools={unreadRegion()} onRetryHostedTools={retry} trackMutation={immediateTrack} onReauth={noReauth} />
+ </I18nextProvider>,
+ );
+ const line = screen.getByRole('status');
+ within(line).getByText(/Couldn't read this Source's tool capabilities|未能读取此供应商的工具能力/);
+ await userEvent.click(within(line).getByRole('button', { name: /^Retry$|^重试$/ }));
+ expect(retry).toHaveBeenCalledTimes(1);
+ });
+
+ it('MH-HOSTED-UI-006: adds no capability column when no model has evidence', () => {
+ const read = status({ enabled: true, bound: null });
+ renderChips({ ...read, tools: read.tools.map((tool) => ({ ...tool, candidates: [] })) });
+ expect(document.querySelector('.model-hub-source-table--capabilities')).toBeNull();
+ expect(document.querySelector('[data-capability]')).toBeNull();
+ });
+});
diff --git a/ui/src/components/settings/models/SourceDetailPanel.tsx b/ui/src/components/settings/models/SourceDetailPanel.tsx
index 3066c1dea..f2dba0198 100644
--- a/ui/src/components/settings/models/SourceDetailPanel.tsx
+++ b/ui/src/components/settings/models/SourceDetailPanel.tsx
@@ -16,6 +16,8 @@ import { classifyModelHubFailure } from './asyncLifetime';
import { Field } from './dialogFields';
import { GuardDialog } from './GuardDialog';
import { GuardImpact } from './GuardImpact';
+import { HostedCapabilityChips } from './HostedCapabilityChips';
+import { modelCapabilities, type ProbeTarget } from './hostedTools';
import { confirmGuardPlan, sendAgreed, unansweredRefusal } from './guardedWrite';
import { ModelHubInfoHint } from './ModelHubInfoHint';
import { SourcePrivateValue, SourcePrivacyToggle } from './SourcePrivacy';
@@ -51,6 +53,7 @@ import {
type TrackSourceMutation,
} from './mutationSettlement';
import { reconcileUnknownWrite } from './reconcileUnknownWrite';
+import { foldRegionRead, regionFailed, type RegionRead } from './regionRead';
import { REPAIR_DESTINATION, REPAIR_LABEL_KEY, reauthBodyKey, reauthCost, repairAction } from './repair';
import { activeSourceAdoption, sourceStatePresentation } from './sourceStatePresentation';
import { useDeadlineClock } from './useDeadlineClock';
@@ -58,6 +61,8 @@ import { SourceTestDialog } from './SourceTestDialog';
import { ACCENT_ICON, ACCENT_TILE, sourceVisual } from './vendorMeta';
import type {
AgentBackend,
+ HostedToolProbeResult,
+ HostedToolsStatus,
RouteHopRef,
Source,
SourcePatch,
@@ -140,6 +145,8 @@ const GUARD_COPY_KIND: Record<GuardedAction['kind'], 'refetch' | 'removeModel'>
const committedPlan = (hops: RouteHopRef[], gaps: SupplyGap[]): ManageGuardPlan | null =>
hops.length > 0 || gaps.length > 0 ? { hops, gaps } : null;
+const NO_PROBES: ReadonlySet<string> = new Set();
+
type SourceReconciliation =
| { kind: 'source'; source: Source }
| { kind: 'gone'; sources: Source[]; snapshot: number };
@@ -166,7 +173,13 @@ export const SourceDetailPanel: React.FC<{
headingRef?: React.Ref<HTMLHeadingElement>;
/** Authoritative backends still using the gateway, when the Agent read is ready. */
activeBackends?: ReadonlySet<AgentBackend>;
-}> = ({ source, trackMutation, onReauth, onMutationCommitted, headingRef, activeBackends }) => {
+ /** The hosted-tools read, for each model's capability chips (§6.2), and its retry. */
+ hostedTools?: RegionRead<HostedToolsStatus>;
+ onRetryHostedTools?: () => void;
+ /** Probe keys running now, and the action a chip's re-check runs. */
+ hostedProbing?: ReadonlySet<string>;
+ onProbeHostedTool?: (target: ProbeTarget) => Promise<HostedToolProbeResult | null>;
+}> = ({ source, trackMutation, onReauth, onMutationCommitted, headingRef, activeBackends, hostedTools, onRetryHostedTools, hostedProbing, onProbeHostedTool }) => {
const { t, i18n } = useTranslation();
const detailsHidden = useSourceDetailsHidden();
const now = useDeadlineClock(source.state.status === 'cooldown' ? source.state.retry_at : null);
@@ -190,6 +203,24 @@ export const SourceDetailPanel: React.FC<{
? models.filter((model) => model.id.toLocaleLowerCase(i18n.language).includes(normalizedQuery))
: models;
const visibleModelIds = new Set(filteredModels.map((model) => model.id));
+ const capabilityStatus = hostedTools
+ ? foldRegionRead<HostedToolsStatus, HostedToolsStatus | null>(hostedTools, {
+ loading: () => null,
+ ready: (data) => data,
+ unread: () => null,
+ degraded: (staleData) => staleData,
+ })
+ : null;
+ const capabilities = new Map(models.map((model) => [
+ model.id,
+ capabilityStatus ? modelCapabilities(capabilityStatus, source.id, model.id) : [],
+ ]));
+ // The column appears only when a model has evidence: unchecked draws nothing.
+ const showCapabilities = [...capabilities.values()].some((list) => list.length > 0)
+ || models.some((model) => (model.refused_efforts?.length ?? 0) > 0);
+ // A failed read is not "nothing checked": say so where chips would be. Only a
+ // hub Source can carry hosted-tool evidence.
+ const capabilitiesFailed = source.supply_channel === 'hub' && hostedTools !== undefined && regionFailed(hostedTools);
const editDraft = 'draft' in manageStage ? manageStage.draft : null;
const editAssessment = editDraft
? assessSourceEdit(source, editDraft)
@@ -723,15 +754,20 @@ export const SourceDetailPanel: React.FC<{
<SourceManageMenu source={source} busy={busy || manageStage.kind !== 'idle'} onEdit={beginEdit} onDelete={beginDelete} />
</div>
</section>
- <section className="model-hub-source-table flex min-h-0 flex-1 flex-col overflow-hidden bg-surface">
+ {capabilitiesFailed && <p role="status" className="model-hub-source-capabilities-failure flex shrink-0 items-center justify-between gap-3 border-b border-border px-5 py-2 text-destructive-ink">
+ <span>{t('settings.models.capability.readFailed')}</span>
+ {onRetryHostedTools && <button type="button" onClick={onRetryHostedTools} className="model-hub-action-mint shrink-0 font-semibold">{t('settings.models.upstream.retry')}</button>}
+ </p>}
+ <section className={cn('model-hub-source-table flex min-h-0 flex-1 flex-col overflow-hidden bg-surface', showCapabilities && 'model-hub-source-table--capabilities')}>
<div className="model-hub-source-table-head hidden border-b border-border font-semibold md:grid">
- <span className="truncate">{t('settings.models.sourceDetail.col.id')}</span><span />
+ <span className="truncate">{t('settings.models.sourceDetail.col.id')}</span>{showCapabilities && <span className="truncate">{t('settings.models.capability.col')}</span>}<span />
</div>
<div className="model-hub-source-table-scroll min-h-0 flex-1 overflow-y-auto">
{filteredModels.length === 0 && !manualDraft && <p className="px-5 py-12 text-center text-[12px] text-muted">{t(normalizedQuery ? 'settings.models.sourceDetail.searchEmpty' : source.last_discovered_at ? 'settings.models.sourceDetail.empty' : 'settings.models.sourceDetail.emptyNeverFetched')}</p>}
{models.map((model) => (
<div key={model.id} hidden={!visibleModelIds.has(model.id)} className="model-hub-source-table-row grid gap-3 border-b border-border last:border-b-0 md:items-center md:gap-y-0">
<span className="flex min-w-0 items-center gap-2"><span className="model-hub-source-model truncate font-mono text-foreground" title={model.id}>{model.id}</span>{model.origin !== 'discovered' && <span className="model-hub-source-pill model-hub-source-entry-pill model-hub-source-entry-pill--manual w-fit rounded-full border font-semibold">{t('settings.models.sourceDetail.entry.manual')}</span>}{result?.added.includes(model.id) && <span className="model-hub-accent-pill--mint model-hub-source-pill rounded-full border px-2 py-0.5 font-semibold">{t('settings.models.sourceDetail.refetch.added')}</span>}</span>
+ {showCapabilities && <span className="model-hub-source-capabilities min-w-0"><HostedCapabilityChips capabilities={capabilities.get(model.id) ?? []} refusedEfforts={model.refused_efforts} probing={hostedProbing ?? NO_PROBES} onProbe={onProbeHostedTool} /></span>}
<div className="model-hub-source-row-actions flex items-center justify-end gap-1">
{removeFailure?.modelId === model.id && <span className="model-hub-source-tier text-right text-destructive-ink">{t('settings.models.sourceDetail.fail.removeModel')} <button type="button" disabled={busy} onClick={() => {
if (!removeFailure.retryRead) void remove(model);
diff --git a/ui/src/components/settings/models/ToolsTab.test.tsx b/ui/src/components/settings/models/ToolsTab.test.tsx
new file mode 100644
index 000000000..a9b5bcc2f
--- /dev/null
+++ b/ui/src/components/settings/models/ToolsTab.test.tsx
@@ -0,0 +1,437 @@
+// @vitest-environment jsdom
+// What the 工具 tab writes and claims (`vibey-hosted-tools.md` §6.1): a toggle and
+// an executor pick each replace the tool's whole setting, the picker offers only
+// what is verified, and no cost is invented where none is known.
+import { cleanup, render, screen, within } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { createInstance } from 'i18next';
+import { I18nextProvider, initReactI18next } from 'react-i18next';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import en from '../../../i18n/en.json';
+import zh from '../../../i18n/zh.json';
+import type { ProbeTarget } from './hostedTools';
+import { readyRegion } from './regionRead';
+import { ToolsTab } from './ToolsTab';
+import type {
+ HostedEvidence,
+ HostedToolCandidate,
+ HostedToolName,
+ HostedToolProbeResult,
+ HostedToolsStatus,
+ HostedToolStatus,
+ Source,
+} from './types';
+
+const translator = (lng: 'en' | 'zh') => {
+ const instance = createInstance();
+ void instance.use(initReactI18next).init({
+ lng,
+ fallbackLng: 'en',
+ resources: { en: { translation: en }, zh: { translation: zh } },
+ interpolation: { escapeValue: false },
+ });
+ return instance;
+};
+
+const source = (id: string, name: string, over: Partial<Source> = {}): Source => ({
+ id,
+ last_discovered_at: null,
+ kind: 'api_key',
+ vendor: 'openai',
+ display_name: name,
+ protocol: 'openai_responses',
+ supply_channel: 'hub',
+ billing: 'metered',
+ state: { status: 'active', retry_at: null, detail_key: null },
+ models: [],
+ ...over,
+});
+
+const RELAY = source('src_relay001', 'relay-gpt');
+const GROK = source('src_grok0001', 'Grok', { vendor: 'xai' });
+const SUBSCRIPTION = source('src_chatgpt1', 'OpenAI subscription', { kind: 'subscription', billing: 'monthly' });
+const CLAUDE = source('src_claude01', 'relay-claude', { vendor: 'anthropic', protocol: 'anthropic' });
+
+const unknown: HostedEvidence = { status: 'unknown', stale: null, basis: null, observed_at: null, detail: null, changes_at: null };
+const verified: HostedEvidence = {
+ status: 'verified', stale: null, basis: 'probe', observed_at: '2026-10-13T10:20:00Z', detail: null, changes_at: '2026-11-12T10:20:00Z',
+};
+const SOURCES = [CLAUDE, RELAY, GROK, SUBSCRIPTION];
+
+/** A candidate as the server reports it; billing follows its Source unless a test states it. */
+type CandidateInput = Pick<HostedToolCandidate, 'source_id' | 'model_id' | 'call' | 'replay'> & Partial<HostedToolCandidate>;
+const tool = (
+ name: HostedToolName,
+ over: Omit<Partial<HostedToolStatus>, 'candidates'> & { candidates?: CandidateInput[] } = {},
+): HostedToolStatus => ({
+ name,
+ enabled: false,
+ executor: null,
+ bound: null,
+ ...over,
+ candidates: (over.candidates ?? []).map((candidate) => ({
+ billing: SOURCES.find((entry) => entry.id === candidate.source_id)?.billing ?? 'metered',
+ price: null,
+ probe_estimate: null,
+ ...candidate,
+ })),
+});
+
+const status = (tools: HostedToolStatus[], reverify = { engine_upgraded: 0, aged: 0 }): HostedToolsStatus => ({ tools, reverify });
+
+type RunProbe = (target: ProbeTarget) => Promise<HostedToolProbeResult | null>;
+const renderTab = (
+ value: HostedToolsStatus,
+ {
+ lng = 'en',
+ pending = new Set<HostedToolName>(),
+ onProbe = vi.fn<RunProbe>(async () => null),
+ }: { lng?: 'en' | 'zh'; pending?: ReadonlySet<HostedToolName>; onProbe?: RunProbe } = {},
+) => {
+ const onChange = vi.fn();
+ render(
+ <I18nextProvider i18n={translator(lng)}>
+ <ToolsTab
+ read={readyRegion(value)}
+ sources={SOURCES}
+ pending={pending}
+ probing={new Set()}
+ onChange={onChange}
+ onProbe={onProbe}
+ onRetry={() => {}}
+ />
+ </I18nextProvider>,
+ );
+ return onChange;
+};
+
+const card = (name: string) => screen.getByRole('region', { name });
+
+afterEach(() => cleanup());
+
+describe('ToolsTab writes', () => {
+ it('MH-HOSTED-UI-001: a toggle replaces the whole setting and keeps the saved executor', async () => {
+ const executor = { source_id: GROK.id, model_id: 'grok-4.6' };
+ const onChange = renderTab(status([
+ tool('web_search', { enabled: true, executor, candidates: [{ ...executor, call: verified, replay: verified }] }),
+ tool('x_search', { bound: executor, candidates: [{ ...executor, call: verified, replay: verified }] }),
+ ]));
+
+ await userEvent.click(within(card('Web search')).getByRole('switch', { name: 'Turn off Web search' }));
+ // The PUT body is total: a toggle that sent only `enabled` would drop the
+ // user's executor back to automatic.
+ expect(onChange).toHaveBeenLastCalledWith('web_search', { enabled: false, executor });
+
+ await userEvent.click(within(card('X search')).getByRole('switch', { name: 'Turn on X search' }));
+ expect(onChange).toHaveBeenLastCalledWith('x_search', { enabled: true, executor: null });
+ });
+
+ it('MH-HOSTED-UI-018: cannot turn a tool on until a pair is verified to run it, but can always turn it off', async () => {
+ const onChange = renderTab(status([
+ tool('web_search', { candidates: [{ source_id: GROK.id, model_id: 'grok-4.6', call: unknown, replay: unknown }] }),
+ tool('x_search', { enabled: true, candidates: [{ source_id: GROK.id, model_id: 'grok-4.6', call: unknown, replay: unknown }] }),
+ ]));
+
+ // On with nothing verified, every call would fail with no way to fix it here.
+ const off = within(card('Web search')).getByRole('switch', { name: 'Turn on Web search' }) as HTMLButtonElement;
+ expect(off.disabled).toBe(true);
+ within(card('Web search')).getByText('Off · check a Source first');
+
+ await userEvent.click(within(card('X search')).getByRole('switch', { name: 'Turn off X search' }));
+ expect(onChange).toHaveBeenLastCalledWith('x_search', { enabled: false, executor: null });
+ });
+
+ it('MH-HOSTED-UI-018: keeps a tool off while the server binds no executor for it, and says to choose one when a verified pair exists', async () => {
+ // Verified, but outside Vibey's Source order: Automatic binds nothing (`bound: null`).
+ const onChange = renderTab(status([tool('web_search', {
+ candidates: [{ source_id: GROK.id, model_id: 'grok-4.6', call: verified, replay: verified }],
+ })]));
+ const toggle = within(card('Web search')).getByRole('switch', { name: 'Turn on Web search' }) as HTMLButtonElement;
+ expect(toggle.disabled).toBe(true);
+ within(card('Web search')).getByText('Off · choose an executor first');
+ // Picking the verified pair explicitly is how it binds.
+ await userEvent.selectOptions(within(card('Web search')).getByRole('combobox'), 'Grok · grok-4.6');
+ expect(onChange).toHaveBeenLastCalledWith('web_search', { enabled: false, executor: { source_id: GROK.id, model_id: 'grok-4.6' } });
+ });
+
+ it('MH-HOSTED-UI-001: writes a saved executor back only while the server would still accept it', async () => {
+ // The saved pair left the candidates (its model went away): resolution skips
+ // it already, and echoing it would get the whole PUT refused.
+ const onChange = renderTab(status([tool('web_search', {
+ enabled: true,
+ executor: { source_id: RELAY.id, model_id: 'gpt-6-retired' },
+ candidates: [{ source_id: GROK.id, model_id: 'grok-4.6', call: unknown, replay: unknown }],
+ })]));
+
+ await userEvent.click(within(card('Web search')).getByRole('switch', { name: 'Turn off Web search' }));
+ expect(onChange).toHaveBeenLastCalledWith('web_search', { enabled: false, executor: null });
+ });
+
+ it('MH-HOSTED-UI-001: the executor picker offers only verified pairs, and a pick keeps the toggle', async () => {
+ const onChange = renderTab(status([
+ tool('web_search', {
+ enabled: true,
+ bound: { source_id: GROK.id, model_id: 'grok-4.6' },
+ candidates: [
+ { source_id: RELAY.id, model_id: 'gpt-6-astra', call: unknown, replay: unknown },
+ { source_id: GROK.id, model_id: 'grok-4.6', call: verified, replay: verified },
+ ],
+ }),
+ tool('x_search', { candidates: [{ source_id: GROK.id, model_id: 'grok-4.6', call: unknown, replay: unknown }] }),
+ ]));
+
+ const picker = within(card('Web search')).getByRole('combobox', { name: 'Proxy executor for Web search' });
+ expect(within(picker).getAllByRole('option').map((option) => option.textContent))
+ // Automatic names what the server binds for it now.
+ .toEqual(['Automatic (Grok · grok-4.6)', 'Grok · grok-4.6']);
+ await userEvent.selectOptions(picker, 'Grok · grok-4.6');
+ expect(onChange).toHaveBeenLastCalledWith('web_search', { enabled: true, executor: { source_id: GROK.id, model_id: 'grok-4.6' } });
+ await userEvent.selectOptions(picker, 'Automatic (Grok · grok-4.6)');
+ expect(onChange).toHaveBeenLastCalledWith('web_search', { enabled: true, executor: null });
+
+ // Nothing verified: nothing to pick, and the control says why.
+ const unverified = within(card('X search')).getByRole('combobox', { name: 'Proxy executor for X search' });
+ expect((unverified as HTMLButtonElement | HTMLSelectElement).disabled).toBe(true);
+ expect((unverified as HTMLSelectElement).selectedOptions[0]?.textContent).toBe('Available after a check');
+ });
+
+ it('MH-HOSTED-UI-001: a saved executor that is no longer verified stays visible as itself', () => {
+ const executor = { source_id: GROK.id, model_id: 'grok-4.6' };
+ renderTab(status([tool('web_search', {
+ enabled: true,
+ executor,
+ // The saved choice is stale, so the server binds the first verified pair.
+ bound: { source_id: RELAY.id, model_id: 'gpt-6-astra' },
+ candidates: [
+ { source_id: RELAY.id, model_id: 'gpt-6-astra', call: verified, replay: verified },
+ { ...executor, call: { ...verified, status: 'unknown', stale: 'wire' }, replay: unknown },
+ ],
+ })]));
+
+ const picker = within(card('Web search')).getByRole('combobox', { name: 'Proxy executor for Web search' });
+ expect((picker as HTMLSelectElement).selectedOptions[0]?.textContent).toBe('Grok · grok-4.6 (not verified)');
+ // The badge is on what a turn binds, not on the saved choice.
+ const badge = within(card('Web search')).getByText('Proxy executor', { selector: '.model-hub-pill' });
+ expect(badge.closest('[data-candidate]')?.getAttribute('data-candidate')).toBe('src_relay001:gpt-6-astra');
+ });
+
+ it('MH-HOSTED-UI-001: keeps a saved executor visible as itself when nothing is verified any more', () => {
+ const executor = { source_id: GROK.id, model_id: 'grok-4.6' };
+ const onChange = renderTab(status([tool('x_search', {
+ enabled: true,
+ executor,
+ candidates: [{ ...executor, call: { ...verified, status: 'unknown', stale: 'wire' }, replay: unknown }],
+ })]));
+
+ const picker = within(card('X search')).getByRole('combobox', { name: 'Proxy executor for X search' }) as HTMLSelectElement;
+ expect(picker.disabled).toBe(true);
+ expect(picker.selectedOptions[0]?.textContent).toBe('Grok · grok-4.6 (not verified)');
+ expect(within(picker).queryByText('Available after a check')).toBeNull();
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it('MH-HOSTED-UI-001: holds a tool\'s controls while its write is in flight', () => {
+ renderTab(status([
+ tool('web_search', { candidates: [{ source_id: GROK.id, model_id: 'grok-4.6', call: verified, replay: verified }] }),
+ tool('x_search', { bound: { source_id: GROK.id, model_id: 'grok-4.6' }, candidates: [{ source_id: GROK.id, model_id: 'grok-4.6', call: verified, replay: verified }] }),
+ ]), { pending: new Set(['web_search']) });
+
+ expect((within(card('Web search')).getByRole('switch') as HTMLButtonElement | HTMLSelectElement).disabled).toBe(true);
+ expect((within(card('Web search')).getByRole('combobox') as HTMLButtonElement | HTMLSelectElement).disabled).toBe(true);
+ expect((within(card('X search')).getByRole('switch') as HTMLButtonElement).disabled).toBe(false);
+ });
+});
+
+describe('ToolsTab claims', () => {
+ it('MH-HOSTED-UI-018: claims routing only while the tool is on, and shows an off tool\'s executor as a saved preference', () => {
+ const executor = { source_id: GROK.id, model_id: 'grok-4.6' };
+ const candidates = [{ ...executor, call: verified, replay: verified }];
+ renderTab(status([
+ tool('web_search', { enabled: true, executor, bound: executor, candidates }),
+ tool('x_search', { enabled: false, executor, bound: executor, candidates }),
+ ]));
+
+ const on = card('Web search');
+ within(on).getByText('Proxy executor', { selector: '.model-hub-pill' });
+ within(on).getByText(/Other models use Grok/);
+
+ // Off: resolution leaves the tool out entirely, so nothing here runs or bills.
+ const off = card('X search');
+ expect(within(off).queryByText('Proxy executor', { selector: '.model-hub-pill' })).toBeNull();
+ expect(off.textContent).not.toMatch(/Other models use|billed/);
+ within(off).getByText('Applies when the tool is on.');
+ expect((within(off).getByRole('combobox') as HTMLSelectElement).selectedOptions[0]?.textContent).toBe('Grok · grok-4.6');
+ });
+
+ it('MH-HOSTED-UI-003: states a cost only where one is known, and never prices an image', () => {
+ renderTab(status([
+ tool('web_search', { candidates: [
+ {
+ source_id: RELAY.id, model_id: 'gpt-6-astra', call: unknown, replay: unknown,
+ price: { unit: 'call', usd_per_1k: 10, extra: [], as_of: '2026-10-13', url: 'https://openai.com/api/pricing' },
+ },
+ { source_id: CLAUDE.id, model_id: 'claude-opus-5-5', call: unknown, replay: unknown },
+ { source_id: SUBSCRIPTION.id, model_id: 'gpt-6.1-sol', call: unknown, replay: unknown },
+ ] }),
+ tool('x_search', { candidates: [{
+ source_id: GROK.id, model_id: 'grok-4.6', call: unknown, replay: unknown,
+ price: { unit: 'post', usd_per_1k: 5, extra: [{ unit: 'profile', usd_per_1k: 10 }], as_of: '2026-10-13', url: 'https://docs.x.ai/pricing' },
+ }] }),
+ tool('image_generation', { candidates: [{ source_id: RELAY.id, model_id: 'gpt-6.1-sol', call: unknown, replay: null }] }),
+ ]));
+
+ const row = (name: string, key: string) => card(name).querySelector(`[data-candidate="${key}"]`) as HTMLElement;
+ within(row('Web search', 'src_relay001:gpt-6-astra')).getByText('≈ $0.01 / call');
+ within(row('Web search', 'src_relay001:gpt-6-astra')).getByText('At API price');
+ // No list price for this provider: said to be unknown, never drawn as zero.
+ within(row('Web search', 'src_claude01:claude-opus-5-5')).getByText('No list price');
+ expect(row('Web search', 'src_claude01:claude-opus-5-5').textContent).not.toMatch(/\$/);
+ within(row('Web search', 'src_chatgpt1:gpt-6.1-sol')).getByText('Included in subscription');
+ within(row('X search', 'src_grok0001:grok-4.6')).getByText('≈ $0.005 / post');
+ within(row('X search', 'src_grok0001:grok-4.6')).getByText('At API price · + $0.01 / profile');
+ within(row('Image generation', 'src_relay001:gpt-6.1-sol')).getByText('Billed per image token · no per-image price yet');
+ expect(row('Image generation', 'src_relay001:gpt-6.1-sol').textContent).not.toMatch(/\$/);
+ });
+
+ it('MH-HOSTED-UI-003: the image cost copy is the orchestrator-decided Chinese line', () => {
+ renderTab(status([tool('image_generation', { candidates: [
+ { source_id: RELAY.id, model_id: 'gpt-6.1-sol', call: unknown, replay: null },
+ { source_id: SUBSCRIPTION.id, model_id: 'gpt-6.1-sol', call: unknown, replay: null },
+ ] })]), { lng: 'zh' });
+
+ const image = card('图片生成');
+ within(image.querySelector('[data-candidate="src_relay001:gpt-6.1-sol"]') as HTMLElement).getByText('按图像 token 计费 · 暂无单价');
+ within(image.querySelector('[data-candidate="src_chatgpt1:gpt-6.1-sol"]') as HTMLElement).getByText('订阅内含');
+ });
+
+ it('MH-HOSTED-UI-003: lets the locale compose a price with its extras', () => {
+ renderTab(status([tool('x_search', { candidates: [{
+ source_id: GROK.id, model_id: 'grok-4.6', call: unknown, replay: unknown,
+ price: { unit: 'post', usd_per_1k: 5, extra: [{ unit: 'profile', usd_per_1k: 10 }], as_of: '2026-10-13', url: 'https://docs.x.ai/pricing' },
+ }] })]), { lng: 'zh' });
+ within(card('X 搜索').querySelector('[data-candidate="src_grok0001:grok-4.6"]') as HTMLElement).getByText('API 标价 · 另加 $0.01 / 个账号');
+ });
+
+ it('MH-HOSTED-UI-004: says how many checks an engine upgrade made stale, and nothing when none did', () => {
+ renderTab(status([tool('web_search')], { engine_upgraded: 2, aged: 1 }));
+ const line = screen.getByRole('status');
+ // One sentence the locale composes, its first part marked.
+ expect(line.textContent).toBe('Engine upgraded · 2 need a new check · 1 check is over 30 days old');
+ expect(within(line).getByText('Engine upgraded · 2 need a new check').className).toContain('model-hub-ink-gold');
+ cleanup();
+
+ renderTab(status([tool('web_search')]));
+ expect(screen.queryByRole('status')).toBeNull();
+ });
+
+ it('MH-HOSTED-UI-006: names the Sources that have no native pair for a tool', () => {
+ renderTab(status([tool('x_search', { candidates: [{ source_id: GROK.id, model_id: 'grok-4.6', call: verified, replay: verified }] })]));
+
+ const note = within(card('X search')).getByText(/have no native X search/);
+ // Grok offers the tool natively, so it is the one Source not named. Whether
+ // a proxy executor serves the others is not this read's to say.
+ expect(note.textContent).toMatch(/^Models on relay-claude, relay-gpt,? (and )?OpenAI subscription have no native X search\.$/);
+ });
+});
+
+describe('ToolsTab checks', () => {
+ const searchable = () => status([
+ tool('web_search', { candidates: [
+ { source_id: RELAY.id, model_id: 'gpt-6-astra', call: unknown, replay: unknown, probe_estimate: { basis: 'list', usd: 0.02 } },
+ { source_id: SUBSCRIPTION.id, model_id: 'gpt-6.1-sol', call: unknown, replay: unknown, probe_estimate: { basis: 'included' } },
+ { source_id: GROK.id, model_id: 'grok-4.6', call: verified, replay: verified, probe_estimate: { basis: 'list', usd: 0.01 } },
+ ] }),
+ tool('image_generation', { candidates: [{ source_id: RELAY.id, model_id: 'gpt-6.1-sol', call: unknown, replay: null }] }),
+ ]);
+ const result = (outcome: HostedToolProbeResult['call']['outcome'], source_id: string, model_id: string): HostedToolProbeResult => ({
+ tool: 'web_search', source_id, model_id, call: { outcome, error: null }, replay: null,
+ });
+
+ it('MH-HOSTED-UI-013: checks one row with its cost on the button, and says when the answer was not evidence', async () => {
+ const onProbe = vi.fn<RunProbe>(async () => result('inconclusive', RELAY.id, 'gpt-6-astra'));
+ renderTab(searchable(), { onProbe });
+
+ const row = card('Web search').querySelector('[data-candidate="src_relay001:gpt-6-astra"]') as HTMLElement;
+ await userEvent.click(within(row).getByRole('button', { name: 'Check · about $0.02' }));
+ expect(onProbe).toHaveBeenCalledTimes(1);
+ expect(onProbe.mock.calls[0][0]).toMatchObject({ tool: 'web_search', candidate: { source_id: RELAY.id, model_id: 'gpt-6-astra' } });
+ // The model never used the tool: not recorded as unsupported, and the row offers another try.
+ within(row).getByText("Not verified · the model didn't use the tool; try again");
+ // Another try is as paid as the first, and says so.
+ within(row).getByRole('button', { name: 'Retry · about $0.02' });
+
+ // A verified row checks again; a subscription row says the check costs nothing extra.
+ within(card('Web search').querySelector('[data-candidate="src_grok0001:grok-4.6"]') as HTMLElement).getByRole('button', { name: 'Check again · about $0.01' });
+ within(card('Web search').querySelector('[data-candidate="src_chatgpt1:gpt-6.1-sol"]') as HTMLElement)
+ .getByRole('button', { name: 'Check · included in subscription' });
+ // Images cannot be checked yet, so their rows offer nothing to run.
+ expect(within(card('Image generation')).queryByRole('button', { name: /Check/ })).toBeNull();
+ });
+
+ it('MH-HOSTED-UI-013: runs the header check only after the dialog shows what it sends and costs', async () => {
+ const onProbe = vi.fn<RunProbe>(async (target) => target.candidate.source_id === RELAY.id
+ ? result('verified', target.candidate.source_id, target.candidate.model_id)
+ : { ...result('transient', target.candidate.source_id, target.candidate.model_id), call: { outcome: 'transient', error: 'models.source.cooldown.rate_limited' } });
+ renderTab(searchable(), { onProbe });
+
+ // Two unchecked pairs (the verified one and the image are not offered); the subscription adds nothing.
+ screen.getByText('2 pairs to check · about $0.02 in total');
+ await userEvent.click(screen.getByRole('button', { name: 'Check available tools' }));
+ const dialog = await screen.findByRole('dialog');
+ within(dialog).getByText('This sends 2 real requests to the Sources below to confirm they can run these tools natively.');
+ expect(onProbe).not.toHaveBeenCalled();
+
+ await userEvent.click(within(dialog).getByRole('button', { name: 'Start check · about $0.02' }));
+ await within(dialog).findByText('Check finished');
+ expect(onProbe).toHaveBeenCalledTimes(2);
+ within(dialog).getByText('1 runs natively');
+ within(dialog).getByText('1 not verified');
+ // The reason sits where the locale puts it in the sentence.
+ within(dialog).getByText('Couldn\'t verify this time (Rate limited). Try again; this is not recorded as unsupported.');
+
+ // Retrying runs only the pair that got no answer.
+ await userEvent.click(within(dialog).getByRole('button', { name: 'Retry 1 · included in subscription' }));
+ await within(dialog).findByText('Check finished');
+ expect(onProbe).toHaveBeenCalledTimes(3);
+ expect(onProbe.mock.calls[2][0]).toMatchObject({ candidate: { source_id: SUBSCRIPTION.id } });
+ });
+
+ it('MH-HOSTED-UI-013: says why a failed check failed, and never shows the server\'s key as text', async () => {
+ const failed = (error: string): HostedToolProbeResult => ({ ...result('inconclusive', RELAY.id, 'gpt-6-astra'), call: { outcome: 'transient', error } });
+ const onProbe = vi.fn<RunProbe>()
+ .mockResolvedValueOnce(failed('models.source.cooldown.rate_limited'))
+ // A detail key this bundle has no copy for.
+ .mockResolvedValueOnce(failed('models.source.cooldown.network'));
+ renderTab(searchable(), { onProbe });
+ const row = card('Web search').querySelector('[data-candidate="src_relay001:gpt-6-astra"]') as HTMLElement;
+
+ await userEvent.click(within(row).getByRole('button', { name: 'Check · about $0.02' }));
+ within(row).getByText("Couldn't verify · Rate limited");
+ await userEvent.click(within(row).getByRole('button', { name: 'Retry · about $0.02' }));
+ within(row).getByText("Couldn't verify · try again");
+ expect(row.textContent).not.toContain('models.source');
+ });
+
+ it('MH-HOSTED-UI-018: says plainly when a tool cannot be checked yet, instead of asking for a check it cannot run', () => {
+ renderTab(status([tool('image_generation', { candidates: [{ source_id: RELAY.id, model_id: 'gpt-6.1-sol', call: unknown, replay: null }] })]));
+ const image = card('Image generation');
+ within(image).getByText('Off · checks for this tool come in a later update');
+ expect((within(image).getByRole('switch') as HTMLButtonElement).disabled).toBe(true);
+ expect(within(image).queryByRole('button', { name: /Check/ })).toBeNull();
+ });
+
+ it('MH-HOSTED-UI-003: says a check\'s cost is unknown before it runs, when no estimate is known', () => {
+ renderTab(status([tool('web_search', { candidates: [{ source_id: CLAUDE.id, model_id: 'claude-opus-5-5', call: unknown, replay: unknown }] })]));
+ within(card('Web search')).getByRole('button', { name: 'Check · cost unknown' });
+ });
+
+ it('MH-HOSTED-UI-018: says an enabled tool with nothing verified fails its calls, instead of naming a proxy', () => {
+ renderTab(status([tool('x_search', {
+ enabled: true,
+ candidates: [{ source_id: GROK.id, model_id: 'grok-4.6', call: { ...verified, status: 'unknown', stale: 'wire' }, replay: unknown }],
+ })]));
+ within(card('X search')).getByText('No Source is verified, so calls to it fail until you check one.');
+ });
+});
+
diff --git a/ui/src/components/settings/models/ToolsTab.tsx b/ui/src/components/settings/models/ToolsTab.tsx
new file mode 100644
index 000000000..f7098b090
--- /dev/null
+++ b/ui/src/components/settings/models/ToolsTab.tsx
@@ -0,0 +1,431 @@
+// 工具 — the hosted tools Vibey may call (`vibey-hosted-tools.md` §6.1, design.pen
+// frames E5IkUQ and XZjhj).
+//
+// One card per catalog tool: its toggle (off by default), the (Source, model)
+// pairs that could run it natively with their evidence and a check for each, and
+// the proxy executor that runs it for every other model. The read is a report:
+// hop resolution reads config and evidence itself, so nothing on this tab decides
+// a route, and every claim about one comes from `bound`, the server's answer.
+import * as React from 'react';
+import { Trans, useTranslation } from 'react-i18next';
+import { AtSign, Ban, Check, Globe, Image as ImageIcon, Info, Loader2, Radar, RotateCw, TriangleAlert, Waypoints } from 'lucide-react';
+
+import { Button } from '@/components/ui/button';
+import { Select } from '@/components/ui/select';
+import { cn } from '@/lib/utils';
+import { ToggleSwitch } from '../SettingsPrimitives';
+import { formatMonthDay, formatNameList, formatSmallUsd } from './format';
+import { HostedProbeDialog, ProbeAnswerNote } from './HostedProbeDialog';
+import {
+ evidenceChip,
+ pendingChecks,
+ probeableTool,
+ probeKey,
+ probeTotal,
+ probeUnanswered,
+ sameExecutor,
+ verifiedCandidates,
+ type HostedEvidenceChip,
+ type ProbeTarget,
+} from './hostedTools';
+import { foldRegionRead, regionFailed, type RegionRead } from './regionRead';
+import { ACCENT_ICON, ACCENT_PILL, ACCENT_TILE, sourceVisual } from './vendorMeta';
+import type {
+ HostedToolCandidate,
+ HostedToolName,
+ HostedToolPriceUnit,
+ HostedToolProbeResult,
+ HostedToolPut,
+ HostedToolsStatus,
+ HostedToolStatus,
+ Source,
+} from './types';
+import { useEstimateLabel } from './useEstimateLabel';
+
+type RunProbe = (target: ProbeTarget) => Promise<HostedToolProbeResult | null>;
+
+const TOOL_ICON: Record<HostedToolName, React.ComponentType<{ className?: string }>> = {
+ web_search: Globe,
+ x_search: AtSign,
+ image_generation: ImageIcon,
+};
+
+const AUTOMATIC = '';
+const executorValue = (executor: { source_id: string; model_id: string } | null): string =>
+ executor ? JSON.stringify([executor.source_id, executor.model_id]) : AUTOMATIC;
+
+/** The native-run cell: the call evidence, or 「未检测」 when there is none. */
+export const NativeEvidenceChip: React.FC<{ chip: HostedEvidenceChip | null }> = ({ chip }) => {
+ const { t } = useTranslation();
+ if (chip === null) {
+ return <span className="model-hub-pill model-hub-fill-0a border border-border text-muted">{t('settings.models.tools.chip.unchecked')}</span>;
+ }
+ const date = chip.at ? formatMonthDay(chip.at) : '';
+ if (chip.kind === 'engineUpgraded') {
+ return <span className="model-hub-pill model-hub-status-gold gap-1 border"><TriangleAlert className="size-3" aria-hidden />{t('settings.models.tools.chip.engineUpgraded')}</span>;
+ }
+ if (chip.aged) {
+ return <span className="model-hub-pill model-hub-status-gold gap-1 border"><RotateCw className="size-3" aria-hidden />{t(chip.kind === 'native' ? 'settings.models.tools.chip.reverify' : 'settings.models.tools.chip.unsupportedAged', { date })}</span>;
+ }
+ return chip.kind === 'native'
+ ? <span className="model-hub-pill model-hub-status-mint gap-1 border"><Check className="size-3" aria-hidden />{t('settings.models.tools.chip.native', { date })}</span>
+ : <span className="model-hub-pill model-hub-fill-0a gap-1 border border-border text-muted"><Ban className="size-3" aria-hidden />{t('settings.models.tools.chip.unsupported')}</span>;
+};
+
+/**
+ * What a call costs on this row: included on a subscription, else the overlay's
+ * list price per unit (an estimate; a relay may bill differently). An image has
+ * no per-image list price (it is billed per image token), and a price nobody
+ * lists is said to be unknown, never shown as zero.
+ */
+const CostCell: React.FC<{ tool: HostedToolName; candidate: HostedToolCandidate }> = ({ tool, candidate }) => {
+ const { t } = useTranslation();
+ if (candidate.billing === 'monthly') {
+ return <span className="flex min-w-0 flex-col"><span className="font-semibold text-foreground">{t('settings.models.tools.cost.included')}</span><span className="model-hub-tool-cost-note">{t('settings.models.tools.cost.includedNote')}</span></span>;
+ }
+ if (tool === 'image_generation') {
+ return <span className="model-hub-tool-cost-note">{t('settings.models.tools.cost.imageTokens')}</span>;
+ }
+ const price = candidate.price;
+ if (!price) return <span className="model-hub-tool-cost-note">{t('settings.models.tools.cost.unknown')}</span>;
+ const perUnit = (usdPer1k: number, unit: HostedToolPriceUnit) => t('settings.models.tools.cost.perUnit', {
+ usd: formatSmallUsd(usdPer1k / 1000),
+ unit: t(`settings.models.tools.cost.unit.${unit}`),
+ }) as string;
+ return (
+ <span className="flex min-w-0 flex-col">
+ <span className="font-semibold text-foreground">{t('settings.models.tools.cost.list', { price: perUnit(price.usd_per_1k, price.unit) })}</span>
+ <span className="model-hub-tool-cost-note">
+ {price.extra.length === 0
+ ? t('settings.models.tools.cost.listNote')
+ : t('settings.models.tools.cost.listNoteExtras', {
+ extras: price.extra
+ .map((extra) => t('settings.models.tools.cost.extra', { price: perUnit(extra.usd_per_1k, extra.unit) }))
+ .join(t('settings.models.tools.cost.extraSeparator')),
+ })}
+ </span>
+ </span>
+ );
+};
+
+/** A row's check: run it now, with its cost on the button (§6.1: the probe's estimate shows first). */
+const ProbeCell: React.FC<{
+ target: ProbeTarget;
+ running: boolean;
+ last: HostedToolProbeResult | null | undefined;
+ onProbe: RunProbe;
+ disabled: boolean;
+}> = ({ target, running, last, onProbe, disabled }) => {
+ const { t } = useTranslation();
+ const estimate = useEstimateLabel()(target.candidate.probe_estimate);
+ const checked = target.candidate.call.basis !== null;
+ const unanswered = last !== undefined && probeUnanswered(last);
+ // Every action that starts a paid request says what it is estimated to cost.
+ const action = unanswered ? 'retry' : checked ? 'recheck' : 'check';
+ const label = running
+ ? t('settings.models.tools.probe.running')
+ : t(`settings.models.tools.probe.${action}Cost`, { cost: estimate ?? t('settings.models.tools.probe.unknown') });
+ return (
+ <span className="flex min-w-0 flex-col items-start gap-1 md:items-end">
+ <Button
+ variant="outline"
+ size="xs"
+ disabled={disabled || running}
+ aria-busy={running}
+ onClick={() => void onProbe(target)}
+ title={estimate ?? undefined}
+ >
+ {running ? <Loader2 className="animate-spin" aria-hidden /> : checked || unanswered ? <RotateCw aria-hidden /> : <Radar aria-hidden />}
+ {label}
+ </Button>
+ {last !== undefined && <ProbeAnswerNote result={last} />}
+ </span>
+ );
+};
+
+const CandidateRow: React.FC<{
+ tool: HostedToolName;
+ candidate: HostedToolCandidate;
+ source: Source | undefined;
+ executor: boolean;
+ probe: { running: boolean; last: HostedToolProbeResult | null | undefined; run: RunProbe; disabled: boolean } | null;
+}> = ({ tool, candidate, source, executor, probe }) => {
+ const { t } = useTranslation();
+ const { Icon, accent } = source ? sourceVisual(source) : { Icon: Globe, accent: 'muted' as const };
+ const name = source?.display_name ?? candidate.source_id;
+ return (
+ <div className="model-hub-tool-row grid items-center rounded-lg border border-border bg-background" data-candidate={`${candidate.source_id}:${candidate.model_id}`}>
+ <span className="flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1">
+ <span className={cn('flex size-[26px] shrink-0 items-center justify-center rounded-[7px]', ACCENT_TILE[accent])}><Icon className={cn('size-[13px]', ACCENT_ICON[accent])} /></span>
+ <span className="truncate font-semibold text-foreground" title={name}>{name}</span>
+ <span className="truncate font-mono text-muted" title={candidate.model_id}>{candidate.model_id}</span>
+ {source && <span className={cn('model-hub-pill border', ACCENT_PILL[source.kind === 'api_key' ? 'cyan' : accent])}>{t(`settings.models.upstream.kind.${source.kind === 'subscription' ? 'subscription' : 'apiKey'}`)}</span>}
+ </span>
+ <span className="flex min-w-0 flex-wrap items-center gap-1.5">
+ <NativeEvidenceChip chip={evidenceChip(candidate.call)} />
+ {executor && <span className="model-hub-pill gap-1 model-hub-accent-pill--cyan border"><Waypoints className="size-3" aria-hidden />{t('settings.models.tools.chip.executor')}</span>}
+ </span>
+ <CostCell tool={tool} candidate={candidate} />
+ {probe
+ ? <ProbeCell target={{ tool, candidate }} running={probe.running} last={probe.last} onProbe={probe.run} disabled={probe.disabled} />
+ : <span />}
+ </div>
+ );
+};
+
+const ToolCard: React.FC<{
+ tool: HostedToolStatus;
+ sources: ReadonlyMap<string, Source>;
+ hubSources: readonly Source[];
+ pending: boolean;
+ probing: ReadonlySet<string>;
+ lastProbes: ReadonlyMap<string, HostedToolProbeResult | null>;
+ onChange: (tool: HostedToolName, body: HostedToolPut) => void;
+ onProbe: RunProbe;
+}> = ({ tool, sources, hubSources, pending, probing, lastProbes, onChange, onProbe }) => {
+ const { t, i18n } = useTranslation();
+ const Icon = TOOL_ICON[tool.name];
+ const name = t(`settings.models.tools.tool.${tool.name}.name`) as string;
+ const toolInline = t(`settings.models.tools.tool.${tool.name}.inline`) as string;
+ const verified = verifiedCandidates(tool);
+ // What a turn would bind now: the server's own answer, so the card claims no
+ // routing it cannot see.
+ const bound = tool.bound;
+ const sourceName = (id: string) => sources.get(id)?.display_name ?? id;
+ // Sources with no (Source, model) pair that could run this tool natively.
+ const offering = new Set(tool.candidates.map((candidate) => candidate.source_id));
+ const withoutNative = hubSources.filter((source) => !offering.has(source.id)).map((source) => source.display_name);
+ // The saved executor as the server would accept it back: a pair still among the
+ // candidates. One that left them (its Source or model went away, or the overlay
+ // stopped offering the tool there) is refused on write, and resolution already
+ // skips it, so it reads and writes as Automatic.
+ const savedExecutor = tool.executor && tool.candidates.some((candidate) => sameExecutor(candidate, tool.executor))
+ ? tool.executor
+ : null;
+ // A stored choice that is no longer verified still shows, so the picker never
+ // silently reads as a different executor than the one saved.
+ const options = savedExecutor && !verified.some((candidate) => sameExecutor(candidate, savedExecutor))
+ ? [...verified, { ...savedExecutor, stale: true as const }]
+ : verified;
+ // With nothing verified there is nothing to pick, but a saved choice still reads as itself.
+ const pickable = verified.length > 0;
+ // Turning a tool on needs an executor the server binds (`bound`): on without
+ // one, every proxied call would fail. A verified pair Automatic cannot bind (its
+ // Source is outside Vibey's order) is picked explicitly, which binds it. Turning
+ // a tool off is always possible.
+ const locked = !tool.enabled && bound === null;
+ return (
+ <section className="model-hub-tool-card overflow-hidden rounded-xl border border-border bg-surface" aria-label={name} data-tool={tool.name}>
+ <header className="model-hub-tool-card-head flex items-center gap-3 border-b border-border">
+ <span className={cn('flex size-9 shrink-0 items-center justify-center rounded-[9px]', ACCENT_TILE.cyan)}><Icon className={cn('size-[17px]', ACCENT_ICON.cyan)} /></span>
+ <span className="flex min-w-0 flex-1 flex-col gap-0.5">
+ <span className="flex min-w-0 flex-wrap items-center gap-2">
+ <h3 className="model-hub-tool-name font-bold text-foreground">{name}</h3>
+ <code className="model-hub-pill model-hub-fill-0a border border-border font-mono font-normal text-muted">{tool.name}</code>
+ </span>
+ <span className="model-hub-tool-description">{t(`settings.models.tools.tool.${tool.name}.description`)}</span>
+ </span>
+ <span className="flex shrink-0 items-center gap-2.5">
+ <span className={cn('model-hub-tool-state font-semibold', tool.enabled ? 'model-hub-ink-mint' : 'text-muted')}>{t(tool.enabled
+ ? 'settings.models.tools.state.on'
+ : !locked
+ ? 'settings.models.tools.state.off'
+ : pickable
+ ? 'settings.models.tools.state.needsExecutor'
+ : probeableTool(tool.name) ? 'settings.models.tools.state.needsCheck' : 'settings.models.tools.state.checkUnavailable')}</span>
+ <ToggleSwitch
+ enabled={tool.enabled}
+ disabled={pending || locked}
+ label={t(tool.enabled ? 'settings.models.tools.toggle.turnOff' : 'settings.models.tools.toggle.turnOn', { name }) as string}
+ onClick={() => onChange(tool.name, { enabled: !tool.enabled, executor: savedExecutor })}
+ />
+ </span>
+ </header>
+ <div className="model-hub-tool-table flex flex-col gap-2">
+ {tool.candidates.length === 0
+ ? <p className="model-hub-tool-note flex items-start gap-2"><Info className="mt-px size-[13px] shrink-0" aria-hidden />{t('settings.models.tools.empty', { toolInline })}</p>
+ : <>
+ <div className="model-hub-tool-table-head hidden font-semibold md:grid" aria-hidden>
+ <span>{t('settings.models.tools.col.source')}</span>
+ <span>{t('settings.models.tools.col.native')}</span>
+ <span>{t('settings.models.tools.col.cost')}</span>
+ <span />
+ </div>
+ {tool.candidates.map((candidate) => {
+ const key = probeKey({ tool: tool.name, candidate });
+ return (
+ <CandidateRow
+ key={key}
+ tool={tool.name}
+ candidate={candidate}
+ source={sources.get(candidate.source_id)}
+ executor={tool.enabled && sameExecutor(candidate, bound)}
+ probe={probeableTool(tool.name)
+ ? { running: probing.has(key), last: lastProbes.get(key), run: onProbe, disabled: probing.size > 0 && !probing.has(key) }
+ : null}
+ />
+ );
+ })}
+ {withoutNative.length > 0 && <p className="model-hub-tool-note flex items-start gap-2"><Info className="mt-px size-[13px] shrink-0" aria-hidden />{t('settings.models.tools.noNative', { sources: formatNameList(withoutNative, i18n.language), toolInline })}</p>}
+ </>}
+ </div>
+ <div className="model-hub-tool-executor flex flex-col gap-2 border-t border-border sm:flex-row sm:items-center sm:gap-3">
+ <span className="shrink-0 font-semibold text-foreground">{t('settings.models.tools.executor.label')}</span>
+ <Select
+ wrapperClassName="sm:w-[330px] shrink-0"
+ className="h-8 text-[12px]"
+ aria-label={t('settings.models.tools.executor.pick', { name }) as string}
+ disabled={pending || !pickable}
+ value={executorValue(savedExecutor)}
+ onChange={(event) => {
+ const picked = options.find((option) => executorValue(option) === event.target.value);
+ onChange(tool.name, {
+ enabled: tool.enabled,
+ executor: picked ? { source_id: picked.source_id, model_id: picked.model_id } : null,
+ });
+ }}
+ >
+ {!pickable && savedExecutor === null
+ ? <option value={AUTOMATIC}>{t('settings.models.tools.executor.unavailable')}</option>
+ : <>
+ {pickable && (
+ <option value={AUTOMATIC}>
+ {/* Automatic names what it resolves to now, when the saved choice is Automatic. */}
+ {savedExecutor === null && bound
+ ? t('settings.models.tools.executor.automaticBound', { source: sourceName(bound.source_id), model: bound.model_id })
+ : t('settings.models.tools.executor.automatic')}
+ </option>
+ )}
+ {options.map((option) => (
+ <option key={executorValue(option)} value={executorValue(option)}>
+ {'stale' in option
+ ? t('settings.models.tools.executor.notVerified', { source: sourceName(option.source_id), model: option.model_id })
+ : t('settings.models.tools.executor.option', { source: sourceName(option.source_id), model: option.model_id })}
+ </option>
+ ))}
+ </>}
+ </Select>
+ <span className="model-hub-tool-note">
+ {/* A routing claim holds only while the tool is on: resolution leaves an
+ off tool out entirely, so its executor is just a saved preference. */}
+ {!tool.enabled
+ ? t('settings.models.tools.executor.note.off')
+ : bound
+ ? t('settings.models.tools.executor.note.bound', { source: sourceName(bound.source_id) })
+ : t('settings.models.tools.executor.note.unbound')}
+ </span>
+ </div>
+ </section>
+ );
+};
+
+export const ToolsTab: React.FC<{
+ read: RegionRead<HostedToolsStatus>;
+ /** The Sources read, for names and glyphs; candidates carry only ids. */
+ sources: readonly Source[];
+ pending: ReadonlySet<HostedToolName>;
+ /** Probe keys (`probeKey`) running now. */
+ probing: ReadonlySet<string>;
+ onChange: (tool: HostedToolName, body: HostedToolPut) => void;
+ onProbe: RunProbe;
+ onRetry: () => void;
+}> = ({ read, sources, pending, probing, onChange, onProbe, onRetry }) => {
+ const { t } = useTranslation();
+ const estimateLabel = useEstimateLabel();
+ // A row's last answer that did not become evidence (inconclusive, transient, a
+ // failed request) shows where it was asked, until that row is checked again.
+ const [lastProbes, setLastProbes] = React.useState<ReadonlyMap<string, HostedToolProbeResult | null>>(() => new Map());
+ const [checking, setChecking] = React.useState<readonly ProbeTarget[] | null>(null);
+ const runProbe = React.useCallback<RunProbe>(async (target) => {
+ const result = await onProbe(target);
+ setLastProbes((previous) => new Map(previous).set(probeKey(target), result));
+ return result;
+ }, [onProbe]);
+ const status = foldRegionRead<HostedToolsStatus, HostedToolsStatus | null>(read, {
+ loading: () => null,
+ ready: (data) => data,
+ unread: () => null,
+ degraded: (staleData) => staleData,
+ });
+ const byId = React.useMemo(() => new Map(sources.map((source) => [source.id, source])), [sources]);
+ const hubSources = React.useMemo(() => sources.filter((source) => source.supply_channel === 'hub'), [sources]);
+ const reverify = status?.reverify;
+ const toCheck = status ? pendingChecks(status) : [];
+ // 「全部已检测」 holds only where there is something a check could run on.
+ const checkable = status?.tools.some((tool) => probeableTool(tool.name) && tool.candidates.length > 0) ?? false;
+ const toCheckTotal = probeTotal(toCheck);
+ const toCheckCost = toCheckTotal === null
+ ? t('settings.models.tools.header.totalUnknown')
+ : toCheckTotal.basis === 'included'
+ ? t('settings.models.tools.header.totalIncluded')
+ : t('settings.models.tools.header.total', { cost: estimateLabel(toCheckTotal) });
+ return (
+ <section className="model-hub-tools flex flex-col" aria-label={t('settings.models.tools.title') as string}>
+ <div className="flex flex-col gap-2 sm:flex-row sm:items-end sm:justify-between">
+ <div className="flex min-w-0 flex-col gap-1">
+ <h2 className="model-hub-tools-title font-bold text-foreground">{t('settings.models.tools.title')}</h2>
+ <p className="model-hub-tools-subtitle">{t('settings.models.tools.subtitle')}</p>
+ </div>
+ <div className="flex shrink-0 flex-col items-start gap-1.5 sm:items-end">
+ <span className="flex flex-wrap items-center gap-x-3 gap-y-1.5">
+ {checkable && (
+ <span className="model-hub-tools-reverify">
+ {toCheck.length > 0
+ ? t('settings.models.tools.header.summary', { pending: t('settings.models.tools.header.pending', { count: toCheck.length }), cost: toCheckCost })
+ : t('settings.models.tools.header.none')}
+ </span>
+ )}
+ <Button
+ size="sm"
+ variant={toCheck.length > 0 ? 'default' : 'outline'}
+ disabled={!status || toCheck.length === 0 || probing.size > 0}
+ onClick={() => setChecking(toCheck)}
+ >
+ <Radar aria-hidden />{t('settings.models.tools.header.action')}
+ </Button>
+ </span>
+ {reverify && (reverify.engine_upgraded > 0 || reverify.aged > 0) && (
+ <p className="model-hub-tools-reverify flex flex-wrap items-center gap-x-2" role="status">
+ {/* Both counts read as one sentence the locale composes. */}
+ <Trans
+ i18nKey={reverify.engine_upgraded > 0
+ ? reverify.aged > 0 ? 'settings.models.tools.reverify.both' : 'settings.models.tools.reverify.upgradedOnly'
+ : 'settings.models.tools.reverify.agedOnly'}
+ values={{
+ engineUpgraded: t('settings.models.tools.reverify.engineUpgraded', { count: reverify.engine_upgraded }),
+ aged: t('settings.models.tools.reverify.aged', { count: reverify.aged }),
+ }}
+ components={{ upgraded: <span className="model-hub-ink-gold font-semibold" /> }}
+ />
+ </p>
+ )}
+ </div>
+ </div>
+ {regionFailed(read) && (
+ <div className="model-hub-usage-failure flex items-center justify-between gap-3 rounded-xl border border-border bg-background text-destructive-ink">
+ <span>{t('settings.models.toast.refreshFailed')}</span>
+ <button type="button" onClick={onRetry} className="model-hub-action-mint shrink-0 font-semibold">{t('settings.models.upstream.retry')}</button>
+ </div>
+ )}
+ {status === null
+ ? read.kind === 'loading' && <p className="model-hub-usage-pending text-muted">{t('common.loading')}</p>
+ : <>
+ {status.tools.map((tool) => (
+ <ToolCard
+ key={tool.name}
+ tool={tool}
+ sources={byId}
+ hubSources={hubSources}
+ pending={pending.has(tool.name)}
+ probing={probing}
+ lastProbes={lastProbes}
+ onChange={onChange}
+ onProbe={runProbe}
+ />
+ ))}
+ <p className="model-hub-tools-foot">{t('settings.models.tools.footnote')}</p>
+ </>}
+ {checking && <HostedProbeDialog targets={checking} sources={byId} onRun={runProbe} onClose={() => setChecking(null)} />}
+ </section>
+ );
+};
diff --git a/ui/src/components/settings/models/format.test.ts b/ui/src/components/settings/models/format.test.ts
index d55f363fe..a3062c643 100644
--- a/ui/src/components/settings/models/format.test.ts
+++ b/ui/src/components/settings/models/format.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest';
-import { atLeast, cooldownEtaMinutes, formatCost, formatCount, formatDayTime, formatNameList, formatPercent, formatTokensCompact, formatUsd } from './format';
+import { atLeast, cooldownEtaMinutes, formatCost, formatCount, formatDayTime, formatNameList, formatPercent, formatSmallUsd, formatTokensCompact, formatUsd } from './format';
describe('formatCount', () => {
it('groups so a figure can be read against a vendor console', () => {
@@ -119,3 +119,15 @@ describe('formatCost', () => {
expect(atLeast('2.0×', false)).toBe('2.0×');
});
});
+
+describe('formatSmallUsd', () => {
+ it('MH-HOSTED-UI-003: keeps the first significant digits of a per-call price, and never shows a nonzero price as zero', () => {
+ expect(formatSmallUsd(0.5)).toBe('0.50');
+ expect(formatSmallUsd(0.005)).toBe('0.005');
+ expect(formatSmallUsd(0.00005)).toBe('0.00005');
+ // Below a hundredth of a cent: two significant digits, not 0.
+ expect(formatSmallUsd(0.0000123)).toBe('0.000012');
+ expect(formatSmallUsd(0.00000001)).toBe('0.00000001');
+ expect(formatSmallUsd(0)).toBe('0');
+ });
+});
diff --git a/ui/src/components/settings/models/format.ts b/ui/src/components/settings/models/format.ts
index 705760585..377746110 100644
--- a/ui/src/components/settings/models/format.ts
+++ b/ui/src/components/settings/models/format.ts
@@ -15,6 +15,14 @@ export function formatNameList(names: readonly string[], locale: string): string
return new Intl.ListFormat(locale, { style: 'narrow', type: 'conjunction' }).format(names);
}
+/**
+ * Sentences read one after another, joined as the locale joins them: a space
+ * in English, nothing in Chinese. `Intl` owns the joiner, as it does above.
+ */
+export function formatSentences(sentences: readonly string[], locale: string): string {
+ return new Intl.ListFormat(locale, { style: 'narrow', type: 'unit' }).format(sentences);
+}
+
/**
* A counted quantity in the reader's own grouping — 「2,968,500」.
*
@@ -103,6 +111,33 @@ export function formatDayTime(instant: string, locale: string): string {
return new Intl.DateTimeFormat(locale, { month: 'numeric', day: 'numeric', hour: '2-digit', minute: '2-digit' }).format(ms);
}
+/**
+ * A small per-call dollar figure with its first significant digits: $0.005, not
+ * $0.01, since a hosted tool's price is often under a cent. A figure of a dime or
+ * more keeps two decimals; one below a hundredth of a cent keeps two significant
+ * digits ($0.000012), so a nonzero price never reads as $0.
+ */
+export function formatSmallUsd(value: number): string {
+ if (value >= 0.1) return value.toFixed(2);
+ const fixed = value >= 0.001 ? value.toFixed(3)
+ : value === 0 || value >= 0.0001 ? value.toFixed(4)
+ // Below a hundredth of a cent, two significant digits, so no listed price reads as $0.
+ : Number(value.toPrecision(2)).toFixed(20);
+ return fixed.replace(/0+$/, '').replace(/\.$/, '');
+}
+
+/**
+ * The local calendar day as `MM-DD`, the stamp the capability chips carry
+ * ("verified 10-13"). Both locales use the same numeric form, so the chip reads
+ * the same width in either. An unparseable stamp renders verbatim.
+ */
+export function formatMonthDay(instant: string): string {
+ const ms = Date.parse(instant);
+ if (Number.isNaN(ms)) return instant;
+ const date = new Date(ms);
+ return `${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
+}
+
/** Whole minutes until a cooldown retry_at (never negative). */
export function cooldownEtaMinutes(retryAt?: string | null): number {
if (!retryAt) return 0;
diff --git a/ui/src/components/settings/models/hostedTools.test.ts b/ui/src/components/settings/models/hostedTools.test.ts
new file mode 100644
index 000000000..b240da2ee
--- /dev/null
+++ b/ui/src/components/settings/models/hostedTools.test.ts
@@ -0,0 +1,98 @@
+import { describe, expect, it } from 'vitest';
+
+import { evidenceChip, modelCapabilities, pendingChecks, probeTotal, type ProbeTarget } from './hostedTools';
+import type { HostedEvidence, HostedToolCandidate } from './types';
+
+const evidence = (overrides: Partial<HostedEvidence>): HostedEvidence => ({
+ status: 'unknown',
+ stale: null,
+ basis: null,
+ observed_at: null,
+ detail: null,
+ changes_at: null,
+ ...overrides,
+});
+
+const AT = '2026-10-13T10:20:00Z';
+
+const candidate = (sourceId: string, modelId: string, call: HostedEvidence): HostedToolCandidate => ({
+ source_id: sourceId,
+ model_id: modelId,
+ call,
+ replay: null,
+ billing: 'metered',
+ price: null,
+ probe_estimate: null,
+});
+
+describe('hosted-tool evidence projection', () => {
+ // Every evidence shape the status read can carry (hosted-tools-status.schema.json),
+ // and the chip each one owes the user. A wire-stale record reads `unknown` for
+ // routing, so a projection keyed on `status` alone would hide that it was
+ // ever checked, and the engine-upgrade re-check would have no row to point at.
+ const cases: [string, HostedEvidence, ReturnType<typeof evidenceChip>][] = [
+ ['no record', evidence({}), null],
+ ['verified on the current engine', evidence({ status: 'verified', basis: 'probe', observed_at: AT }), { kind: 'native', aged: false, at: AT }],
+ ['verified, older than 30 days', evidence({ status: 'verified', stale: 'age', basis: 'probe', observed_at: AT }), { kind: 'native', aged: true, at: AT }],
+ ['taken on another engine', evidence({ status: 'unknown', stale: 'wire', basis: 'probe', observed_at: AT }), { kind: 'engineUpgraded', aged: false, at: AT }],
+ ['refused by a probe', evidence({ status: 'unsupported', basis: 'probe', observed_at: AT, detail: '400 · unsupported_tool_type' }), { kind: 'unsupported', aged: false, at: AT }],
+ // An old refusal still routes, but it is counted in `reverify.aged`, so its
+ // row has to say which record that count is about.
+ ['refused by a probe older than 30 days', evidence({ status: 'unsupported', stale: 'age', basis: 'probe', observed_at: AT, detail: '400 · unsupported_tool_type' }), { kind: 'unsupported', aged: true, at: AT }],
+ ['refused by a real request', evidence({ status: 'unsupported', basis: 'observed', observed_at: AT, detail: '400 · unsupported_tool_type' }), { kind: 'unsupported', aged: false, at: AT }],
+ ];
+ it('MH-HOSTED-UI-002: gives every evidence shape the chip it owes the user', () => {
+ for (const [name, call, chip] of cases) expect(evidenceChip(call), name).toEqual(chip);
+ });
+
+ it('MH-HOSTED-UI-003: totals a check only from what the server estimates, and never counts unknown as zero', () => {
+ const at = (estimate: HostedToolCandidate['probe_estimate']): ProbeTarget => ({
+ tool: 'web_search',
+ candidate: { ...candidate('src_relay001', 'gpt-6-astra', evidence({})), probe_estimate: estimate },
+ });
+
+ expect(probeTotal([at({ basis: 'list', usd: 0.02 }), at({ basis: 'included' }), at({ basis: 'list', usd: 0.03 })]))
+ .toEqual({ basis: 'list', usd: 0.05 });
+ // One unknown estimate makes the whole set's cost unknown.
+ expect(probeTotal([at({ basis: 'list', usd: 0.02 }), at(null)])).toBeNull();
+ // A check run only on subscriptions adds no charge.
+ expect(probeTotal([at({ basis: 'included' })])).toEqual({ basis: 'included' });
+ });
+
+ it('MH-HOSTED-UI-013: offers to check every pair with no current answer, and never an image', () => {
+ const verified = evidence({ status: 'verified', basis: 'probe', observed_at: AT });
+ const status = {
+ tools: [
+ { name: 'web_search' as const, enabled: false, executor: null, bound: null, candidates: [
+ candidate('src_relay001', 'gpt-6-astra', evidence({})),
+ candidate('src_relay001', 'gpt-6-sol', verified),
+ candidate('src_relay001', 'gpt-6-luna', evidence({ status: 'unknown', stale: 'wire', basis: 'probe', observed_at: AT })),
+ candidate('src_relay001', 'gpt-6-terra', evidence({ status: 'verified', stale: 'age', basis: 'probe', observed_at: AT })),
+ ] },
+ { name: 'image_generation' as const, enabled: false, executor: null, bound: null, candidates: [candidate('src_relay001', 'gpt-6.1-sol', evidence({}))] },
+ ],
+ reverify: { engine_upgraded: 1, aged: 1 },
+ };
+
+ expect(pendingChecks(status).map(({ tool, candidate: c }) => `${tool}:${c.model_id}`))
+ .toEqual(['web_search:gpt-6-astra', 'web_search:gpt-6-luna', 'web_search:gpt-6-terra']);
+ });
+
+ it('MH-HOSTED-UI-006: gives a Source model one capability per tool with evidence, in catalog order', () => {
+ const verified = evidence({ status: 'verified', basis: 'probe', observed_at: AT });
+ const refused = evidence({ status: 'unsupported', basis: 'observed', observed_at: AT, detail: '400 · unsupported_tool_type' });
+ const status = {
+ tools: [
+ { name: 'web_search' as const, enabled: true, executor: null, bound: null, candidates: [candidate('src_relay001', 'gpt-6-astra', verified)] },
+ { name: 'x_search' as const, enabled: true, executor: null, bound: null, candidates: [candidate('src_relay001', 'gpt-6-astra', refused)] },
+ // Unchecked draws nothing: absence is the normal state, not a problem.
+ { name: 'image_generation' as const, enabled: false, executor: null, bound: null, candidates: [candidate('src_relay001', 'gpt-6-astra', evidence({}))] },
+ ],
+ reverify: { engine_upgraded: 0, aged: 0 },
+ };
+
+ expect(modelCapabilities(status, 'src_relay001', 'gpt-6-astra').map(({ tool, chip }) => [tool, chip.kind]))
+ .toEqual([['web_search', 'native'], ['x_search', 'unsupported']]);
+ expect(modelCapabilities(status, 'src_relay001', 'gpt-6-sol')).toEqual([]);
+ });
+});
diff --git a/ui/src/components/settings/models/hostedTools.ts b/ui/src/components/settings/models/hostedTools.ts
new file mode 100644
index 000000000..4011ef8e5
--- /dev/null
+++ b/ui/src/components/settings/models/hostedTools.ts
@@ -0,0 +1,112 @@
+// What the Tools tab and the Source chips say about hosted-tool evidence
+// (`vibey-hosted-tools.md` §6.1–§6.2). Pure projections of the Tools-tab read
+// (`hosted-tools-status.schema.json`): the server has already folded staleness
+// into `status`, so nothing here re-derives routing.
+import type {
+ HostedCostEstimate,
+ HostedEvidence,
+ HostedToolCandidate,
+ HostedToolExecutor,
+ HostedToolName,
+ HostedToolProbeResult,
+ HostedToolsStatus,
+ HostedToolStatus,
+} from './types';
+
+/**
+ * One call-evidence record as a chip.
+ *
+ * - `native`: verified; the tool runs natively.
+ * - `unsupported`: the Source refused the tool, by probe or by a real error.
+ * - `engineUpgraded`: taken on another engine or probe shape. It routes as
+ * unknown, i.e. through the proxy, until the user checks again.
+ *
+ * `aged` marks a probe record older than 30 days, whichever way it went: it
+ * still routes as recorded and only asks for a new check.
+ *
+ * `null` is no record: unchecked, which is the normal state and draws no chip
+ * on a Source (§6.2).
+ */
+export type HostedEvidenceChip = {
+ kind: 'native' | 'unsupported' | 'engineUpgraded';
+ aged: boolean;
+ at: string | null;
+};
+
+export const evidenceChip = (evidence: HostedEvidence): HostedEvidenceChip | null => {
+ // Staleness first: a wire-stale record reads `unknown` but still has a past
+ // the user needs to see, whatever it once said.
+ if (evidence.stale === 'wire') return { kind: 'engineUpgraded', aged: false, at: evidence.observed_at };
+ const aged = evidence.stale === 'age';
+ if (evidence.status === 'verified') return { kind: 'native', aged, at: evidence.observed_at };
+ if (evidence.status === 'unsupported') return { kind: 'unsupported', aged, at: evidence.observed_at };
+ return null;
+};
+
+export const sameExecutor = (left: HostedToolExecutor | null, right: HostedToolExecutor | null): boolean =>
+ left !== null && right !== null && left.source_id === right.source_id && left.model_id === right.model_id;
+
+/** The candidates a user may pick as executor: those verified for the call now. */
+export const verifiedCandidates = (tool: HostedToolStatus): HostedToolCandidate[] =>
+ tool.candidates.filter((candidate) => candidate.call.status === 'verified');
+
+export type ModelCapability = {
+ tool: HostedToolName;
+ evidence: HostedEvidence;
+ chip: HostedEvidenceChip;
+ candidate: HostedToolCandidate;
+ /** The tool is on and a turn would bind an executor (`bound`): a model that
+ * cannot run it natively reaches it through that proxy. */
+ proxied: boolean;
+};
+
+/** A Source model's evidence for each tool, in catalog order, for its detail chips. */
+export const modelCapabilities = (status: HostedToolsStatus, sourceId: string, modelId: string): ModelCapability[] =>
+ status.tools.flatMap((tool) => {
+ const candidate = tool.candidates.find((entry) => entry.source_id === sourceId && entry.model_id === modelId);
+ const chip = candidate ? evidenceChip(candidate.call) : null;
+ return candidate && chip
+ ? [{ tool: tool.name, evidence: candidate.call, chip, candidate, proxied: tool.enabled && tool.bound !== null }]
+ : [];
+ });
+
+/** Tools a user can check. An image probe waits until Vibey parses image results, so the server refuses it. */
+export const probeableTool = (tool: HostedToolName): boolean => tool !== 'image_generation';
+
+export type ProbeTarget = { tool: HostedToolName; candidate: HostedToolCandidate };
+
+export const probeKey = ({ tool, candidate }: ProbeTarget): string => `${tool}:${candidate.source_id}:${candidate.model_id}`;
+
+/**
+ * What the header check offers to run: every checkable pair with no current
+ * answer, i.e. no record, or one an engine upgrade or age made stale.
+ */
+export const pendingChecks = (status: HostedToolsStatus): ProbeTarget[] =>
+ status.tools.flatMap((tool) => (probeableTool(tool.name)
+ ? tool.candidates
+ .filter((candidate) => candidate.call.status === 'unknown' || candidate.call.stale !== null)
+ .map((candidate) => ({ tool: tool.name, candidate }))
+ : []));
+
+/**
+ * The cost of running these probes, as the server estimates each one. Unknown is
+ * never zero: one unknown estimate makes the total unknown. A set run entirely on
+ * subscriptions is included.
+ */
+/** Whether a probe's answer became no evidence: inconclusive, transient, or a request that failed (null). */
+export const probeUnanswered = (result: HostedToolProbeResult | null): boolean =>
+ result === null || result.call.outcome === 'inconclusive' || result.call.outcome === 'transient';
+
+export const probeTotal = (targets: readonly ProbeTarget[]): HostedCostEstimate | null => {
+ let usd = 0;
+ let listed = false;
+ for (const { candidate } of targets) {
+ const estimate = candidate.probe_estimate;
+ if (!estimate) return null;
+ if (estimate.basis === 'list') {
+ usd += estimate.usd;
+ listed = true;
+ }
+ }
+ return listed ? { basis: 'list', usd } : { basis: 'included' };
+};
diff --git a/ui/src/components/settings/models/modelHubSurface.css b/ui/src/components/settings/models/modelHubSurface.css
index 7a41d81da..1dd9e6660 100644
--- a/ui/src/components/settings/models/modelHubSurface.css
+++ b/ui/src/components/settings/models/modelHubSurface.css
@@ -216,6 +216,13 @@
--model-hub-quota-row-gap: 14px;
--model-hub-quota-nested-indent: 12px;
+ /* Tools tab: hosted tools (frames E5IkUQ, XZjhj). Reuses the usage tab's type scale. */
+ --model-hub-tools-gap: 16px;
+ --model-hub-tool-pad-x: 20px;
+ --model-hub-tool-row-pad-x: 14px;
+ --model-hub-tool-row-pad-y: 9px;
+ --model-hub-tool-columns: minmax(0, 1.5fr) minmax(0, 1.3fr) minmax(0, 1fr) auto;
+
/* Backend model catalog dialog. `--model-hub-catalog-row-gap` is read from a
* Tailwind arbitrary value in the dialog's markup, which has no selector of
* its own to declare it on. */
@@ -1523,6 +1530,30 @@
min-height: var(--model-hub-source-table-row-height);
padding-block: var(--model-hub-source-table-padding-y);
}
+/* Capability chips (frame FB4vC): their own column from md, a full-width line
+ under the model id below it. */
+@media (min-width: 768px) {
+ .model-hub-source-table--capabilities {
+ --model-hub-source-table-columns: minmax(0, 0.8fr) minmax(0, 1.7fr) auto;
+ }
+}
+@media (max-width: 767px) {
+ .model-hub-source-table--capabilities .model-hub-source-capabilities {
+ grid-column: 1 / -1;
+ order: 3;
+ }
+}
+.model-hub-capability-detail { font-size: var(--model-hub-usage-cell-size); line-height: 18px; }
+.model-hub-source-capabilities-failure { font-size: var(--model-hub-source-tier-size); }
+.model-hub-capability-explain { color: var(--model-hub-usage-note-ink); }
+.model-hub-capability-facts {
+ grid-template-columns: auto minmax(0, 1fr);
+ padding: 8px 10px;
+ background: var(--model-hub-wash-05);
+ font-size: var(--model-hub-usage-note-size);
+}
+.model-hub-capability-facts dt { color: var(--model-hub-ink-73); }
+.model-hub-capability-facts dd { overflow-wrap: anywhere; }
/* The draft spans the table width, with commands on their own trailing line. */
.model-hub-source-table-draft {
grid-template-columns: minmax(0, 1fr) auto;
@@ -2078,6 +2109,78 @@
font-size: var(--model-hub-usage-cell-size);
}
.model-hub-usage-pending { font-size: var(--model-hub-usage-title-size); }
+
+/* Tools tab. */
+.model-hub-tools { gap: var(--model-hub-tools-gap); }
+.model-hub-tools-title { font-size: 15px; line-height: 21px; }
+.model-hub-tools-subtitle,
+.model-hub-tools-reverify,
+.model-hub-tools-foot {
+ color: var(--model-hub-usage-note-ink);
+ font-size: var(--model-hub-usage-cell-size);
+ line-height: 18px;
+}
+.model-hub-tools-foot { font-size: var(--model-hub-usage-note-size); line-height: 16px; }
+.model-hub-tool-card-head { padding: 14px var(--model-hub-tool-pad-x); }
+.model-hub-tool-name { font-size: 14px; line-height: 20px; }
+.model-hub-tool-description,
+.model-hub-tool-state { font-size: var(--model-hub-usage-cell-size); }
+.model-hub-tool-description { color: var(--model-hub-usage-note-ink); }
+.model-hub-tool-table { padding: 12px var(--model-hub-tool-row-pad-x) 14px; }
+.model-hub-tool-table-head,
+.model-hub-tool-row {
+ grid-template-columns: var(--model-hub-tool-columns);
+ column-gap: var(--model-hub-usage-gutter);
+ padding-inline: var(--model-hub-tool-row-pad-x);
+}
+.model-hub-tool-table-head {
+ color: var(--model-hub-ink-73);
+ font-size: var(--model-hub-usage-label-size);
+ line-height: 15px;
+}
+.model-hub-tool-row {
+ row-gap: 8px;
+ padding-block: var(--model-hub-tool-row-pad-y);
+ font-size: var(--model-hub-usage-cell-size);
+}
+/* Below md the row stacks: identity, then evidence, then cost. */
+@media (max-width: 767px) {
+ .model-hub-tool-row { grid-template-columns: minmax(0, 1fr); }
+}
+.model-hub-tool-cost-note {
+ color: var(--model-hub-usage-note-ink);
+ font-size: var(--model-hub-usage-note-size);
+ line-height: 15px;
+}
+.model-hub-tool-note {
+ color: var(--model-hub-usage-note-ink);
+ font-size: var(--model-hub-usage-note-size);
+ line-height: 16px;
+}
+/* Check dialogs (frame vQPXo). */
+.model-hub-probe-head { padding: 16px 20px 12px; font-size: var(--model-hub-usage-cell-size); }
+.model-hub-probe-body { padding: 14px 20px; font-size: var(--model-hub-usage-cell-size); line-height: 18px; }
+.model-hub-probe-foot { padding: 12px 20px; }
+.model-hub-probe-row { padding: 9px 12px; font-size: var(--model-hub-usage-cell-size); }
+.model-hub-probe-privacy {
+ padding: 9px 12px;
+ background: var(--model-hub-mint-14);
+ color: var(--foreground);
+}
+.model-hub-probe-label {
+ color: var(--model-hub-ink-73);
+ font-size: var(--model-hub-usage-label-size);
+}
+.model-hub-probe-total { padding: 6px 12px 0; }
+.model-hub-probe-reason {
+ padding: 0 12px;
+ color: var(--model-hub-usage-note-ink);
+ font-size: var(--model-hub-usage-note-size);
+}
+.model-hub-tool-executor {
+ padding: 12px var(--model-hub-tool-pad-x);
+ font-size: var(--model-hub-usage-cell-size);
+}
.model-hub-usage-empty {
padding: 26px var(--model-hub-usage-padding-x);
font-size: var(--model-hub-usage-cell-size);
diff --git a/ui/src/components/settings/models/modelsApi.ts b/ui/src/components/settings/models/modelsApi.ts
index 6fbef1603..e26d72eb6 100644
--- a/ui/src/components/settings/models/modelsApi.ts
+++ b/ui/src/components/settings/models/modelsApi.ts
@@ -28,6 +28,11 @@ import type {
ModelCandidateModelsDev,
ModelCandidateSupplier,
ModelsDevMatch,
+ HostedToolExecutor,
+ HostedToolName,
+ HostedToolProbeResult,
+ HostedToolPut,
+ HostedToolsStatus,
NativeProtocol,
OAuthFlow,
ProbeResult,
@@ -168,6 +173,12 @@ export type ModelsApi = {
getQuota(): Promise<QuotaSummary>;
/** The same report, re-read now (the service bounds how often). */
refreshQuota(): Promise<QuotaSummary>;
+ /** The Tools tab read: each hosted tool's toggle, executor and evidence. */
+ getHostedTools(): Promise<HostedToolsStatus>;
+ /** Replace one tool's toggle and executor; answers the whole status again. */
+ putHostedTool(tool: HostedToolName, body: HostedToolPut): Promise<HostedToolsStatus>;
+ /** One user-started call probe on exactly one (Source, model); answers the status it left. */
+ probeHostedTool(tool: HostedToolName, target: HostedToolExecutor): Promise<{ probe: HostedToolProbeResult; hosted_tools: HostedToolsStatus }>;
getRuntimeStatus(): Promise<RuntimeDependency>;
/** Start the contract-owned client installation transaction. */
installRuntime(): Promise<RuntimeDependency>;
@@ -675,6 +686,13 @@ export const modelsApi: ModelsApi = {
call<{ usage: UsageReport }>(`/api/models/usage?window=${window}`).then((r) => r.usage),
getQuota: () => call<{ quota: QuotaSummary }>('/api/models/quota').then((r) => r.quota),
refreshQuota: () => call<{ quota: QuotaSummary }>('/api/models/quota/refresh', jsonInit('POST')).then((r) => r.quota),
+ getHostedTools: () => call<{ hosted_tools: HostedToolsStatus }>('/api/models/hosted-tools').then((r) => r.hosted_tools),
+ putHostedTool: (tool, body) => call<{ hosted_tools: HostedToolsStatus }>(
+ `/api/models/hosted-tools/${encodeURIComponent(tool)}`, jsonInit('PUT', body),
+ ).then((r) => r.hosted_tools),
+ probeHostedTool: (tool, target) => call<{ probe: HostedToolProbeResult; hosted_tools: HostedToolsStatus }>(
+ `/api/models/hosted-tools/${encodeURIComponent(tool)}/probe`, jsonInit('POST', target),
+ ),
getRuntimeStatus: () => call<{ runtime?: RuntimeDependency } & RuntimeDependency>('/api/models/runtime/status').then((r) => (r.runtime ?? r) as RuntimeDependency),
installRuntime: () => call<{ runtime?: RuntimeDependency } & RuntimeDependency>('/api/models/runtime/install', jsonInit('POST')).then((r) => (r.runtime ?? r) as RuntimeDependency),
startRuntime: () => call<{ runtime?: RuntimeDependency } & RuntimeDependency>('/api/models/runtime/start', jsonInit('POST')).then((r) => (r.runtime ?? r) as RuntimeDependency),
diff --git a/ui/src/components/settings/models/types.ts b/ui/src/components/settings/models/types.ts
index 776f459f3..a887fa774 100644
--- a/ui/src/components/settings/models/types.ts
+++ b/ui/src/components/settings/models/types.ts
@@ -112,6 +112,18 @@ export type SuppliedModel = {
/** Persistent retirement tombstone; retired entries stay readable but are not callable. */
retired?: boolean;
discovered_at?: string | null;
+ /** Server-derived, read-only: the reasoning efforts this Source model currently
+ * refuses (capability evidence). Absent when none; never written back. */
+ refused_efforts?: RefusedEffort[];
+};
+
+/** One reasoning effort a Source model refused, as capability evidence records it. */
+export type RefusedEffort = {
+ effort: string;
+ basis: 'probe' | 'observed';
+ observed_at: string;
+ detail: string | null;
+ changes_at: string | null;
};
export type Source = {
@@ -1007,6 +1019,88 @@ export type QuotaSummary = {
value?: QuotaValueTotals;
};
+// ── hosted-tools-status.schema.json ─────────────────────────────────────
+/** The catalog's tools, in catalog order (`vibey-hosted-tools.md` §2). */
+export const HOSTED_TOOL_NAMES = ['web_search', 'x_search', 'image_generation'] as const;
+export type HostedToolName = (typeof HOSTED_TOOL_NAMES)[number];
+
+/** One capability record as routing reads it: `status` already folds in staleness,
+ * so a wire-stale record reads `unknown` here even though it once verified. */
+export type HostedEvidence = {
+ status: 'verified' | 'unsupported' | 'unknown';
+ /** `wire`: taken on another engine or probe shape, so it routes as unknown.
+ * `age`: older than 30 days, so it still routes and only asks for a re-check. */
+ stale: null | 'wire' | 'age';
+ basis: null | 'probe' | 'observed';
+ observed_at: string | null;
+ detail: string | null;
+ /** When the record stops reading as it does now: an observed record's expiry,
+ * or a probe record's 30-day re-verify mark; null when nothing is scheduled. */
+ changes_at: string | null;
+};
+
+/** The overlay's list price for one hosted tool on a provider (`usd_per_1k` per `unit`). */
+export type HostedToolPriceUnit = 'call' | 'search' | 'post' | 'profile';
+export type HostedToolListPrice = {
+ unit: HostedToolPriceUnit;
+ usd_per_1k: number;
+ extra: { unit: HostedToolPriceUnit; usd_per_1k: number }[];
+ as_of: string;
+ url: string;
+};
+
+/** A cost the server states: at list price (`usd`), or included in a subscription (no `usd`). */
+export type HostedCostEstimate = { basis: 'list'; usd: number } | { basis: 'included' };
+
+export type HostedToolExecutor = { source_id: string; model_id: string };
+
+/** A (Source, model) the overlay offers the tool on, with an eligible credential
+ * and an untranslated path; Vibey's Source order first. */
+export type HostedToolCandidate = HostedToolExecutor & {
+ call: HostedEvidence;
+ /** Null for image generation, which is never replayed. */
+ replay: HostedEvidence | null;
+ billing: 'monthly' | 'metered';
+ /** Null when no list price is known, never zero (image generation has none). */
+ price: HostedToolListPrice | null;
+ /** One call probe's cost; null when unknown, which is never added as zero. */
+ probe_estimate: HostedCostEstimate | null;
+};
+
+export type HostedToolStatus = {
+ name: HostedToolName;
+ enabled: boolean;
+ /** The user's choice, or null for the first verified candidate. */
+ executor: HostedToolExecutor | null;
+ /** The executor a turn would bind now, by hop resolution's own rule; null when none is verified. */
+ bound: HostedToolExecutor | null;
+ candidates: HostedToolCandidate[];
+};
+
+export type HostedToolsStatus = {
+ tools: HostedToolStatus[];
+ reverify: { engine_upgraded: number; aged: number };
+};
+
+/** PUT /api/models/hosted-tools/<tool>: the whole setting, applied from the next turn. */
+export type HostedToolPut = { enabled: boolean; executor: HostedToolExecutor | null };
+
+/** One aspect of a probe: only verified and unsupported become evidence. */
+export type HostedProbeAspect = {
+ outcome: 'verified' | 'unsupported' | 'inconclusive' | 'transient';
+ /** The Source test's detail key, for a request that failed before completing. */
+ error: string | null;
+};
+
+/** POST /api/models/hosted-tools/<tool>/probe (`hosted-tool-probe-result.schema.json`). */
+export type HostedToolProbeResult = {
+ tool: HostedToolName;
+ source_id: string;
+ model_id: string;
+ call: HostedProbeAspect;
+ replay: HostedProbeAspect | null;
+};
+
// ── API envelope + request shapes (api.md) ──────────────────────────────
export type ApiOk<T> = { ok: true; contract_version: typeof CONTRACT_VERSION } & T;
export type ApiErr = {
diff --git a/ui/src/components/settings/models/useEstimateLabel.ts b/ui/src/components/settings/models/useEstimateLabel.ts
new file mode 100644
index 000000000..66146a9bf
--- /dev/null
+++ b/ui/src/components/settings/models/useEstimateLabel.ts
@@ -0,0 +1,15 @@
+import { useTranslation } from 'react-i18next';
+
+import { formatSmallUsd } from './format';
+import type { HostedCostEstimate } from './types';
+
+/** 「约 $0.02」, 「订阅内含」, or nothing when the estimate is unknown. */
+export const useEstimateLabel = () => {
+ const { t } = useTranslation();
+ return (estimate: HostedCostEstimate | null | undefined): string | null => {
+ if (!estimate) return null;
+ return estimate.basis === 'included'
+ ? t('settings.models.tools.probe.included') as string
+ : t('settings.models.tools.probe.about', { usd: formatSmallUsd(estimate.usd) }) as string;
+ };
+};
diff --git a/ui/src/components/settings/models/useHostedTools.test.tsx b/ui/src/components/settings/models/useHostedTools.test.tsx
new file mode 100644
index 000000000..3fa13a762
--- /dev/null
+++ b/ui/src/components/settings/models/useHostedTools.test.tsx
@@ -0,0 +1,272 @@
+// @vitest-environment jsdom
+// How the hosted-tools report is ordered against its writes. Each write answers
+// the whole status, so what is on screen must be the newest state the server
+// committed, whatever order the requests happen to return in.
+import * as React from 'react';
+import { act, cleanup, renderHook, waitFor } from '@testing-library/react';
+import { I18nextProvider } from 'react-i18next';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { ToastProvider } from '@/context/ToastProvider';
+import i18n from '@/i18n';
+import { modelsApi } from './modelsApi';
+import { foldRegionRead, type RegionRead } from './regionRead';
+import type { HostedToolsStatus } from './types';
+import { useHostedTools } from './useHostedTools';
+
+const status = (enabled: boolean): HostedToolsStatus => ({
+ tools: [{ name: 'web_search', enabled, executor: null, bound: null, candidates: [] }],
+ reverify: { engine_upgraded: 0, aged: 0 },
+});
+
+const deferred = <T,>() => {
+ let resolve!: (value: T) => void;
+ let reject!: (error: unknown) => void;
+ const promise = new Promise<T>((done, fail) => { resolve = done; reject = fail; });
+ return { promise, resolve, reject };
+};
+
+const shown = (read: RegionRead<HostedToolsStatus>) => foldRegionRead<HostedToolsStatus, boolean | null>(read, {
+ loading: () => null,
+ ready: (data) => data.tools[0].enabled,
+ unread: () => null,
+ degraded: (data) => data.tools[0].enabled,
+});
+
+const wrapper: React.FC<{ children: React.ReactNode }> = ({ children }) => (
+ <ToastProvider><I18nextProvider i18n={i18n}>{children}</I18nextProvider></ToastProvider>
+);
+
+afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+});
+
+describe('useHostedTools ordering', () => {
+ it('MH-HOSTED-UI-007: a read asked for during a write waits, so it cannot paint the pre-write state over the write', async () => {
+ const get = vi.spyOn(modelsApi, 'getHostedTools').mockResolvedValue(status(false));
+ const put = deferred<HostedToolsStatus>();
+ vi.spyOn(modelsApi, 'putHostedTool').mockReturnValue(put.promise);
+ const { result } = renderHook(() => useHostedTools(true), { wrapper });
+ await waitFor(() => expect(shown(result.current.read)).toBe(false));
+
+ let saving!: Promise<void>;
+ act(() => { saving = result.current.save('web_search', { enabled: true, executor: null }); });
+ // The tab is left and reopened while the PUT is still out.
+ await act(async () => { await result.current.refresh(); });
+ expect(get).toHaveBeenCalledTimes(1);
+
+ get.mockResolvedValue(status(true));
+ await act(async () => { put.resolve(status(true)); await saving; });
+ expect(shown(result.current.read)).toBe(true);
+ // The held read runs once the write has settled, and agrees with it.
+ await waitFor(() => expect(get).toHaveBeenCalledTimes(2));
+ expect(shown(result.current.read)).toBe(true);
+ });
+
+ it('MH-HOSTED-UI-007: runs writes one at a time, so each answer lands in the order the server committed them', async () => {
+ vi.spyOn(modelsApi, 'getHostedTools').mockResolvedValue(status(false));
+ const first = deferred<HostedToolsStatus>();
+ const second = deferred<HostedToolsStatus>();
+ const put = vi.spyOn(modelsApi, 'putHostedTool').mockReturnValueOnce(first.promise).mockReturnValueOnce(second.promise);
+ const { result } = renderHook(() => useHostedTools(true), { wrapper });
+ await waitFor(() => expect(shown(result.current.read)).toBe(false));
+
+ let writes!: Promise<void>[];
+ act(() => {
+ writes = [
+ result.current.save('web_search', { enabled: true, executor: null }),
+ result.current.save('x_search', { enabled: true, executor: null }),
+ ];
+ });
+ // The second PUT has not left: had both, the server could commit them in
+ // either order and the client would have no way to tell which answer is newer.
+ await waitFor(() => expect(put).toHaveBeenCalledTimes(1));
+ await act(async () => { first.resolve(status(true)); await writes[0]; });
+ await waitFor(() => expect(put).toHaveBeenCalledTimes(2));
+ await act(async () => { second.resolve(status(false)); await writes[1]; });
+ // The screen holds the answer to the last write the server committed.
+ expect(shown(result.current.read)).toBe(false);
+ });
+
+ it('MH-HOSTED-UI-007: drops a read that was already out when a write started', async () => {
+ const first = deferred<HostedToolsStatus>();
+ vi.spyOn(modelsApi, 'getHostedTools').mockReturnValueOnce(first.promise);
+ vi.spyOn(modelsApi, 'putHostedTool').mockResolvedValue(status(true));
+ const { result } = renderHook(() => useHostedTools(true), { wrapper });
+
+ await act(async () => { await result.current.save('web_search', { enabled: true, executor: null }); });
+ expect(shown(result.current.read)).toBe(true);
+ // The read cannot tell whether it saw the write, so its answer never lands.
+ await act(async () => { first.resolve(status(false)); await first.promise; });
+ expect(shown(result.current.read)).toBe(true);
+ });
+
+ it('MH-HOSTED-UI-007: re-reads after the newest write fails, because a lost answer may have committed', async () => {
+ const get = vi.spyOn(modelsApi, 'getHostedTools').mockResolvedValue(status(false));
+ vi.spyOn(modelsApi, 'putHostedTool').mockRejectedValue(new Error('offline'));
+ const { result } = renderHook(() => useHostedTools(true), { wrapper });
+ await waitFor(() => expect(get).toHaveBeenCalledTimes(1));
+
+ get.mockResolvedValue(status(true));
+ await act(async () => { await result.current.save('web_search', { enabled: true, executor: null }); });
+ await waitFor(() => expect(get).toHaveBeenCalledTimes(2));
+ expect(shown(result.current.read)).toBe(true);
+ });
+
+ it('MH-HOSTED-UI-007: re-reads when the open Source changes, since an edit can drop its evidence', async () => {
+ const get = vi.spyOn(modelsApi, 'getHostedTools').mockResolvedValue(status(false));
+ const { rerender } = renderHook(({ revision }) => useHostedTools(true, revision), {
+ wrapper,
+ initialProps: { revision: 'source-a' },
+ });
+ await waitFor(() => expect(get).toHaveBeenCalledTimes(1));
+ rerender({ revision: 'source-a-with-a-new-key' });
+ await waitFor(() => expect(get).toHaveBeenCalledTimes(2));
+ });
+
+ it('MH-HOSTED-UI-007: keeps the status a probe answered with when the read after it fails', async () => {
+ // Before: unchecked (shown here as off). The probe's answer: the tool's state after it.
+ vi.spyOn(modelsApi, 'getHostedTools')
+ .mockResolvedValueOnce(status(false))
+ .mockRejectedValueOnce(new Error('offline'));
+ vi.spyOn(modelsApi, 'probeHostedTool').mockResolvedValue({
+ probe: { tool: 'web_search', source_id: 'src_relay001', model_id: 'gpt-6-astra', call: { outcome: 'verified', error: null }, replay: null },
+ hosted_tools: status(true),
+ });
+ const { result } = renderHook(() => useHostedTools(true), { wrapper });
+ await waitFor(() => expect(shown(result.current.read)).toBe(false));
+
+ const candidate = {
+ source_id: 'src_relay001', model_id: 'gpt-6-astra', billing: 'metered' as const, price: null, probe_estimate: null,
+ call: { status: 'unknown' as const, stale: null, basis: null, observed_at: null, detail: null, changes_at: null },
+ replay: null,
+ };
+ await act(async () => { await result.current.probe({ tool: 'web_search', candidate }); });
+ // The read that follows failed; what the probe answered still stands.
+ await waitFor(() => expect(shown(result.current.read)).toBe(true));
+ });
+
+ it('MH-HOSTED-UI-013: reads the record before calling a probe unanswered when its answer was lost', async () => {
+ const before = { status: 'unknown' as const, stale: null, basis: null, observed_at: null, detail: null, changes_at: null };
+ const candidate = {
+ source_id: 'src_relay001', model_id: 'gpt-6-astra', billing: 'metered' as const, price: null, probe_estimate: null, call: before, replay: null,
+ };
+ const recorded: HostedToolsStatus = {
+ tools: [{
+ name: 'web_search', enabled: false, executor: null, bound: null,
+ candidates: [{ ...candidate, call: { ...before, status: 'verified', basis: 'probe', observed_at: '2026-10-14T07:00:00Z' } }],
+ }],
+ reverify: { engine_upgraded: 0, aged: 0 },
+ };
+ vi.spyOn(modelsApi, 'getHostedTools').mockResolvedValueOnce(status(false)).mockResolvedValue(recorded);
+ // The probe ran and recorded its evidence, but its answer never arrived.
+ vi.spyOn(modelsApi, 'probeHostedTool').mockRejectedValue(new Error('connection reset'));
+ const { result } = renderHook(() => useHostedTools(true), { wrapper });
+ await waitFor(() => expect(shown(result.current.read)).toBe(false));
+
+ let outcome: Awaited<ReturnType<typeof result.current.probe>> = null;
+ await act(async () => { outcome = await result.current.probe({ tool: 'web_search', candidate }); });
+ // Verified, not "no answer", so nothing invites a second paid request.
+ expect(outcome).toMatchObject({ call: { outcome: 'verified' } });
+ });
+
+ it('MH-HOSTED-UI-007: lands the status read for a lost probe answer, even when the read after it fails', async () => {
+ const before = { status: 'unknown' as const, stale: null, basis: null, observed_at: null, detail: null, changes_at: null };
+ const candidate = {
+ source_id: 'src_relay001', model_id: 'gpt-6-astra', billing: 'metered' as const, price: null, probe_estimate: null, call: before, replay: null,
+ };
+ const recorded: HostedToolsStatus = {
+ tools: [{
+ name: 'web_search', enabled: true, executor: null, bound: null,
+ candidates: [{ ...candidate, call: { ...before, status: 'verified', basis: 'probe', observed_at: '2026-10-14T07:00:00Z' } }],
+ }],
+ reverify: { engine_upgraded: 0, aged: 0 },
+ };
+ vi.spyOn(modelsApi, 'getHostedTools')
+ .mockResolvedValueOnce(status(false))
+ .mockResolvedValueOnce(recorded)
+ .mockRejectedValue(new Error('offline'));
+ vi.spyOn(modelsApi, 'probeHostedTool').mockRejectedValue(new Error('connection reset'));
+ const { result } = renderHook(() => useHostedTools(true), { wrapper });
+ await waitFor(() => expect(shown(result.current.read)).toBe(false));
+
+ await act(async () => { await result.current.probe({ tool: 'web_search', candidate }); });
+ // The recovered status shows; the failed read after it only marks it degraded.
+ await waitFor(() => expect(shown(result.current.read)).toBe(true));
+ });
+
+ it('MH-HOSTED-UI-007: shows no status of the previous Source identity while the new identity\'s read fails', async () => {
+ vi.spyOn(modelsApi, 'getHostedTools').mockResolvedValueOnce(status(true)).mockRejectedValue(new Error('offline'));
+ const { result, rerender } = renderHook(({ revision }) => useHostedTools(true, revision), {
+ wrapper,
+ initialProps: { revision: 'identity-a' },
+ });
+ await waitFor(() => expect(shown(result.current.read)).toBe(true));
+
+ // The key was replaced: the server dropped the old identity's evidence.
+ rerender({ revision: 'identity-b' });
+ await waitFor(() => expect(result.current.read.kind).not.toBe('loading'));
+ expect(shown(result.current.read)).toBeNull();
+ });
+
+ it('MH-HOSTED-UI-007: keeps a tool pending until the read reconciling its lost write lands', async () => {
+ const reconcile = deferred<HostedToolsStatus>();
+ vi.spyOn(modelsApi, 'getHostedTools').mockResolvedValueOnce(status(false)).mockReturnValueOnce(reconcile.promise);
+ vi.spyOn(modelsApi, 'putHostedTool').mockRejectedValue(new Error('connection reset'));
+ const { result } = renderHook(() => useHostedTools(true), { wrapper });
+ await waitFor(() => expect(shown(result.current.read)).toBe(false));
+
+ let saving!: Promise<void>;
+ act(() => { saving = result.current.save('web_search', { enabled: true, executor: null }); });
+ // The answer was lost and the write may have committed: still pending while the read is out.
+ await waitFor(() => expect(modelsApi.getHostedTools).toHaveBeenCalledTimes(2));
+ expect(result.current.pending.has('web_search')).toBe(true);
+
+ await act(async () => { reconcile.resolve(status(true)); await saving; });
+ expect(result.current.pending.has('web_search')).toBe(false);
+ expect(shown(result.current.read)).toBe(true);
+ });
+
+ it('MH-HOSTED-UI-007: drops a write answer asked under another Source identity', async () => {
+ const put = deferred<HostedToolsStatus>();
+ vi.spyOn(modelsApi, 'getHostedTools').mockResolvedValueOnce(status(false)).mockRejectedValue(new Error('offline'));
+ vi.spyOn(modelsApi, 'putHostedTool').mockReturnValue(put.promise);
+ const { result, rerender } = renderHook(({ revision }) => useHostedTools(true, revision), {
+ wrapper,
+ initialProps: { revision: 'identity-a' },
+ });
+ await waitFor(() => expect(shown(result.current.read)).toBe(false));
+
+ let saving!: Promise<void>;
+ act(() => { saving = result.current.save('web_search', { enabled: true, executor: null }); });
+ // The key is replaced while the write is out.
+ rerender({ revision: 'identity-b' });
+ await act(async () => { put.resolve(status(true)); await saving; });
+ // That answer described the old identity; the new one's read failed, so nothing shows.
+ expect(shown(result.current.read)).toBeNull();
+ });
+
+ it('MH-HOSTED-UI-013: reads a verdict the status does not carry as not verified, with why', async () => {
+ const unknown = { status: 'unknown' as const, stale: null, basis: null, observed_at: null, detail: null, changes_at: null };
+ const candidate = {
+ source_id: 'src_relay001', model_id: 'gpt-6-astra', billing: 'metered' as const, price: null, probe_estimate: null, call: unknown, replay: null,
+ };
+ const unrecorded: HostedToolsStatus = {
+ tools: [{ name: 'web_search', enabled: false, executor: null, bound: null, candidates: [candidate] }],
+ reverify: { engine_upgraded: 0, aged: 0 },
+ };
+ vi.spyOn(modelsApi, 'getHostedTools').mockResolvedValue(unrecorded);
+ // The probe verified the tool, but the server could not write the record.
+ vi.spyOn(modelsApi, 'probeHostedTool').mockResolvedValue({
+ probe: { tool: 'web_search', source_id: 'src_relay001', model_id: 'gpt-6-astra', call: { outcome: 'verified', error: null }, replay: null },
+ hosted_tools: unrecorded,
+ });
+ const { result } = renderHook(() => useHostedTools(true), { wrapper });
+ await waitFor(() => expect(result.current.read.kind).toBe('ready'));
+
+ let outcome: Awaited<ReturnType<typeof result.current.probe>> = null;
+ await act(async () => { outcome = await result.current.probe({ tool: 'web_search', candidate }); });
+ expect(outcome).toMatchObject({ call: { outcome: 'transient', error: 'settings.models.tools.probe.notRecorded' } });
+ });
+});
diff --git a/ui/src/components/settings/models/useHostedTools.ts b/ui/src/components/settings/models/useHostedTools.ts
new file mode 100644
index 000000000..3b52f3525
--- /dev/null
+++ b/ui/src/components/settings/models/useHostedTools.ts
@@ -0,0 +1,224 @@
+import * as React from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useToast } from '@/context/ToastContext';
+import { modelsApi } from './modelsApi';
+import { beginRegionRead, loadingRegion, readRegion, readyRegion, settleRegionRead, type RegionRead } from './regionRead';
+import { probeKey, sameExecutor, type ProbeTarget } from './hostedTools';
+import type { HostedToolName, HostedToolProbeResult, HostedToolPut, HostedToolsStatus } from './types';
+
+/**
+ * The hosted-tools read, shared by the Tools tab and the Source chips.
+ *
+ * Read lazily, while either surface is open, like the other report tabs, and
+ * again whenever `revision` changes: `revision` is the open Source's identity
+ * (as `retry.source_identity` defines it: endpoint, credential, verification),
+ * a change of which drops its evidence on the server, so the old status is
+ * dropped here too before the new read.
+ *
+ * Every write answers the whole status, so writes run one at a time: each PUT
+ * starts after the previous one settled, and each answer is then the newest
+ * state the server committed. A read never overlaps a write: one asked for
+ * while writes are queued waits for them to drain, and one already out when a
+ * write is queued is dropped, because it cannot tell whether it saw that write.
+ */
+export function useHostedTools(active: boolean, revision: string | null = null) {
+ const { t } = useTranslation();
+ const { showToast } = useToast();
+ const alive = React.useRef(true);
+ React.useEffect(() => {
+ alive.current = true;
+ return () => { alive.current = false; };
+ }, []);
+ const [read, setRead] = React.useState<RegionRead<HostedToolsStatus>>(loadingRegion);
+ const [pending, setPending] = React.useState<ReadonlySet<HostedToolName>>(() => new Set());
+ const [probing, setProbing] = React.useState<ReadonlySet<string>>(() => new Set());
+ const order = React.useRef({ reads: 0, writes: 0, queued: 0, rereadAfterWrites: false });
+ const writeQueue = React.useRef<Promise<void>>(Promise.resolve());
+
+ /** Read the status. `forget` drops what is shown first: it belonged to another Source identity. */
+ const refresh = React.useCallback(async ({ forget = false }: { forget?: boolean } = {}) => {
+ const clock = order.current;
+ if (forget) setRead(loadingRegion);
+ if (clock.queued > 0) {
+ clock.rereadAfterWrites = true;
+ return;
+ }
+ const readId = ++clock.reads;
+ const writesAtStart = clock.writes;
+ if (!forget) setRead(beginRegionRead);
+ const incoming = await readRegion(() => modelsApi.getHostedTools());
+ if (!alive.current || readId !== clock.reads || writesAtStart !== clock.writes) return;
+ setRead((previous) => settleRegionRead(previous, incoming));
+ }, []);
+
+ // `revision` is the open Source's identity. Evidence follows it, so a new one
+ // never shows the old one's records, even if its own read fails.
+ const shownRevision = React.useRef(revision);
+ React.useEffect(() => {
+ if (!active) return;
+ const forget = shownRevision.current !== revision;
+ shownRevision.current = revision;
+ void refresh({ forget });
+ }, [active, revision, refresh]);
+
+ // Tools whose write ended without an answer: they stay pending until the read
+ // that reconciles them lands, so no control writes a body built on the status
+ // that write may already have changed.
+ const unsettled = React.useRef<Set<HostedToolName>>(new Set());
+ const release = React.useCallback((tools: Iterable<HostedToolName>) => {
+ const done = [...tools];
+ if (!alive.current || done.length === 0) return;
+ setPending((previous) => {
+ const next = new Set(previous);
+ for (const tool of done) next.delete(tool);
+ return next;
+ });
+ }, []);
+
+ const save = React.useCallback(async (tool: HostedToolName, body: HostedToolPut) => {
+ const clock = order.current;
+ clock.writes += 1;
+ clock.queued += 1;
+ // An answer is for the Source identity it was asked under (see `shownRevision`).
+ const revisionAtStart = shownRevision.current;
+ setPending((previous) => new Set(previous).add(tool));
+ const write = writeQueue.current.then(async () => {
+ try {
+ const status = await modelsApi.putHostedTool(tool, body);
+ if (!alive.current) return;
+ if (shownRevision.current === revisionAtStart) setRead(readyRegion(status));
+ else clock.rereadAfterWrites = true;
+ } catch {
+ // A refused write changed nothing, and a lost answer may have committed;
+ // either way the tab converges on what the server now holds.
+ clock.rereadAfterWrites = true;
+ unsettled.current.add(tool);
+ if (alive.current) {
+ showToast(t('settings.models.tools.saveFailed', { toolInline: t(`settings.models.tools.tool.${tool}.inline`) }) as string, 'error');
+ }
+ }
+ });
+ writeQueue.current = write;
+ await write;
+ clock.queued -= 1;
+ if (!alive.current) return;
+ if (!unsettled.current.has(tool)) release([tool]);
+ if (clock.queued === 0 && clock.rereadAfterWrites) {
+ clock.rereadAfterWrites = false;
+ const reconciling = [...unsettled.current];
+ unsettled.current.clear();
+ await refresh();
+ release(reconciling);
+ }
+ }, [refresh, release, showToast, t]);
+
+ /**
+ * Run one call probe: a real, cost-bearing request the user asked for. Its
+ * answer carries the status it left, which lands at once unless a write went
+ * out while it ran (that write's answer is newer); an ordinary read then
+ * reconciles, and if that read fails the probe's status still stands.
+ * Null when the request itself failed.
+ */
+ const probe = React.useCallback(async (target: ProbeTarget): Promise<HostedToolProbeResult | null> => {
+ const key = probeKey(target);
+ const clock = order.current;
+ const writesAtStart = clock.writes;
+ const recordBefore = target.candidate.call.observed_at;
+ const revisionAtStart = shownRevision.current;
+ setProbing((previous) => new Set(previous).add(key));
+ try {
+ const { probe: answered, hosted_tools: status } = await modelsApi.probeHostedTool(target.tool, {
+ source_id: target.candidate.source_id,
+ model_id: target.candidate.model_id,
+ });
+ const result = recordedOutcome(answered, status, target, recordBefore);
+ if (alive.current && clock.writes === writesAtStart && clock.queued === 0 && shownRevision.current === revisionAtStart) {
+ // Newer than any read still out, which must not overwrite it.
+ clock.reads += 1;
+ setRead(readyRegion(status));
+ }
+ return result;
+ } catch {
+ // The request may have run and recorded its evidence though its answer was
+ // lost: read the record before calling it unanswered, and keep the check
+ // running until then, so no second paid request starts meanwhile. The
+ // status read for that lands as a probe's answer would.
+ const recovered = await lostProbeOutcome(target, recordBefore);
+ if (recovered && alive.current && clock.writes === writesAtStart && clock.queued === 0 && shownRevision.current === revisionAtStart) {
+ clock.reads += 1;
+ setRead(readyRegion(recovered.status));
+ }
+ return recovered?.result ?? null;
+ } finally {
+ if (alive.current) {
+ setProbing((previous) => {
+ const next = new Set(previous);
+ next.delete(key);
+ return next;
+ });
+ void refresh();
+ }
+ }
+ }, [refresh]);
+
+ return { read, pending, probing, refresh, save, probe };
+}
+
+/**
+ * A probe's outcome as far as it was recorded. Only a verified or unsupported
+ * record routes, so an answer the status does not carry as a new probe record
+ * for the pair (the record could not be written, or the Source's identity
+ * changed while it ran) reads as not verified, with that reason, rather than as
+ * a verdict routing never sees.
+ */
+function recordedOutcome(
+ result: HostedToolProbeResult,
+ status: HostedToolsStatus,
+ target: ProbeTarget,
+ recordBefore: string | null,
+): HostedToolProbeResult {
+ const { outcome } = result.call;
+ if (outcome !== 'verified' && outcome !== 'unsupported') return result;
+ const call = status.tools
+ .find((tool) => tool.name === target.tool)?.candidates
+ .find((candidate) => sameExecutor(candidate, target.candidate))?.call;
+ if (call && call.basis === 'probe' && call.observed_at !== recordBefore && call.status === outcome) return result;
+ return { ...result, call: { outcome: 'transient', error: PROBE_NOT_RECORDED } };
+}
+
+/** The reason a probe's verdict did not become a record (a UI key, read as the server's error keys are). */
+const PROBE_NOT_RECORDED = 'settings.models.tools.probe.notRecorded';
+
+/**
+ * What a probe whose answer was lost left behind: a new probe record for its
+ * pair (one the read did not have before it) is its outcome; anything else is
+ * no answer (null).
+ */
+async function lostProbeOutcome(
+ target: ProbeTarget,
+ recordBefore: string | null,
+): Promise<{ result: HostedToolProbeResult | null; status: HostedToolsStatus } | null> {
+ try {
+ const status = await modelsApi.getHostedTools();
+ const call = status.tools
+ .find((tool) => tool.name === target.tool)?.candidates
+ .find((candidate) => sameExecutor(candidate, target.candidate))?.call;
+ if (!call || call.basis !== 'probe' || call.observed_at === recordBefore || call.status === 'unknown') {
+ return { status, result: null };
+ }
+ return {
+ status,
+ result: {
+ tool: target.tool,
+ source_id: target.candidate.source_id,
+ model_id: target.candidate.model_id,
+ call: { outcome: call.status, error: null },
+ replay: null,
+ },
+ };
+ } catch {
+ // Unread: still no answer.
+ return null;
+ }
+}
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 5327c89e9..5ccc6d921 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -973,6 +973,7 @@
},
"tab": {
"hub": "Sources & gateway",
+ "tools": "Tools",
"quota": "Subscription quota",
"usage": "Usage",
"logs": "Logs"
@@ -2344,6 +2345,207 @@
"refreshed": "Updated",
"unresolved": "Still not working",
"failed": "Couldn't do that, please retry"
+ },
+ "tools": {
+ "title": "Hosted tools",
+ "subtitle": "Vendor-hosted tools Vibey can call in a conversation. They are off by default: a call may cost money, and its content goes to the vendor that runs the tool.",
+ "reverify": {
+ "engineUpgraded_one": "Engine upgraded · {{count}} needs a new check",
+ "engineUpgraded_other": "Engine upgraded · {{count}} need a new check",
+ "aged_one": "{{count}} check is over 30 days old",
+ "aged_other": "{{count}} checks are over 30 days old",
+ "both": "<upgraded>{{engineUpgraded}}</upgraded> · {{aged}}",
+ "upgradedOnly": "<upgraded>{{engineUpgraded}}</upgraded>",
+ "agedOnly": "{{aged}}"
+ },
+ "tool": {
+ "web_search": {
+ "name": "Web search",
+ "inline": "web search",
+ "description": "Searches the web and cites its sources in the answer."
+ },
+ "x_search": {
+ "name": "X search",
+ "inline": "X search",
+ "description": "Searches posts on X, with operators such as from: and within_time:."
+ },
+ "image_generation": {
+ "name": "Image generation",
+ "inline": "image generation",
+ "description": "Generates images, shown in the answer and saved as files."
+ }
+ },
+ "state": {
+ "on": "On",
+ "off": "Off",
+ "needsCheck": "Off · check a Source first",
+ "needsExecutor": "Off · choose an executor first",
+ "checkUnavailable": "Off · checks for this tool come in a later update"
+ },
+ "toggle": {
+ "turnOn": "Turn on {{name}}",
+ "turnOff": "Turn off {{name}}"
+ },
+ "col": {
+ "source": "Source · model",
+ "native": "Runs natively",
+ "cost": "Cost per call"
+ },
+ "chip": {
+ "unsupportedAged": "Not supported as of {{date}} · check again",
+ "native": "Native · verified {{date}}",
+ "reverify": "Verified {{date}} · check again",
+ "engineUpgraded": "Engine upgraded · check again",
+ "unsupported": "Not supported on this Source",
+ "unchecked": "Not checked",
+ "executor": "Proxy executor"
+ },
+ "cost": {
+ "included": "Included in subscription",
+ "includedNote": "No extra charge",
+ "imageTokens": "Billed per image token · no per-image price yet",
+ "list": "≈ {{price}}",
+ "perUnit": "${{usd}} / {{unit}}",
+ "unit": {
+ "call": "call",
+ "search": "search",
+ "post": "post",
+ "profile": "profile"
+ },
+ "listNote": "At API price",
+ "listNoteExtras": "At API price · {{extras}}",
+ "extra": "+ {{price}}",
+ "extraSeparator": " · ",
+ "unknown": "No list price"
+ },
+ "empty": "None of your Sources can run {{toolInline}} natively. Add a Source that offers it, then check it here.",
+ "noNative": "Models on {{sources}} have no native {{toolInline}}.",
+ "executor": {
+ "label": "Proxy executor",
+ "pick": "Proxy executor for {{name}}",
+ "automatic": "Automatic: first verified in Vibey's order",
+ "unavailable": "Available after a check",
+ "option": "{{source}} · {{model}}",
+ "notVerified": "{{source}} · {{model}} (not verified)",
+ "note": {
+ "off": "Applies when the tool is on.",
+ "bound": "Verified models run it natively. Other models use {{source}}, and those calls are billed to it.",
+ "unbound": "No Source is verified, so calls to it fail until you check one."
+ },
+ "automaticBound": "Automatic ({{source}} · {{model}})"
+ },
+ "footnote": "Costs are estimates per call. API keys are valued at the vendor's list price, and a relay may bill differently. Subscriptions add no charge. A Claude subscription can't run hosted tools.",
+ "saveFailed": "Couldn't save the {{toolInline}} setting. Please retry.",
+ "probe": {
+ "check": "Check",
+ "checkCost": "Check · {{cost}}",
+ "recheckCost": "Check again · {{cost}}",
+ "retryCost": "Retry · {{cost}}",
+ "recheck": "Check again",
+ "retry": "Retry",
+ "running": "Checking…",
+ "about": "about ${{usd}}",
+ "included": "included in subscription",
+ "unknown": "cost unknown",
+ "notRecorded": "the result couldn't be recorded",
+ "outcome": {
+ "inconclusive": "Not verified · the model didn't use the tool; try again",
+ "transient": "Couldn't verify · try again",
+ "transientReason": "Couldn't verify · {{reason}}"
+ }
+ },
+ "header": {
+ "pending_one": "{{count}} pair to check",
+ "pending_other": "{{count}} pairs to check",
+ "total": "{{cost}} in total",
+ "totalIncluded": "included in subscriptions",
+ "totalUnknown": "cost unknown",
+ "summary": "{{pending}} · {{cost}}",
+ "none": "Everything is checked",
+ "action": "Check available tools"
+ },
+ "dialog": {
+ "title": "Check available tools",
+ "subtitle": "Hosted tools · Vibey",
+ "body_one": "This sends {{count}} real request to the Source below to confirm it can run the tool natively.",
+ "body_other": "This sends {{count}} real requests to the Sources below to confirm they can run these tools natively.",
+ "privacy": "Each request carries one fixed test query and none of your conversation. Checking turns no tool on and changes no route.",
+ "listTitle": "To check",
+ "pair": "<tool>{{tool}}</tool><muted>·</muted><source>{{source}}</source><model>{{model}}</model>",
+ "total": "Total",
+ "totalNote": "Estimated at API price; a relay may bill differently",
+ "cancel": "Cancel",
+ "start": "Start check",
+ "startCost": "Start check · {{cost}}",
+ "running_one": "Checking {{done}} of {{count}}…",
+ "running_other": "Checking {{done}} of {{count}}…"
+ },
+ "result": {
+ "title": "Check finished",
+ "verified_one": "{{count}} runs natively",
+ "verified_other": "{{count}} run natively",
+ "unsupported_one": "{{count}} not supported",
+ "unsupported_other": "{{count}} not supported",
+ "unverified_one": "{{count}} not verified",
+ "unverified_other": "{{count}} not verified",
+ "outcome": {
+ "verified": "Runs natively",
+ "unsupported": "Not supported",
+ "unverified": "Not verified"
+ },
+ "reason": {
+ "inconclusive": "The model didn't use the tool. Try again; this is not recorded as unsupported.",
+ "transient": "Couldn't verify this time. Try again; this is not recorded as unsupported.",
+ "transientReason": "Couldn't verify this time ({{reason}}). Try again; this is not recorded as unsupported."
+ },
+ "note": "Verified models call the tool natively; other models use the proxy executor. Tools stay off until you turn them on.",
+ "retry_one": "Retry {{count}}",
+ "retry_other": "Retry {{count}}",
+ "retryCost_one": "Retry {{count}} · {{cost}}",
+ "retryCost_other": "Retry {{count}} · {{cost}}",
+ "done": "Done"
+ }
+ },
+ "capability": {
+ "readFailed": "Couldn't read this Source's tool capabilities.",
+ "col": "Capabilities",
+ "chip": {
+ "unsupportedAged": "{{tool}} · not supported as of {{date}} · check again",
+ "native": "{{tool}} · native · verified {{date}}",
+ "reverify": "{{tool}} · verified {{date}} · check again",
+ "engineUpgraded": "{{tool}} · engine upgraded · check again",
+ "unsupported": "{{tool}} · not supported on this Source",
+ "viaProxy": "{{tool}} · via proxy",
+ "viaProxyAged": "{{tool}} · via proxy · check again"
+ },
+ "explain": {
+ "unsupportedAged": "This Source refused {{toolInline}} in a check over 30 days old. Check again to see whether it supports it now.",
+ "native": "Verified: this model runs the vendor's own tool on this Source.",
+ "reverify": "This check is over 30 days old. The tool still runs natively; check again when convenient.",
+ "engineUpgraded": "The model engine was upgraded after this check, so it no longer counts as verified until it is checked again.",
+ "unsupported": "This Source refused {{toolInline}}, so it is never sent here.",
+ "viaProxy": "{{tool}} is on, but this Source can't run it natively, so calls go to the proxy executor.",
+ "viaProxyAged": "{{tool}} is on. This Source refused it in a check over 30 days old, so calls go to the proxy executor; check again to see whether it runs natively now."
+ },
+ "recorded": "Recorded",
+ "recordedValue": "{{time}} · {{basis}}",
+ "basis": {
+ "probe": "a check",
+ "observed": "a real request"
+ },
+ "reason": "Reason",
+ "expiry": "Valid",
+ "expiryObserved": "until {{date}}, then the default applies",
+ "expiryProbe": "check again after {{date}}",
+ "recheck": "Check again",
+ "recheckCost": "Check again · {{cost}}",
+ "accessibleName": "{{label}}. {{explanation}}",
+ "accessibleNameFacts": "{{label}}. {{explanation}} {{facts}}",
+ "accessibleFact": "{{term}}: {{value}}.",
+ "effort": {
+ "unsupported": "{{effort}} · not supported on this Source",
+ "explain": "This Source refused this reasoning effort, so requests at it skip this Source."
+ }
}
}
},
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index b53edf3d5..1981b427b 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -973,6 +973,7 @@
},
"tab": {
"hub": "供应商与路由",
+ "tools": "工具",
"quota": "订阅额度",
"usage": "用量",
"logs": "日志"
@@ -2344,6 +2345,207 @@
"refreshed": "已更新",
"unresolved": "仍然不可用",
"failed": "没能处理,请重试"
+ },
+ "tools": {
+ "title": "托管工具",
+ "subtitle": "Vibey 在对话中可调用的厂商托管工具。默认关闭:开启后每次调用可能产生费用,内容会发给提供该工具的厂商。",
+ "reverify": {
+ "engineUpgraded_one": "引擎已升级 · {{count}} 项需重新检测",
+ "engineUpgraded_other": "引擎已升级 · {{count}} 项需重新检测",
+ "aged_one": "{{count}} 项检测已超过 30 天",
+ "aged_other": "{{count}} 项检测已超过 30 天",
+ "both": "<upgraded>{{engineUpgraded}}</upgraded> · {{aged}}",
+ "upgradedOnly": "<upgraded>{{engineUpgraded}}</upgraded>",
+ "agedOnly": "{{aged}}"
+ },
+ "tool": {
+ "web_search": {
+ "name": "网页搜索",
+ "inline": "网页搜索",
+ "description": "搜索网页,并在回答中注明出处。"
+ },
+ "x_search": {
+ "name": "X 搜索",
+ "inline": "X 搜索",
+ "description": "搜索 X 上的帖子,支持 from:、within_time: 等高级语法。"
+ },
+ "image_generation": {
+ "name": "图片生成",
+ "inline": "图片生成",
+ "description": "生成图片,显示在回答里并保存为文件。"
+ }
+ },
+ "state": {
+ "on": "已开启",
+ "off": "已关闭",
+ "needsCheck": "已关闭 · 需先检测",
+ "needsExecutor": "已关闭 · 需先选择代理执行者",
+ "checkUnavailable": "已关闭 · 此工具的检测将在后续更新中提供"
+ },
+ "toggle": {
+ "turnOn": "开启{{name}}",
+ "turnOff": "关闭{{name}}"
+ },
+ "col": {
+ "source": "供应商 · 模型",
+ "native": "原生运行",
+ "cost": "每次费用"
+ },
+ "chip": {
+ "unsupportedAged": "{{date}} 检测为不支持 · 需重新检测",
+ "native": "原生 · {{date}} 已验证",
+ "reverify": "{{date}} 已验证 · 需重新检测",
+ "engineUpgraded": "引擎已升级 · 需重新检测",
+ "unsupported": "此供应商不支持",
+ "unchecked": "未检测",
+ "executor": "代理执行者"
+ },
+ "cost": {
+ "included": "订阅内含",
+ "includedNote": "不另计费",
+ "imageTokens": "按图像 token 计费 · 暂无单价",
+ "list": "≈ {{price}}",
+ "perUnit": "${{usd}} / {{unit}}",
+ "unit": {
+ "call": "次",
+ "search": "次搜索",
+ "post": "条帖子",
+ "profile": "个账号"
+ },
+ "listNote": "API 标价",
+ "listNoteExtras": "API 标价 · {{extras}}",
+ "extra": "另加 {{price}}",
+ "extraSeparator": ",",
+ "unknown": "暂无标价"
+ },
+ "empty": "你的供应商都不能原生运行{{toolInline}}。添加提供该工具的供应商后,在这里检测。",
+ "noNative": "{{sources}} 上的模型没有原生{{toolInline}}。",
+ "executor": {
+ "label": "代理执行",
+ "pick": "{{name}}的代理执行者",
+ "automatic": "自动:Vibey 顺序中第一个已验证的",
+ "unavailable": "检测后可选",
+ "option": "{{source}} · {{model}}",
+ "notVerified": "{{source}} · {{model}}(未验证)",
+ "note": {
+ "off": "开启后生效。",
+ "bound": "已验证的模型直接原生调用;其他模型由 {{source}} 代为调用,费用记在 {{source}}。",
+ "unbound": "还没有已验证的供应商:在检测通过前调用会失败。"
+ },
+ "automaticBound": "自动({{source}} · {{model}})"
+ },
+ "footnote": "费用为每次调用的估算:API Key 按厂商 API 标价估算,中转的实际账单可能不同;订阅不另计费。Claude 订阅不能运行托管工具。",
+ "saveFailed": "{{toolInline}}设置未能保存,请重试。",
+ "probe": {
+ "check": "检测",
+ "checkCost": "检测 · {{cost}}",
+ "recheckCost": "重新检测 · {{cost}}",
+ "retryCost": "重试 · {{cost}}",
+ "recheck": "重新检测",
+ "retry": "重试",
+ "running": "检测中…",
+ "about": "约 ${{usd}}",
+ "included": "订阅内含",
+ "unknown": "费用未知",
+ "notRecorded": "结果未能记录",
+ "outcome": {
+ "inconclusive": "未能检测 · 模型没有调用工具,请重试",
+ "transient": "未能检测 · 请重试",
+ "transientReason": "未能检测 · {{reason}}"
+ }
+ },
+ "header": {
+ "pending_one": "{{count}} 项可检测",
+ "pending_other": "{{count}} 项可检测",
+ "total": "共{{cost}}",
+ "totalIncluded": "均为订阅内含",
+ "totalUnknown": "费用未知",
+ "summary": "{{pending}} · {{cost}}",
+ "none": "均已检测",
+ "action": "检测可用工具"
+ },
+ "dialog": {
+ "title": "检测可用工具",
+ "subtitle": "托管工具 · Vibey",
+ "body_one": "检测会向下面的供应商发送 {{count}} 次真实请求,确认它们能否原生运行这些工具。",
+ "body_other": "检测会向下面的供应商发送 {{count}} 次真实请求,确认它们能否原生运行这些工具。",
+ "privacy": "请求只带一条固定的测试查询,不含你的对话。检测不会开启任何工具,也不会改动路由。",
+ "listTitle": "将检测",
+ "pair": "<tool>{{tool}}</tool><muted>·</muted><source>{{source}}</source><model>{{model}}</model>",
+ "total": "合计",
+ "totalNote": "按 API 标价估算;中转的实际账单可能不同",
+ "cancel": "取消",
+ "start": "开始检测",
+ "startCost": "开始检测 · {{cost}}",
+ "running_one": "正在检测 {{done}}/{{count}}…",
+ "running_other": "正在检测 {{done}}/{{count}}…"
+ },
+ "result": {
+ "title": "检测完成",
+ "verified_one": "{{count}} 项原生可用",
+ "verified_other": "{{count}} 项原生可用",
+ "unsupported_one": "{{count}} 项不支持",
+ "unsupported_other": "{{count}} 项不支持",
+ "unverified_one": "{{count}} 项未能检测",
+ "unverified_other": "{{count}} 项未能检测",
+ "outcome": {
+ "verified": "原生可用",
+ "unsupported": "不支持",
+ "unverified": "未能检测"
+ },
+ "reason": {
+ "inconclusive": "模型没有调用工具。可重试,不会记为“不支持”。",
+ "transient": "这次未能检测。可重试,不会记为“不支持”。",
+ "transientReason": "这次未能检测({{reason}})。可重试,不会记为“不支持”。"
+ },
+ "note": "已验证的模型会直接原生调用;其他模型由代理执行者代为调用。工具开关在“工具”页,默认仍是关闭。",
+ "retry_one": "重试 {{count}} 项",
+ "retry_other": "重试 {{count}} 项",
+ "retryCost_one": "重试 {{count}} 项 · {{cost}}",
+ "retryCost_other": "重试 {{count}} 项 · {{cost}}",
+ "done": "完成"
+ }
+ },
+ "capability": {
+ "readFailed": "未能读取此供应商的工具能力。",
+ "col": "能力",
+ "chip": {
+ "unsupportedAged": "{{tool}} · {{date}} 检测为不支持 · 需重新检测",
+ "native": "{{tool}} · 原生 · {{date}} 已验证",
+ "reverify": "{{tool}} · {{date}} 已验证 · 需重新检测",
+ "engineUpgraded": "{{tool}} · 引擎已升级 · 需重新检测",
+ "unsupported": "{{tool}} · 此供应商不支持",
+ "viaProxy": "{{tool}} · 由代理提供",
+ "viaProxyAged": "{{tool}} · 由代理提供 · 需重新检测"
+ },
+ "explain": {
+ "unsupportedAged": "此供应商在超过 30 天前的检测中不支持{{toolInline}},可重新检测现在是否已支持。",
+ "native": "检测通过:这个模型在此供应商上直接调用厂商自带的工具。",
+ "reverify": "检测已超过 30 天,仍按原结果原生运行,可重新检测。",
+ "engineUpgraded": "检测之后模型引擎已升级,重新检测前不再算作已验证。",
+ "unsupported": "此供应商拒绝过{{toolInline}},之后不会再发到这里。",
+ "viaProxy": "{{tool}}已开启,但此供应商不能原生运行,调用交给代理执行者。",
+ "viaProxyAged": "{{tool}}已开启。此供应商在超过 30 天前的检测中不支持它,调用交给代理执行者;可重新检测现在是否已能原生运行。"
+ },
+ "recorded": "记录时间",
+ "recordedValue": "{{time}} · {{basis}}",
+ "basis": {
+ "probe": "一次检测",
+ "observed": "一次真实请求"
+ },
+ "reason": "失败原因",
+ "expiry": "有效期",
+ "expiryObserved": "到 {{date}},过期后按默认判断",
+ "expiryProbe": "{{date}} 后需重新检测",
+ "recheck": "重新检测",
+ "recheckCost": "重新检测 · {{cost}}",
+ "accessibleName": "{{label}}。{{explanation}}",
+ "accessibleNameFacts": "{{label}}。{{explanation}}{{facts}}",
+ "accessibleFact": "{{term}}:{{value}}。",
+ "effort": {
+ "unsupported": "{{effort}} · 此供应商不支持",
+ "explain": "此供应商拒绝过这个推理强度,之后的请求会跳过它。"
+ }
}
}
},