import { invoke } from "@tauri-apps/api/core"; import { listen } from "@tauri-apps/api/event"; import { useCallback, useEffect, useRef, useState } from "react"; import { ChatPanel } from "./features/chat/ChatPanel"; import { StatusBubble } from "./features/chat/StatusBubble"; import { ProfileManager } from "./features/profiles/ProfileManager"; import { PetPackImporter } from "./features/pet/PetPackImporter"; import { connectionRuntimeStatusSchema } from "./features/chat/types"; import aemeathSpritesheet from "./features/pet/assets/aemeath/aemeath-spritesheet.png?inline"; import { bootstrapStatusSchema, type BootstrapStatus } from "./types/bootstrap"; type PageKey = "chat" | "connections" | "desktop" | "pet" | "diagnostics"; type ChatLayout = "single" | "focus-companion" | "focus-operations"; type ChatSlot = "companion" | "operations"; type PetDisplayMode = "app-ui" | "desktop-floating"; const initialStatus: BootstrapStatus = { appVersion: "unknown", platform: "unknown", rustCore: "pending", protocolVersion: "desktop-v1alpha1", databaseSchemaVersion: 4, }; const AEMEATH_SPRITESHEET = aemeathSpritesheet; const AEMEATH_FRAMES: Record<"idle" | "working" | "resting" | "speaking" | "error", number[]> = { idle: [0, 1, 2, 3, 4, 5], working: [80, 81, 82, 83, 84, 85, 86, 87, 104, 105, 106, 107, 108, 109, 110, 111], resting: [48, 49, 50, 51, 52, 53], speaking: [72, 73, 74, 75, 76, 77, 78, 79], error: [40, 41, 42, 43, 44, 45, 46, 47], }; 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 [status, setStatus] = useState(initialStatus); const [error, setError] = useState(null); const [chatLayout, setChatLayout] = useState("single"); 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(() => { 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 (
{error ?

IPC 暂不可用:{error}

: null} {page === "chat" ? ( void invoke("open_quick_chat_window", { slot: quickTarget }) } /> ) : 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 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: 24, y: 96 }; } catch { return { x: 24, y: 96 }; } }); const dragRef = useRef<{ pointerId: number; offsetX: number; offsetY: number } | null>(null); const savePosition = (x: number, y: number) => { const next = { x: Math.max(0, Math.min(x, window.innerWidth - 188)), y: Math.max(0, Math.min(y, window.innerHeight - 226)), }; setPosition(next); localStorage.setItem("astrbot.petPosition", JSON.stringify(next)); }; 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 PageHeader({ page }: { page: PageKey }) { const current = navigation.find((item) => item.key === page) ?? navigation[0]; return (

AstrBot Desktop

{current.label}

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

双槽位架构
); } function ChatPage({ chatLayout, quickTarget, onLayoutChange, onOpenQuickChat, }: { chatLayout: ChatLayout; quickTarget: ChatSlot; onLayoutChange: (layout: ChatLayout) => void; onOpenQuickChat: () => void; }) { return (
Conversation hub

今天想和哪个实例聊天?

陪伴实例适合日常交流,运维实例用于经过确认的本机诊断提案。

Workspace view 对话布局
onLayoutChange("single")} > 单面板 onLayoutChange("focus-companion")} > 聚焦陪伴 onLayoutChange("focus-operations")} > 聚焦运维
快速聊天目标:{slotLabel(quickTarget)}
); } function LayoutButton({ active, children, onClick, }: { active: boolean; children: React.ReactNode; onClick: () => void; }) { return ( ); } function DesktopBehaviorPage({ bubbleTarget, quickTarget, onBubbleTargetChange, onQuickTargetChange, onOpenQuickChat, }: { bubbleTarget: "main" | "quick"; quickTarget: ChatSlot; onBubbleTargetChange: (value: "main" | "quick") => void; onQuickTargetChange: (value: ChatSlot) => void; onOpenQuickChat: () => void; }) { return (
气泡状态显示已预留
Desktop companion

后续桌面能力

托盘与单实例 窗口置顶开关 多显示器策略 游戏模式靠边活动

这些能力先保留为独立设置区,后续接入 Rust 本机能力层,不会与聊天状态混在一起。

); } function PetPage({ displayMode, onDisplayModeChange, }: { displayMode: PetDisplayMode; onDisplayModeChange: (value: PetDisplayMode) => void; }) { return (
{displayMode === "app-ui" ? (
App UI

应用内活动桌宠

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

) : null}
{displayMode === "desktop-floating" ? ( ) : ( 应用内活动桌宠已显示,可直接拖动 )}
); } function DesktopPetView({ embedded = false }: { embedded?: boolean }) { const [state, setState] = useState<"idle" | "working" | "resting" | "speaking" | "error">("idle"); const [frameIndex, setFrameIndex] = useState(0); const [spriteReady, setSpriteReady] = useState(false); const [spriteError, setSpriteError] = useState(null); const [gameMode, setGameMode] = useState(false); const spriteImageRef = useRef(null); const spriteCanvasRef = useRef(null); useEffect(() => { if (embedded) return; document.documentElement.classList.add("pet-view"); return () => document.documentElement.classList.remove("pet-view"); }, [embedded]); useEffect(() => { let unlisten: (() => void) | undefined; void listen("pet-game-mode-toggle", () => setGameMode((current) => !current)).then((cleanup) => { unlisten = cleanup; }); return () => unlisten?.(); }, []); useEffect(() => { const image = new Image(); image.onload = () => { spriteImageRef.current = image; setSpriteError(null); setSpriteReady(true); }; image.onerror = () => { setSpriteError("????????"); }; image.src = AEMEATH_SPRITESHEET; return () => { image.onload = null; }; }, []); useEffect(() => { let cancelled = false; const refreshPetState = async () => { try { const result = connectionRuntimeStatusSchema.parse( await invoke("connection_runtime_status"), ); if (cancelled) return; const states = [result.companion.state, result.operations.state]; if (states.includes("authExpired") || states.includes("fatalError")) { setState("error"); } else if (states.includes("syncing")) { setState("working"); } else if (states.includes("reconnecting")) { setState("speaking"); } else if (states.every((value) => value === "disconnected" || value === "offline")) { setState("resting"); } else { setState("idle"); } } catch { if (!cancelled) setState("idle"); } }; void refreshPetState(); const refreshTimer = window.setInterval(() => void refreshPetState(), 2000); const timer = window.setInterval(() => { setState((current) => (current === "idle" ? "resting" : current === "resting" ? "idle" : current)); }, 4200); return () => { cancelled = true; window.clearInterval(refreshTimer); window.clearInterval(timer); }; }, []); useEffect(() => { setFrameIndex(0); const frames = AEMEATH_FRAMES[state]; const timer = window.setInterval(() => { setFrameIndex((current) => (current + 1) % frames.length); }, state === "resting" ? 180 : 125); return () => window.clearInterval(timer); }, [state]); const frame = AEMEATH_FRAMES[state][frameIndex % AEMEATH_FRAMES[state].length]; const frameRow = Math.floor(frame / 8); const frameColumn = frame % 8; useEffect(() => { const canvas = spriteCanvasRef.current; const image = spriteImageRef.current; if (!canvas || !image || !spriteReady) return; const context = canvas.getContext("2d"); if (!context) { setSpriteError("?? Canvas ????"); return; } try { context.clearRect(0, 0, 192, 208); context.imageSmoothingEnabled = false; context.drawImage(image, frameColumn * 192, frameRow * 208, 192, 208, 0, 0, 192, 208); } catch (reason) { setSpriteError(reason instanceof Error ? reason.message : "??????"); } }, [frameColumn, frameRow, spriteReady]); return (
{ event.preventDefault(); void invoke("show_pet_context_menu"); }} >
setSpriteReady(true)} onError={() => setSpriteError("????????")} style={{ left: -(frameColumn * 192), top: -(frameRow * 208), }} />
{spriteError ? {spriteError} : null} {!spriteReady && !spriteError ? Loading pet... : null} {state === "working" ? "正在写写画画" : state === "resting" ? "休息中" : state === "speaking" ? "正在回应" : state === "error" ? "需要重新登录或检查连接" : "陪伴中"}
); } function DiagnosticsPage({ status, onRefresh, }: { status: BootstrapStatus; onRefresh: () => void; }) { return (
Security boundary

本机能力保持可审计

  • 凭据只在 Rust 与 Windows 安全存储之间流动。
  • 两个 REST/SSE 槽位保持独立状态、会话、消息与未读数。
  • 本机操作必须经过白名单、角色、路径和用户授权。
  • 文件事务默认保留源文件,不静默覆盖目标。
); } function SettingCard({ title, description, children, }: { title: string; description: string; children: React.ReactNode; }) { return (
Settings

{title}

{description}

{children}
); } function slotLabel(slot: ChatSlot) { return slot === "companion" ? "陪伴实例" : "运维实例"; } interface StatusCardProps { label: string; value: string; } function StatusCard({ label, value }: StatusCardProps) { return (
{label} {value}
); }