mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-11-20 23:20:46 +00:00
* feat(ai): customizable provider name, icon, and protocol style
Issue #1101 reported that the only way to wire DeepSeek through the
Catty Agent was to add an "Anthropic" provider with a DeepSeek base URL,
which (a) wasn't relabelable except on the "custom" providerId and
(b) implicitly conflated wire-protocol style with providerId, locking
"custom" to the OpenAI-compatible client.
ProviderConfig now carries three optional fields — `style`
(anthropic/openai/google), `iconId` (built-in brand glyph key), and
`iconDataUrl` (user upload). createModelFromConfig routes on the
resolved style first, falling back to providerId only for per-vendor
quirks (ollama's throwaway apiKey and openrouter's baseURL). Display
name becomes editable for every provider, not just custom.
The icon picker exposes a curated lobe-icons subset (MIT) covering the
common Anthropic/OpenAI-compatible third parties — DeepSeek, Moonshot,
Kimi, Qwen, Zhipu, Doubao, Mistral, Cohere, Grok, Perplexity, Groq,
Hugging Face — plus the existing six built-ins. Uploads are downsampled
to 64×64 WebP on a canvas so localStorage doesn't blow up. See
public/ai/providers/NOTICE.md for attribution.
Closes part of #1101 (problem 2). PR2 will reuse the new name/icon
plumbing in the Catty Agent chat input to surface a provider switcher.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* polish(ai): bigger labelled icon tiles and auto-fill display name
The first pass shipped the icon picker as an 8-column grid of bare
20px badges. Reviewer feedback: the icons are too small to read at a
glance, every preset should announce its brand name, and a second
click on a selected preset should let the user back out.
Switches the grid to auto-fill 120px tiles with a 32px icon plus a
truncated label so the picker reads like a brand list, not a sprite
sheet. Selecting a preset now also writes the brand's canonical
English display name into the Display Name field — the picker labels
keep their "/ 中文" suffix as a bilingual hint, but a new `name` field
on each catalog entry supplies a clean string for autofill (e.g.
"Qwen / 通义" → "Qwen"). Re-clicking the selected tile clears
iconId/iconDataUrl but leaves the typed name alone, so users who
already edited the name don't lose their edit on accidental toggle.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* polish(ai): add explicit close button to icon picker
The picker only opened via the icon badge above the Display Name field,
which left no obvious affordance to collapse it once a preset was
chosen — users either had to scroll past or click back up to the icon.
Drops a ghost Close button in the bottom-right of the picker's action
row (next to Upload/Reset) so dismissing the panel is one click and
visible without hunting.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(ai): wire model discovery to the resolved provider style
Codex review on #1105 flagged that ModelSelector still derives auth
headers from `providerId` (`x-api-key` only when providerId is the
literal "anthropic"). Now that ProviderConfig lets the user override
`style` independently, the form persists the override but the model
discovery call ignored it — so picking an Anthropic providerId pointed
at an OpenAI-compatible backend (or vice versa) would send the wrong
header and fail to list models even though chat routing already used
the override.
Extracts `buildModelDiscoveryHeaders(style, apiKey)` as a pure helper
in infrastructure/ai/. ModelSelector now resolves the protocol family
via `resolveProviderStyle` with the explicit `style` prop taking
precedence, then asks the helper for headers. ProviderConfigForm
passes the resolved style through. The `needsApiKey = providerId !==
"ollama"` shortcut stays as-is — that's a per-vendor concession, not a
style decision.
Refs codex review on #1105.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(ai): apply per-vendor URL fallbacks across every style override
Codex review on #1105 caught that the openrouter (and ollama) baseURL
fallback was sitting inside the `style === 'openai'` branch, so a user
who picked OpenRouter providerId + Anthropic/Google style with an
empty baseURL would skip the fallback entirely. The SDK then routed
to its own default endpoint (api.anthropic.com /
generativelanguage.googleapis.com) using the user's OpenRouter key —
silent misrouting plus auth failures.
Pulls the per-vendor quirks out into a new pure helper
`resolveProviderEndpoint(config, style, safeApiKey)`. The URL
fallback now fires for every style — the user picked openrouter for a
reason, even if they overrode the wire format. The ollama-only
`'ollama'` literal apiKey swap stays gated on `style === 'openai'`
because Anthropic/Google clients need a real key, not the throwaway
placeholder.
Refs codex review on #1105.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(ai): send x-goog-api-key for google-style model discovery
Codex review on #1105 flagged that buildModelDiscoveryHeaders bucketed
google-style providers with the OpenAI-compat default, so a model
refresh against any google-routed endpoint was sending `Authorization:
Bearer …`. That's the wrong auth header — Google Generative AI
rejects Bearer entirely and expects `x-goog-api-key` (or `?key=`).
The runtime chat path already uses `createGoogleGenerativeAI`, which
authenticates with the Google header family, so discovery was the
odd one out.
Adds an explicit `google` branch returning `{ "x-goog-api-key":
<apiKey> }` and updates the unit test. The default google providerId
never hits this path today (PROVIDER_PRESETS["google"] has no
modelsEndpoint), but the style override surface created in this PR
lets users compose providerId + style pairs where discovery does
fire — e.g. an openai/anthropic-style providerId pointed at a Google
endpoint via baseURL override.
Refs codex review on #1105.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(ai): pick discovery endpoint from resolved provider style
Codex review on #1105 pointed out the lopsided fix in ae7394c8: I
switched discovery *headers* to honor the resolved `style` but left
the URL path coming straight from `PROVIDER_PRESETS[providerId]`. So
the moment style and providerId disagree the request shape is half
correct — e.g. Anthropic providerId + style=openai sends Bearer
(right) at `/v1/models` (wrong; the OpenAI-compat backend exposes
/models). 404s either way.
Adds `STYLE_DEFAULT_MODELS_ENDPOINT` (`anthropic → /v1/models`,
`openai → /models`, `google → undefined`) and a
`resolveModelsDiscoveryEndpoint(style, presetEndpoint)` helper. The
style's convention wins; the caller-supplied `presetEndpoint` is the
fallback for styles with no listing convention (currently just
google).
Behavior for stock configs is unchanged — every preset's existing
modelsEndpoint matches its style's default. Mismatches now line up
(headers + path together), and `custom` providers gain a sensible
discovery attempt when the user sets a style. My earlier inline reply
ducking this was wrong; codex's call was right.
Added three unit tests covering style defaults, the override-on-flip,
and the google-style passthrough.
Refs codex review on #1105.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
189 lines
8.1 KiB
TypeScript
189 lines
8.1 KiB
TypeScript
import React, { useCallback, useEffect, useMemo, useState } from "react";
|
|
import { Check, ChevronDown, RefreshCw } from "lucide-react";
|
|
import type { AIProviderId, ProviderStyle } from "../../../../infrastructure/ai/types";
|
|
import { resolveProviderStyle } from "../../../../infrastructure/ai/types";
|
|
import { buildModelDiscoveryHeaders, resolveModelsDiscoveryEndpoint } from "../../../../infrastructure/ai/modelDiscoveryHeaders";
|
|
import { useI18n } from "../../../../application/i18n/I18nProvider";
|
|
import { Button } from "../../../ui/button";
|
|
import { Tooltip, TooltipContent, TooltipTrigger } from "../../../ui/tooltip";
|
|
import { cn } from "../../../../lib/utils";
|
|
import type { FetchedModel } from "./types";
|
|
import { getFetchBridge } from "./types";
|
|
|
|
export const ModelSelector: React.FC<{
|
|
value: string;
|
|
onChange: (value: string) => void;
|
|
baseURL: string;
|
|
modelsEndpoint?: string;
|
|
placeholder?: string;
|
|
apiKey?: string;
|
|
providerId?: AIProviderId;
|
|
/** Optional protocol-family override; falls back to `providerId` via {@link resolveProviderStyle}. */
|
|
style?: ProviderStyle;
|
|
skipTLSVerify?: boolean;
|
|
}> = ({ value, onChange, baseURL, modelsEndpoint, placeholder, apiKey, providerId, style, skipTLSVerify }) => {
|
|
const { t } = useI18n();
|
|
const [models, setModels] = useState<FetchedModel[]>([]);
|
|
const [isLoading, setIsLoading] = useState(false);
|
|
const [error, setError] = useState<string | null>(null);
|
|
const [isOpen, setIsOpen] = useState(false);
|
|
const [hasFetched, setHasFetched] = useState(false);
|
|
|
|
// Resolve the wire-protocol family: prefer an explicit style override (set in
|
|
// the form), then fall back to the providerId-derived default.
|
|
const resolvedStyle: ProviderStyle = style
|
|
?? (providerId ? resolveProviderStyle({ providerId }) : "openai");
|
|
// Endpoint follows the resolved style so a providerId+style mismatch (e.g.
|
|
// Anthropic providerId switched to OpenAI style) still hits the right path.
|
|
const effectiveModelsEndpoint = resolveModelsDiscoveryEndpoint(resolvedStyle, modelsEndpoint);
|
|
// Ollama runs locally without auth; all other providers need an API key to list models
|
|
const needsApiKey = providerId !== "ollama";
|
|
const canFetch = !!effectiveModelsEndpoint && (!needsApiKey || !!apiKey);
|
|
|
|
const fetchModels = useCallback(async () => {
|
|
if (!effectiveModelsEndpoint) return;
|
|
const bridge = getFetchBridge();
|
|
if (!bridge?.aiFetch) return;
|
|
|
|
setIsLoading(true);
|
|
setError(null);
|
|
try {
|
|
// Temporarily allow the provider's host in the backend fetch allowlist
|
|
// so model listing works for URLs not yet synced from the main window.
|
|
if (bridge.aiAllowlistAddHost && baseURL) {
|
|
await bridge.aiAllowlistAddHost(baseURL);
|
|
}
|
|
const url = `${baseURL.replace(/\/+$/, "")}${effectiveModelsEndpoint}`;
|
|
const headers = buildModelDiscoveryHeaders(resolvedStyle, apiKey);
|
|
const result = await bridge.aiFetch(url, "GET", headers, undefined, undefined, undefined, undefined, skipTLSVerify);
|
|
if (!result.ok) {
|
|
setError(`Failed to fetch models (${result.error || "unknown error"})`);
|
|
return;
|
|
}
|
|
const parsed = JSON.parse(result.data);
|
|
const list: FetchedModel[] = (parsed.data || parsed.models || []).map((m: { id: string; name?: string }) => ({
|
|
id: m.id,
|
|
name: m.name,
|
|
}));
|
|
list.sort((a, b) => (a.name || a.id).localeCompare(b.name || b.id));
|
|
setModels(list);
|
|
setHasFetched(true);
|
|
} catch (err) {
|
|
setError(err instanceof Error ? err.message : "Failed to parse response");
|
|
} finally {
|
|
setIsLoading(false);
|
|
}
|
|
}, [baseURL, effectiveModelsEndpoint, apiKey, resolvedStyle, skipTLSVerify]);
|
|
|
|
// Auto-fetch when dropdown first opens
|
|
useEffect(() => {
|
|
if (isOpen && canFetch && !hasFetched && !isLoading) {
|
|
void fetchModels();
|
|
}
|
|
}, [isOpen, canFetch, hasFetched, isLoading, fetchModels]);
|
|
|
|
// Filter models by current input value (inline autocomplete)
|
|
const suggestions = useMemo(() => {
|
|
if (!hasFetched || models.length === 0) return [];
|
|
if (!value.trim()) return models;
|
|
const q = value.toLowerCase();
|
|
return models.filter((m) =>
|
|
m.id.toLowerCase().includes(q) || (m.name && m.name.toLowerCase().includes(q)),
|
|
);
|
|
}, [models, value, hasFetched]);
|
|
|
|
const showSuggestions = isOpen && canFetch;
|
|
|
|
return (
|
|
<div className="relative">
|
|
<div className="flex items-center gap-2">
|
|
<div className="relative flex-1">
|
|
<input
|
|
type="text"
|
|
value={value}
|
|
onChange={(e) => {
|
|
onChange(e.target.value);
|
|
if (canFetch && hasFetched && !isOpen) setIsOpen(true);
|
|
}}
|
|
onFocus={() => { if (canFetch) setIsOpen(true); }}
|
|
onBlur={() => { setIsOpen(false); }}
|
|
placeholder={placeholder ?? (canFetch ? t('ai.providers.searchModel') : t('ai.providers.defaultModel.placeholder'))}
|
|
className={cn(
|
|
"w-full h-8 rounded-md border border-input bg-background px-3 text-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",
|
|
canFetch && "pr-8",
|
|
)}
|
|
/>
|
|
{canFetch && (
|
|
<button
|
|
type="button"
|
|
onMouseDown={(e) => { e.preventDefault(); setIsOpen(!isOpen); }}
|
|
className="absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
|
|
>
|
|
<ChevronDown size={14} className={cn("transition-transform", isOpen && "rotate-180")} />
|
|
</button>
|
|
)}
|
|
</div>
|
|
{canFetch && (
|
|
<Tooltip>
|
|
<TooltipTrigger asChild>
|
|
<Button
|
|
variant="outline"
|
|
size="sm"
|
|
onClick={() => { setHasFetched(false); void fetchModels(); }}
|
|
disabled={isLoading}
|
|
className="shrink-0 px-2"
|
|
>
|
|
<RefreshCw size={14} className={isLoading ? "animate-spin" : ""} />
|
|
</Button>
|
|
</TooltipTrigger>
|
|
<TooltipContent>{t('ai.providers.refreshModels')}</TooltipContent>
|
|
</Tooltip>
|
|
)}
|
|
</div>
|
|
|
|
{/* Suggestions dropdown */}
|
|
{showSuggestions && (
|
|
<div className="absolute top-full left-0 right-0 mt-1 z-[101] rounded-md border border-border bg-popover shadow-md">
|
|
<div className="max-h-60 overflow-y-auto">
|
|
{isLoading ? (
|
|
<div className="px-3 py-3 text-center text-xs text-muted-foreground">
|
|
<RefreshCw size={14} className="animate-spin inline mr-1.5" />
|
|
{t('ai.providers.loadingModels')}
|
|
</div>
|
|
) : error ? (
|
|
<div className="px-3 py-3 text-center text-xs text-destructive">{error}</div>
|
|
) : suggestions.length === 0 ? (
|
|
<div className="px-3 py-3 text-center text-xs text-muted-foreground">
|
|
{hasFetched ? t('ai.providers.noMatchingModels') : t('ai.providers.clickToLoadModels')}
|
|
</div>
|
|
) : (
|
|
suggestions.slice(0, 100).map((m) => (
|
|
<button
|
|
key={m.id}
|
|
onMouseDown={(e) => {
|
|
e.preventDefault();
|
|
onChange(m.id);
|
|
setIsOpen(false);
|
|
}}
|
|
className={cn(
|
|
"w-full text-left px-3 py-1.5 text-xs hover:bg-accent transition-colors flex items-center justify-between gap-2",
|
|
m.id === value && "bg-accent",
|
|
)}
|
|
>
|
|
<span className="font-mono truncate">{m.id}</span>
|
|
{m.id === value && <Check size={12} className="text-primary shrink-0" />}
|
|
</button>
|
|
))
|
|
)}
|
|
{suggestions.length > 100 && (
|
|
<div className="px-3 py-2 text-center text-[10px] text-muted-foreground border-t border-border/40">
|
|
{t('ai.providers.showingModels').replace('{count}', String(suggestions.length))}
|
|
</div>
|
|
)}
|
|
</div>
|
|
</div>
|
|
)}
|
|
</div>
|
|
);
|
|
};
|