diff --git a/src/features/chat/ChatPanel.test.tsx b/src/features/chat/ChatPanel.test.tsx index 37b35ec..f02435e 100644 --- a/src/features/chat/ChatPanel.test.tsx +++ b/src/features/chat/ChatPanel.test.tsx @@ -1,5 +1,5 @@ import { invoke } from "@tauri-apps/api/core"; -import { render, screen, waitFor } from "@testing-library/react"; +import { fireEvent, render, screen, waitFor } from "@testing-library/react"; import { StrictMode } from "react"; import { beforeEach, expect, it, vi } from "vitest"; @@ -30,32 +30,63 @@ function connectedSnapshot(slot: "companion" | "operations") { }; } -function mockChatCommands() { - vi.mocked(invoke).mockImplementation(async (command: string) => { - switch (command) { - case "connection_runtime_status": - return { - companion: connectedSnapshot("companion"), - operations: connectedSnapshot("operations"), - }; - case "list_chat_sessions": - case "connection_slot_sessions": - case "load_chat_messages": - return []; - case "connection_slot_capabilities": - return { - transport: "astrbot-openapi", - textChat: true, - streaming: true, - modelSelection: false, - fileUpload: false, - imageInput: false, - models: [], - }; - default: - return undefined; - } - }); +function mockChatCommands(options?: { + fileUpload?: boolean; + onSend?: (payload: unknown) => unknown; +}) { + vi.mocked(invoke).mockImplementation( + async (command: string, payload?: unknown) => { + switch (command) { + case "connection_runtime_status": + return { + companion: connectedSnapshot("companion"), + operations: connectedSnapshot("operations"), + }; + case "list_chat_sessions": + case "connection_slot_sessions": + case "load_chat_messages": + return []; + case "connection_slot_capabilities": + return { + transport: "astrbot-openapi", + textChat: true, + streaming: true, + modelSelection: false, + fileUpload: options?.fileUpload ?? false, + imageInput: false, + models: [], + }; + case "upload_connection_slot_file": + return { + attachmentId: "attachment-1", + fileName: "note.txt", + mimeType: "text/plain", + sizeBytes: 4, + }; + case "send_connection_slot_message": + if (options?.onSend) return options.onSend(payload); + return connectedSnapshot("companion"); + default: + return undefined; + } + }, + ); +} + +/** Renders with the slot tabs enabled, then waits for the first status poll. */ +async function renderWithTabs() { + const view = render(); + await flushListen(); + await screen.findByRole("tab", { name: /陪伴/ }); + return view; +} + +function selectSlot(name: RegExp) { + fireEvent.click(screen.getByRole("tab", { name })); +} + +function composer() { + return screen.getByLabelText("聊天消息"); } function deltaEvent(delta: string) { @@ -104,3 +135,65 @@ it("releases every listener on unmount", async () => { expect(activeListeners("connection-runtime-event")).toBe(0); }); }); + +it("keeps drafts on the slot they were typed in", async () => { + await renderWithTabs(); + + fireEvent.change(composer(), { target: { value: "写给陪伴的" } }); + expect(composer()).toHaveValue("写给陪伴的"); + + selectSlot(/运维/); + expect(composer()).toHaveValue(""); + + selectSlot(/陪伴/); + expect(composer()).toHaveValue("写给陪伴的"); +}); + +it("keeps attachments on the slot they were uploaded to", async () => { + mockChatCommands({ fileUpload: true }); + await renderWithTabs(); + + const picker = screen.getByText("添加图片/文件").parentElement + ?.children[1] as HTMLInputElement; + fireEvent.change(picker, { + target: { files: [new File(["note"], "note.txt", { type: "text/plain" })] }, + }); + expect(await screen.findByLabelText("移除 note.txt")).toBeInTheDocument(); + + selectSlot(/运维/); + expect(screen.queryByLabelText("移除 note.txt")).not.toBeInTheDocument(); + + // Sending from the other slot must not pick up the companion's attachment. + fireEvent.change(composer(), { target: { value: "运维消息" } }); + fireEvent.submit(composer().closest("form") as HTMLFormElement); + await waitFor(() => { + expect(invoke).toHaveBeenCalledWith("send_connection_slot_message", { + request: { slot: "operations", message: "运维消息", attachments: [] }, + }); + }); + + selectSlot(/陪伴/); + expect(screen.getByLabelText("移除 note.txt")).toBeInTheDocument(); +}); + +it("shows an error banner only on the slot that produced it", async () => { + mockChatCommands({ + onSend: () => { + throw { code: "runtimeUnavailable", message: "未连接到 AstrBot。" }; + }, + }); + await renderWithTabs(); + + fireEvent.change(composer(), { target: { value: "在线吗" } }); + fireEvent.submit(composer().closest("form") as HTMLFormElement); + + // Also asserts the shared errorMessage() shape rather than [object Object], + // and that the 500ms status poll no longer wipes an action error. + expect(await screen.findByText("未连接到 AstrBot。")).toBeInTheDocument(); + + selectSlot(/运维/); + expect(screen.queryByText("未连接到 AstrBot。")).not.toBeInTheDocument(); + + selectSlot(/陪伴/); + expect(screen.getByText("未连接到 AstrBot。")).toBeInTheDocument(); +}); diff --git a/src/features/chat/ChatPanel.tsx b/src/features/chat/ChatPanel.tsx index 5742080..8a11710 100644 --- a/src/features/chat/ChatPanel.tsx +++ b/src/features/chat/ChatPanel.tsx @@ -74,13 +74,28 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) { const historySessionId = selectedSessionId ?? storedSessions[selectedSlot][0]?.sessionId; const selectedTransport = selectedSnapshot.transport; - const [draft, setDraft] = useState(""); - const [error, setError] = useState(null); + const [draft, setDraft] = useState>({ + 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(null); + const [slotError, setSlotError] = useState>({ + companion: null, + operations: null, + }); const [capabilities, setCapabilities] = useState(null); const [pendingAttachments, setPendingAttachments] = useState< - AstrBotAttachment[] - >([]); + Record + >({ + companion: [], + operations: [], + }); const [uploading, setUploading] = useState(false); const [voiceListening, setVoiceListening] = useState(false); const [sending, setSending] = useState>({ @@ -95,6 +110,9 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) { 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( @@ -130,18 +148,22 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) { const result = await invoke("connection_runtime_status"); const parsed = connectionRuntimeStatusSchema.safeParse(result); if (!parsed.success) { - setError("连接状态暂不可用,请检查连接配置。"); + setRuntimeError("连接状态暂不可用,请检查连接配置。"); return false; } setStatus(parsed.data); - setError(null); + setRuntimeError(null); return true; } catch { - setError("连接状态暂不可用,请检查本地运行时。"); + setRuntimeError("连接状态暂不可用,请检查本地运行时。"); return false; } }, []); + const reportSlotError = (slot: ChatSlot, message: string | null) => { + setSlotError((current) => ({ ...current, [slot]: message })); + }; + useEffect(() => { // `listen()` resolves after the effect may already have been cleaned up. // Assigning the unregister function unconditionally dropped it in that @@ -372,8 +394,12 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) { 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); - setError(null); + reportSlotError(slot, null); try { const uploaded: AstrBotAttachment[] = []; for (const file of Array.from(files)) { @@ -382,7 +408,7 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) { const bytes = Array.from(new Uint8Array(await file.arrayBuffer())); const result = await invoke("upload_connection_slot_file", { request: { - slot: selectedSlot, + slot, fileName: file.name, mimeType: file.type || "application/octet-stream", bytes, @@ -390,30 +416,37 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) { }); uploaded.push(astrbotAttachmentSchema.parse(result)); } - setPendingAttachments((current) => current.concat(uploaded)); + setPendingAttachments((current) => ({ + ...current, + [slot]: current[slot].concat(uploaded), + })); } catch (reason) { - setError(errorMessage(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.trim() || - (pendingAttachments.length > 0 ? "Please check the attachment." : ""); - if (!message || uploading || sending[selectedSlot]) return; + draft[slot].trim() || + (slotAttachments.length > 0 ? "Please check the attachment." : ""); + if (!message || uploading || sending[slot]) return; const id = `local-${Date.now()}`; - const attachments = messageOverride ? [] : pendingAttachments; - setDraft(""); - if (!messageOverride) setPendingAttachments([]); - setSending((current) => ({ ...current, [selectedSlot]: true })); + 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[selectedSlot].activeSessionId, - slot: selectedSlot, + sessionId: status[slot].activeSessionId, + slot, role: "user", content: message, }), @@ -422,13 +455,13 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) { const result = slotRuntimeSnapshotSchema.parse( await invoke("send_connection_slot_message", { request: { - slot: selectedSlot, + slot, message, attachments, }, }), ); - setStatus((current) => ({ ...current, [selectedSlot]: result })); + setStatus((current) => ({ ...current, [slot]: result })); setMessages((current) => current.map((item) => item.id === id @@ -436,28 +469,29 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) { : item, ), ); - setError(null); + reportSlotError(slot, null); } catch (reason) { - setError(errorMessage(reason)); + reportSlotError(slot, errorMessage(reason)); setMessages((current) => current.map((item) => item.id === id ? { ...item, error: true } : item, ), ); } finally { - setSending((current) => ({ ...current, [selectedSlot]: false })); + setSending((current) => ({ ...current, [slot]: false })); } }; const stopGeneration = async () => { + const slot = selectedSlot; try { await invoke("cancel_connection_slot_message", { - request: { slot: selectedSlot }, + request: { slot }, }); - setSending((current) => ({ ...current, [selectedSlot]: false })); + setSending((current) => ({ ...current, [slot]: false })); setMessages((current) => current.map((item) => - item.slot === selectedSlot && item.streaming + item.slot === slot && item.streaming ? { ...item, streaming: false, @@ -467,18 +501,19 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) { : item, ), ); - setError(null); + reportSlotError(slot, null); } catch (reason) { - setError(errorMessage(reason)); + reportSlotError(slot, errorMessage(reason)); } }; const copyMessage = async (content: string) => { + const slot = selectedSlot; try { await navigator.clipboard.writeText(content); - setError(null); + reportSlotError(slot, null); } catch { - setError("复制失败,请检查剪贴板权限。"); + reportSlotError(slot, "复制失败,请检查剪贴板权限。"); } }; @@ -492,31 +527,29 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) { }; const startNewSession = async () => { - if ( - !status[selectedSlot].state || - status[selectedSlot].state === "disconnected" - ) { - setError("Connect the selected slot first."); + 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("switch_connection_slot_session", { - request: { slot: selectedSlot, sessionId }, + request: { slot, sessionId }, }), ); setMessages((current) => current.filter( (item) => - item.slot !== selectedSlot || - item.sessionId !== status[selectedSlot].activeSessionId, + item.slot !== slot || + item.sessionId !== status[slot].activeSessionId, ), ); - setStatus((current) => ({ ...current, [selectedSlot]: result })); - setError(null); + setStatus((current) => ({ ...current, [slot]: result })); + reportSlotError(slot, null); } catch (reason) { - setError(errorMessage(reason)); + reportSlotError(slot, errorMessage(reason)); } }; @@ -525,36 +558,39 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) { }; const reconnectConnection = async () => { - const profileId = status[selectedSlot].profileId; + const slot = selectedSlot; + const profileId = status[slot].profileId; if (!profileId) { - setError("No Profile is assigned to the selected slot."); + reportSlotError(slot, "No Profile is assigned to the selected slot."); return; } try { const result = slotRuntimeSnapshotSchema.parse( await invoke("probe_connection_slot", { - request: { slot: selectedSlot, profileId }, + request: { slot, profileId }, }), ); - setStatus((current) => ({ ...current, [selectedSlot]: result })); - setError(null); + setStatus((current) => ({ ...current, [slot]: result })); + reportSlotError(slot, null); } catch (reason) { - setError(errorMessage(reason)); + reportSlotError(slot, errorMessage(reason)); } }; const disconnectConnection = async () => { + const slot = selectedSlot; try { await invoke("disconnect_connection_slot", { - request: { slot: selectedSlot }, + request: { slot }, }); await refresh(); } catch (reason) { - setError(errorMessage(reason)); + reportSlotError(slot, errorMessage(reason)); } }; const toggleVoiceInput = () => { + const slot = selectedSlot; if (voiceListening) { speechRecognition.current?.stop(); setVoiceListening(false); @@ -567,7 +603,7 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) { const Recognition = browserWindow.SpeechRecognition ?? browserWindow.webkitSpeechRecognition; if (!Recognition) { - setError("当前 WebView 不支持语音输入。"); + reportSlotError(slot, "当前 WebView 不支持语音输入。"); return; } const recognition = new Recognition(); @@ -577,14 +613,13 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) { const result = event as { results?: ArrayLike>; }; - setDraft( - Array.from(result.results ?? []) - .map((item) => item[0]?.transcript ?? "") - .join(""), - ); + const transcript = Array.from(result.results ?? []) + .map((item) => item[0]?.transcript ?? "") + .join(""); + setDraft((current) => ({ ...current, [slot]: transcript })); }; recognition.onerror = () => { - setError("语音输入失败,请检查麦克风权限。"); + reportSlotError(slot, "语音输入失败,请检查麦克风权限。"); setVoiceListening(false); }; recognition.onend = () => setVoiceListening(false); @@ -713,9 +748,7 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) { }) .then(() => void refresh()) .catch((reason) => - setError( - errorMessage(reason), - ), + reportSlotError(selectedSlot, errorMessage(reason)), ); }} > @@ -764,7 +797,10 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) { {message.streaming ? 生成中 : null} {message.content ? ( - + ) : (

正在生成…

)} @@ -826,9 +862,9 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) { }) )} - {error ? ( + {visibleError ? (

- {error} + {visibleError}

) : null}
@@ -856,20 +892,21 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) { {voiceListening ? "停止录音" : "语音输入"}
- {pendingAttachments.length > 0 ? ( + {selectedAttachments.length > 0 ? (
- {pendingAttachments.map((attachment) => ( + {selectedAttachments.map((attachment) => ( {attachment.fileName}