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 { errorMessage } from "./lib/errorMessage"; import { petPositionModeSchema, petWindowPreferencesSchema, type PetPositionMode, } from "./features/pet/types"; 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"; /// Shared with `ChatPanel`, which portals its slot tabs into this element. export const WINDOW_CHROME_MOUNT_ID = "window-chrome-mount"; 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(errorMessage(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(errorMessage(reason)); }); }, [isBubbleView, isPetView, isQuickView, petDisplayMode]); if (isBubbleView) return ; // `DesktopPetView` is lazy and this branch returns before the shell's own // boundary, so it had none. React 19 turned out to tolerate that — removing // this wrapper still rendered the pet — so it is not the reason the floating // pet does not appear. Kept because relying on that tolerance is not a // contract, and the bubble and quick views already have their own. if (isPetView) { return ( ); } if (isQuickView) { return (
); } return (
setTheme((current) => (current === "dark" ? "light" : "dark")) } onError={setError} />
{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, onError, }: { theme: ThemeMode; onToggleTheme: () => void; onError: (message: string) => 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; } }, []); /// Every one of these is an ACL-gated IPC call. They used to be bare /// `void ...()` expressions, so when the capability set was missing the /// window permissions the rejection was swallowed and the buttons simply did /// nothing, with no way to tell that from an unwired handler. const runWindowAction = async (action: () => Promise) => { if (!currentWindow) return; try { await action(); } catch (reason) { onError(errorMessage(reason)); } }; const toggleMaximize = () => runWindowAction(async () => { await currentWindow!.toggleMaximize(); setMaximized(await currentWindow!.isMaximized()); }); return (
void toggleMaximize()} onMouseDown={(event) => { if ( event.button === 0 && !(event.target as HTMLElement).closest( '[data-tauri-drag-region="false"]', ) ) { void runWindowAction(() => currentWindow!.startDragging()); } }} > AstrBot Desktop {/* Mount point for controls that belong to the active page but should sit in the title bar. ChatPanel portals its slot tabs here, which keeps the slot state and its status polling where they already live instead of lifting both into the shell. */}
); } 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 active = true; let unlisten: (() => void) | undefined; void listen("pet-hide-requested", () => setVisible(false)) .then((cleanup) => { if (active) { unlisten = cleanup; } else { cleanup(); } }) .catch(() => undefined); return () => { active = false; unlisten?.(); unlisten = undefined; }; }, []); 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 (

加载中…

); } 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(false); const [gameMode, setGameMode] = useState(false); useEffect(() => { void invoke("list_monitor_geometries") .then((value) => setMonitors(value as typeof monitors)) .catch(() => setMonitors([])); }, []); // Adopt what the window is actually doing. These controls used to start from // literals, so leaving the page and coming back showed monitor 1 / safe edge // / always-on-top regardless of the truth — and because every edit re-sends // the whole payload, the next single change pushed those wrong values back // onto the window as if the user had chosen them. useEffect(() => { let cancelled = false; void invoke("pet_window_preferences") .then((value) => { if (cancelled) return; const preferences = petWindowPreferencesSchema.parse(value); setMonitorIndex(preferences.monitorIndex ?? 0); setPositionMode(preferences.positionMode); setAlwaysOnTop(preferences.alwaysOnTop); setGameMode(preferences.gameMode); }) .catch(() => undefined); return () => { cancelled = true; }; }, []); const applyPetPreferences = ( next: Partial<{ positionMode: PetPositionMode; 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}
); }