fix(ui): release tauri event listeners on unmount

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 <noreply@anthropic.com>
这个提交存在于:
YokiiroBW 2026-07-27 00:23:42 +08:00
父节点 02ac2046d6
当前提交 124cf32fa2
共有 6 个文件被更改,包括 251 次插入 和 19 次删除

查看文件

@ -390,13 +390,22 @@ function InAppPetOverlay() {
}, [clampPosition, position.x, position.y]); }, [clampPosition, position.x, position.y]);
useEffect(() => { useEffect(() => {
let active = true;
let unlisten: (() => void) | undefined; let unlisten: (() => void) | undefined;
void listen("pet-hide-requested", () => setVisible(false)).then( void listen("pet-hide-requested", () => setVisible(false))
(cleanup) => { .then((cleanup) => {
if (active) {
unlisten = cleanup; unlisten = cleanup;
}, } else {
); cleanup();
return () => unlisten?.(); }
})
.catch(() => undefined);
return () => {
active = false;
unlisten?.();
unlisten = undefined;
};
}, []); }, []);
return visible ? ( return visible ? (

查看文件

@ -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>
<ChatPanel fixedSlot="companion" />
</StrictMode>,
);
// 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(<ChatPanel fixedSlot="companion" />);
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);
});
});

查看文件

@ -143,16 +143,32 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
}, []); }, []);
useEffect(() => { 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; let unlisten: (() => void) | undefined;
void listen<unknown>("connection-runtime-event", (event) => { void listen<unknown>("connection-runtime-event", (event) => {
const parsed = boundRuntimeEventSchema.safeParse(event.payload); const parsed = boundRuntimeEventSchema.safeParse(event.payload);
if (parsed.success) { if (parsed.success) {
setMessages((current) => applyRuntimeEvents(current, [parsed.data])); setMessages((current) => applyRuntimeEvents(current, [parsed.data]));
} }
}).then((cleanup) => { })
.then((cleanup) => {
if (active) {
unlisten = cleanup; unlisten = cleanup;
}); } else {
return () => unlisten?.(); cleanup();
}
})
.catch(() => undefined);
return () => {
active = false;
unlisten?.();
unlisten = undefined;
};
}, []); }, []);
useEffect(() => { useEffect(() => {

查看文件

@ -44,13 +44,20 @@ export function DesktopPetView({ embedded = false }: { embedded?: boolean }) {
const completionTimerRef = useRef<number | null>(null); const completionTimerRef = useRef<number | null>(null);
useEffect(() => { useEffect(() => {
let active = true;
let unlisten: (() => void) | undefined; let unlisten: (() => void) | undefined;
let unlistenRuntime: (() => void) | undefined; let unlistenRuntime: (() => void) | undefined;
void listen("pet-game-mode-toggle", () => void listen("pet-game-mode-toggle", () =>
setGameMode((current) => !current), setGameMode((current) => !current),
).then((cleanup) => { )
.then((cleanup) => {
if (active) {
unlisten = cleanup; unlisten = cleanup;
}); } else {
cleanup();
}
})
.catch(() => undefined);
void listen<unknown>("connection-runtime-event", (event) => { void listen<unknown>("connection-runtime-event", (event) => {
const parsed = boundRuntimeEventSchema.safeParse(event.payload); const parsed = boundRuntimeEventSchema.safeParse(event.payload);
if (!parsed.success || parsed.data.slot !== PET_TARGET_SLOT) return; if (!parsed.success || parsed.data.slot !== PET_TARGET_SLOT) return;
@ -68,12 +75,21 @@ export function DesktopPetView({ embedded = false }: { embedded?: boolean }) {
}, 2200); }, 2200);
} }
if (parsed.data.eventType === "error") setState("error"); if (parsed.data.eventType === "error") setState("error");
}).then((cleanup) => { })
.then((cleanup) => {
if (active) {
unlistenRuntime = cleanup; unlistenRuntime = cleanup;
}); } else {
cleanup();
}
})
.catch(() => undefined);
return () => { return () => {
active = false;
unlisten?.(); unlisten?.();
unlistenRuntime?.(); unlistenRuntime?.();
unlisten = undefined;
unlistenRuntime = undefined;
if (completionTimerRef.current !== null) { if (completionTimerRef.current !== null) {
window.clearTimeout(completionTimerRef.current); window.clearTimeout(completionTimerRef.current);
completionTimerRef.current = null; completionTimerRef.current = null;

查看文件

@ -1,13 +1,19 @@
import "@testing-library/jest-dom/vitest"; import "@testing-library/jest-dom/vitest";
import { vi } from "vitest"; import { vi } from "vitest";
vi.mock("@tauri-apps/api/event", () => ({ vi.mock("@tauri-apps/api/event", async () => {
listen: vi.fn(async () => () => undefined), const { listenMock } = await import("./tauriEvent");
})); return { listen: listenMock };
});
import { cleanup } from "@testing-library/react"; import { cleanup } from "@testing-library/react";
import { afterEach } from "vitest"; import { afterEach } from "vitest";
import { resetTauriEvent } from "./tauriEvent";
afterEach(() => { afterEach(() => {
cleanup(); cleanup();
// The registry is plain module state, so `clearMocks` does not reach it.
// Without this, listeners leak across test files.
resetTauriEvent();
}); });

79
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<void> {
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();
}