AstrBot-Desktop/src/features/chat/ChatPanel.tsx
YokiiroBW 529357523c
一些检测仍在等待运行
ci / Portable quality checks (push) Waiting to run
ci / Windows Tauri build (push) Waiting to run
feat(chat): follow the newest message in the conversation
The message list had no scroll code at all. Opening a conversation
landed at the top of the history, and every message sent or received
appeared below the fold, so reading a reply meant scrolling down by
hand each time.

Scroll to the tail when the rendered messages change and when the slot
or session changes. Following stops as soon as the reader scrolls more
than 80px away from the bottom and resumes when they return, so reading
back through history is not interrupted by an arriving delta.

scrollTo carries the smooth behaviour but is not universally available —
jsdom has none — so it falls back to assigning scrollTop.

Refs: F-44 (audit P2-28).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-27 02:21:30 +08:00

1123 行
36 KiB
TypeScript

此文件含有模棱两可的 Unicode 字符

此文件含有可能会与其他字符混淆的 Unicode 字符。 如果您是想特意这样的,可以安全地忽略该警告。 使用 Escape 按钮显示他们。

import { invoke } from "@tauri-apps/api/core";
import { listen } from "@tauri-apps/api/event";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { errorMessage } from "../../lib/errorMessage";
import { MessageContent } from "./MessageContent";
import {
astrbotAttachmentSchema,
astrbotCapabilitySnapshotSchema,
boundRuntimeEventSchema,
chatSessionSchema,
connectionRuntimeStatusSchema,
type AstrBotAttachment,
type AstrBotCapabilitySnapshot,
type BoundRuntimeEvent,
type ChatSession,
mergeLoadedChatMessages,
remoteChatSessionSchema,
type ChatMessage,
type ChatSlot,
type RemoteChatSession,
type ConnectionRuntimeStatus,
storedChatMessageSchema,
slotRuntimeSnapshotSchema,
} 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 interface ChatPanelProps {
fixedSlot?: ChatSlot;
}
type SpeechRecognitionLike = {
lang: string;
interimResults: boolean;
onresult: ((event: unknown) => void) | null;
onerror: (() => void) | null;
onend: (() => void) | null;
start: () => void;
stop: () => void;
};
export function ChatPanel({ fixedSlot }: ChatPanelProps) {
const [status, setStatus] = useState(emptyStatus);
const [messages, setMessages] = useState<ChatMessage[]>([]);
const [remoteSessions, setRemoteSessions] = useState<RemoteChatSession[]>([]);
const [storedSessions, setStoredSessions] = useState<
Record<ChatSlot, ChatSession[]>
>({
companion: [],
operations: [],
});
const [activeSlot, setActiveSlot] = useState<ChatSlot>(
fixedSlot ?? "companion",
);
const selectedSlot = fixedSlot ?? activeSlot;
const selectedSnapshot = status[selectedSlot];
const selectedProfileId = selectedSnapshot.profileId;
const selectedServerInstanceId = selectedSnapshot.serverInstanceId;
const selectedSessionId = selectedSnapshot.activeSessionId;
const historySessionId =
selectedSessionId ?? storedSessions[selectedSlot][0]?.sessionId;
const selectedTransport = selectedSnapshot.transport;
const [draft, setDraft] = useState<Record<ChatSlot, string>>({
companion: "",
operations: "",
});
// Two separate errors on purpose. `refresh()` runs every 500ms and used to
// write the shared error on failure and clear it on success, so any send or
// upload error was wiped within half a second. The polling failure describes
// the IPC channel, not a slot, so it keeps its own state and the per-slot
// error is owned solely by user actions.
const [runtimeError, setRuntimeError] = useState<string | null>(null);
const [slotError, setSlotError] = useState<Record<ChatSlot, string | null>>({
companion: null,
operations: null,
});
const [capabilities, setCapabilities] =
useState<AstrBotCapabilitySnapshot | null>(null);
const [pendingAttachments, setPendingAttachments] = useState<
Record<ChatSlot, AstrBotAttachment[]>
>({
companion: [],
operations: [],
});
const [uploading, setUploading] = useState(false);
const [voiceListening, setVoiceListening] = useState(false);
const [sending, setSending] = useState<Record<ChatSlot, boolean>>({
companion: false,
operations: false,
});
const messageListRef = useRef<HTMLDivElement | null>(null);
/// Whether the view should follow new content.
///
/// Starts true so opening a conversation lands on the newest message, and
/// stays true until the reader scrolls up — following unconditionally would
/// yank someone out of the history they were reading.
const followTail = useRef(true);
const speechRecognition = useRef<{
start: () => void;
stop: () => void;
} | null>(null);
const [unreadCounts, setUnreadCounts] = useState<Record<ChatSlot, number>>({
companion: 0,
operations: 0,
});
const selectedAttachments = pendingAttachments[selectedSlot];
// A slot-scoped action error wins over the runtime-wide polling error.
const visibleError = slotError[selectedSlot] ?? runtimeError;
const activeMessages = useMemo(
() =>
messages.filter(
(item) =>
item.slot === selectedSlot &&
(!status[selectedSlot].activeSessionId ||
item.sessionId === status[selectedSlot].activeSessionId),
),
[messages, selectedSlot, status],
);
const visibleMessages = useMemo(
() =>
activeMessages.filter(
(message) =>
message.content.trim().length > 0 ||
message.streaming ||
message.error,
),
[activeMessages],
);
const displaySessions =
remoteSessions.length > 0
? remoteSessions
: storedSessions[selectedSlot].map((session) => ({
sessionId: session.sessionId,
displayName: undefined,
updatedAt: session.lastMessageAt,
}));
const refresh = useCallback(async () => {
try {
const result = await invoke<unknown>("connection_runtime_status");
const parsed = connectionRuntimeStatusSchema.safeParse(result);
if (!parsed.success) {
setRuntimeError("连接状态暂不可用,请检查连接配置。");
return false;
}
setStatus(parsed.data);
setRuntimeError(null);
return true;
} catch {
setRuntimeError("连接状态暂不可用,请检查本地运行时。");
return false;
}
}, []);
const reportSlotError = (slot: ChatSlot, message: string | null) => {
setSlotError((current) => ({ ...current, [slot]: message }));
};
/// Distance from the bottom that still counts as "reading the newest".
const TAIL_THRESHOLD_PX = 80;
const scrollToTail = useCallback((behavior: ScrollBehavior) => {
const list = messageListRef.current;
if (!list) return;
// `scrollTo` carries the smooth behaviour, but it is not universally
// available — jsdom has no implementation at all — so fall back to the
// property, which every engine supports.
if (typeof list.scrollTo === "function") {
list.scrollTo({ top: list.scrollHeight, behavior });
} else {
list.scrollTop = list.scrollHeight;
}
}, []);
// Follow the tail whenever the rendered messages change: a sent message, a
// streamed delta, or a freshly loaded history. The list had no scroll code at
// all, so every send left the new message below the fold.
useEffect(() => {
if (!followTail.current) return;
scrollToTail("smooth");
}, [visibleMessages, scrollToTail]);
// Opening a conversation, or switching slot or session, starts at the newest
// message rather than at the top.
useEffect(() => {
followTail.current = true;
const frame = window.requestAnimationFrame(() => scrollToTail("auto"));
return () => window.cancelAnimationFrame(frame);
}, [selectedSlot, historySessionId, scrollToTail]);
useEffect(() => {
// `listen()` resolves after the effect may already have been cleaned up.
// Assigning the unregister function unconditionally dropped it in that
// case, and under StrictMode's mount/cleanup/mount the first listener
// leaked permanently — every delta was then applied twice, doubling each
// character of the streamed reply.
let active = true;
let unlisten: (() => void) | undefined;
void listen<unknown>("connection-runtime-event", (event) => {
const parsed = boundRuntimeEventSchema.safeParse(event.payload);
if (parsed.success) {
setMessages((current) => applyRuntimeEvents(current, [parsed.data]));
}
})
.then((cleanup) => {
if (active) {
unlisten = cleanup;
} else {
cleanup();
}
})
.catch(() => undefined);
return () => {
active = false;
unlisten?.();
unlisten = undefined;
};
}, []);
useEffect(() => {
const snapshot = {
profileId: selectedProfileId,
serverInstanceId: selectedServerInstanceId,
activeSessionId: selectedSessionId,
transport: selectedTransport,
};
if (!snapshot.profileId || !snapshot.serverInstanceId) return;
let cancelled = false;
void invoke<unknown>("list_chat_sessions", {
request: {
profileId: snapshot.profileId,
slot: selectedSlot,
serverInstanceId: snapshot.serverInstanceId,
},
})
.then((result) => {
if (cancelled) return;
const sessions = chatSessionSchema.array().parse(result);
setStoredSessions((current) => ({
...current,
[selectedSlot]: sessions,
}));
setUnreadCounts((current) => ({
...current,
[selectedSlot]: sessions.reduce(
(total, session) => total + session.unreadCount,
0,
),
}));
})
.catch(() => undefined);
return () => {
cancelled = true;
};
}, [
selectedSlot,
selectedProfileId,
selectedServerInstanceId,
selectedSessionId,
historySessionId,
selectedTransport,
]);
useEffect(() => {
const snapshot = {
profileId: selectedProfileId,
serverInstanceId: selectedServerInstanceId,
activeSessionId: selectedSessionId,
transport: selectedTransport,
};
setRemoteSessions([]);
if (!snapshot.profileId) return;
let cancelled = false;
void invoke<unknown>("connection_slot_sessions", {
request: { slot: selectedSlot },
})
.then((result) => {
if (cancelled) return;
setRemoteSessions(remoteChatSessionSchema.array().parse(result));
})
.catch(() => undefined);
return () => {
cancelled = true;
};
}, [
selectedSlot,
selectedProfileId,
selectedServerInstanceId,
selectedSessionId,
historySessionId,
selectedTransport,
]);
useEffect(() => {
const snapshot = {
profileId: selectedProfileId,
serverInstanceId: selectedServerInstanceId,
activeSessionId: selectedSessionId,
transport: selectedTransport,
};
setCapabilities(null);
if (!snapshot.profileId || snapshot.transport !== "astr-bot-open-api")
return;
let cancelled = false;
void invoke<unknown>("connection_slot_capabilities", {
request: { slot: selectedSlot },
})
.then((result) => {
if (cancelled) return;
const next = astrbotCapabilitySnapshotSchema.parse(result);
setCapabilities(next);
})
.catch(() => undefined);
return () => {
cancelled = true;
};
}, [
selectedSlot,
selectedProfileId,
selectedServerInstanceId,
selectedSessionId,
historySessionId,
selectedTransport,
]);
useEffect(() => {
const snapshot = {
profileId: selectedProfileId,
serverInstanceId: selectedServerInstanceId,
activeSessionId: historySessionId,
transport: selectedTransport,
};
if (
!snapshot.profileId ||
!snapshot.serverInstanceId ||
!snapshot.activeSessionId
)
return;
void invoke("mark_chat_session_read", {
request: {
profileId: snapshot.profileId,
slot: selectedSlot,
serverInstanceId: snapshot.serverInstanceId,
sessionId: snapshot.activeSessionId,
},
}).catch(() => undefined);
setUnreadCounts((current) => ({ ...current, [selectedSlot]: 0 }));
}, [
selectedSlot,
selectedProfileId,
selectedServerInstanceId,
selectedSessionId,
historySessionId,
selectedTransport,
]);
useEffect(() => {
const snapshot = {
profileId: selectedProfileId,
serverInstanceId: selectedServerInstanceId,
activeSessionId: historySessionId,
transport: selectedTransport,
};
if (
!snapshot.profileId ||
!snapshot.serverInstanceId ||
!snapshot.activeSessionId
)
return;
let cancelled = false;
void invoke<unknown>("load_chat_messages", {
request: {
profileId: snapshot.profileId,
slot: selectedSlot,
serverInstanceId: snapshot.serverInstanceId,
sessionId: snapshot.activeSessionId,
limit: 100,
},
})
.then((result) => {
if (cancelled) return;
const records = storedChatMessageSchema.array().parse(result);
setMessages((current) =>
mergeLoadedChatMessages(
current,
records,
selectedSlot,
snapshot.activeSessionId,
),
);
})
.catch(() => undefined);
return () => {
cancelled = true;
};
}, [
selectedSlot,
selectedProfileId,
selectedServerInstanceId,
selectedSessionId,
historySessionId,
selectedTransport,
]);
useEffect(() => {
let timer: number | undefined;
void refresh().then((available) => {
if (!available) return;
timer = window.setInterval(() => {
void refresh();
}, 500);
});
return () => {
if (timer !== undefined) window.clearInterval(timer);
};
}, [refresh]);
const uploadFiles = async (files: FileList | null) => {
if (!files?.length) return;
// Pin the slot for the whole action. An upload that resolves after the user
// switched tabs must land on the slot it was uploaded to, not the one that
// happens to be selected when the promise settles.
const slot = selectedSlot;
setUploading(true);
reportSlotError(slot, null);
try {
const uploaded: AstrBotAttachment[] = [];
for (const file of Array.from(files)) {
if (file.size > 16 * 1024 * 1024)
throw new Error(`${file.name} 超过 16 MiB 限制`);
const bytes = Array.from(new Uint8Array(await file.arrayBuffer()));
const result = await invoke<unknown>("upload_connection_slot_file", {
request: {
slot,
fileName: file.name,
mimeType: file.type || "application/octet-stream",
bytes,
},
});
uploaded.push(astrbotAttachmentSchema.parse(result));
}
setPendingAttachments((current) => ({
...current,
[slot]: current[slot].concat(uploaded),
}));
} catch (reason) {
reportSlotError(slot, errorMessage(reason));
} finally {
setUploading(false);
}
};
const send = async (messageOverride?: string) => {
const slot = selectedSlot;
const slotAttachments = pendingAttachments[slot];
const message =
messageOverride?.trim() ||
draft[slot].trim() ||
(slotAttachments.length > 0 ? "Please check the attachment." : "");
if (!message || uploading || sending[slot]) return;
const id = `local-${Date.now()}`;
const attachments = messageOverride ? [] : slotAttachments;
setDraft((current) => ({ ...current, [slot]: "" }));
if (!messageOverride) {
setPendingAttachments((current) => ({ ...current, [slot]: [] }));
}
setSending((current) => ({ ...current, [slot]: true }));
setMessages((current) =>
current.concat({
id,
sessionId: status[slot].activeSessionId,
slot,
role: "user",
content: message,
}),
);
try {
const result = slotRuntimeSnapshotSchema.parse(
await invoke<unknown>("send_connection_slot_message", {
request: {
slot,
message,
attachments,
},
}),
);
setStatus((current) => ({ ...current, [slot]: result }));
setMessages((current) =>
current.map((item) =>
item.id === id
? { ...item, sessionId: result.activeSessionId }
: item,
),
);
reportSlotError(slot, null);
} catch (reason) {
reportSlotError(slot, errorMessage(reason));
setMessages((current) =>
current.map((item) =>
item.id === id ? { ...item, error: true } : item,
),
);
} finally {
setSending((current) => ({ ...current, [slot]: false }));
}
};
const stopGeneration = async () => {
const slot = selectedSlot;
try {
await invoke("cancel_connection_slot_message", {
request: { slot },
});
setSending((current) => ({ ...current, [slot]: false }));
setMessages((current) =>
current.map((item) =>
item.slot === slot && item.streaming
? {
...item,
streaming: false,
content: item.content || "Generation stopped.",
error: true,
}
: item,
),
);
reportSlotError(slot, null);
} catch (reason) {
reportSlotError(slot, errorMessage(reason));
}
};
const copyMessage = async (content: string) => {
const slot = selectedSlot;
try {
await navigator.clipboard.writeText(content);
reportSlotError(slot, null);
} catch {
reportSlotError(slot, "复制失败,请检查剪贴板权限。");
}
};
const retryMessage = (messageId: string) => {
const index = messages.findIndex((item) => item.id === messageId);
const previousUser = [...messages]
.slice(0, index)
.reverse()
.find((item) => item.role === "user" && item.slot === selectedSlot);
if (previousUser) void send(previousUser.content);
};
const startNewSession = async () => {
const slot = selectedSlot;
if (!status[slot].state || status[slot].state === "disconnected") {
reportSlotError(slot, "Connect the selected slot first.");
return;
}
try {
const sessionId = crypto.randomUUID();
const result = slotRuntimeSnapshotSchema.parse(
await invoke<unknown>("switch_connection_slot_session", {
request: { slot, sessionId },
}),
);
setMessages((current) =>
current.filter(
(item) =>
item.slot !== slot ||
item.sessionId !== status[slot].activeSessionId,
),
);
setStatus((current) => ({ ...current, [slot]: result }));
reportSlotError(slot, null);
} catch (reason) {
reportSlotError(slot, errorMessage(reason));
}
};
const refreshConnection = async () => {
await refresh();
};
const reconnectConnection = async () => {
const slot = selectedSlot;
const profileId = status[slot].profileId;
if (!profileId) {
reportSlotError(slot, "No Profile is assigned to the selected slot.");
return;
}
try {
const result = slotRuntimeSnapshotSchema.parse(
await invoke<unknown>("probe_connection_slot", {
request: { slot, profileId },
}),
);
setStatus((current) => ({ ...current, [slot]: result }));
reportSlotError(slot, null);
} catch (reason) {
reportSlotError(slot, errorMessage(reason));
}
};
const disconnectConnection = async () => {
const slot = selectedSlot;
try {
await invoke("disconnect_connection_slot", {
request: { slot },
});
await refresh();
} catch (reason) {
reportSlotError(slot, errorMessage(reason));
}
};
const toggleVoiceInput = () => {
const slot = selectedSlot;
if (voiceListening) {
speechRecognition.current?.stop();
setVoiceListening(false);
return;
}
const browserWindow = window as unknown as {
SpeechRecognition?: new () => SpeechRecognitionLike;
webkitSpeechRecognition?: new () => SpeechRecognitionLike;
};
const Recognition =
browserWindow.SpeechRecognition ?? browserWindow.webkitSpeechRecognition;
if (!Recognition) {
reportSlotError(slot, "当前 WebView 不支持语音输入。");
return;
}
const recognition = new Recognition();
recognition.lang = "zh-CN";
recognition.interimResults = true;
recognition.onresult = (event) => {
const result = event as {
results?: ArrayLike<ArrayLike<{ transcript?: string }>>;
};
const transcript = Array.from(result.results ?? [])
.map((item) => item[0]?.transcript ?? "")
.join("");
setDraft((current) => ({ ...current, [slot]: transcript }));
};
recognition.onerror = () => {
reportSlotError(slot, "语音输入失败,请检查麦克风权限。");
setVoiceListening(false);
};
recognition.onend = () => setVoiceListening(false);
speechRecognition.current = recognition;
recognition.start();
setVoiceListening(true);
};
const speakMessage = (content: string) => {
if (!window.speechSynthesis) return;
window.speechSynthesis.cancel();
const utterance = new SpeechSynthesisUtterance(content);
utterance.lang = "zh-CN";
window.speechSynthesis.speak(utterance);
};
return (
<section className="chat-panel" aria-label="聊天面板">
<div className="chat-heading">
<div>
<p className="eyebrow">共享聊天运行时</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}
disabled={Boolean(fixedSlot)}
onClick={() => setActiveSlot(slot)}
role="tab"
aria-selected={activeSlot === slot}
aria-controls={`chat-panel-${slot}`}
tabIndex={fixedSlot || activeSlot === slot ? 0 : -1}
onKeyDown={(event) => {
if (event.key !== "ArrowRight" && event.key !== "ArrowLeft")
return;
event.preventDefault();
setActiveSlot(
slot === "companion" ? "operations" : "companion",
);
}}
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">
<div>
<span>配置</span>
<strong>{status[selectedSlot].profileId ?? "未连接"}</strong>
</div>
<div>
<span>会话</span>
<strong>{status[selectedSlot].activeSessionId ?? "新会话"}</strong>
</div>
<div>
<span>状态</span>
<strong>{connectionStateLabel(status[selectedSlot].state)}</strong>
</div>
<div className="chat-runtime-actions">
<button type="button" onClick={() => void refreshConnection()}>
刷新
</button>
<button type="button" onClick={() => void reconnectConnection()}>
重连
</button>
<button
type="button"
onClick={() => void disconnectConnection()}
disabled={status[selectedSlot].state === "disconnected"}
>
断开
</button>
<button type="button" onClick={() => void startNewSession()}>
新对话
</button>
</div>
</div>
{status[selectedSlot].lastError ? (
<p className="chat-runtime-error" role="status">
{status[selectedSlot].lastError}
</p>
) : null}
{status[selectedSlot].state === "authExpired" ? (
<div className="warning-banner" role="alert">
<strong>认证已过期</strong>
<span>
请到“连接”设置重新登录 AstrBot,当前槽位不会继续发送消息。
</span>
<button type="button" onClick={() => void invoke("open_main_window")}>
打开连接设置
</button>
</div>
) : null}
{displaySessions.length > 0 ? (
<div className="chat-session-list" aria-label="Chat sessions">
{displaySessions.map((session, index) => (
<button
className={
session.sessionId === status[selectedSlot].activeSessionId
? "chat-session active"
: "chat-session"
}
key={session.sessionId}
title={`会话标识:${session.sessionId}`}
type="button"
onClick={() => {
void invoke("switch_connection_slot_session", {
request: { slot: selectedSlot, sessionId: session.sessionId },
})
.then(() => void refresh())
.catch((reason) =>
reportSlotError(selectedSlot, errorMessage(reason)),
);
}}
>
<strong>{session.displayName || `会话 ${index + 1}`}</strong>
<small>{formatSessionTime(session.updatedAt)}</small>
</button>
))}
</div>
) : null}
<div
id={`chat-panel-${selectedSlot}`}
className="chat-message-list"
ref={messageListRef}
onScroll={(event) => {
const list = event.currentTarget;
const distanceFromTail =
list.scrollHeight - list.scrollTop - list.clientHeight;
followTail.current = distanceFromTail <= TAIL_THRESHOLD_PX;
}}
role="tabpanel"
aria-label={`${selectedSlot} messages`}
aria-busy={sending[selectedSlot]}
aria-live="polite"
>
{visibleMessages.length === 0 ? (
<p className="chat-empty">
当前槽位还没有消息。连接 Profile 后即可开始聊天。
</p>
) : (
visibleMessages.map((message) => {
return (
<article
className={`chat-message-row ${message.role}${message.error ? " failed" : ""}`}
key={message.id}
>
<div className="chat-avatar" aria-hidden="true">
{message.role === "user"
? "You"
: message.role === "assistant"
? "A"
: "!"}
</div>
<div className="chat-message-content">
<div className="chat-bubble">
<div className="chat-bubble-header">
<span>
{message.role === "user"
? "你"
: message.role === "assistant"
? "AstrBot"
: "系统"}
</span>
{message.streaming ? <small>生成中</small> : null}
</div>
{message.content ? (
<MessageContent
content={message.content}
slot={selectedSlot}
/>
) : (
<p className="message-placeholder">正在生成…</p>
)}
</div>
{message.role === "assistant" &&
message.content &&
!message.streaming ? (
<div className="chat-message-actions" aria-label="消息操作">
<button
type="button"
aria-label="复制消息"
title="复制消息"
onClick={() => void copyMessage(message.content)}
>
<span
className="message-action-icon icon-copy"
aria-hidden="true"
/>
<span className="message-action-label">复制</span>
</button>
<button
type="button"
aria-label="重试消息"
title="重试消息"
onClick={() => retryMessage(message.id)}
>
<span
className="message-action-icon icon-retry"
aria-hidden="true"
/>
<span className="message-action-label">重试</span>
</button>
<button
type="button"
aria-label="朗读消息"
title="朗读消息"
onClick={() => speakMessage(message.content)}
>
<span
className="message-action-icon icon-read"
aria-hidden="true"
/>
<span className="message-action-label">朗读</span>
</button>
</div>
) : null}
{message.streaming && sending[selectedSlot] ? (
<button
className="chat-stop-button"
type="button"
onClick={() => void stopGeneration()}
>
停止生成
</button>
) : null}
</div>
</article>
);
})
)}
</div>
{visibleError ? (
<p className="chat-error" role="alert">
{visibleError}
</p>
) : null}
<div className="chat-composer-toolbar">
<label className="file-picker">
<span>添加图片/文件</span>
<input
className="file-picker-input"
type="file"
multiple
onChange={(event) => {
void uploadFiles(event.target.files);
event.target.value = "";
}}
disabled={uploading || !capabilities?.fileUpload}
/>
</label>
{uploading ? <span className="toolbar-note">上传中…</span> : null}
<button
type="button"
onClick={toggleVoiceInput}
className={voiceListening ? "voice-button active" : "voice-button"}
aria-pressed={voiceListening}
>
{voiceListening ? "停止录音" : "语音输入"}
</button>
</div>
{selectedAttachments.length > 0 ? (
<div className="attachment-list">
{selectedAttachments.map((attachment) => (
<span key={attachment.attachmentId}>
{attachment.fileName}
<button
type="button"
aria-label={`移除 ${attachment.fileName}`}
onClick={() =>
setPendingAttachments((current) => ({
...current,
[selectedSlot]: current[selectedSlot].filter(
(item) => item.attachmentId !== attachment.attachmentId,
),
}))
}
>
×
</button>
</span>
))}
</div>
) : null}
<form
className="chat-composer"
onSubmit={(event) => {
event.preventDefault();
void send();
}}
>
<textarea
aria-label="聊天消息"
onChange={(event) =>
setDraft((current) => ({
...current,
[selectedSlot]: event.target.value,
}))
}
placeholder={
selectedSlot === "companion"
? "和陪伴实例说点什么…(Enter 发送,Shift+Enter 换行)"
: "向运维实例描述问题…(Enter 发送,Shift+Enter 换行)"
}
value={draft[selectedSlot]}
rows={3}
onKeyDown={(event) => {
if (
event.key !== "Enter" ||
event.shiftKey ||
event.nativeEvent.isComposing
)
return;
event.preventDefault();
void send();
}}
/>
<button
className="chat-send-button"
disabled={
(!draft[selectedSlot].trim() && selectedAttachments.length === 0) ||
uploading
}
type="submit"
>
<span className="send-button-icon" aria-hidden="true">
↑
</span>
<span>发送</span>
</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 &&
item.sessionId === event.sessionId,
);
if (existing) {
existing.content += delta;
existing.streaming = true;
} else
next.push({
id,
sessionId: event.sessionId,
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 &&
item.sessionId === event.sessionId,
);
const completedContent = payloadString(event, "content")?.trim() ?? "";
if (existing) {
if (completedContent) {
existing.content = completedContent;
} else if (!existing.content.trim()) {
existing.content = "未收到有效回复";
existing.error = true;
}
existing.streaming = false;
} else
next.push({
id,
sessionId: event.sessionId,
slot: event.slot,
role: "assistant",
content: completedContent || "未收到有效回复",
error: !completedContent,
});
} else if (event.eventType === "error") {
next.push({
id: event.eventId,
sessionId: event.sessionId,
slot: event.slot,
role: "system",
content: payloadString(event, "message") || "连接错误",
error: true,
});
} else if (event.eventType === "message.proactive") {
next.push({
id: event.eventId,
sessionId: event.sessionId,
slot: event.slot,
role: "assistant",
content: payloadString(event, "content") || "",
});
}
}
return next;
}
function formatSessionTime(value?: string | null): string {
if (!value) return "本地历史";
const date = new Date(value);
if (Number.isNaN(date.getTime())) return "本地历史";
return new Intl.DateTimeFormat("zh-CN", {
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
}).format(date);
}
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];
}