fix(webui): refresh pairing prompts on gateway changes (#6401)
This commit is contained in:
1 parent
9e9e22d331
commit
8af6313c56
26 files changed
+630
-82
No files matched your search
+44
-26
@@ -1281,6 +1281,7 @@ function Shell({
|
||||
const [pairingBusyCode, setPairingBusyCode] = useState<string | null>(null);
|
||||
const [pairingError, setPairingError] = useState<string | null>(null);
|
||||
const pairingRefreshRef = useRef<Promise<number> | null>(null);
|
||||
const pairingRefreshPendingRef = useRef(false);
|
||||
const [snoozedPairingCodes, setSnoozedPairingCodes] = useState<Map<string, {
|
||||
until: number;
|
||||
deliveryStatus: PairingRequestInfo["delivery_status"];
|
||||
@@ -1473,32 +1474,41 @@ function Shell({
|
||||
}, [updatedChatIds]);
|
||||
|
||||
const refreshPairingRequests = useCallback((): Promise<number> => {
|
||||
if (pairingRefreshRef.current) return pairingRefreshRef.current;
|
||||
if (pairingRefreshRef.current) {
|
||||
// An earlier snapshot may predate the notice or completed mutation.
|
||||
pairingRefreshPendingRef.current = true;
|
||||
return pairingRefreshRef.current;
|
||||
}
|
||||
|
||||
const request = (async () => {
|
||||
try {
|
||||
const payload = await fetchPairingRequests(getToken());
|
||||
const requests = Array.isArray(payload.requests) ? payload.requests : [];
|
||||
setPairingRequests(requests);
|
||||
setSnoozedPairingCodes((current) => {
|
||||
if (current.size === 0) return current;
|
||||
const activeRequests = new Map(requests.map((request) => [request.code, request]));
|
||||
const now = Date.now();
|
||||
const next = new Map(
|
||||
Array.from(current).filter(
|
||||
([code, snooze]) => activeRequests.has(code)
|
||||
&& snooze.until > now
|
||||
&& activeRequests.get(code)?.delivery_status === snooze.deliveryStatus,
|
||||
),
|
||||
);
|
||||
return next.size === current.size ? current : next;
|
||||
});
|
||||
return requests.length;
|
||||
} catch {
|
||||
// Pairing is an opportunistic WebUI affordance. The slash command path
|
||||
// remains available if this polling request fails.
|
||||
return 0;
|
||||
}
|
||||
let requestCount: number;
|
||||
do {
|
||||
pairingRefreshPendingRef.current = false;
|
||||
try {
|
||||
const payload = await fetchPairingRequests(getToken());
|
||||
const requests = Array.isArray(payload.requests) ? payload.requests : [];
|
||||
setPairingRequests(requests);
|
||||
setSnoozedPairingCodes((current) => {
|
||||
if (current.size === 0) return current;
|
||||
const activeRequests = new Map(requests.map((request) => [request.code, request]));
|
||||
const now = Date.now();
|
||||
const next = new Map(
|
||||
Array.from(current).filter(
|
||||
([code, snooze]) => activeRequests.has(code)
|
||||
&& snooze.until > now
|
||||
&& activeRequests.get(code)?.delivery_status === snooze.deliveryStatus,
|
||||
),
|
||||
);
|
||||
return next.size === current.size ? current : next;
|
||||
});
|
||||
requestCount = requests.length;
|
||||
} catch {
|
||||
// Pairing is an opportunistic WebUI affordance. The slash command path
|
||||
// remains available if this polling request fails.
|
||||
requestCount = 0;
|
||||
}
|
||||
} while (pairingRefreshPendingRef.current);
|
||||
return requestCount;
|
||||
})();
|
||||
const clearRequest = () => {
|
||||
if (pairingRefreshRef.current === request) pairingRefreshRef.current = null;
|
||||
@@ -1516,17 +1526,24 @@ function Shell({
|
||||
const poll = async () => {
|
||||
const requestCount = await refreshPairingRequests();
|
||||
if (disposed) return;
|
||||
if (timer !== null) window.clearTimeout(timer);
|
||||
timer = window.setTimeout(
|
||||
() => void poll(),
|
||||
requestCount > 0 ? PAIRING_POLL_INTERVAL_MS : PAIRING_IDLE_POLL_INTERVAL_MS,
|
||||
);
|
||||
};
|
||||
const requestRefresh = () => { void poll(); };
|
||||
const unsubscribePairing = client.onPairingChange(requestRefresh);
|
||||
const unsubscribeReady = client.onReady(requestRefresh);
|
||||
void poll();
|
||||
return () => {
|
||||
disposed = true;
|
||||
pairingRefreshPendingRef.current = false;
|
||||
if (timer !== null) window.clearTimeout(timer);
|
||||
unsubscribePairing();
|
||||
unsubscribeReady();
|
||||
};
|
||||
}, [pageVisible, refreshPairingRequests]);
|
||||
}, [client, pageVisible, refreshPairingRequests]);
|
||||
|
||||
const activeSession = useMemo<ChatSummary | null>(() => {
|
||||
if (!activeKey) return null;
|
||||
@@ -2465,9 +2482,10 @@ function Shell({
|
||||
});
|
||||
} catch (e) {
|
||||
setPairingError((e as Error).message);
|
||||
void refreshPairingRequests();
|
||||
} finally {
|
||||
setPairingBusyCode(null);
|
||||
// A mutation reply can be older than an already-delivered notification.
|
||||
void refreshPairingRequests();
|
||||
}
|
||||
},
|
||||
[client, refreshPairingRequests],
|
||||
|
||||
@@ -87,6 +87,7 @@ type SessionUpdateHandler = (
|
||||
workspaceScope?: WorkspaceScopePayload,
|
||||
) => void;
|
||||
type SidebarStateUpdateHandler = (state: SidebarStatePayload) => void;
|
||||
type PairingChangeHandler = () => void;
|
||||
type RunStatusHandler = (chatId: string, state: RunState) => void;
|
||||
|
||||
/** Structured errors surfaced to the UI.
|
||||
@@ -238,6 +239,8 @@ export class NanobotClient {
|
||||
private runCompletionHandlers = new Set<RunCompletionHandler>();
|
||||
private errorHandlers = new Set<ErrorHandler>();
|
||||
private taskNoticeHandlers = new Set<(notice: TaskNotice) => void>();
|
||||
private pairingChangeHandlers = new Set<PairingChangeHandler>();
|
||||
private readyHandlers = new Set<() => void>();
|
||||
private chatHandlers = new Map<string, Set<EventHandler>>();
|
||||
private transcriptHandlers = new Map<string, { handler: EventHandler }>();
|
||||
/** Inbound frames received while the transcript owner is absent, regardless of observers. */
|
||||
@@ -317,6 +320,16 @@ export class NanobotClient {
|
||||
};
|
||||
}
|
||||
|
||||
onPairingChange(handler: PairingChangeHandler): Unsubscribe {
|
||||
this.pairingChangeHandlers.add(handler);
|
||||
return () => { this.pairingChangeHandlers.delete(handler); };
|
||||
}
|
||||
|
||||
onReady(handler: () => void): Unsubscribe {
|
||||
this.readyHandlers.add(handler);
|
||||
return () => { this.readyHandlers.delete(handler); };
|
||||
}
|
||||
|
||||
onSidebarStateUpdate(handler: SidebarStateUpdateHandler): Unsubscribe {
|
||||
this.sidebarStateUpdateHandlers.add(handler);
|
||||
return () => {
|
||||
@@ -966,6 +979,9 @@ export class NanobotClient {
|
||||
this.upload = uploadCapability(parsed.upload);
|
||||
this.readyChatId = parsed.chat_id;
|
||||
this.knownChats.add(parsed.chat_id);
|
||||
for (const handler of this.readyHandlers) {
|
||||
try { handler(); } catch { /* One listener must not block another ready consumer. */ }
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -987,6 +1003,13 @@ export class NanobotClient {
|
||||
return;
|
||||
}
|
||||
|
||||
if (parsed.event === "pairing_changed") {
|
||||
for (const handler of this.pairingChangeHandlers) {
|
||||
try { handler(); } catch { /* One listener must not block another pairing refresh. */ }
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (parsed.event === "runtime_model_updated") {
|
||||
this.emitRuntimeModelUpdate(parsed.model_name || null, parsed.model_preset ?? null);
|
||||
return;
|
||||
|
||||
@@ -1572,6 +1572,7 @@ export type InboundEvent =
|
||||
/** Legacy persisted transcripts may carry the final reasoning text here. */
|
||||
text?: string;
|
||||
} & InboundTurnMetadata)
|
||||
| { event: "pairing_changed" }
|
||||
| {
|
||||
event: "runtime_model_updated";
|
||||
model_name: string;
|
||||
|
||||
@@ -44,6 +44,8 @@ const sessionUpdateHandlers = new Set<(
|
||||
workspaceScope?: WorkspaceScopePayload,
|
||||
) => void>();
|
||||
const sidebarStateUpdateHandlers = new Set<(state: SidebarStatePayload) => void>();
|
||||
const pairingChangeHandlers = new Set<() => void>();
|
||||
const readyHandlers = new Set<() => void>();
|
||||
let mockSessions: ChatSummary[] = [];
|
||||
const HERO_GREETING_PATTERN =
|
||||
/What should we work on\?|Where should we start\?|What are we building today\?|What should we tackle together\?/;
|
||||
@@ -261,6 +263,14 @@ vi.mock("@/lib/nanobot-client", async (importOriginal) => {
|
||||
return () => statusHandlers.delete(handler);
|
||||
};
|
||||
onRuntimeModelUpdate = () => () => {};
|
||||
onPairingChange = (handler: () => void) => {
|
||||
pairingChangeHandlers.add(handler);
|
||||
return () => pairingChangeHandlers.delete(handler);
|
||||
};
|
||||
onReady = (handler: () => void) => {
|
||||
readyHandlers.add(handler);
|
||||
return () => readyHandlers.delete(handler);
|
||||
};
|
||||
onError = () => () => {};
|
||||
onChat = () => () => {};
|
||||
onTranscript = () => () => {};
|
||||
@@ -348,6 +358,8 @@ describe("App layout", () => {
|
||||
runStatusHandlers.clear();
|
||||
sessionUpdateHandlers.clear();
|
||||
sidebarStateUpdateHandlers.clear();
|
||||
pairingChangeHandlers.clear();
|
||||
readyHandlers.clear();
|
||||
window.history.replaceState(null, "", "/");
|
||||
sessionStorage.removeItem("nanobot.remote-instance");
|
||||
Reflect.deleteProperty(window, "nanobotHost");
|
||||
@@ -4435,6 +4447,141 @@ describe("App layout", () => {
|
||||
unmount();
|
||||
});
|
||||
|
||||
it("refreshes pairing immediately on notices and ready, only while visible", async () => {
|
||||
vi.useFakeTimers();
|
||||
let requests: Record<string, unknown>[] = [];
|
||||
mockFetchRoutes({ "/api/settings/pairing": () => ({ requests }) });
|
||||
const { unmount } = render(<App />);
|
||||
await act(async () => {});
|
||||
const pairingReads = () => vi.mocked(fetch).mock.calls.filter(([input]) => String(input) === "/api/settings/pairing").length;
|
||||
expect(pairingReads()).toBe(1);
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(1_000); });
|
||||
requests = [{ code: "ABCD-EFGH", channel: "feishu", sender_id: "alice", delivery_status: "sent" }];
|
||||
await act(async () => { for (const handler of pairingChangeHandlers) handler(); });
|
||||
expect(screen.getByRole("dialog", { name: "Pair account" })).toBeVisible();
|
||||
expect(pairingReads()).toBe(2);
|
||||
requests = [];
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(5_000); });
|
||||
expect(pairingReads()).toBe(3);
|
||||
expect(screen.queryByRole("dialog", { name: "Pair account" })).not.toBeInTheDocument();
|
||||
|
||||
const visibilityDescriptor = Object.getOwnPropertyDescriptor(document, "visibilityState");
|
||||
const setVisibility = (state: DocumentVisibilityState) => {
|
||||
Object.defineProperty(document, "visibilityState", { configurable: true, value: state });
|
||||
document.dispatchEvent(new Event("visibilitychange"));
|
||||
};
|
||||
try {
|
||||
act(() => setVisibility("hidden"));
|
||||
requests = [];
|
||||
await act(async () => {
|
||||
for (const handler of pairingChangeHandlers) handler();
|
||||
for (const handler of readyHandlers) handler();
|
||||
await vi.advanceTimersByTimeAsync(15_000);
|
||||
});
|
||||
expect(pairingReads()).toBe(3);
|
||||
await act(async () => setVisibility("visible"));
|
||||
expect(pairingReads()).toBe(4);
|
||||
expect(screen.queryByRole("dialog", { name: "Pair account" })).not.toBeInTheDocument();
|
||||
|
||||
requests = [{ code: "IJKL-MNOP", channel: "feishu", sender_id: "bob", delivery_status: "sent" }];
|
||||
await act(async () => { for (const handler of readyHandlers) handler(); });
|
||||
expect(screen.getByRole("dialog", { name: "Pair account" })).toBeVisible();
|
||||
expect(pairingReads()).toBe(5);
|
||||
unmount();
|
||||
await act(async () => {
|
||||
for (const handler of pairingChangeHandlers) handler();
|
||||
for (const handler of readyHandlers) handler();
|
||||
await vi.advanceTimersByTimeAsync(15_000);
|
||||
});
|
||||
expect(pairingReads()).toBe(5);
|
||||
} finally {
|
||||
if (visibilityDescriptor) Object.defineProperty(document, "visibilityState", visibilityDescriptor);
|
||||
else Reflect.deleteProperty(document, "visibilityState");
|
||||
}
|
||||
});
|
||||
|
||||
it("polls for cross-process pairing changes and expiry without a notice", async () => {
|
||||
vi.useFakeTimers();
|
||||
let requests: Record<string, unknown>[] = [];
|
||||
mockFetchRoutes({ "/api/settings/pairing": () => ({ requests }) });
|
||||
render(<App />);
|
||||
await act(async () => {});
|
||||
requests = [{ code: "ABCD-EFGH", channel: "feishu", sender_id: "alice", expires_in_seconds: 5 }];
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(14_999); });
|
||||
expect(screen.queryByRole("dialog", { name: "Pair account" })).not.toBeInTheDocument();
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(1); });
|
||||
expect(screen.getByRole("dialog", { name: "Pair account" })).toHaveTextContent("Code expires 5s.");
|
||||
requests = [];
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(4_999); });
|
||||
expect(screen.getByRole("dialog", { name: "Pair account" })).toBeVisible();
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(1); });
|
||||
expect(screen.queryByRole("dialog", { name: "Pair account" })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it.each([false, true])("coalesces notices during an older pairing read and pauses while hidden (%s)", async (hide) => {
|
||||
let finishOldRead!: (value: unknown) => void;
|
||||
const oldSnapshot = new Promise((resolve) => { finishOldRead = resolve; });
|
||||
let reads = 0;
|
||||
mockFetchRoutes({ "/api/settings/pairing": () => ++reads === 1 ? oldSnapshot : { requests: [{
|
||||
code: "ABCD-EFGH", channel: "feishu", sender_id: "alice", delivery_status: "sent",
|
||||
}] } });
|
||||
const visibilityDescriptor = Object.getOwnPropertyDescriptor(document, "visibilityState");
|
||||
const setVisibility = (state: DocumentVisibilityState) => {
|
||||
Object.defineProperty(document, "visibilityState", { configurable: true, value: state });
|
||||
document.dispatchEvent(new Event("visibilitychange"));
|
||||
};
|
||||
const { unmount } = render(<App />);
|
||||
try {
|
||||
await waitFor(() => expect(reads).toBe(1));
|
||||
act(() => {
|
||||
for (let notice = 0; notice < 3; notice += 1) {
|
||||
for (const handler of pairingChangeHandlers) handler();
|
||||
}
|
||||
if (hide) setVisibility("hidden");
|
||||
});
|
||||
expect(reads).toBe(1);
|
||||
await act(async () => { finishOldRead({ requests: [] }); });
|
||||
if (hide) {
|
||||
expect(reads).toBe(1);
|
||||
await act(async () => setVisibility("visible"));
|
||||
}
|
||||
expect(screen.getByRole("dialog", { name: "Pair account" })).toBeVisible();
|
||||
expect(reads).toBe(2);
|
||||
} finally {
|
||||
unmount();
|
||||
if (visibilityDescriptor) Object.defineProperty(document, "visibilityState", visibilityDescriptor);
|
||||
else Reflect.deleteProperty(document, "visibilityState");
|
||||
}
|
||||
});
|
||||
|
||||
it.each(["success", "failure"])("reconciles a late pairing mutation after a notice shows a newer request (%s)", async (outcome) => {
|
||||
let requests = [{
|
||||
code: "ABCD-EFGH", channel: "feishu", sender_id: "alice", expires_in_seconds: 120,
|
||||
}];
|
||||
mockFetchRoutes({ "/api/settings/pairing": () => ({ requests }) });
|
||||
let reply!: (payload: unknown) => void;
|
||||
let fail!: (error: Error) => void;
|
||||
requestMutationSpy.mockImplementationOnce(() => new Promise((resolve, reject) => { reply = resolve; fail = reject; }));
|
||||
render(<App />);
|
||||
const popup = await screen.findByRole("dialog", { name: "Pair account" });
|
||||
fireEvent.change(within(popup).getByRole("textbox", { name: "Pairing code" }), {
|
||||
target: { value: "ABCD-EFGH" },
|
||||
});
|
||||
expect(requestMutationSpy).toHaveBeenCalledWith("settings.pairing.approve", { code: "ABCD-EFGH" }, expect.any(Number));
|
||||
requests = [{
|
||||
code: "IJKL-MNOP", channel: "feishu.second", sender_id: "bob", expires_in_seconds: 240,
|
||||
}];
|
||||
await act(async () => { for (const handler of pairingChangeHandlers) handler(); });
|
||||
expect(popup).toHaveTextContent("Code expires 4 min.");
|
||||
await act(async () => {
|
||||
if (outcome === "success") reply({ requests: [] });
|
||||
else fail(new Error("Approval unavailable"));
|
||||
});
|
||||
expect(screen.getByRole("dialog", { name: "Pair account" })).toHaveTextContent("Code expires 4 min.");
|
||||
expect(vi.mocked(fetch).mock.calls.filter(([input]) => String(input) === "/api/settings/pairing")).toHaveLength(3);
|
||||
expect(requestMutationSpy).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it.each(["sending", "failed"])("explains an undelivered pairing reply (%s) without empty code slots", async (delivery_status) => {
|
||||
mockFetchRoutes({ "/api/settings/pairing": { requests: [{
|
||||
code: "ABCD-EFGH", channel: "feishu", sender_id: "alice", delivery_status,
|
||||
@@ -4511,16 +4658,18 @@ describe("App layout", () => {
|
||||
expect(screen.queryByRole("dialog", { name: "Pair account" })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("reuses an in-flight pairing poll when the page becomes visible again", async () => {
|
||||
it("reuses an in-flight pairing poll then reads current requests on visible return", async () => {
|
||||
let resolvePairing!: (response: Response) => void;
|
||||
const pendingPairing = new Promise<Response>((resolve) => {
|
||||
resolvePairing = resolve;
|
||||
});
|
||||
const fetchMock = vi.fn((input: RequestInfo | URL) => (
|
||||
String(input) === "/api/settings/pairing"
|
||||
? pendingPairing
|
||||
: Promise.resolve({ ok: false, status: 404 } as Response)
|
||||
));
|
||||
let reads = 0;
|
||||
const fetchMock = vi.fn((input: RequestInfo | URL) => {
|
||||
if (String(input) !== "/api/settings/pairing") return Promise.resolve({ ok: false, status: 404 } as Response);
|
||||
return ++reads === 1 ? pendingPairing : Promise.resolve(jsonResponse({ requests: [{
|
||||
code: "ABCD-EFGH", channel: "feishu", sender_id: "alice", delivery_status: "sent",
|
||||
}] }));
|
||||
});
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
const visibilityDescriptor = Object.getOwnPropertyDescriptor(document, "visibilityState");
|
||||
|
||||
@@ -4550,6 +4699,8 @@ describe("App layout", () => {
|
||||
resolvePairing(jsonResponse({ requests: [] }));
|
||||
await pendingPairing;
|
||||
});
|
||||
expect(screen.getByRole("dialog", { name: "Pair account" })).toBeVisible();
|
||||
expect(reads).toBe(2);
|
||||
} finally {
|
||||
if (visibilityDescriptor) {
|
||||
Object.defineProperty(document, "visibilityState", visibilityDescriptor);
|
||||
|
||||
@@ -71,6 +71,45 @@ afterEach(() => {
|
||||
});
|
||||
|
||||
describe("NanobotClient", () => {
|
||||
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();
|
||||
const unsubscribe = client.onReady(ready);
|
||||
client.connect();
|
||||
lastSocket().fakeOpen();
|
||||
expect(ready).not.toHaveBeenCalled();
|
||||
lastSocket().fakeMessage({ event: "ready", chat_id: "first" });
|
||||
expect(ready).toHaveBeenCalledTimes(1);
|
||||
expect(client.defaultChatId).toBe("first");
|
||||
lastSocket().close();
|
||||
await vi.advanceTimersByTimeAsync(1_000);
|
||||
lastSocket().fakeOpen();
|
||||
lastSocket().fakeMessage({ event: "ready", chat_id: "second" });
|
||||
expect(ready).toHaveBeenCalledTimes(2);
|
||||
expect(client.defaultChatId).toBe("second");
|
||||
unsubscribe();
|
||||
lastSocket().fakeMessage({ event: "ready", chat_id: "third" });
|
||||
expect(client.defaultChatId).toBe("third");
|
||||
expect(ready).toHaveBeenCalledTimes(2);
|
||||
client.close();
|
||||
});
|
||||
|
||||
it("delivers payload-free pairing changes, isolates listeners and unsubscribes", () => {
|
||||
const client = new NanobotClient({ url: "ws://test", socketFactory: (url) => new FakeSocket(url) as unknown as WebSocket });
|
||||
const pairing = vi.fn();
|
||||
client.onPairingChange(() => { throw new Error("view failed"); });
|
||||
const unsubscribe = client.onPairingChange(pairing);
|
||||
client.connect();
|
||||
lastSocket().fakeOpen();
|
||||
lastSocket().fakeMessage({ event: "pairing_changed" });
|
||||
expect(pairing).toHaveBeenCalledTimes(1);
|
||||
expect(pairing).toHaveBeenCalledWith();
|
||||
unsubscribe();
|
||||
lastSocket().fakeMessage({ event: "pairing_changed" });
|
||||
expect(pairing).toHaveBeenCalledTimes(1);
|
||||
client.close();
|
||||
});
|
||||
|
||||
it("emits live task notices without mounted chats, not when the chat replays", () => {
|
||||
const client = new NanobotClient({ url: "ws://test", reconnect: false,
|
||||
socketFactory: (url) => new FakeSocket(url) as unknown as WebSocket });
|
||||
|
||||
Reference in new issue
Block a user