import { invoke } from "@tauri-apps/api/core"; import { useCallback, useEffect, useMemo, useState } from "react"; import { boundRuntimeEventSchema, chatSessionSchema, connectionRuntimeStatusSchema, type BoundRuntimeEvent, type ChatMessage, type ChatSlot, type ConnectionRuntimeStatus, storedChatMessageSchema, } from "./types"; const emptyStatus: ConnectionRuntimeStatus = { companion: { slot: "companion", state: "disconnected" }, operations: { slot: "operations", state: "disconnected" }, }; function payloadString( event: BoundRuntimeEvent, key: string, ): string | undefined { if (!event.payload || typeof event.payload !== "object") return undefined; const value = (event.payload as Record)[key]; return typeof value === "string" ? value : undefined; } export interface ChatPanelProps { fixedSlot?: ChatSlot; } export function ChatPanel({ fixedSlot }: ChatPanelProps) { const [status, setStatus] = useState(emptyStatus); const [messages, setMessages] = useState([]); const [activeSlot, setActiveSlot] = useState( fixedSlot ?? "companion", ); const selectedSlot = fixedSlot ?? activeSlot; const [draft, setDraft] = useState(""); const [error, setError] = useState(null); const [unreadCounts, setUnreadCounts] = useState>({ companion: 0, operations: 0, }); const activeMessages = useMemo( () => messages.filter((item) => item.slot === selectedSlot), [messages, selectedSlot], ); const refresh = useCallback(async () => { try { const result = await invoke("connection_runtime_status"); setStatus(connectionRuntimeStatusSchema.parse(result)); setError(null); return true; } catch (reason) { setError(reason instanceof Error ? reason.message : String(reason)); return false; } }, []); const drainEvents = useCallback(async () => { try { const result = await invoke("drain_connection_runtime_events", { request: { limit: 64 }, }); const events = boundRuntimeEventSchema.array().parse(result); if (events.length > 0) setMessages((current) => applyRuntimeEvents(current, events)); } catch { // Browser fallback keeps the shell usable without Rust IPC. } }, []); useEffect(() => { const snapshot = status[selectedSlot]; if (!snapshot.profileId || !snapshot.serverInstanceId) return; let cancelled = false; void invoke("list_chat_sessions", { request: { profileId: snapshot.profileId, serverInstanceId: snapshot.serverInstanceId, }, }) .then((result) => { if (cancelled) return; const sessions = chatSessionSchema.array().parse(result); setUnreadCounts((current) => ({ ...current, [selectedSlot]: sessions.reduce( (total, session) => total + session.unreadCount, 0, ), })); }) .catch(() => undefined); return () => { cancelled = true; }; }, [selectedSlot, status]); useEffect(() => { const snapshot = status[selectedSlot]; if ( !snapshot.profileId || !snapshot.serverInstanceId || !snapshot.activeSessionId ) return; void invoke("mark_chat_session_read", { request: { profileId: snapshot.profileId, serverInstanceId: snapshot.serverInstanceId, sessionId: snapshot.activeSessionId, }, }).catch(() => undefined); setUnreadCounts((current) => ({ ...current, [selectedSlot]: 0 })); }, [selectedSlot, status]); useEffect(() => { const snapshot = status[selectedSlot]; if ( !snapshot.profileId || !snapshot.serverInstanceId || !snapshot.activeSessionId ) return; let cancelled = false; void invoke("load_chat_messages", { request: { profileId: snapshot.profileId, serverInstanceId: snapshot.serverInstanceId, sessionId: snapshot.activeSessionId, limit: 100, }, }) .then((result) => { if (cancelled) return; const records = storedChatMessageSchema.array().parse(result); setMessages((current) => { const otherSlots = current.filter( (item) => item.slot !== selectedSlot, ); const restored = records.map((record) => ({ id: record.messageId, slot: record.slot, role: record.role, content: record.content, streaming: record.streaming, error: record.error, })); return otherSlots.concat(restored); }); }) .catch(() => undefined); return () => { cancelled = true; }; }, [selectedSlot, status]); useEffect(() => { let timer: number | undefined; void refresh().then((available) => { if (!available) return; timer = window.setInterval(() => { void refresh(); void drainEvents(); }, 500); }); return () => { if (timer !== undefined) window.clearInterval(timer); }; }, [drainEvents, refresh]); const send = async () => { const message = draft.trim(); if (!message) return; const id = "local-" + Date.now(); setDraft(""); setMessages((current) => current.concat({ id, slot: selectedSlot, role: "user", content: message, }), ); try { await invoke("send_connection_slot_message", { request: { slot: selectedSlot, message }, }); setError(null); } catch (reason) { setError(reason instanceof Error ? reason.message : String(reason)); setMessages((current) => current.map((item) => item.id === id ? { ...item, error: true } : item, ), ); } }; return (

Q1 shared chat runtime

统一聊天运行时

主页面、快速聊天和气泡共享同一套消息状态。

{(["companion", "operations"] as const).map((slot) => ( ))}
Profile:{status[selectedSlot].profileId ?? "未连接"} Session:{status[selectedSlot].activeSessionId ?? "未建立"} 状态:{connectionStateLabel(status[selectedSlot].state)}
{activeMessages.length === 0 ? (

当前槽位还没有消息。连接 Profile 后即可开始聊天。

) : ( activeMessages.map((message) => (
{message.role === "user" ? "我" : message.role === "assistant" ? "AstrBot" : "系统"}

{message.content || "…"}

{message.streaming ? 生成中 : null}
)) )}
{error ?

{error}

: null}
{ event.preventDefault(); void send(); }} >