AstrBot-Desktop/src/features/chat/ChatPanel.tsx

357 行
11 KiB
TypeScript

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<string, unknown>)[key];
return typeof value === "string" ? value : undefined;
}
export function ChatPanel() {
const [status, setStatus] = useState(emptyStatus);
const [messages, setMessages] = useState<ChatMessage[]>([]);
const [activeSlot, setActiveSlot] = useState<ChatSlot>("companion");
const [draft, setDraft] = useState("");
const [error, setError] = useState<string | null>(null);
const [unreadCounts, setUnreadCounts] = useState<Record<ChatSlot, number>>({
companion: 0,
operations: 0,
});
const activeMessages = useMemo(
() => messages.filter((item) => item.slot === activeSlot),
[messages, activeSlot],
);
const refresh = useCallback(async () => {
try {
const result = await invoke<unknown>("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<unknown>("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[activeSlot];
if (!snapshot.profileId || !snapshot.serverInstanceId) return;
let cancelled = false;
void invoke<unknown>("list_chat_sessions", {
request: {
profileId: snapshot.profileId,
serverInstanceId: snapshot.serverInstanceId,
},
})
.then((result) => {
if (cancelled) return;
const sessions = chatSessionSchema.array().parse(result);
setUnreadCounts((current) => ({
...current,
[activeSlot]: sessions.reduce(
(total, session) => total + session.unreadCount,
0,
),
}));
})
.catch(() => undefined);
return () => {
cancelled = true;
};
}, [activeSlot, status]);
useEffect(() => {
const snapshot = status[activeSlot];
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, [activeSlot]: 0 }));
}, [activeSlot, status]);
useEffect(() => {
const snapshot = status[activeSlot];
if (
!snapshot.profileId ||
!snapshot.serverInstanceId ||
!snapshot.activeSessionId
)
return;
let cancelled = false;
void invoke<unknown>("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 !== activeSlot);
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;
};
}, [activeSlot, 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: activeSlot, role: "user", content: message }),
);
try {
await invoke("send_connection_slot_message", {
request: { slot: activeSlot, 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 (
<section className="chat-panel" aria-label="聊天面板">
<div className="chat-heading">
<div>
<p className="eyebrow">Q1 shared chat runtime</p>
<h2>统一聊天运行时</h2>
<p className="chat-note">
主页面、快速聊天和气泡共享同一套消息状态。
</p>
</div>
<div className="chat-slot-tabs" role="tablist" aria-label="聊天槽位">
{(["companion", "operations"] as const).map((slot) => (
<button
className={activeSlot === slot ? "chat-slot active" : "chat-slot"}
key={slot}
onClick={() => setActiveSlot(slot)}
role="tab"
aria-selected={activeSlot === slot}
type="button"
>
{slot === "companion" ? "陪伴" : "运维"}
{unreadCounts[slot] > 0 ? (
<strong>{unreadCounts[slot]}</strong>
) : null}
<span>{connectionStateLabel(status[slot].state)}</span>
</button>
))}
</div>
</div>
<div className="chat-runtime-strip">
<span>Profile:{status[activeSlot].profileId ?? "未连接"}</span>
<span>Session:{status[activeSlot].activeSessionId ?? "未建立"}</span>
<span>状态:{connectionStateLabel(status[activeSlot].state)}</span>
</div>
<div className="chat-message-list" aria-live="polite">
{activeMessages.length === 0 ? (
<p className="chat-empty">
当前槽位还没有消息。连接 Profile 后即可开始聊天。
</p>
) : (
activeMessages.map((message) => (
<article
className={
"chat-message " +
message.role +
(message.error ? " failed" : "")
}
key={message.id}
>
<span className="chat-message-role">
{message.role === "user"
? "我"
: message.role === "assistant"
? "AstrBot"
: "系统"}
</span>
<p>{message.content || "…"}</p>
{message.streaming ? <small>生成中</small> : null}
</article>
))
)}
</div>
{error ? <p className="chat-error">{error}</p> : null}
<form
className="chat-composer"
onSubmit={(event) => {
event.preventDefault();
void send();
}}
>
<textarea
aria-label="聊天消息"
onChange={(event) => setDraft(event.target.value)}
placeholder={
activeSlot === "companion"
? "和陪伴实例说点什么…"
: "向运维实例描述问题…"
}
value={draft}
rows={3}
/>
<button disabled={!draft.trim()} type="submit">
发送
</button>
</form>
</section>
);
}
function applyRuntimeEvents(
current: ChatMessage[],
events: BoundRuntimeEvent[],
): ChatMessage[] {
const next = current.map((item) => ({ ...item }));
for (const event of events) {
if (event.eventType === "message.delta") {
const id =
event.messageId || payloadString(event, "messageId") || event.eventId;
const delta =
payloadString(event, "delta") || payloadString(event, "content") || "";
const existing = next.find(
(item) => item.id === id && item.slot === event.slot,
);
if (existing) {
existing.content += delta;
existing.streaming = true;
} else
next.push({
id,
slot: event.slot,
role: "assistant",
content: delta,
streaming: true,
});
} else if (event.eventType === "message.completed") {
const id =
event.messageId || payloadString(event, "messageId") || event.eventId;
const existing = next.find(
(item) => item.id === id && item.slot === event.slot,
);
if (existing) existing.streaming = false;
else
next.push({
id,
slot: event.slot,
role: "assistant",
content: payloadString(event, "content") || "",
});
} else if (event.eventType === "error") {
next.push({
id: event.eventId,
slot: event.slot,
role: "system",
content: payloadString(event, "message") || "连接错误",
error: true,
});
} else if (event.eventType === "message.proactive") {
next.push({
id: event.eventId,
slot: event.slot,
role: "assistant",
content: payloadString(event, "content") || "",
});
}
}
return next;
}
function connectionStateLabel(
state: ConnectionRuntimeStatus["companion"]["state"],
): string {
const labels: Record<typeof state, string> = {
disconnected: "未连接",
connecting: "连接中",
authenticating: "认证中",
syncing: "同步中",
connected: "已连接",
reconnecting: "重连中",
authExpired: "认证已过期",
incompatible: "协议不兼容",
serverUnavailable: "服务不可用",
offline: "离线",
certificateChanged: "证书已变化",
fatalError: "连接错误",
};
return labels[state];
}