From 124cf32fa268a2ee8c1bae8fbb57814599c8cbfe Mon Sep 17 00:00:00 2001 From: YokiiroBW Date: Mon, 27 Jul 2026 00:23:42 +0800 Subject: [PATCH] fix(ui): release tauri event listeners on unmount MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit All four listen() call sites assigned the resolved unregister function unconditionally. When the effect was cleaned up before the promise settled, that assignment landed on a dead closure and the listener was never unregistered. React StrictMode mounts, cleans up and mounts again, so the first listener leaked on every development mount. In ChatPanel that meant applyRuntimeEvents ran twice per event and, because a delta is appended to the existing content, every character of a streamed reply was doubled. Track whether the effect is still live and unregister immediately when the promise settles late. Each site also gains a catch, since these were all bare void listen(...).then(...) chains — a rejected listen, such as the missing desktop-pet capability, became an unhandled rejection rather than anything observable. The listener mock in src/test/setup.ts resolved eagerly, which made the race impossible to express. Replace it with a controllable double in src/test/tauriEvent.ts that defers resolution until the test asks for it, tracks each registration separately, and only dispatches to handlers that have not been unregistered. The registry is plain module state, so setup.ts resets it after each test. ChatPanel had no test file; this adds one. Both new tests were checked against a mutation restoring the old assignment, and both fail under it. Refs: F-15 (audit P1-10). Co-Authored-By: Claude Opus 5 --- src/App.tsx | 21 ++++-- src/features/chat/ChatPanel.test.tsx | 106 +++++++++++++++++++++++++++ src/features/chat/ChatPanel.tsx | 24 +++++- src/features/pet/DesktopPetView.tsx | 28 +++++-- src/test/setup.ts | 12 ++- src/test/tauriEvent.ts | 79 ++++++++++++++++++++ 6 files changed, 251 insertions(+), 19 deletions(-) create mode 100644 src/features/chat/ChatPanel.test.tsx create mode 100644 src/test/tauriEvent.ts diff --git a/src/App.tsx b/src/App.tsx index 2f25114..86dbc8f 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -390,13 +390,22 @@ function InAppPetOverlay() { }, [clampPosition, position.x, position.y]); useEffect(() => { + let active = true; let unlisten: (() => void) | undefined; - void listen("pet-hide-requested", () => setVisible(false)).then( - (cleanup) => { - unlisten = cleanup; - }, - ); - return () => unlisten?.(); + void listen("pet-hide-requested", () => setVisible(false)) + .then((cleanup) => { + if (active) { + unlisten = cleanup; + } else { + cleanup(); + } + }) + .catch(() => undefined); + return () => { + active = false; + unlisten?.(); + unlisten = undefined; + }; }, []); return visible ? ( diff --git a/src/features/chat/ChatPanel.test.tsx b/src/features/chat/ChatPanel.test.tsx new file mode 100644 index 0000000..37b35ec --- /dev/null +++ b/src/features/chat/ChatPanel.test.tsx @@ -0,0 +1,106 @@ +import { invoke } from "@tauri-apps/api/core"; +import { render, screen, waitFor } from "@testing-library/react"; +import { StrictMode } from "react"; +import { beforeEach, expect, it, vi } from "vitest"; + +import { + activeListeners, + emitTauriEvent, + flushListen, +} from "../../test/tauriEvent"; +import { ChatPanel } from "./ChatPanel"; + +vi.mock("@tauri-apps/api/core", () => ({ + invoke: vi.fn(), +})); + +const PROFILE_ID = "11111111-1111-1111-1111-111111111111"; +const SERVER_INSTANCE_ID = "server-1"; +const SESSION_ID = "session-1"; + +function connectedSnapshot(slot: "companion" | "operations") { + return { + slot, + profileId: PROFILE_ID, + transport: "astr-bot-open-api", + state: "connected", + serverInstanceId: SERVER_INSTANCE_ID, + activeSessionId: SESSION_ID, + lastError: null, + }; +} + +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 deltaEvent(delta: string) { + return { + profileId: PROFILE_ID, + slot: "companion", + eventId: "astrbot-server-1-stream-1", + eventType: "message.delta", + serverInstanceId: SERVER_INSTANCE_ID, + sessionId: SESSION_ID, + messageId: "message-1", + payload: { delta }, + }; +} + +beforeEach(() => { + mockChatCommands(); +}); + +it("applies each streaming delta once under strict mode", async () => { + render( + + + , + ); + + // StrictMode mounts, cleans up, then mounts again. The first listener used to + // survive that cleanup because `listen()` had not resolved yet, so every + // delta was applied twice. + await flushListen(); + emitTauriEvent("connection-runtime-event", deltaEvent("你好")); + + expect(await screen.findByText("你好")).toBeInTheDocument(); + expect(screen.queryByText("你好你好")).not.toBeInTheDocument(); +}); + +it("releases every listener on unmount", async () => { + const view = render(); + + view.unmount(); + // Settling *after* unmount is the real leak path: the cleanup has already + // run, so the resolved unregister function must be called immediately. + await flushListen(); + + await waitFor(() => { + expect(activeListeners("connection-runtime-event")).toBe(0); + }); +}); diff --git a/src/features/chat/ChatPanel.tsx b/src/features/chat/ChatPanel.tsx index d55e347..5742080 100644 --- a/src/features/chat/ChatPanel.tsx +++ b/src/features/chat/ChatPanel.tsx @@ -143,16 +143,32 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) { }, []); 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("connection-runtime-event", (event) => { const parsed = boundRuntimeEventSchema.safeParse(event.payload); if (parsed.success) { setMessages((current) => applyRuntimeEvents(current, [parsed.data])); } - }).then((cleanup) => { - unlisten = cleanup; - }); - return () => unlisten?.(); + }) + .then((cleanup) => { + if (active) { + unlisten = cleanup; + } else { + cleanup(); + } + }) + .catch(() => undefined); + return () => { + active = false; + unlisten?.(); + unlisten = undefined; + }; }, []); useEffect(() => { diff --git a/src/features/pet/DesktopPetView.tsx b/src/features/pet/DesktopPetView.tsx index 6ca09ed..0c65e4f 100644 --- a/src/features/pet/DesktopPetView.tsx +++ b/src/features/pet/DesktopPetView.tsx @@ -44,13 +44,20 @@ export function DesktopPetView({ embedded = false }: { embedded?: boolean }) { const completionTimerRef = useRef(null); useEffect(() => { + let active = true; let unlisten: (() => void) | undefined; let unlistenRuntime: (() => void) | undefined; void listen("pet-game-mode-toggle", () => setGameMode((current) => !current), - ).then((cleanup) => { - unlisten = cleanup; - }); + ) + .then((cleanup) => { + if (active) { + unlisten = cleanup; + } else { + cleanup(); + } + }) + .catch(() => undefined); void listen("connection-runtime-event", (event) => { const parsed = boundRuntimeEventSchema.safeParse(event.payload); if (!parsed.success || parsed.data.slot !== PET_TARGET_SLOT) return; @@ -68,12 +75,21 @@ export function DesktopPetView({ embedded = false }: { embedded?: boolean }) { }, 2200); } if (parsed.data.eventType === "error") setState("error"); - }).then((cleanup) => { - unlistenRuntime = cleanup; - }); + }) + .then((cleanup) => { + if (active) { + unlistenRuntime = cleanup; + } else { + cleanup(); + } + }) + .catch(() => undefined); return () => { + active = false; unlisten?.(); unlistenRuntime?.(); + unlisten = undefined; + unlistenRuntime = undefined; if (completionTimerRef.current !== null) { window.clearTimeout(completionTimerRef.current); completionTimerRef.current = null; diff --git a/src/test/setup.ts b/src/test/setup.ts index c514d83..1dbed39 100644 --- a/src/test/setup.ts +++ b/src/test/setup.ts @@ -1,13 +1,19 @@ import "@testing-library/jest-dom/vitest"; import { vi } from "vitest"; -vi.mock("@tauri-apps/api/event", () => ({ - listen: vi.fn(async () => () => undefined), -})); +vi.mock("@tauri-apps/api/event", async () => { + const { listenMock } = await import("./tauriEvent"); + return { listen: listenMock }; +}); import { cleanup } from "@testing-library/react"; import { afterEach } from "vitest"; +import { resetTauriEvent } from "./tauriEvent"; + afterEach(() => { cleanup(); + // The registry is plain module state, so `clearMocks` does not reach it. + // Without this, listeners leak across test files. + resetTauriEvent(); }); diff --git a/src/test/tauriEvent.ts b/src/test/tauriEvent.ts new file mode 100644 index 0000000..6c7e10d --- /dev/null +++ b/src/test/tauriEvent.ts @@ -0,0 +1,79 @@ +import { vi } from "vitest"; + +type EventHandler = (event: { payload: unknown }) => void; + +interface Registration { + name: string; + handler: EventHandler; + unlisten: () => void; + settle: (unlisten: () => void) => void; + settled: boolean; + released: boolean; +} + +const registrations: Registration[] = []; + +/** + * A deliberately deferred stand-in for `listen()`. + * + * The real one resolves asynchronously, and that gap is what makes the + * unregister race possible: a cleanup that runs before the promise settles has + * nothing to call. A mock that resolves eagerly would hide the exact defect + * these tests exist to catch, so this one only settles when `flushListen` says + * so. + */ +export const listenMock = vi.fn( + (name: string, handler: EventHandler) => + new Promise<() => void>((resolve) => { + const registration: Registration = { + name, + handler, + unlisten: () => { + registration.released = true; + }, + settle: resolve, + settled: false, + released: false, + }; + registrations.push(registration); + }), +); + +/** Settles every pending `listen()` promise. */ +export async function flushListen(): Promise { + for (const registration of registrations) { + if (registration.settled) continue; + registration.settled = true; + registration.settle(registration.unlisten); + } + await Promise.resolve(); + await Promise.resolve(); +} + +/** + * Dispatches to every handler that has not been unregistered. + * + * A handler is live from the moment `listen()` is called, exactly as it is in + * Tauri — the promise only hands back the unregister function. A leaked + * registration therefore keeps receiving events, which is what turns the race + * into doubled streaming deltas. + */ +export function emitTauriEvent(name: string, payload: unknown): void { + for (const registration of [...registrations]) { + if (registration.name !== name || registration.released) continue; + registration.handler({ payload }); + } +} + +export function activeListeners(name?: string): number { + return registrations.filter( + (registration) => + !registration.released && + (name === undefined || registration.name === name), + ).length; +} + +export function resetTauriEvent(): void { + registrations.length = 0; + listenMock.mockClear(); +}