fix(webui): correlate chat requests and cancel stale reconnects (#6617)
* fix(webui): correlate chat requests and cancel stale reconnects * refactor(webui): remove chat request capability negotiation * docs(webui): clarify version pairing and cover HTTP startup * test(webui): focus lifecycle coverage and clarify support policy
This commit is contained in:
1 parent
9f7ae6fb7b
commit
1046a37be1
16 files changed
+478
-138
No files matched your search
+4
-3
@@ -611,8 +611,9 @@ export default function App() {
|
||||
const bootstrapSecretRef = useRef("");
|
||||
|
||||
const refreshReadyClient = useCallback(
|
||||
async (client: NanobotClient, fallbackSurface: RuntimeSurface) => {
|
||||
async (client: NanobotClient, fallbackSurface: RuntimeSurface, signal?: AbortSignal) => {
|
||||
const boot = await fetchBootstrap("", bootstrapSecretRef.current);
|
||||
signal?.throwIfAborted();
|
||||
const url = deriveWsUrl(boot.ws_path, boot.token, boot.ws_url);
|
||||
const runtimeSurface = resolveRuntimeSurface(boot.runtime_surface, fallbackSurface);
|
||||
const runtimeHost = createRuntimeHost(runtimeSurface, boot.runtime_capabilities);
|
||||
@@ -661,9 +662,9 @@ export default function App() {
|
||||
url,
|
||||
maxFrameBytes: boot.limits?.transport.max_frame_bytes,
|
||||
socketFactory: runtimeHost.socketFactory,
|
||||
onReauth: async () => {
|
||||
onReauth: async (signal) => {
|
||||
try {
|
||||
const refreshed = await refreshReadyClient(client, runtimeSurface);
|
||||
const refreshed = await refreshReadyClient(client, runtimeSurface, signal);
|
||||
return refreshed.url;
|
||||
} catch {
|
||||
return null;
|
||||
|
||||
+105
-86
@@ -143,8 +143,11 @@ class WebUIMutationError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
type ChatRequestFrame = Extract<Outbound, { type: "new_chat" | "new_temporary_chat" | "fork_chat" }>;
|
||||
|
||||
interface PendingChatRequest extends PendingRequest<string> {
|
||||
temporary: boolean;
|
||||
frame: ChatRequestFrame & { request_id: string };
|
||||
phase: "queued" | "sent";
|
||||
}
|
||||
|
||||
const SYSTEM_COMMAND_TURN_PREFIX = "webui-system:";
|
||||
@@ -165,8 +168,8 @@ export interface NanobotClientOptions {
|
||||
reconnect?: boolean;
|
||||
/** Maximum UTF-8 bytes accepted for one websocket message. */
|
||||
maxFrameBytes?: number;
|
||||
/** Called when a connection drops so the app can refresh its token. */
|
||||
onReauth?: () => Promise<string | null>;
|
||||
/** Refresh authentication; discard side effects when the connection's signal aborts. */
|
||||
onReauth?: (signal: AbortSignal) => Promise<string | null>;
|
||||
socketFactory?: (url: string) => WebSocket;
|
||||
maxBackoffMs?: number;
|
||||
}
|
||||
@@ -250,12 +253,13 @@ export class NanobotClient {
|
||||
/** Last tracked application frame written, for conservative transport-error attribution. */
|
||||
private lastSocketMessageSend: { chatId: string; turnId: string } | null = null;
|
||||
private goalStateByChatId = new Map<string, GoalStateWsPayload>();
|
||||
private pendingNewChat: PendingChatRequest | null = null;
|
||||
private pendingChatRequest: PendingChatRequest | null = null;
|
||||
private pendingTranscriptions = new Map<string, PendingRequest<string>>();
|
||||
private pendingSystemCommands = new Map<string, PendingRequest<void>>();
|
||||
private pendingWebUIRequests = new Map<string, PendingWebUIRequest>();
|
||||
private sendQueue: Outbound[] = [];
|
||||
private reconnectAttempts = 0;
|
||||
private reconnectController: AbortController | null = null;
|
||||
private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
private readonly shouldReconnect: boolean;
|
||||
private readonly maxBackoffMs: number;
|
||||
@@ -458,7 +462,7 @@ export class NanobotClient {
|
||||
if (
|
||||
ev.detail === "workspace_scope_rejected"
|
||||
&& ev.chat_id === undefined
|
||||
&& this.pendingNewChat
|
||||
&& this.pendingChatRequest
|
||||
) return null;
|
||||
return this.runs.soleSentTurn(this.lastSocketMessageSend, ev.chat_id);
|
||||
}
|
||||
@@ -550,33 +554,27 @@ export class NanobotClient {
|
||||
|
||||
connect(): void {
|
||||
if (this.socket && this.socket.readyState < WS_CLOSING) return;
|
||||
this.cancelReconnect();
|
||||
this.intentionallyClosed = false;
|
||||
this.setStatus("connecting");
|
||||
const sock = this.socketFactory(this.currentUrl);
|
||||
this.socket = sock;
|
||||
sock.onopen = () => this.handleOpen();
|
||||
sock.onmessage = (ev) => this.handleMessage(ev);
|
||||
sock.onerror = () => this.setStatus("error");
|
||||
sock.onclose = (ev) => this.handleClose(ev);
|
||||
sock.onopen = () => { if (this.socket === sock) this.handleOpen(); };
|
||||
sock.onmessage = (ev) => { if (this.socket === sock) this.handleMessage(ev); };
|
||||
sock.onerror = () => { if (this.socket === sock) this.setStatus("error"); };
|
||||
sock.onclose = (ev) => { if (this.socket === sock) this.handleClose(ev); };
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.upload = null;
|
||||
this.receipts.close();
|
||||
this.intentionallyClosed = true;
|
||||
if (this.reconnectTimer) {
|
||||
clearTimeout(this.reconnectTimer);
|
||||
this.reconnectTimer = null;
|
||||
}
|
||||
const sock = this.socket;
|
||||
this.socket = null;
|
||||
// Settle connection-owned work now, not in a possibly delayed close callback.
|
||||
this.handleClose();
|
||||
try {
|
||||
sock?.close();
|
||||
} catch {
|
||||
// ignore
|
||||
// Local cleanup has already completed.
|
||||
}
|
||||
this.clearTemporaryChats();
|
||||
this.setStatus("closed");
|
||||
}
|
||||
|
||||
discardTemporaryChat(chatId: string): void {
|
||||
@@ -589,37 +587,55 @@ export class NanobotClient {
|
||||
|
||||
/** Ask the server to provision a new chat_id; resolves with the assigned id. */
|
||||
newChat(timeoutMs: number = 5_000, workspaceScope?: WorkspaceScopePayload | null): Promise<string> {
|
||||
if (this.pendingNewChat) {
|
||||
return Promise.reject(new Error("newChat already in flight"));
|
||||
}
|
||||
return new Promise<string>((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
this.pendingNewChat = null;
|
||||
reject(new Error("newChat timed out"));
|
||||
}, timeoutMs);
|
||||
this.pendingNewChat = { resolve, reject, timer, temporary: false };
|
||||
this.queueSend({
|
||||
type: "new_chat",
|
||||
...(workspaceScope ? { workspace_scope: workspaceScope } : {}),
|
||||
});
|
||||
});
|
||||
return this.requestChat({
|
||||
type: "new_chat",
|
||||
...(workspaceScope ? { workspace_scope: workspaceScope } : {}),
|
||||
}, timeoutMs, "newChat");
|
||||
}
|
||||
|
||||
/** Ask the WebUI gateway to create a connection-owned non-persistent chat. */
|
||||
newTemporaryChat(timeoutMs: number = 5_000): Promise<string> {
|
||||
if (this.pendingNewChat) {
|
||||
return Promise.reject(new Error("newChat already in flight"));
|
||||
}
|
||||
return this.requestChat({ type: "new_temporary_chat" }, timeoutMs, "newTemporaryChat");
|
||||
}
|
||||
|
||||
private requestChat(frame: ChatRequestFrame, timeoutMs: number, name: string): Promise<string> {
|
||||
if (this.intentionallyClosed) return Promise.reject(new Error("socket closed"));
|
||||
if (this.pendingChatRequest) return Promise.reject(new Error("newChat already in flight"));
|
||||
return new Promise<string>((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
this.pendingNewChat = null;
|
||||
reject(new Error("newTemporaryChat timed out"));
|
||||
}, timeoutMs);
|
||||
this.pendingNewChat = { resolve, reject, timer, temporary: true };
|
||||
this.queueSend({ type: "new_temporary_chat" });
|
||||
const pending: PendingChatRequest = {
|
||||
frame: { ...frame, request_id: crypto.randomUUID() },
|
||||
phase: "queued", resolve, reject,
|
||||
timer: setTimeout(() => {
|
||||
const sent = pending.phase === "sent";
|
||||
this.pendingChatRequest = null;
|
||||
reject(new Error(`${name} timed out${sent ? "; creation outcome is unknown" : " before sending"}`));
|
||||
}, timeoutMs),
|
||||
};
|
||||
this.pendingChatRequest = pending;
|
||||
this.sendPendingChat();
|
||||
});
|
||||
}
|
||||
|
||||
private sendPendingChat(): void {
|
||||
const pending = this.pendingChatRequest;
|
||||
if (!pending || pending.phase !== "queued" || this.socket?.readyState !== WS_OPEN) return;
|
||||
try {
|
||||
this.socket.send(JSON.stringify(pending.frame));
|
||||
pending.phase = "sent";
|
||||
this.lastSocketMessageSend = null;
|
||||
} catch {
|
||||
this.rejectPendingChat("Could not send chat request");
|
||||
}
|
||||
}
|
||||
|
||||
private rejectPendingChat(detail: string): void {
|
||||
const pending = this.pendingChatRequest;
|
||||
if (!pending) return;
|
||||
this.pendingChatRequest = null;
|
||||
clearTimeout(pending.timer);
|
||||
pending.reject(new Error(detail));
|
||||
}
|
||||
|
||||
transcribeAudio(
|
||||
dataUrl: string,
|
||||
options?: { durationMs?: number; timeoutMs?: number },
|
||||
@@ -710,22 +726,12 @@ export class NanobotClient {
|
||||
title?: string,
|
||||
timeoutMs: number = 5_000,
|
||||
): Promise<string> {
|
||||
if (this.pendingNewChat) {
|
||||
return Promise.reject(new Error("newChat already in flight"));
|
||||
}
|
||||
return new Promise<string>((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
this.pendingNewChat = null;
|
||||
reject(new Error("forkChat timed out"));
|
||||
}, timeoutMs);
|
||||
this.pendingNewChat = { resolve, reject, timer, temporary: false };
|
||||
this.queueSend({
|
||||
type: "fork_chat",
|
||||
source_chat_id: sourceChatId,
|
||||
before_user_index: beforeUserIndex,
|
||||
...(title?.trim() ? { title: title.trim() } : {}),
|
||||
});
|
||||
});
|
||||
return this.requestChat({
|
||||
type: "fork_chat",
|
||||
source_chat_id: sourceChatId,
|
||||
before_user_index: beforeUserIndex,
|
||||
...(title?.trim() ? { title: title.trim() } : {}),
|
||||
}, timeoutMs, "forkChat");
|
||||
}
|
||||
|
||||
attach(chatId: string): void {
|
||||
@@ -891,6 +897,7 @@ export class NanobotClient {
|
||||
}
|
||||
const queued = this.sendQueue.splice(0);
|
||||
for (const frame of queued) this.rawSend(frame);
|
||||
this.sendPendingChat();
|
||||
}
|
||||
|
||||
private handleMessage(ev: MessageEvent): void {
|
||||
@@ -930,6 +937,17 @@ export class NanobotClient {
|
||||
return;
|
||||
}
|
||||
|
||||
if (parsed.event === "error" && parsed.request_id !== undefined) {
|
||||
const pending = this.pendingChatRequest;
|
||||
if (pending && pending.phase !== "queued" && pending.frame.request_id === parsed.request_id) {
|
||||
this.rejectPendingChat([parsed.detail, parsed.reason].filter(Boolean).join(":") || "server error");
|
||||
if (parsed.detail === "workspace_scope_rejected") {
|
||||
this.emitError({ kind: "workspace_scope_rejected", reason: parsed.reason });
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (parsed.event === "error" && !parsed.turn_id) {
|
||||
const fallback = this.legacyRejectionTarget(parsed);
|
||||
if (fallback) {
|
||||
@@ -1006,19 +1024,24 @@ export class NanobotClient {
|
||||
}
|
||||
|
||||
if (parsed.event === "attached") {
|
||||
const pending = this.pendingChatRequest;
|
||||
const known = this.knownChats.has(parsed.chat_id) || this.temporaryChatIds.has(parsed.chat_id);
|
||||
const matches = pending?.phase === "sent" && parsed.request_id === pending.frame.request_id;
|
||||
if (matches) {
|
||||
clearTimeout(pending.timer);
|
||||
this.pendingChatRequest = null;
|
||||
pending.resolve(parsed.chat_id);
|
||||
}
|
||||
if (!matches && parsed.request_id !== undefined && !known) {
|
||||
// A late success is not a new user selection; temporary resources need disposal.
|
||||
if (parsed.temporary) this.rawSend({ type: "discard_temporary_chat", chat_id: parsed.chat_id });
|
||||
return;
|
||||
}
|
||||
if (parsed.temporary === true) {
|
||||
this.temporaryChatIds.add(parsed.chat_id);
|
||||
} else {
|
||||
this.knownChats.add(parsed.chat_id);
|
||||
}
|
||||
if (
|
||||
this.pendingNewChat
|
||||
&& this.pendingNewChat.temporary === (parsed.temporary === true)
|
||||
) {
|
||||
clearTimeout(this.pendingNewChat.timer);
|
||||
this.pendingNewChat.resolve(parsed.chat_id);
|
||||
this.pendingNewChat = null;
|
||||
}
|
||||
this.dispatch(parsed.chat_id, parsed);
|
||||
return;
|
||||
}
|
||||
@@ -1062,19 +1085,6 @@ export class NanobotClient {
|
||||
chatId: parsed.chat_id,
|
||||
turnId: parsed.turn_id,
|
||||
});
|
||||
if (this.pendingNewChat) {
|
||||
clearTimeout(this.pendingNewChat.timer);
|
||||
this.pendingNewChat.reject(new Error(`workspace_scope_rejected:${parsed.reason || ""}`));
|
||||
this.pendingNewChat = null;
|
||||
}
|
||||
}
|
||||
|
||||
if (parsed.event === "error" && this.pendingNewChat) {
|
||||
clearTimeout(this.pendingNewChat.timer);
|
||||
const detail = typeof parsed.detail === "string" ? parsed.detail : "server error";
|
||||
const reason = typeof parsed.reason === "string" && parsed.reason ? `:${parsed.reason}` : "";
|
||||
this.pendingNewChat.reject(new Error(`${detail}${reason}`));
|
||||
this.pendingNewChat = null;
|
||||
}
|
||||
|
||||
if (correlatedChatId) {
|
||||
@@ -1140,16 +1150,13 @@ export class NanobotClient {
|
||||
}
|
||||
|
||||
private handleClose(event?: { code?: number }): void {
|
||||
this.cancelReconnect();
|
||||
this.upload = null;
|
||||
this.receipts.close();
|
||||
this.socket = null;
|
||||
this.clearTemporaryChats();
|
||||
const willReconnect = !this.intentionallyClosed && this.shouldReconnect;
|
||||
if (this.pendingNewChat) {
|
||||
clearTimeout(this.pendingNewChat.timer);
|
||||
this.pendingNewChat.reject(new Error("socket closed"));
|
||||
this.pendingNewChat = null;
|
||||
}
|
||||
this.rejectPendingChat("socket closed");
|
||||
this.rejectAllTranscriptions("socket closed");
|
||||
if (!willReconnect) {
|
||||
for (const pending of this.pendingWebUIRequests.values()) {
|
||||
@@ -1252,20 +1259,32 @@ export class NanobotClient {
|
||||
pending.reject(new Error(detail));
|
||||
}
|
||||
|
||||
private cancelReconnect(): void {
|
||||
this.reconnectController?.abort();
|
||||
this.reconnectController = null;
|
||||
if (this.reconnectTimer) clearTimeout(this.reconnectTimer);
|
||||
this.reconnectTimer = null;
|
||||
}
|
||||
|
||||
private scheduleReconnect(): void {
|
||||
const controller = new AbortController();
|
||||
this.reconnectController = controller;
|
||||
this.setStatus("reconnecting");
|
||||
const attempt = this.reconnectAttempts++;
|
||||
const delay = Math.min(500 * 2 ** attempt, this.maxBackoffMs);
|
||||
this.reconnectTimer = setTimeout(async () => {
|
||||
this.reconnectTimer = null;
|
||||
if (controller.signal.aborted) return;
|
||||
let refreshed: string | null = null;
|
||||
if (this.options.onReauth) {
|
||||
try {
|
||||
const refreshed = await this.options.onReauth();
|
||||
if (refreshed) this.currentUrl = refreshed;
|
||||
refreshed = await this.options.onReauth(controller.signal);
|
||||
} catch {
|
||||
// fall through to retry with current URL
|
||||
}
|
||||
}
|
||||
if (controller.signal.aborted) return;
|
||||
if (refreshed) this.currentUrl = refreshed;
|
||||
this.connect();
|
||||
}, delay);
|
||||
}
|
||||
|
||||
@@ -1520,6 +1520,7 @@ export type InboundEvent =
|
||||
| {
|
||||
event: "attached";
|
||||
chat_id: string;
|
||||
request_id?: string;
|
||||
temporary?: boolean;
|
||||
recovery_state?: RecoveryState;
|
||||
usage?: TurnUsage;
|
||||
@@ -1704,6 +1705,7 @@ export type InboundEvent =
|
||||
}
|
||||
| {
|
||||
event: "error";
|
||||
request_id?: string;
|
||||
chat_id?: string;
|
||||
detail?: string;
|
||||
reason?: string;
|
||||
@@ -1840,15 +1842,15 @@ export type FilePreviewPayload = FilePreviewMetadata & (
|
||||
);
|
||||
|
||||
export type Outbound =
|
||||
| { type: "new_chat"; workspace_scope?: WorkspaceScopePayload }
|
||||
| { type: "new_temporary_chat" }
|
||||
| { type: "new_chat"; workspace_scope?: WorkspaceScopePayload; request_id?: string }
|
||||
| { type: "new_temporary_chat"; request_id?: string }
|
||||
| {
|
||||
type: "webui_request";
|
||||
request_id: string;
|
||||
action: string;
|
||||
payload: Record<string, unknown>;
|
||||
}
|
||||
| { type: "fork_chat"; source_chat_id: string; before_user_index: number; title?: string }
|
||||
| { type: "fork_chat"; source_chat_id: string; before_user_index: number; title?: string; request_id?: string }
|
||||
| { type: "attach"; chat_id: string }
|
||||
| { type: "set_sidebar_state"; state: SidebarStatePayload }
|
||||
| { type: "discard_temporary_chat"; chat_id: string }
|
||||
|
||||
@@ -6,7 +6,7 @@ import type { Window as HappyWindow } from "happy-dom";
|
||||
import i18n from "@/i18n";
|
||||
import { DEFAULT_TRANSCRIPTION_SETTINGS } from "@/components/settings/capabilities/TranscriptionSettings";
|
||||
import { useSessions } from "@/hooks/useSessions";
|
||||
import type { RunState } from "@/lib/nanobot-client";
|
||||
import type { NanobotClientOptions, RunState } from "@/lib/nanobot-client";
|
||||
import { activateReloadCache, clearReloadCache, writeReloadCache } from "@/lib/reload-cache";
|
||||
import type {
|
||||
ChatSummary,
|
||||
@@ -19,6 +19,7 @@ import type {
|
||||
(window as unknown as HappyWindow).happyDOM.settings.disableIframePageLoading = true;
|
||||
|
||||
const connectSpy = vi.fn();
|
||||
let clientOptions: NanobotClientOptions | undefined;
|
||||
const refreshSpy = vi.fn();
|
||||
const createChatSpy = vi.fn().mockResolvedValue("chat-1");
|
||||
const deleteChatSpy = vi.fn();
|
||||
@@ -254,6 +255,7 @@ vi.mock("@/lib/bootstrap", () => ({
|
||||
vi.mock("@/lib/nanobot-client", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("@/lib/nanobot-client")>();
|
||||
class MockClient {
|
||||
constructor(options: NanobotClientOptions) { clientOptions = options; }
|
||||
onTaskNotice = () => () => {};
|
||||
status = "idle" as const;
|
||||
defaultChatId = mockDefaultChatId;
|
||||
@@ -335,6 +337,7 @@ describe("App layout", () => {
|
||||
vi.mocked(useSessions).mockImplementation(defaultUseSessions);
|
||||
clearReloadCache();
|
||||
connectSpy.mockClear();
|
||||
clientOptions = undefined;
|
||||
updateUrlSpy.mockClear();
|
||||
refreshSpy.mockReset();
|
||||
createChatSpy.mockClear();
|
||||
@@ -4475,6 +4478,28 @@ describe("App layout", () => {
|
||||
expect(within(sidebar).getByText("Existing chat")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("does not apply a bootstrap refresh after its reconnect is cancelled", async () => {
|
||||
const { unmount } = render(<App />);
|
||||
await waitFor(() => expect(connectSpy).toHaveBeenCalled());
|
||||
let complete!: (boot: Awaited<ReturnType<typeof fetchBootstrap>>) => void;
|
||||
vi.mocked(fetchBootstrap).mockImplementationOnce(() => new Promise((resolve) => { complete = resolve; }));
|
||||
vi.mocked(deriveWsUrl).mockImplementation((_path, token) => `ws://test?token=${token}`);
|
||||
const controller = new AbortController();
|
||||
const refresh = clientOptions!.onReauth!(controller.signal);
|
||||
controller.abort();
|
||||
await act(async () => {
|
||||
complete({ token: "stale", api_token: "stale-api", ws_path: "/" });
|
||||
await expect(refresh).resolves.toBeNull();
|
||||
});
|
||||
expect(updateUrlSpy).not.toHaveBeenCalled();
|
||||
vi.mocked(fetchBootstrap).mockResolvedValueOnce({ token: "fresh", api_token: "fresh-api", ws_path: "/" });
|
||||
await act(async () => {
|
||||
await expect(clientOptions!.onReauth!(new AbortController().signal)).resolves.toBe("ws://test?token=fresh");
|
||||
});
|
||||
expect(updateUrlSpy).toHaveBeenCalledWith("ws://test?token=fresh");
|
||||
unmount();
|
||||
});
|
||||
|
||||
it("refreshes the bootstrap token before REST settings auth expires", async () => {
|
||||
vi.useFakeTimers();
|
||||
vi.mocked(fetchBootstrap)
|
||||
|
||||
@@ -53,6 +53,12 @@ function lastSocket(): FakeSocket {
|
||||
return s;
|
||||
}
|
||||
|
||||
function lastRequestId(socket: FakeSocket = lastSocket()): string {
|
||||
const frame = JSON.parse(socket.sent.at(-1) ?? "{}");
|
||||
if (typeof frame.request_id !== "string") throw new Error("Expected a request ID on the last sent frame");
|
||||
return frame.request_id;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
FakeSocket.instances = [];
|
||||
vi.useFakeTimers();
|
||||
@@ -64,6 +70,155 @@ afterEach(() => {
|
||||
});
|
||||
|
||||
describe("NanobotClient", () => {
|
||||
const chatRequests = [
|
||||
{ type: "new_chat", start: (client: NanobotClient, timeout: number) => client.newChat(timeout) },
|
||||
{ type: "new_temporary_chat", start: (client: NanobotClient, timeout: number) => client.newTemporaryChat(timeout) },
|
||||
{ type: "fork_chat", start: (client: NanobotClient, timeout: number) => client.forkChat("source", 1, undefined, timeout) },
|
||||
];
|
||||
|
||||
it("does not send an expired queued creation after reconnect", async () => {
|
||||
const client = new NanobotClient({ url: "ws://test", socketFactory: (url) => new FakeSocket(url) as unknown as WebSocket });
|
||||
client.connect();
|
||||
lastSocket().fakeOpen();
|
||||
lastSocket().close();
|
||||
const expired = expect(client.newChat(100)).rejects.toThrow("timed out");
|
||||
await vi.advanceTimersByTimeAsync(100);
|
||||
await expired;
|
||||
await vi.advanceTimersByTimeAsync(400);
|
||||
const socket = lastSocket();
|
||||
socket.fakeOpen();
|
||||
expect(socket.sent.map((frame) => JSON.parse(frame).type)).not.toContain("new_chat");
|
||||
client.close();
|
||||
});
|
||||
|
||||
it("does not confuse a reconnect attachment with fork creation", async () => {
|
||||
const client = new NanobotClient({ url: "ws://test", socketFactory: (url) => new FakeSocket(url) as unknown as WebSocket });
|
||||
client.connect();
|
||||
lastSocket().fakeOpen();
|
||||
client.attach("existing");
|
||||
lastSocket().close();
|
||||
const resolved = vi.fn();
|
||||
const creation = client.forkChat("source", 1).then(resolved);
|
||||
await vi.advanceTimersByTimeAsync(500);
|
||||
const socket = lastSocket();
|
||||
socket.fakeOpen();
|
||||
socket.fakeMessage({ event: "attached", chat_id: "existing" });
|
||||
await Promise.resolve();
|
||||
expect(resolved).not.toHaveBeenCalled();
|
||||
socket.fakeMessage({ event: "attached", chat_id: "fresh", request_id: lastRequestId(socket) });
|
||||
await creation;
|
||||
expect(resolved).toHaveBeenCalledWith("fresh");
|
||||
client.close();
|
||||
});
|
||||
|
||||
it.each(chatRequests)("matches $type replies by ID and ignores late successes and errors", async ({ type, start }) => {
|
||||
const client = new NanobotClient({ url: "ws://test", socketFactory: (url) => new FakeSocket(url) as unknown as WebSocket });
|
||||
client.connect();
|
||||
const socket = lastSocket();
|
||||
socket.fakeOpen();
|
||||
socket.fakeMessage({ event: "ready", chat_id: "default", client_id: "webui" });
|
||||
const expired = expect(start(client, 100)).rejects.toThrow("outcome is unknown");
|
||||
const oldFrame = JSON.parse(socket.sent.at(-1)!);
|
||||
await vi.advanceTimersByTimeAsync(100);
|
||||
await expired;
|
||||
const resolved = vi.fn();
|
||||
const rejected = vi.fn();
|
||||
const creation = start(client, 1_000).then(resolved, rejected);
|
||||
const frame = JSON.parse(socket.sent.at(-1)!);
|
||||
expect(frame.request_id).not.toBe(oldFrame.request_id);
|
||||
const temporary = type === "new_temporary_chat";
|
||||
socket.fakeMessage({ event: "attached", chat_id: "old", temporary, request_id: oldFrame.request_id });
|
||||
socket.fakeMessage({ event: "error", detail: "workspace_scope_rejected", request_id: oldFrame.request_id });
|
||||
// Ordinary attachment responses do not complete a creation request.
|
||||
socket.fakeMessage({ event: "attached", chat_id: "unrelated", temporary });
|
||||
socket.fakeMessage({ event: "error", detail: "fork_chat_failed" });
|
||||
socket.fakeMessage({ event: "error", detail: "workspace_scope_rejected", chat_id: "another", turn_id: "turn" });
|
||||
socket.fakeMessage({ event: "error", detail: "invalid_sidebar_state" });
|
||||
await Promise.resolve();
|
||||
expect(resolved).not.toHaveBeenCalled();
|
||||
expect(rejected).not.toHaveBeenCalled();
|
||||
if (temporary) {
|
||||
expect(socket.sent.map((value) => JSON.parse(value))).toContainEqual({ type: "discard_temporary_chat", chat_id: "old" });
|
||||
}
|
||||
socket.fakeMessage({ event: "attached", chat_id: "fresh", temporary, request_id: frame.request_id });
|
||||
await creation;
|
||||
expect(resolved).toHaveBeenCalledWith("fresh");
|
||||
client.close();
|
||||
});
|
||||
|
||||
it("does not replay a sent chat request after reconnect and correlates the next request", async () => {
|
||||
const client = new NanobotClient({ url: "ws://test", onReauth: async () => "ws://refreshed",
|
||||
socketFactory: (url) => new FakeSocket(url) as unknown as WebSocket });
|
||||
client.connect();
|
||||
lastSocket().fakeOpen();
|
||||
lastSocket().fakeMessage({ event: "ready", chat_id: "default", client_id: "webui" });
|
||||
const interrupted = expect(client.newChat()).rejects.toThrow("socket closed");
|
||||
const interruptedRequestId = lastRequestId();
|
||||
lastSocket().close();
|
||||
await interrupted;
|
||||
await vi.advanceTimersByTimeAsync(500);
|
||||
const socket = lastSocket();
|
||||
expect(socket.url).toBe("ws://refreshed");
|
||||
socket.fakeOpen();
|
||||
socket.fakeMessage({ event: "ready", chat_id: "default", client_id: "webui" });
|
||||
expect(socket.sent.filter((value) => JSON.parse(value).type === "new_chat")).toHaveLength(0);
|
||||
const creation = client.newChat();
|
||||
expect(lastRequestId(socket)).not.toBe(interruptedRequestId);
|
||||
socket.fakeMessage({ event: "attached", chat_id: "fresh", request_id: lastRequestId(socket) });
|
||||
await expect(creation).resolves.toBe("fresh");
|
||||
expect(socket.sent.filter((value) => JSON.parse(value).type === "new_chat")).toHaveLength(1);
|
||||
client.close();
|
||||
});
|
||||
|
||||
it("does not reconnect when closed while reauthentication is pending", async () => {
|
||||
let finishAuth!: (url: string) => void;
|
||||
const onReauth = vi.fn(() => new Promise<string>((resolve) => { finishAuth = resolve; }));
|
||||
const client = new NanobotClient({ url: "ws://test", onReauth,
|
||||
socketFactory: (url) => new FakeSocket(url) as unknown as WebSocket });
|
||||
client.connect();
|
||||
lastSocket().fakeOpen();
|
||||
lastSocket().close();
|
||||
await vi.advanceTimersByTimeAsync(500);
|
||||
expect(onReauth).toHaveBeenCalledOnce();
|
||||
client.close();
|
||||
client.updateUrl("ws://replacement");
|
||||
finishAuth("ws://stale-auth");
|
||||
await Promise.resolve();
|
||||
expect(client.status).toBe("closed");
|
||||
expect(FakeSocket.instances).toHaveLength(1);
|
||||
client.connect();
|
||||
expect(lastSocket().url).toBe("ws://replacement");
|
||||
client.close();
|
||||
});
|
||||
|
||||
it("settles queued creation on close and ignores callbacks from the replaced socket", async () => {
|
||||
const client = new NanobotClient({ url: "ws://test", socketFactory: (url) => new FakeSocket(url) as unknown as WebSocket });
|
||||
client.connect();
|
||||
const previous = lastSocket();
|
||||
// Browser close() returns before its queued close event is delivered.
|
||||
previous.close = () => { previous.readyState = FakeSocket.CLOSING; };
|
||||
const closed = expect(client.newChat()).rejects.toThrow("socket closed");
|
||||
client.close();
|
||||
await closed;
|
||||
client.connect();
|
||||
const current = lastSocket();
|
||||
current.fakeOpen();
|
||||
expect(current.sent.map((value) => JSON.parse(value).type)).not.toContain("new_chat");
|
||||
const resolved = vi.fn();
|
||||
const creation = client.newChat().then(resolved);
|
||||
previous.fakeOpen();
|
||||
previous.fakeMessage({ event: "attached", chat_id: "stale" });
|
||||
previous.onerror?.();
|
||||
previous.onclose?.();
|
||||
await Promise.resolve();
|
||||
expect(client.status).toBe("open");
|
||||
expect(resolved).not.toHaveBeenCalled();
|
||||
current.fakeMessage({ event: "attached", chat_id: "fresh", request_id: lastRequestId(current) });
|
||||
await creation;
|
||||
expect(resolved).toHaveBeenCalledWith("fresh");
|
||||
client.close();
|
||||
});
|
||||
|
||||
it("notifies ready consumers after server ready frames, including reconnects", async () => {
|
||||
const client = new NanobotClient({ url: "ws://test?token=fixture-token", socketFactory: (url) => new FakeSocket(url) as unknown as WebSocket });
|
||||
const ready = vi.fn();
|
||||
@@ -128,7 +283,7 @@ describe("NanobotClient", () => {
|
||||
const socket = lastSocket();
|
||||
socket.fakeOpen();
|
||||
const created = client.newTemporaryChat();
|
||||
socket.fakeMessage({ event: "attached", chat_id: "temporary", temporary: true });
|
||||
socket.fakeMessage({ event: "attached", chat_id: "temporary", temporary: true, request_id: lastRequestId(socket) });
|
||||
await created;
|
||||
const notice = vi.fn();
|
||||
client.onTaskNotice(notice);
|
||||
@@ -151,7 +306,7 @@ describe("NanobotClient", () => {
|
||||
const socket = lastSocket();
|
||||
socket.fakeOpen();
|
||||
const created = client.newTemporaryChat();
|
||||
socket.fakeMessage({ event: "attached", chat_id: "temporary", temporary: true });
|
||||
socket.fakeMessage({ event: "attached", chat_id: "temporary", temporary: true, request_id: lastRequestId(socket) });
|
||||
await created;
|
||||
for (let index = 0; index < 2_010; index++) {
|
||||
for (const chatId of ["regular", "temporary"]) {
|
||||
@@ -465,9 +620,9 @@ describe("NanobotClient", () => {
|
||||
lastSocket().fakeOpen();
|
||||
const creation = client.newTemporaryChat();
|
||||
expect(JSON.parse(lastSocket().sent.at(-1) as string)).toEqual({
|
||||
type: "new_temporary_chat",
|
||||
type: "new_temporary_chat", request_id: expect.any(String),
|
||||
});
|
||||
lastSocket().fakeMessage({ event: "attached", chat_id: chatId, temporary: true });
|
||||
lastSocket().fakeMessage({ event: "attached", chat_id: chatId, temporary: true, request_id: lastRequestId() });
|
||||
await expect(creation).resolves.toBe(chatId);
|
||||
lastSocket().sent = [];
|
||||
client.onChat(chatId, vi.fn());
|
||||
@@ -510,6 +665,7 @@ describe("NanobotClient", () => {
|
||||
lastSocket().fakeMessage({
|
||||
event: "attached",
|
||||
chat_id: "server-temporary-chat",
|
||||
request_id: lastRequestId(),
|
||||
temporary: true,
|
||||
});
|
||||
await expect(creation).resolves.toBe("server-temporary-chat");
|
||||
@@ -530,6 +686,7 @@ describe("NanobotClient", () => {
|
||||
lastSocket().fakeMessage({
|
||||
event: "attached",
|
||||
chat_id: "temp-drop-a",
|
||||
request_id: lastRequestId(),
|
||||
temporary: true,
|
||||
});
|
||||
await firstCreation;
|
||||
@@ -537,6 +694,7 @@ describe("NanobotClient", () => {
|
||||
lastSocket().fakeMessage({
|
||||
event: "attached",
|
||||
chat_id: "temp-drop-b",
|
||||
request_id: lastRequestId(),
|
||||
temporary: true,
|
||||
});
|
||||
await secondCreation;
|
||||
@@ -1688,6 +1846,7 @@ describe("NanobotClient", () => {
|
||||
event: "error",
|
||||
detail: "workspace_scope_rejected",
|
||||
reason: "project_path must be an existing directory",
|
||||
request_id: lastRequestId(),
|
||||
});
|
||||
|
||||
await expect(pendingChat).rejects.toThrow("workspace_scope_rejected");
|
||||
@@ -2184,8 +2343,8 @@ describe("NanobotClient", () => {
|
||||
client.connect();
|
||||
lastSocket().fakeOpen();
|
||||
const promise = client.newChat(1_000);
|
||||
expect(lastSocket().sent).toContain(JSON.stringify({ type: "new_chat" }));
|
||||
lastSocket().fakeMessage({ event: "attached", chat_id: "fresh-id" });
|
||||
expect(lastSocket().sent.map((value) => JSON.parse(value))).toContainEqual({ type: "new_chat", request_id: expect.any(String) });
|
||||
lastSocket().fakeMessage({ event: "attached", chat_id: "fresh-id", request_id: lastRequestId() });
|
||||
await expect(promise).resolves.toBe("fresh-id");
|
||||
});
|
||||
|
||||
@@ -2205,10 +2364,10 @@ describe("NanobotClient", () => {
|
||||
lastSocket().fakeOpen();
|
||||
|
||||
const promise = client.newChat(1_000, workspaceScope);
|
||||
expect(lastSocket().sent).toContain(
|
||||
JSON.stringify({ type: "new_chat", workspace_scope: workspaceScope }),
|
||||
);
|
||||
lastSocket().fakeMessage({ event: "attached", chat_id: "fresh-id" });
|
||||
expect(lastSocket().sent.map((value) => JSON.parse(value))).toContainEqual({
|
||||
type: "new_chat", workspace_scope: workspaceScope, request_id: expect.any(String),
|
||||
});
|
||||
lastSocket().fakeMessage({ event: "attached", chat_id: "fresh-id", request_id: lastRequestId() });
|
||||
await expect(promise).resolves.toBe("fresh-id");
|
||||
|
||||
client.sendMessage("fresh-id", "hello", undefined, { workspaceScope });
|
||||
@@ -2675,8 +2834,9 @@ describe("NanobotClient", () => {
|
||||
event: "error",
|
||||
detail: "workspace_scope_rejected",
|
||||
reason: "project_path must be an existing directory",
|
||||
request_id: lastRequestId(),
|
||||
});
|
||||
await expect(pending).rejects.toThrow("workspace_scope_rejected");
|
||||
await expect(pending).rejects.toThrow("workspace_scope_rejected:project_path must be an existing directory");
|
||||
});
|
||||
|
||||
it("isolates throwing error handlers so reconnect bookkeeping still runs", async () => {
|
||||
|
||||
@@ -53,7 +53,7 @@ class TestSocket {
|
||||
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 }));
|
||||
queueMicrotask(() => this.receive({ event: "attached", chat_id: chatId, temporary: true, request_id: frame.request_id }));
|
||||
} else if (frame.type === "set_sidebar_state") {
|
||||
queueMicrotask(() => this.receive({ event: "sidebar_state_updated", state: frame.state }));
|
||||
} else if (frame.type === "webui_request" && frame.action === "temporary_chat.file_preview") {
|
||||
|
||||
Reference in new issue
Block a user