fix(webui): retain temporary chat state across navigation
This commit is contained in:
1 parent
7a317c3968
commit
bfb5129e6f
6 files changed
+370
-5
No files matched your search
@@ -63,6 +63,7 @@ import {
|
||||
import { displayTitle, sortSessions } from "@/lib/chat-groups";
|
||||
import { deriveTitle } from "@/lib/format";
|
||||
import { NanobotClient } from "@/lib/nanobot-client";
|
||||
import { ThreadMessageCache } from "@/lib/thread-message-cache";
|
||||
import { ClientProvider, useClient } from "@/providers/ClientProvider";
|
||||
import type {
|
||||
BootstrapResponse,
|
||||
@@ -1212,6 +1213,19 @@ function Shell({
|
||||
() => temporarySessionList.map((session) => session.chatId),
|
||||
[temporarySessionList],
|
||||
);
|
||||
// Pane shells can unmount during navigation. Keep replay state for this app
|
||||
// session, pinning temporary chats because they cannot reload disk history.
|
||||
const retainedTemporaryChatIdsRef = useRef(new Set<string>());
|
||||
const [threadMessageCache] = useState(() => new ThreadMessageCache(
|
||||
(key) => retainedTemporaryChatIdsRef.current.has(key),
|
||||
));
|
||||
useEffect(() => {
|
||||
const retained = new Set(temporaryChatIds);
|
||||
for (const chatId of retainedTemporaryChatIdsRef.current) {
|
||||
if (!retained.has(chatId)) threadMessageCache.delete(chatId);
|
||||
}
|
||||
retainedTemporaryChatIdsRef.current = retained;
|
||||
}, [temporaryChatIds, threadMessageCache]);
|
||||
|
||||
const navigate = useCallback(
|
||||
(route: ShellRoute, options?: { replace?: boolean }) => {
|
||||
@@ -2830,6 +2844,7 @@ function Shell({
|
||||
title={headerTitle}
|
||||
temporary={temporaryChatRequested}
|
||||
temporaryChatIds={temporaryChatIds}
|
||||
messageCache={threadMessageCache}
|
||||
temporaryChatEnabled={temporaryChatEnabled}
|
||||
onTemporaryChatEnabledChange={
|
||||
!activeKey ? onTemporaryChatEnabledChange : undefined
|
||||
@@ -2874,6 +2889,8 @@ function Shell({
|
||||
session={paneSession}
|
||||
sessions={sessions}
|
||||
title={pane.title}
|
||||
temporaryChatIds={temporaryChatIds}
|
||||
messageCache={threadMessageCache}
|
||||
onToggleSidebar={toggleSidebar}
|
||||
onNewChat={onNewChat}
|
||||
onCreateChat={onCreateChat}
|
||||
|
||||
@@ -395,6 +395,7 @@ interface ThreadShellProps {
|
||||
title: string;
|
||||
temporary?: boolean;
|
||||
temporaryChatIds?: readonly string[];
|
||||
messageCache?: ThreadMessageCache;
|
||||
temporaryChatEnabled?: boolean;
|
||||
onTemporaryChatEnabledChange?: (enabled: boolean) => void;
|
||||
onToggleSidebar: () => void;
|
||||
@@ -609,6 +610,7 @@ export function ThreadShell({
|
||||
title,
|
||||
temporary = false,
|
||||
temporaryChatIds = [],
|
||||
messageCache,
|
||||
temporaryChatEnabled = false,
|
||||
onTemporaryChatEnabledChange,
|
||||
onToggleSidebar,
|
||||
@@ -715,9 +717,11 @@ export function ThreadShell({
|
||||
const viewportRef = useRef<ThreadViewportHandle | null>(null);
|
||||
const activeViewportTurnByChatIdRef = useRef<Map<string, string>>(new Map());
|
||||
const knownTemporaryChatIdsRef = useRef(new Set<string>());
|
||||
const messageCacheRef = useRef(new ThreadMessageCache(
|
||||
const localMessageCacheRef = useRef(new ThreadMessageCache(
|
||||
(key) => knownTemporaryChatIdsRef.current.has(key),
|
||||
));
|
||||
const messageCacheRef = useRef(messageCache ?? localMessageCacheRef.current);
|
||||
messageCacheRef.current = messageCache ?? localMessageCacheRef.current;
|
||||
/** Last chatId we associated with the in-memory thread (for cache-on-switch). */
|
||||
const prevChatIdForCacheRef = useRef<string | null>(null);
|
||||
/** Skip one message-cache write right after chatId changes (messages may not match yet). */
|
||||
@@ -747,6 +751,9 @@ export function ThreadShell({
|
||||
setSubmittedViewportTurnId(null);
|
||||
onTurnEnd?.();
|
||||
}, [chatId, onTurnEnd]);
|
||||
const handleStreamDetach = useCallback((snapshot: UIMessage[]) => {
|
||||
if (chatId) messageCacheRef.current.set(chatId, projectWebuiThreadMessages(snapshot));
|
||||
}, [chatId]);
|
||||
const {
|
||||
messages,
|
||||
messagesReady,
|
||||
@@ -764,7 +771,7 @@ export function ThreadShell({
|
||||
setMessages,
|
||||
streamError,
|
||||
dismissStreamError,
|
||||
} = useNanobotStream(chatId, initial, hasPendingToolCalls, handleTurnEnd);
|
||||
} = useNanobotStream(chatId, initial, hasPendingToolCalls, handleTurnEnd, handleStreamDetach);
|
||||
|
||||
const loadTraceDetails = useCallback(async (refs: string[]) => {
|
||||
const requestKey = historyKey;
|
||||
@@ -843,12 +850,13 @@ export function ThreadShell({
|
||||
for (const chatId of retained) knownTemporaryChatIdsRef.current.add(chatId);
|
||||
for (const cachedChatId of knownTemporaryChatIdsRef.current) {
|
||||
if (!retained.has(cachedChatId)) {
|
||||
messageCacheRef.current.delete(cachedChatId);
|
||||
// Shared caches are retained/pruned by the app, not by individual panes.
|
||||
if (!messageCache) messageCacheRef.current.delete(cachedChatId);
|
||||
activeViewportTurnByChatIdRef.current.delete(cachedChatId);
|
||||
knownTemporaryChatIdsRef.current.delete(cachedChatId);
|
||||
}
|
||||
}
|
||||
}, [temporaryChatIds]);
|
||||
}, [messageCache, temporaryChatIds]);
|
||||
|
||||
const handleQuoteSelection = useCallback((text: string) => {
|
||||
setQuotedContext(text);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { acceptsCompactionPhase } from "../../../packages/client-events/notifications";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useThreadVisibility } from "@/hooks/useThreadVisibility";
|
||||
|
||||
@@ -135,6 +135,7 @@ export function useNanobotStream(
|
||||
initialMessages: UIMessage[] = [],
|
||||
hasPendingToolCalls = false,
|
||||
onTurnEnd?: () => void,
|
||||
onStreamDetach?: (messages: UIMessage[]) => void,
|
||||
): {
|
||||
messages: UIMessage[];
|
||||
/** Whether ``messages`` belongs to the current ``chatId`` after a session switch. */
|
||||
@@ -173,6 +174,8 @@ export function useNanobotStream(
|
||||
const { t } = useTranslation();
|
||||
const initialRunStartedAt = chatId ? client.getRunStartedAt(chatId) : null;
|
||||
const [messages, setMessages] = useState<UIMessage[]>(initialMessages);
|
||||
const committedMessagesRef = useRef(messages);
|
||||
useLayoutEffect(() => { committedMessagesRef.current = messages; }, [messages]);
|
||||
const [messageOwnerChatId, setMessageOwnerChatId] = useState(chatId);
|
||||
/** If history ends in unfinished agent activity, keep the loading spinner alive. */
|
||||
const initialStreaming = hasPendingAgentActivity(initialMessages);
|
||||
@@ -884,11 +887,20 @@ export function useNanobotStream(
|
||||
const unsub = client.onChat(chatId, handle);
|
||||
return () => {
|
||||
unsub();
|
||||
// Navigation may happen before the throttled paint. Snapshot the pending
|
||||
// deltas synchronously while they still belong to this subscription.
|
||||
const pending = pendingStreamEventsRef.current;
|
||||
const snapshot = pending.length > 0
|
||||
? applyPendingStreamEvents(committedMessagesRef.current, pending)
|
||||
: committedMessagesRef.current;
|
||||
onStreamDetach?.(snapshot);
|
||||
if (pending.length > 0) setMessages(snapshot);
|
||||
projectionRef.current = resetThreadProjectionCursor(projectionRef.current);
|
||||
clearPendingStreamWork();
|
||||
};
|
||||
}, [
|
||||
applyProjectionEvent,
|
||||
applyPendingStreamEvents,
|
||||
applyStreamError,
|
||||
chatId,
|
||||
closeActiveAssistantStream,
|
||||
@@ -899,6 +911,7 @@ export function useNanobotStream(
|
||||
isSideChannelEvent,
|
||||
notifyInBackground,
|
||||
onTurnEnd,
|
||||
onStreamDetach,
|
||||
schedulePendingStreamFlush,
|
||||
t,
|
||||
]);
|
||||
|
||||
@@ -1300,6 +1300,10 @@ export class NanobotClient {
|
||||
this.pendingInboundByChat.set(chatId, q);
|
||||
}
|
||||
q.push(ev);
|
||||
// Temporary chats have no canonical history to recover evicted events from.
|
||||
// Like their pinned message snapshots, retain them until resubscribe, close
|
||||
// or disconnect. Disk-backed chats keep the bounded replay tail below.
|
||||
if (this.temporaryChatIds.has(chatId)) return;
|
||||
const over = q.length - NanobotClient.PENDING_INBOUND_MAX;
|
||||
if (over > 0) {
|
||||
q.splice(0, over);
|
||||
|
||||
@@ -71,6 +71,38 @@ afterEach(() => {
|
||||
});
|
||||
|
||||
describe("NanobotClient", () => {
|
||||
it("bounds regular replay tails but retains temporary events until discard", async () => {
|
||||
const client = new NanobotClient({
|
||||
url: "ws://test", reconnect: false,
|
||||
socketFactory: (url) => new FakeSocket(url) as unknown as WebSocket,
|
||||
});
|
||||
client.connect();
|
||||
const socket = lastSocket();
|
||||
socket.fakeOpen();
|
||||
const created = client.newTemporaryChat();
|
||||
socket.fakeMessage({ event: "attached", chat_id: "temporary", temporary: true });
|
||||
await created;
|
||||
for (let index = 0; index < 2_010; index++) {
|
||||
for (const chatId of ["regular", "temporary"]) {
|
||||
socket.fakeMessage({ event: "delta", chat_id: chatId, text: String(index) });
|
||||
}
|
||||
}
|
||||
const regular = vi.fn();
|
||||
const temporary = vi.fn();
|
||||
client.onChat("regular", regular);
|
||||
const unsubscribe = client.onChat("temporary", temporary);
|
||||
expect(regular).toHaveBeenCalledTimes(2_000);
|
||||
expect(regular.mock.calls[0][0].text).toBe("10");
|
||||
expect(temporary.mock.calls.filter(([event]) => event.event === "delta")).toHaveLength(2_010);
|
||||
unsubscribe();
|
||||
socket.fakeMessage({ event: "delta", chat_id: "temporary", text: "discard me" });
|
||||
client.discardTemporaryChat("temporary");
|
||||
const discarded = vi.fn();
|
||||
client.onChat("temporary", discarded);
|
||||
expect(discarded).not.toHaveBeenCalled();
|
||||
client.close();
|
||||
});
|
||||
|
||||
it("reconciles simultaneous client submissions to the gateway-owned turn", () => {
|
||||
const client = new NanobotClient({
|
||||
url: "ws://test",
|
||||
|
||||
@@ -0,0 +1,291 @@
|
||||
import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import App from "@/App";
|
||||
import { ThreadMessageCache } from "@/lib/thread-message-cache";
|
||||
import type { InboundEvent, Outbound } from "@/lib/types";
|
||||
|
||||
let groupedTopics = false;
|
||||
|
||||
vi.mock("@/lib/bootstrap", async (importOriginal) => ({
|
||||
...await importOriginal<typeof import("@/lib/bootstrap")>(),
|
||||
fetchBootstrap: async () => ({ token: "test", api_token: "test", ws_path: "/" }),
|
||||
deriveWsUrl: () => "ws://test",
|
||||
}));
|
||||
|
||||
// Only the network is fake: App, the workbench, stream hook and multiplexed client are real.
|
||||
class TestSocket {
|
||||
static current: TestSocket;
|
||||
readyState = 0;
|
||||
sent: Outbound[] = [];
|
||||
onopen: (() => void) | null = null;
|
||||
onmessage: ((event: MessageEvent) => void) | null = null;
|
||||
onclose: (() => void) | null = null;
|
||||
private nextChat = 0;
|
||||
|
||||
constructor() {
|
||||
TestSocket.current = this;
|
||||
}
|
||||
|
||||
open() {
|
||||
this.readyState = 1;
|
||||
this.onopen?.();
|
||||
}
|
||||
|
||||
close() {
|
||||
this.readyState = 3;
|
||||
this.onclose?.();
|
||||
}
|
||||
|
||||
receive(event: InboundEvent) {
|
||||
this.onmessage?.(new MessageEvent("message", { data: JSON.stringify(event) }));
|
||||
}
|
||||
|
||||
send(data: string) {
|
||||
const frame = JSON.parse(data) as Outbound;
|
||||
this.sent.push(frame);
|
||||
if (frame.type === "new_temporary_chat") {
|
||||
const chatId = `00000000-0000-4000-8000-${String(++this.nextChat).padStart(12, "0")}`;
|
||||
queueMicrotask(() => this.receive({ event: "attached", chat_id: chatId, temporary: true }));
|
||||
} else if (frame.type === "set_sidebar_state") {
|
||||
queueMicrotask(() => this.receive({ event: "sidebar_state_updated", state: frame.state }));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function startTemporaryChat(text: string) {
|
||||
fireEvent.click(await screen.findByRole("button", { name: "Temporary chat" }));
|
||||
fireEvent.change(screen.getByLabelText("Message input"), { target: { value: text } });
|
||||
fireEvent.click(screen.getByRole("button", { name: "Send message" }));
|
||||
await waitFor(() => expect(window.location.hash).toMatch(/^#\/temporary\//));
|
||||
const chatId = window.location.hash.split("/").at(-1)!;
|
||||
await waitFor(() => expect(
|
||||
within(screen.getByTestId("thread-message-region")).getByText(text),
|
||||
).toBeInTheDocument());
|
||||
await waitFor(() => expect(TestSocket.current.sent).toContainEqual(expect.objectContaining({
|
||||
type: "message", chat_id: chatId, content: text,
|
||||
})));
|
||||
const frame = TestSocket.current.sent.find((frame) => frame.type === "message" && frame.chat_id === chatId);
|
||||
if (frame?.type !== "message") throw new Error("Missing submitted turn");
|
||||
act(() => TestSocket.current.receive({
|
||||
event: "goal_status", chat_id: chatId, turn_id: frame.turn_id,
|
||||
status: "running", started_at: Date.now() / 1000,
|
||||
}));
|
||||
return chatId;
|
||||
}
|
||||
|
||||
async function selectTopic(name: string) {
|
||||
const sidebar = screen.getByRole("navigation", { name: "Sidebar navigation" });
|
||||
fireEvent.click(within(sidebar).getByRole("button", { name }));
|
||||
}
|
||||
|
||||
describe("temporary chat navigation", () => {
|
||||
beforeEach(() => {
|
||||
groupedTopics = false;
|
||||
localStorage.clear();
|
||||
sessionStorage.clear();
|
||||
window.history.replaceState(null, "", "/");
|
||||
vi.stubGlobal("WebSocket", TestSocket);
|
||||
vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => {
|
||||
const path = String(input);
|
||||
if (path === "/api/sessions") {
|
||||
return Response.json({ sessions: ["regular", ...(groupedTopics ? ["child"] : [])].map((id) => ({
|
||||
key: `websocket:${id}`,
|
||||
title: id === "regular" ? "Regular topic" : "Second pane",
|
||||
created_at: "2026-09-01T00:00:00Z",
|
||||
updated_at: "2026-09-01T00:00:00Z",
|
||||
})) });
|
||||
}
|
||||
if (path === "/api/webui/sidebar-state" && groupedTopics) {
|
||||
return Response.json({ workbench: { version: 1, tabs: {
|
||||
"tab:websocket:regular": {
|
||||
explicit: true, title: "Regular topic",
|
||||
paneKeys: ["websocket:regular", "websocket:child"], layout: "columns",
|
||||
},
|
||||
} } });
|
||||
}
|
||||
return new Response(null, { status: 404 });
|
||||
}));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
vi.useRealTimers();
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it("keeps messages when navigating to a regular workbench and back", async () => {
|
||||
render(<App />);
|
||||
await screen.findByRole("button", { name: "Temporary chat" });
|
||||
act(() => TestSocket.current.open());
|
||||
const chatId = await startTemporaryChat("Count from one to three");
|
||||
|
||||
await selectTopic("Regular topic");
|
||||
await waitFor(() => expect(window.location.hash).toBe("#/chat/websocket%3Aregular"));
|
||||
await selectTopic("Count from one to three");
|
||||
await waitFor(() => expect(window.location.hash).toBe(`#/temporary/${chatId}`));
|
||||
|
||||
expect(within(screen.getByTestId("thread-message-region")).getByText(
|
||||
"Count from one to three",
|
||||
)).toBeInTheDocument();
|
||||
expect(screen.queryByTestId("hero-greeting")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it.each(["before leaving", "while away", "after returning"])(
|
||||
"preserves streamed output when the turn finishes %s",
|
||||
async (completion) => {
|
||||
render(<App />);
|
||||
await screen.findByRole("button", { name: "Temporary chat" });
|
||||
act(() => TestSocket.current.open());
|
||||
const chatId = await startTemporaryChat("Count from one to three");
|
||||
const socket = TestSocket.current;
|
||||
const turnId = socket.sent.find((frame) => frame.type === "message")?.turn_id;
|
||||
const emit = (event: InboundEvent) => act(() => socket.receive(event));
|
||||
const finish = () => {
|
||||
emit({ event: "delta", chat_id: chatId, turn_id: turnId, text: " two three" });
|
||||
emit({ event: "stream_end", chat_id: chatId, turn_id: turnId });
|
||||
emit({ event: "turn_end", chat_id: chatId, turn_id: turnId });
|
||||
};
|
||||
emit({ event: "delta", chat_id: chatId, turn_id: turnId, text: "one" });
|
||||
await screen.findByText("one");
|
||||
if (completion === "before leaving") finish();
|
||||
|
||||
await selectTopic("Regular topic");
|
||||
if (completion === "while away") finish();
|
||||
await selectTopic("Count from one to three");
|
||||
if (completion === "after returning") {
|
||||
expect(screen.getByRole("button", { name: "Stop response" })).toBeInTheDocument();
|
||||
finish();
|
||||
}
|
||||
|
||||
await waitFor(() => expect(within(screen.getByTestId("thread-message-region"))
|
||||
.getAllByText("one two three")).toHaveLength(1));
|
||||
expect(within(screen.getByTestId("thread-message-region"))
|
||||
.getAllByText("Count from one to three")).toHaveLength(1);
|
||||
expect(screen.queryByRole("button", { name: "Stop response" })).not.toBeInTheDocument();
|
||||
},
|
||||
);
|
||||
|
||||
it("keeps temporary messages when a compact workbench unmounts the root pane", async () => {
|
||||
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());
|
||||
await startTemporaryChat("Count from one to three");
|
||||
await selectTopic("Second pane");
|
||||
expect(screen.queryByTestId("workbench-pane-websocket:regular")).not.toBeInTheDocument();
|
||||
await selectTopic("Count from one to three");
|
||||
expect(within(screen.getByTestId("thread-message-region"))
|
||||
.getByText("Count from one to three")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("retains deltas received just before switching away, before the next paint", async () => {
|
||||
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(() => {
|
||||
TestSocket.current.receive({ event: "delta", chat_id: chatId, turn_id: turnId, text: "one" });
|
||||
const sidebar = screen.getByRole("navigation", { name: "Sidebar navigation" });
|
||||
fireEvent.click(within(sidebar).getByRole("button", { name: "Regular topic" }));
|
||||
});
|
||||
await selectTopic("Count from one to three");
|
||||
await waitFor(() => expect(within(screen.getByTestId("thread-message-region"))
|
||||
.getAllByText("one")).toHaveLength(1));
|
||||
});
|
||||
|
||||
it("keeps multiple temporary chats isolated and releases the closed chat's cache", async () => {
|
||||
const deleteCache = vi.spyOn(ThreadMessageCache.prototype, "delete");
|
||||
render(<App />);
|
||||
await screen.findByRole("button", { name: "Temporary chat" });
|
||||
act(() => TestSocket.current.open());
|
||||
const firstChatId = await startTemporaryChat("Count from one to three");
|
||||
const firstTurnId = TestSocket.current.sent.find((frame) => frame.type === "message")?.turn_id;
|
||||
await selectTopic("New topic");
|
||||
const secondChatId = await startTemporaryChat("List three colors");
|
||||
act(() => {
|
||||
TestSocket.current.receive({ event: "delta", chat_id: firstChatId, turn_id: firstTurnId, text: "one two three" });
|
||||
TestSocket.current.receive({ event: "turn_end", chat_id: firstChatId, turn_id: firstTurnId });
|
||||
});
|
||||
expect(screen.queryByText("one two three")).not.toBeInTheDocument();
|
||||
await selectTopic("Regular topic");
|
||||
await selectTopic("Count from one to three");
|
||||
await waitFor(() => expect(within(screen.getByTestId("thread-message-region"))
|
||||
.getAllByText("one two three")).toHaveLength(1));
|
||||
expect(within(screen.getByTestId("thread-message-region"))
|
||||
.queryByText("List three colors")).not.toBeInTheDocument();
|
||||
await selectTopic("List three colors");
|
||||
expect(within(screen.getByTestId("thread-message-region"))
|
||||
.getAllByText("List three colors")).toHaveLength(1);
|
||||
|
||||
await selectTopic("Close temporary chat: Count from one to three");
|
||||
expect(deleteCache).toHaveBeenCalledWith(firstChatId);
|
||||
expect(TestSocket.current.sent).toContainEqual({ type: "discard_temporary_chat", chat_id: firstChatId });
|
||||
expect(window.location.hash).toBe(`#/temporary/${secondChatId}`);
|
||||
await selectTopic("Close temporary chat: List three colors");
|
||||
expect(deleteCache).toHaveBeenCalledWith(secondChatId);
|
||||
expect(await screen.findByTestId("hero-greeting")).toBeInTheDocument();
|
||||
for (const cache of deleteCache.mock.contexts) {
|
||||
if (!(cache instanceof ThreadMessageCache)) throw new Error("Expected thread message cache");
|
||||
expect(cache.get(firstChatId)).toBeUndefined();
|
||||
expect(cache.get(secondChatId)).toBeUndefined();
|
||||
}
|
||||
|
||||
// No history reads, sidebar persistence or browser storage may contain these chats.
|
||||
const requests = vi.mocked(fetch).mock.calls.map(([url]) => String(url));
|
||||
for (const chatId of [firstChatId, secondChatId]) {
|
||||
expect(requests.some((url) => url.includes(chatId))).toBe(false);
|
||||
expect(JSON.stringify(TestSocket.current.sent.filter((frame) => frame.type === "set_sidebar_state")))
|
||||
.not.toContain(chatId);
|
||||
}
|
||||
for (const storage of [localStorage, sessionStorage]) {
|
||||
const values = Array.from({ length: storage.length }, (_, index) => storage.getItem(storage.key(index)!));
|
||||
expect(JSON.stringify(values)).not.toMatch(/Count from one to three|List three colors|one two three/);
|
||||
}
|
||||
deleteCache.mockRestore();
|
||||
});
|
||||
|
||||
it("still ends temporary chats and clears their cache on disconnect", async () => {
|
||||
const deleteCache = vi.spyOn(ThreadMessageCache.prototype, "delete");
|
||||
render(<App />);
|
||||
await screen.findByRole("button", { name: "Temporary chat" });
|
||||
act(() => TestSocket.current.open());
|
||||
const chatId = await startTemporaryChat("Count from one to three");
|
||||
await selectTopic("Regular topic");
|
||||
// Do not let the synthetic disconnected client reconnect after teardown.
|
||||
vi.useFakeTimers();
|
||||
await act(async () => TestSocket.current.close());
|
||||
expect(deleteCache).toHaveBeenCalledWith(chatId);
|
||||
for (const cache of deleteCache.mock.contexts) {
|
||||
if (!(cache instanceof ThreadMessageCache)) throw new Error("Expected thread message cache");
|
||||
expect(cache.get(chatId)).toBeUndefined();
|
||||
}
|
||||
expect(screen.queryByRole("button", { name: "Count from one to three" })).not.toBeInTheDocument();
|
||||
deleteCache.mockRestore();
|
||||
});
|
||||
|
||||
it("does not truncate a temporary reply that keeps streaming while away", async () => {
|
||||
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;
|
||||
await selectTopic("Regular topic");
|
||||
const chunks = Array.from({ length: 2_010 }, (_, index) => `word${index} `);
|
||||
act(() => {
|
||||
for (const text of chunks) {
|
||||
TestSocket.current.receive({ event: "delta", chat_id: chatId, turn_id: turnId, text });
|
||||
}
|
||||
TestSocket.current.receive({ event: "turn_end", chat_id: chatId, turn_id: turnId });
|
||||
});
|
||||
await selectTopic("Count from one to three");
|
||||
await waitFor(() => expect(within(screen.getByTestId("thread-message-region"))
|
||||
.getAllByText(chunks.join("").trim())).toHaveLength(1));
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user