Merge remote-tracking branch 'origin/main' into feat/auto-failover-switch

# Conflicts:
#	src/components/providers/ProviderList.tsx
This commit is contained in:
YoVinchen
2025-12-22 17:02:16 +08:00
7 changed files with 257 additions and 93 deletions
-38
View File
@@ -223,44 +223,6 @@ pub fn run() {
log::warn!("初始化 Updater 插件失败,已跳过:{e}");
}
}
#[cfg(target_os = "macos")]
{
// 设置 macOS 标题栏背景色为主界面蓝色
if let Some(window) = app.get_webview_window("main") {
use objc2::rc::Retained;
use objc2::runtime::AnyObject;
use objc2_app_kit::NSColor;
match window.ns_window() {
Ok(ns_window_ptr) => {
if let Some(ns_window) =
unsafe { Retained::retain(ns_window_ptr as *mut AnyObject) }
{
// 使用与主界面 banner 相同的蓝色 #3498db
// #3498db = RGB(52, 152, 219)
let bg_color = unsafe {
NSColor::colorWithRed_green_blue_alpha(
52.0 / 255.0, // R: 52
152.0 / 255.0, // G: 152
219.0 / 255.0, // B: 219
1.0, // Alpha: 1.0
)
};
unsafe {
use objc2::msg_send;
let _: () =
msg_send![&*ns_window, setBackgroundColor: &*bg_color];
}
} else {
log::warn!("Failed to retain NSWindow reference");
}
}
Err(e) => log::warn!("Failed to get NSWindow pointer: {e}"),
}
}
}
// 初始化日志
if cfg!(debug_assertions) {
app.handle().plugin(
+57 -49
View File
@@ -47,6 +47,10 @@ import { Button } from "@/components/ui/button";
type View = "providers" | "settings" | "prompts" | "skills" | "mcp" | "agents";
const DRAG_BAR_HEIGHT = 28; // px
const HEADER_HEIGHT = 64; // px
const CONTENT_TOP_OFFSET = DRAG_BAR_HEIGHT + HEADER_HEIGHT;
function App() {
const { t } = useTranslation();
const queryClient = useQueryClient();
@@ -112,7 +116,7 @@ function App() {
if (event.appType === activeApp) {
await refetch();
}
},
}
);
} catch (error) {
console.error("[App] Failed to subscribe provider switch event", error);
@@ -142,7 +146,7 @@ function App() {
} catch (error) {
console.error(
"[App] Failed to check environment conflicts on startup:",
error,
error
);
}
};
@@ -158,7 +162,7 @@ function App() {
if (migrated) {
toast.success(
t("migration.success", { defaultValue: "配置迁移成功" }),
{ closeButton: true },
{ closeButton: true }
);
}
} catch (error) {
@@ -179,10 +183,10 @@ function App() {
// 合并新检测到的冲突
setEnvConflicts((prev) => {
const existingKeys = new Set(
prev.map((c) => `${c.varName}:${c.sourcePath}`),
prev.map((c) => `${c.varName}:${c.sourcePath}`)
);
const newConflicts = conflicts.filter(
(c) => !existingKeys.has(`${c.varName}:${c.sourcePath}`),
(c) => !existingKeys.has(`${c.varName}:${c.sourcePath}`)
);
return [...prev, ...newConflicts];
});
@@ -194,7 +198,7 @@ function App() {
} catch (error) {
console.error(
"[App] Failed to check environment conflicts on app switch:",
error,
error
);
}
};
@@ -255,7 +259,7 @@ function App() {
(p) =>
p.sortIndex !== undefined &&
p.sortIndex >= newSortIndex! &&
p.id !== provider.id,
p.id !== provider.id
)
.map((p) => ({
id: p.id,
@@ -271,7 +275,7 @@ function App() {
toast.error(
t("provider.sortUpdateFailed", {
defaultValue: "排序更新失败",
}),
})
);
return; // 如果排序更新失败,不继续添加
}
@@ -345,7 +349,7 @@ function App() {
return (
<div className="mx-auto max-w-[56rem] px-5 flex flex-col h-[calc(100vh-8rem)] overflow-hidden">
{/* 独立滚动容器 - 解决 Linux/Ubuntu 下 DndContext 与滚轮事件冲突 */}
<div className="flex-1 overflow-y-auto overflow-x-hidden pb-12 px-1">
<div className="flex-1 px-1 pb-12 overflow-x-hidden overflow-y-auto">
<AnimatePresence mode="wait">
<motion.div
key={activeApp}
@@ -383,14 +387,14 @@ function App() {
return (
<div
className="flex min-h-screen flex-col bg-background text-foreground selection:bg-primary/30"
style={{ overflowX: "hidden" }}
className="flex flex-col h-screen overflow-hidden bg-background text-foreground selection:bg-primary/30"
style={{ overflowX: "hidden", paddingTop: CONTENT_TOP_OFFSET }}
>
{/* 全局拖拽区域(顶部 4px),避免上边框无法拖动 */}
{/* 全局拖拽区域(顶部 28px),避免上边框无法拖动 */}
<div
className="fixed top-0 left-0 right-0 h-4 z-[60]"
className="fixed top-0 left-0 right-0 z-[60]"
data-tauri-drag-region
style={{ WebkitAppRegion: "drag" } as any}
style={{ WebkitAppRegion: "drag", height: DRAG_BAR_HEIGHT } as any}
/>
{/* 环境变量警告横幅 */}
{showEnvBanner && envConflicts.length > 0 && (
@@ -412,7 +416,7 @@ function App() {
} catch (error) {
console.error(
"[App] Failed to re-check conflicts after deletion:",
error,
error
);
}
}}
@@ -420,13 +424,18 @@ function App() {
)}
<header
className="fixed top-0 z-50 w-full py-3 bg-background/80 backdrop-blur-md transition-all duration-300"
className="fixed z-50 w-full transition-all duration-300 bg-background/80 backdrop-blur-md"
data-tauri-drag-region
style={{ WebkitAppRegion: "drag" } as any}
style={
{
WebkitAppRegion: "drag",
top: DRAG_BAR_HEIGHT,
height: HEADER_HEIGHT,
} as any
}
>
<div className="h-4 w-full" aria-hidden data-tauri-drag-region />
<div
className="mx-auto max-w-[56rem] px-6 flex flex-wrap items-center justify-between gap-2"
className="mx-auto flex h-full max-w-[56rem] flex-wrap items-center justify-between gap-2 px-6"
data-tauri-drag-region
style={{ WebkitAppRegion: "drag" } as any}
>
@@ -442,7 +451,7 @@ function App() {
onClick={() => setCurrentView("providers")}
className="mr-2 rounded-lg"
>
<ArrowLeft className="h-4 w-4" />
<ArrowLeft className="w-4 h-4" />
</Button>
<h1 className="text-lg font-semibold">
{currentView === "settings" && t("settings.title")}
@@ -464,7 +473,7 @@ function App() {
"text-xl font-semibold transition-colors",
isProxyRunning && isCurrentAppTakeoverActive
? "text-emerald-500 hover:text-emerald-600 dark:text-emerald-400 dark:hover:text-emerald-300"
: "text-blue-500 hover:text-blue-600 dark:text-blue-400 dark:hover:text-blue-300",
: "text-blue-500 hover:text-blue-600 dark:text-blue-400 dark:hover:text-blue-300"
)}
>
CC Switch
@@ -476,7 +485,7 @@ function App() {
title={t("common.settings")}
className="hover:bg-black/5 dark:hover:bg-white/5"
>
<Settings className="h-4 w-4" />
<Settings className="w-4 h-4" />
</Button>
</div>
<UpdateBadge onClick={() => setCurrentView("settings")} />
@@ -495,7 +504,7 @@ function App() {
className={addActionButtonClass}
title={t("prompts.add")}
>
<Plus className="h-5 w-5" />
<Plus className="w-5 h-5" />
</Button>
)}
{currentView === "mcp" && (
@@ -505,7 +514,7 @@ function App() {
className={addActionButtonClass}
title={t("mcp.unifiedPanel.addServer")}
>
<Plus className="h-5 w-5" />
<Plus className="w-5 h-5" />
</Button>
)}
{currentView === "skills" && (
@@ -516,7 +525,7 @@ function App() {
onClick={() => skillsPageRef.current?.refresh()}
className="hover:bg-black/5 dark:hover:bg-white/5"
>
<RefreshCw className="h-4 w-4 mr-2" />
<RefreshCw className="w-4 h-4 mr-2" />
{t("skills.refresh")}
</Button>
<Button
@@ -525,7 +534,7 @@ function App() {
onClick={() => skillsPageRef.current?.openRepoManager()}
className="hover:bg-black/5 dark:hover:bg-white/5"
>
<Settings className="h-4 w-4 mr-2" />
<Settings className="w-4 h-4 mr-2" />
{t("skills.repoManager")}
</Button>
</>
@@ -536,7 +545,7 @@ function App() {
<AppSwitcher activeApp={activeApp} onSwitch={setActiveApp} />
<div className="bg-muted p-1 rounded-xl flex items-center gap-1">
<div className="flex items-center gap-1 p-1 bg-muted rounded-xl">
<Button
variant="ghost"
size="sm"
@@ -546,24 +555,24 @@ function App() {
"transition-all duration-200 ease-in-out overflow-hidden",
hasSkillsSupport
? "opacity-100 w-8 scale-100 px-2"
: "opacity-0 w-0 scale-75 pointer-events-none px-0 -ml-1",
: "opacity-0 w-0 scale-75 pointer-events-none px-0 -ml-1"
)}
title={t("skills.manage")}
>
<Wrench className="h-4 w-4 flex-shrink-0" />
<Wrench className="flex-shrink-0 w-4 h-4" />
</Button>
{/* TODO: Agents 功能开发中,暂时隐藏入口 */}
{/* {isClaudeApp && (
<Button
variant="ghost"
size="sm"
onClick={() => setCurrentView("agents")}
className="text-muted-foreground hover:text-foreground hover:bg-black/5 dark:hover:bg-white/5"
title="Agents"
>
<Bot className="h-4 w-4" />
</Button>
)} */}
<Button
variant="ghost"
size="sm"
onClick={() => setCurrentView("agents")}
className="text-muted-foreground hover:text-foreground hover:bg-black/5 dark:hover:bg-white/5"
title="Agents"
>
<Bot className="w-4 h-4" />
</Button>
)} */}
<Button
variant="ghost"
size="sm"
@@ -571,7 +580,7 @@ function App() {
className="text-muted-foreground hover:text-foreground hover:bg-black/5 dark:hover:bg-white/5"
title={t("prompts.manage")}
>
<Book className="h-4 w-4" />
<Book className="w-4 h-4" />
</Button>
<Button
variant="ghost"
@@ -580,7 +589,7 @@ function App() {
className="text-muted-foreground hover:text-foreground hover:bg-black/5 dark:hover:bg-white/5"
title={t("mcp.title")}
>
<Server className="h-4 w-4" />
<Server className="w-4 h-4" />
</Button>
</div>
@@ -589,7 +598,7 @@ function App() {
size="icon"
className={`ml-2 ${addActionButtonClass}`}
>
<Plus className="h-5 w-5" />
<Plus className="w-5 h-5" />
</Button>
</>
)}
@@ -597,13 +606,12 @@ function App() {
</div>
</header>
<main
className={`flex-1 overflow-y-auto pb-12 animate-fade-in scroll-overlay ${
currentView === "providers" ? "pt-24" : "pt-20"
}`}
style={{ overflowX: "hidden" }}
>
{renderContent()}
<main className="flex-1 pb-12 animate-fade-in ">
<div
className={cn("pb-12", currentView === "providers" ? "pt-6" : "pt-4")}
>
{renderContent()}
</div>
</main>
<AddProviderDialog
+139 -6
View File
@@ -5,7 +5,16 @@ import {
useSortable,
verticalListSortingStrategy,
} from "@dnd-kit/sortable";
import type { CSSProperties } from "react";
import {
useEffect,
useMemo,
useRef,
useState,
type CSSProperties,
} from "react";
import { AnimatePresence, motion } from "framer-motion";
import { Search, X } from "lucide-react";
import { useTranslation } from "react-i18next";
import type { Provider } from "@/types";
import type { AppId } from "@/lib/api";
import { useDragSort } from "@/hooks/useDragSort";
@@ -19,6 +28,8 @@ import {
useRemoveFromFailoverQueue,
} from "@/lib/query/failover";
import { useCallback } from "react";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
interface ProviderListProps {
providers: Record<string, Provider>;
@@ -53,9 +64,10 @@ export function ProviderList({
isProxyTakeover = false,
activeProviderId,
}: ProviderListProps) {
const { t } = useTranslation();
const { sortedProviders, sensors, handleDragEnd } = useDragSort(
providers,
appId,
appId
);
// 流式健康检查
@@ -108,13 +120,56 @@ export function ProviderList({
checkProvider(provider.id, provider.name);
};
const [searchTerm, setSearchTerm] = useState("");
const [isSearchOpen, setIsSearchOpen] = useState(false);
const searchInputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
const handleKeyDown = (event: KeyboardEvent) => {
const key = event.key.toLowerCase();
if ((event.metaKey || event.ctrlKey) && key === "f") {
event.preventDefault();
setIsSearchOpen(true);
return;
}
if (key === "escape") {
setIsSearchOpen(false);
}
};
window.addEventListener("keydown", handleKeyDown);
return () => window.removeEventListener("keydown", handleKeyDown);
}, []);
useEffect(() => {
if (isSearchOpen) {
const frame = requestAnimationFrame(() => {
searchInputRef.current?.focus();
searchInputRef.current?.select();
});
return () => cancelAnimationFrame(frame);
}
}, [isSearchOpen]);
const filteredProviders = useMemo(() => {
const keyword = searchTerm.trim().toLowerCase();
if (!keyword) return sortedProviders;
return sortedProviders.filter((provider) => {
const fields = [provider.name, provider.notes, provider.websiteUrl];
return fields.some((field) =>
field?.toString().toLowerCase().includes(keyword)
);
});
}, [searchTerm, sortedProviders]);
if (isLoading) {
return (
<div className="space-y-3">
{[0, 1, 2].map((index) => (
<div
key={index}
className="h-28 w-full rounded-lg border border-dashed border-muted-foreground/40 bg-muted/40"
className="w-full border border-dashed rounded-lg h-28 border-muted-foreground/40 bg-muted/40"
/>
))}
</div>
@@ -125,18 +180,18 @@ export function ProviderList({
return <ProviderEmptyState onCreate={onCreate} />;
}
return (
const renderProviderList = () => (
<DndContext
sensors={sensors}
collisionDetection={closestCenter}
onDragEnd={handleDragEnd}
>
<SortableContext
items={sortedProviders.map((provider) => provider.id)}
items={filteredProviders.map((provider) => provider.id)}
strategy={verticalListSortingStrategy}
>
<div className="space-y-3">
{sortedProviders.map((provider) => (
{filteredProviders.map((provider) => (
<SortableProviderCard
key={provider.id}
provider={provider}
@@ -166,6 +221,84 @@ export function ProviderList({
</SortableContext>
</DndContext>
);
return (
<div className="mt-4 space-y-4">
<AnimatePresence>
{isSearchOpen && (
<motion.div
key="provider-search"
initial={{ opacity: 0, y: -8, scale: 0.98 }}
animate={{ opacity: 1, y: 0, scale: 1 }}
exit={{ opacity: 0, y: -8, scale: 0.98 }}
transition={{ duration: 0.18, ease: "easeOut" }}
className="fixed left-1/2 top-[6.5rem] z-40 w-[min(90vw,26rem)] -translate-x-1/2 sm:right-6 sm:left-auto sm:translate-x-0"
>
<div className="p-4 space-y-3 border shadow-md rounded-2xl border-white/10 bg-background/95 shadow-black/20 backdrop-blur-md">
<div className="relative flex items-center gap-2">
<Search className="absolute w-4 h-4 -translate-y-1/2 pointer-events-none left-3 top-1/2 text-muted-foreground" />
<Input
ref={searchInputRef}
value={searchTerm}
onChange={(event) => setSearchTerm(event.target.value)}
placeholder={t("provider.searchPlaceholder", {
defaultValue: "Search name, notes, or URL...",
})}
aria-label={t("provider.searchAriaLabel", {
defaultValue: "Search providers",
})}
className="pr-16 pl-9"
/>
{searchTerm && (
<Button
variant="ghost"
size="sm"
className="absolute text-xs -translate-y-1/2 right-11 top-1/2"
onClick={() => setSearchTerm("")}
>
{t("common.clear", { defaultValue: "Clear" })}
</Button>
)}
<Button
variant="ghost"
size="icon"
className="ml-auto"
onClick={() => setIsSearchOpen(false)}
aria-label={t("provider.searchCloseAriaLabel", {
defaultValue: "Close provider search",
})}
>
<X className="w-4 h-4" />
</Button>
</div>
<div className="flex flex-wrap items-center justify-between gap-2 text-[11px] text-muted-foreground">
<span>
{t("provider.searchScopeHint", {
defaultValue: "Matches provider name, notes, and URL.",
})}
</span>
<span>
{t("provider.searchCloseHint", {
defaultValue: "Press Esc to close",
})}
</span>
</div>
</div>
</motion.div>
)}
</AnimatePresence>
{filteredProviders.length === 0 ? (
<div className="px-6 py-8 text-sm text-center border border-dashed rounded-lg border-border text-muted-foreground">
{t("provider.noSearchResults", {
defaultValue: "No providers match your search.",
})}
</div>
) : (
renderProviderList()
)}
</div>
);
}
interface SortableProviderCardProps {
+6
View File
@@ -87,6 +87,12 @@
"removeFromClaudePlugin": "Remove from Claude plugin",
"dragToReorder": "Drag to reorder",
"dragHandle": "Drag to reorder",
"searchPlaceholder": "Search name, notes, or URL...",
"searchAriaLabel": "Search providers",
"searchScopeHint": "Matches provider name, notes, and URL.",
"searchCloseHint": "Press Esc to close",
"searchCloseAriaLabel": "Close provider search",
"noSearchResults": "No providers match your search.",
"duplicate": "Duplicate",
"sortUpdateFailed": "Failed to update sort order",
"configureUsage": "Configure usage query",
+6
View File
@@ -87,6 +87,12 @@
"removeFromClaudePlugin": "Claude プラグインから解除",
"dragToReorder": "ドラッグで並べ替え",
"dragHandle": "ドラッグで並べ替え",
"searchPlaceholder": "名前・メモ・URLで検索...",
"searchAriaLabel": "プロバイダーを検索",
"searchScopeHint": "名前・メモ・URL を対象に検索します。",
"searchCloseHint": "Esc で閉じる",
"searchCloseAriaLabel": "検索を閉じる",
"noSearchResults": "一致するプロバイダーがありません。",
"duplicate": "複製",
"sortUpdateFailed": "並び順の更新に失敗しました",
"configureUsage": "利用状況を設定",
+6
View File
@@ -87,6 +87,12 @@
"removeFromClaudePlugin": "从 Claude 插件移除",
"dragToReorder": "拖拽以重新排序",
"dragHandle": "拖拽排序",
"searchPlaceholder": "按名称/备注/网址搜索供应商...",
"searchAriaLabel": "搜索供应商",
"searchScopeHint": "根据名称、备注和官网链接匹配结果。",
"searchCloseHint": "按 Esc 关闭",
"searchCloseAriaLabel": "关闭供应商搜索",
"noSearchResults": "没有符合搜索条件的供应商。",
"duplicate": "复制",
"sortUpdateFailed": "排序更新失败",
"configureUsage": "配置用量查询",
+43
View File
@@ -251,4 +251,47 @@ describe("ProviderList Component", () => {
"claude",
);
});
it("filters providers with the search input", () => {
const providerAlpha = createProvider({ id: "alpha", name: "Alpha Labs" });
const providerBeta = createProvider({ id: "beta", name: "Beta Works" });
useDragSortMock.mockReturnValue({
sortedProviders: [providerAlpha, providerBeta],
sensors: [],
handleDragEnd: vi.fn(),
});
render(
<ProviderList
providers={{ alpha: providerAlpha, beta: providerBeta }}
currentProviderId=""
appId="claude"
onSwitch={vi.fn()}
onEdit={vi.fn()}
onDelete={vi.fn()}
onDuplicate={vi.fn()}
onOpenWebsite={vi.fn()}
/>,
);
fireEvent.keyDown(window, { key: "f", metaKey: true });
const searchInput = screen.getByPlaceholderText(
"Search name, notes, or URL...",
);
// Initially both providers are rendered
expect(screen.getByTestId("provider-card-alpha")).toBeInTheDocument();
expect(screen.getByTestId("provider-card-beta")).toBeInTheDocument();
fireEvent.change(searchInput, { target: { value: "beta" } });
expect(screen.queryByTestId("provider-card-alpha")).not.toBeInTheDocument();
expect(screen.getByTestId("provider-card-beta")).toBeInTheDocument();
fireEvent.change(searchInput, { target: { value: "gamma" } });
expect(screen.queryByTestId("provider-card-alpha")).not.toBeInTheDocument();
expect(screen.queryByTestId("provider-card-beta")).not.toBeInTheDocument();
expect(
screen.getByText("No providers match your search."),
).toBeInTheDocument();
});
});