fix(webui): snapshot received messages before pane unmount
This commit is contained in:
1 parent
bfb5129e6f
commit
8eea1cb7a4
2 files changed
+54
-14
No files matched your search
@@ -1,5 +1,5 @@
|
|||||||
import { acceptsCompactionPhase } from "../../../packages/client-events/notifications";
|
import { acceptsCompactionPhase } from "../../../packages/client-events/notifications";
|
||||||
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
|
import { useCallback, useEffect, useRef, useState } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { useThreadVisibility } from "@/hooks/useThreadVisibility";
|
import { useThreadVisibility } from "@/hooks/useThreadVisibility";
|
||||||
|
|
||||||
@@ -173,9 +173,15 @@ export function useNanobotStream(
|
|||||||
threadVisibleRef.current = threadVisible;
|
threadVisibleRef.current = threadVisible;
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const initialRunStartedAt = chatId ? client.getRunStartedAt(chatId) : null;
|
const initialRunStartedAt = chatId ? client.getRunStartedAt(chatId) : null;
|
||||||
const [messages, setMessages] = useState<UIMessage[]>(initialMessages);
|
const [messages, setRenderedMessages] = useState<UIMessage[]>(initialMessages);
|
||||||
const committedMessagesRef = useRef(messages);
|
const messagesRef = useRef(messages);
|
||||||
useLayoutEffect(() => { committedMessagesRef.current = messages; }, [messages]);
|
// Keep received state ahead of React's batched render: navigation can unmount
|
||||||
|
// this hook after a stream flush but before the queued render commits.
|
||||||
|
const setMessages = useCallback<React.Dispatch<React.SetStateAction<UIMessage[]>>>((update) => {
|
||||||
|
const next = typeof update === "function" ? update(messagesRef.current) : update;
|
||||||
|
messagesRef.current = next;
|
||||||
|
setRenderedMessages(next);
|
||||||
|
}, []);
|
||||||
const [messageOwnerChatId, setMessageOwnerChatId] = useState(chatId);
|
const [messageOwnerChatId, setMessageOwnerChatId] = useState(chatId);
|
||||||
/** If history ends in unfinished agent activity, keep the loading spinner alive. */
|
/** If history ends in unfinished agent activity, keep the loading spinner alive. */
|
||||||
const initialStreaming = hasPendingAgentActivity(initialMessages);
|
const initialStreaming = hasPendingAgentActivity(initialMessages);
|
||||||
@@ -305,7 +311,7 @@ export function useNanobotStream(
|
|||||||
suppressUntilTurnEnd: false,
|
suppressUntilTurnEnd: false,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}, [chatId, client]);
|
}, [chatId, client, setMessages]);
|
||||||
|
|
||||||
useEffect(() => client.onError(applyStreamError), [applyStreamError, client]);
|
useEffect(() => client.onError(applyStreamError), [applyStreamError, client]);
|
||||||
|
|
||||||
@@ -415,7 +421,7 @@ export function useNanobotStream(
|
|||||||
projectionRef.current = projection;
|
projectionRef.current = projection;
|
||||||
return projection.messages;
|
return projection.messages;
|
||||||
});
|
});
|
||||||
}, [applyPendingStreamEvents, chatId, closeActiveAssistantStream]);
|
}, [applyPendingStreamEvents, chatId, closeActiveAssistantStream, setMessages]);
|
||||||
|
|
||||||
const schedulePendingStreamFlush = useCallback(function schedule() {
|
const schedulePendingStreamFlush = useCallback(function schedule() {
|
||||||
if (streamFrameRef.current !== null || streamTimerRef.current !== null) return;
|
if (streamFrameRef.current !== null || streamTimerRef.current !== null) return;
|
||||||
@@ -446,7 +452,7 @@ export function useNanobotStream(
|
|||||||
lastStreamFlushRef.current = performance.now();
|
lastStreamFlushRef.current = performance.now();
|
||||||
setMessages((prev) => applyPendingStreamEvents(prev, events));
|
setMessages((prev) => applyPendingStreamEvents(prev, events));
|
||||||
});
|
});
|
||||||
}, [applyPendingStreamEvents]);
|
}, [applyPendingStreamEvents, setMessages]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (threadVisible) {
|
if (threadVisible) {
|
||||||
@@ -500,7 +506,7 @@ export function useNanobotStream(
|
|||||||
setRunStartedAt(null);
|
setRunStartedAt(null);
|
||||||
setIsStreaming(false);
|
setIsStreaming(false);
|
||||||
});
|
});
|
||||||
}, [chatId, client, clearActivitySegment, flushPendingStreamEvents]);
|
}, [chatId, client, clearActivitySegment, flushPendingStreamEvents, setMessages]);
|
||||||
|
|
||||||
// Reset local state when switching chats. Do not reset on every
|
// Reset local state when switching chats. Do not reset on every
|
||||||
// ``initialMessages`` update: a brand-new chat can receive an empty/404
|
// ``initialMessages`` update: a brand-new chat can receive an empty/404
|
||||||
@@ -523,7 +529,7 @@ export function useNanobotStream(
|
|||||||
clearPendingStreamWork();
|
clearPendingStreamWork();
|
||||||
sideChannelTurnIdsRef.current.clear();
|
sideChannelTurnIdsRef.current.clear();
|
||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
}, [chatId, client, clearActivitySegment, clearPendingStreamWork]);
|
}, [chatId, client, clearActivitySegment, clearPendingStreamWork, setMessages]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (hasPendingToolCalls) setIsStreaming(true);
|
if (hasPendingToolCalls) setIsStreaming(true);
|
||||||
@@ -546,7 +552,7 @@ export function useNanobotStream(
|
|||||||
projectionRef.current = projection;
|
projectionRef.current = projection;
|
||||||
return projection.messages;
|
return projection.messages;
|
||||||
});
|
});
|
||||||
}, []);
|
}, [setMessages]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!chatId) return;
|
if (!chatId) return;
|
||||||
@@ -891,8 +897,8 @@ export function useNanobotStream(
|
|||||||
// deltas synchronously while they still belong to this subscription.
|
// deltas synchronously while they still belong to this subscription.
|
||||||
const pending = pendingStreamEventsRef.current;
|
const pending = pendingStreamEventsRef.current;
|
||||||
const snapshot = pending.length > 0
|
const snapshot = pending.length > 0
|
||||||
? applyPendingStreamEvents(committedMessagesRef.current, pending)
|
? applyPendingStreamEvents(messagesRef.current, pending)
|
||||||
: committedMessagesRef.current;
|
: messagesRef.current;
|
||||||
onStreamDetach?.(snapshot);
|
onStreamDetach?.(snapshot);
|
||||||
if (pending.length > 0) setMessages(snapshot);
|
if (pending.length > 0) setMessages(snapshot);
|
||||||
projectionRef.current = resetThreadProjectionCursor(projectionRef.current);
|
projectionRef.current = resetThreadProjectionCursor(projectionRef.current);
|
||||||
@@ -913,6 +919,7 @@ export function useNanobotStream(
|
|||||||
onTurnEnd,
|
onTurnEnd,
|
||||||
onStreamDetach,
|
onStreamDetach,
|
||||||
schedulePendingStreamFlush,
|
schedulePendingStreamFlush,
|
||||||
|
setMessages,
|
||||||
t,
|
t,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
@@ -987,7 +994,7 @@ export function useNanobotStream(
|
|||||||
client.sendMessage(chatId, outboundContent, wireMedia, clientOptions);
|
client.sendMessage(chatId, outboundContent, wireMedia, clientOptions);
|
||||||
return { turnId, userMessageId, sideChannel };
|
return { turnId, userMessageId, sideChannel };
|
||||||
},
|
},
|
||||||
[chatId, clearActivitySegment, client, flushPendingStreamEvents],
|
[chatId, clearActivitySegment, client, flushPendingStreamEvents, setMessages],
|
||||||
);
|
);
|
||||||
|
|
||||||
const stop = useCallback(() => {
|
const stop = useCallback(() => {
|
||||||
@@ -1003,7 +1010,7 @@ export function useNanobotStream(
|
|||||||
setRunStartedAt(null);
|
setRunStartedAt(null);
|
||||||
client.finishRunLocally(chatId);
|
client.finishRunLocally(chatId);
|
||||||
client.sendMessage(chatId, "/stop");
|
client.sendMessage(chatId, "/stop");
|
||||||
}, [chatId, clearActivitySegment, client, flushPendingStreamEvents]);
|
}, [chatId, clearActivitySegment, client, flushPendingStreamEvents, setMessages]);
|
||||||
|
|
||||||
const reconcileTurnComplete = useCallback(() => {
|
const reconcileTurnComplete = useCallback(() => {
|
||||||
clearPendingStreamWork();
|
clearPendingStreamWork();
|
||||||
|
|||||||
@@ -200,6 +200,39 @@ describe("temporary chat navigation", () => {
|
|||||||
.getAllByText("one")).toHaveLength(1));
|
.getAllByText("one")).toHaveLength(1));
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it.each(["stream_end", "turn_end", "message"] as const)(
|
||||||
|
"retains a received %s when navigation unmounts the pane before React commits",
|
||||||
|
async (event) => {
|
||||||
|
groupedTopics = true;
|
||||||
|
vi.stubGlobal("matchMedia", (query: string) => ({
|
||||||
|
matches: query.includes("max-width: 767px"), media: query,
|
||||||
|
addEventListener: vi.fn(), removeEventListener: vi.fn(),
|
||||||
|
}));
|
||||||
|
render(<App />);
|
||||||
|
await screen.findByRole("button", { name: "Temporary chat" });
|
||||||
|
act(() => TestSocket.current.open());
|
||||||
|
const chatId = await startTemporaryChat("Count from one to three");
|
||||||
|
const turnId = TestSocket.current.sent.find((frame) => frame.type === "message")?.turn_id;
|
||||||
|
act(() => {
|
||||||
|
if (event !== "message") {
|
||||||
|
TestSocket.current.receive({ event: "delta", chat_id: chatId, turn_id: turnId, text: "one two three" });
|
||||||
|
}
|
||||||
|
TestSocket.current.receive({ event, chat_id: chatId, turn_id: turnId, text: "one two three" });
|
||||||
|
const sidebar = screen.getByRole("navigation", { name: "Sidebar navigation" });
|
||||||
|
fireEvent.click(within(sidebar).getByRole("button", { name: "Second pane" }));
|
||||||
|
});
|
||||||
|
expect(screen.queryByTestId("workbench-pane-websocket:regular")).not.toBeInTheDocument();
|
||||||
|
await selectTopic("Count from one to three");
|
||||||
|
const region = screen.getByTestId("thread-message-region");
|
||||||
|
expect(region.textContent).toContain("one two three");
|
||||||
|
expect(within(region).getAllByText("one two three")).toHaveLength(1);
|
||||||
|
expect(within(region).getAllByText("Count from one to three")).toHaveLength(1);
|
||||||
|
if (event === "turn_end") {
|
||||||
|
expect(screen.queryByRole("button", { name: "Stop response" })).not.toBeInTheDocument();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
it("keeps multiple temporary chats isolated and releases the closed chat's cache", async () => {
|
it("keeps multiple temporary chats isolated and releases the closed chat's cache", async () => {
|
||||||
const deleteCache = vi.spyOn(ThreadMessageCache.prototype, "delete");
|
const deleteCache = vi.spyOn(ThreadMessageCache.prototype, "delete");
|
||||||
render(<App />);
|
render(<App />);
|
||||||
|
|||||||
Reference in new issue
Block a user