import { invoke } from "@tauri-apps/api/core"; import { listen } from "@tauri-apps/api/event"; import { getCurrentWindow } from "@tauri-apps/api/window"; import { lazy, Suspense, useCallback, useEffect, useRef, useState, } from "react"; import { ChatPanel } from "./features/chat/ChatPanel"; import { StatusBubble } from "./features/chat/StatusBubble"; const ProfileManager = lazy(() => import("./features/profiles/ProfileManager").then(({ ProfileManager }) => ({ default: ProfileManager, })), ); const PetPackImporter = lazy(() => import("./features/pet/PetPackImporter").then(({ PetPackImporter }) => ({ default: PetPackImporter, })), ); const DesktopBehaviorPage = lazy(() => import("./pages/SettingsPages").then(({ DesktopBehaviorPage }) => ({ default: DesktopBehaviorPage, })), ); const DesktopPetView = lazy(() => import("./features/pet/DesktopPetView").then(({ DesktopPetView }) => ({ default: DesktopPetView, })), ); const DiagnosticsPage = lazy(() => import("./pages/SettingsPages").then(({ DiagnosticsPage }) => ({ default: DiagnosticsPage, })), ); import { bootstrapStatusSchema, type BootstrapStatus } from "./types/bootstrap"; type PageKey = "chat" | "connections" | "desktop" | "pet" | "diagnostics"; type ChatSlot = "companion" | "operations"; type PetDisplayMode = "app-ui" | "desktop-floating"; type ThemeMode = "dark" | "light"; const initialStatus: BootstrapStatus = { appVersion: "unknown", platform: "unknown", rustCore: "pending", protocolVersion: "desktop-v1alpha1", databaseSchemaVersion: 4, }; const navigation: Array<{ key: PageKey; label: string; description: string }> = [ { key: "chat", label: "聊天", description: "陪伴与运维对话" }, { key: "connections", label: "连接", description: "实例与槽位管理" }, { key: "desktop", label: "桌面行为", description: "快速聊天与状态气泡" }, { key: "pet", label: "桌宠", description: "形象与活动范围" }, { key: "diagnostics", label: "诊断与设置", description: "运行状态与安全边界", }, ]; export function App() { const params = new URLSearchParams(window.location.search); const view = params.get("view"); const isQuickView = view === "quick"; const isBubbleView = view === "bubble"; const isPetView = view === "pet" || window.location.hash === "#pet" || document.documentElement.dataset.astrbotPet === "true"; const quickSlot = params.get("slot"); const [page, setPage] = useState("chat"); const [theme, setTheme] = useState(() => localStorage.getItem("astrbot.theme") === "light" ? "light" : "dark", ); const [status, setStatus] = useState(initialStatus); const [error, setError] = useState(null); const [quickTarget, setQuickTarget] = useState(() => localStorage.getItem("astrbot.quickTarget") === "operations" ? "operations" : "companion", ); const [bubbleTarget, setBubbleTarget] = useState<"main" | "quick">(() => localStorage.getItem("astrbot.bubbleTarget") === "quick" ? "quick" : "main", ); const [petDisplayMode, setPetDisplayMode] = useState(() => localStorage.getItem("astrbot.petDisplayMode") === "desktop-floating" ? "desktop-floating" : "app-ui", ); const refreshStatus = useCallback(async () => { try { const result = await invoke("bootstrap_status"); setStatus(bootstrapStatusSchema.parse(result)); setError(null); } catch (reason) { setError(reason instanceof Error ? reason.message : String(reason)); } }, []); useEffect(() => { document.documentElement.dataset.theme = theme; localStorage.setItem("astrbot.theme", theme); }, [theme]); useEffect(() => { void refreshStatus(); }, [refreshStatus]); useEffect(() => { if (isBubbleView || isPetView || isQuickView) return; const command = petDisplayMode === "desktop-floating" ? "open_pet_window" : "close_pet_window"; void invoke(command).catch((reason) => { setError(reason instanceof Error ? reason.message : String(reason)); }); }, [isBubbleView, isPetView, isQuickView, petDisplayMode]); if (isBubbleView) return ; if (isPetView) return ; if (isQuickView) { return (
); } return (
setTheme((current) => (current === "dark" ? "light" : "dark")) } />
{page === "chat" ? null : } {error ? (

IPC 暂不可用:{error}

) : null} }> {page === "chat" ? : null} {page === "connections" ? : null} {page === "desktop" ? ( { setBubbleTarget(value); localStorage.setItem("astrbot.bubbleTarget", value); }} onQuickTargetChange={(value) => { setQuickTarget(value); localStorage.setItem("astrbot.quickTarget", value); }} onOpenQuickChat={() => void invoke("open_quick_chat_window", { slot: quickTarget }) } /> ) : null} {page === "pet" ? ( { setPetDisplayMode(value); localStorage.setItem("astrbot.petDisplayMode", value); }} /> ) : null} {page === "diagnostics" ? ( void refreshStatus()} /> ) : null}
{petDisplayMode === "app-ui" ? ( ) : null}
); } function WindowChrome({ theme, onToggleTheme, }: { theme: ThemeMode; onToggleTheme: () => void; }) { const [currentWindow, setCurrentWindow] = useState | null>(null); const [maximized, setMaximized] = useState(false); useEffect(() => { try { const windowHandle = getCurrentWindow(); setCurrentWindow(windowHandle); void windowHandle.isMaximized().then(setMaximized); } catch { return; } }, []); const toggleMaximize = async () => { if (!currentWindow) return; await currentWindow.toggleMaximize(); setMaximized(await currentWindow.isMaximized()); }; return (
void toggleMaximize()} onMouseDown={(event) => { if (event.button === 0) void currentWindow?.startDragging(); }} > AstrBot Desktop
); } function InAppPetOverlay() { const [visible, setVisible] = useState(true); const [position, setPosition] = useState(() => { try { const saved = JSON.parse( localStorage.getItem("astrbot.petPosition") ?? "null", ); return saved && typeof saved.x === "number" && typeof saved.y === "number" ? saved : { x: window.innerWidth >= 720 ? 280 : 24, y: 96 }; } catch { return { x: window.innerWidth >= 720 ? 280 : 24, y: 96 }; } }); const dragRef = useRef<{ pointerId: number; offsetX: number; offsetY: number; } | null>(null); const clampPosition = useCallback((x: number, y: number) => { const safeLeft = window.innerWidth >= 720 ? 248 : 0; const maxX = Math.max(safeLeft, window.innerWidth - 188); return { x: Math.max(safeLeft, Math.min(x, maxX)), y: Math.max(0, Math.min(y, window.innerHeight - 226)), }; }, []); const savePosition = (x: number, y: number) => { const next = clampPosition(x, y); setPosition(next); localStorage.setItem("astrbot.petPosition", JSON.stringify(next)); }; useEffect(() => { const normalizePosition = () => { const next = clampPosition(position.x, position.y); if (next.x === position.x && next.y === position.y) return; setPosition(next); localStorage.setItem("astrbot.petPosition", JSON.stringify(next)); }; normalizePosition(); window.addEventListener("resize", normalizePosition); return () => window.removeEventListener("resize", normalizePosition); }, [clampPosition, position.x, position.y]); useEffect(() => { let unlisten: (() => void) | undefined; void listen("pet-hide-requested", () => setVisible(false)).then( (cleanup) => { unlisten = cleanup; }, ); return () => unlisten?.(); }, []); return visible ? (
{ event.preventDefault(); void invoke("show_pet_context_menu"); }} onPointerDown={(event) => { if (event.button !== 0) return; event.currentTarget.setPointerCapture(event.pointerId); dragRef.current = { pointerId: event.pointerId, offsetX: event.clientX - position.x, offsetY: event.clientY - position.y, }; }} onPointerMove={(event) => { if (dragRef.current?.pointerId !== event.pointerId) return; savePosition( event.clientX - dragRef.current.offsetX, event.clientY - dragRef.current.offsetY, ); }} onPointerUp={(event) => { if (dragRef.current?.pointerId === event.pointerId) dragRef.current = null; }} onPointerCancel={() => { dragRef.current = null; }} >
) : null; } function navIcon(page: PageKey) { return { chat: "⌁", connections: "◎", desktop: "◈", pet: "✦", diagnostics: "⚙", }[page]; } function PageLoading() { return (

Loading?

); } function PageHeader({ page }: { page: PageKey }) { const current = navigation.find((item) => item.key === page) ?? navigation[0]; return (

AstrBot Desktop

{current.label}

{current.description},所有本机能力都经过客户端权限边界。

双槽位架构
); } function ChatPage() { return (
); } function PetPage({ displayMode, onDisplayModeChange, }: { displayMode: PetDisplayMode; onDisplayModeChange: (value: PetDisplayMode) => void; }) { const [monitors, setMonitors] = useState< Array<{ name?: string; width: number; height: number; scaleFactor: number; isPrimary: boolean; }> >([]); const [monitorIndex, setMonitorIndex] = useState(0); const [positionMode, setPositionMode] = useState("edge"); const [alwaysOnTop, setAlwaysOnTop] = useState(true); const [gameMode, setGameMode] = useState(false); useEffect(() => { void invoke("list_monitor_geometries") .then((value) => setMonitors(value as typeof monitors)) .catch(() => setMonitors([])); }, []); const applyPetPreferences = ( next: Partial<{ positionMode: string; monitorIndex: number; alwaysOnTop: boolean; gameMode: boolean; }> = {}, ) => { const preferences = { positionMode: next.positionMode ?? positionMode, monitorIndex: next.monitorIndex ?? monitorIndex, alwaysOnTop: next.alwaysOnTop ?? alwaysOnTop, gameMode: next.gameMode ?? gameMode, }; void invoke("set_pet_window_preferences", { preferences }).catch( () => undefined, ); }; return (
{displayMode === "app-ui" ? (
App UI

应用内活动桌宠

桌宠已叠加在主界面上,可直接拖动;关闭后可重新打开应用。

) : null}
{displayMode === "desktop-floating" ? ( ) : ( 应用内活动桌宠已显示,可直接拖动 )}
); } function SettingCard({ title, description, children, }: { title: string; description: string; children: React.ReactNode; }) { return (
Settings

{title}

{description}

{children}
); }