fix(webui): reconcile turns after reconnect (#6211)

* fix(webui): reconcile turns after reconnect

* perf(webui): bound reconnect recovery and index turn reconciliation

* refactor(webui): simplify reconnect reconciliation

* fix(webui): preserve turn authority during recovery

* fix(webui): validate canonical completion identities
This commit is contained in:
chengyongru authored and GitHub committed 2026-10-16 11:38:05 +08:00
1 parent aeca1c0f1a
commit fdeda8a468
18 files changed
+1741 -225

No files matched your search

+53
View File
@@ -0,0 +1,53 @@
import type { CanonicalRunSnapshot } from "./nanobot-client";
import { projectThreadEvents } from "./thread-event-projection";
import type { UIMessage, WebuiThreadPersistedPayload } from "./types";
export function completedAssistantTurnIds(messages: UIMessage[]): string[] {
return Array.from(new Set(messages.flatMap((message) => (
message.role === "assistant" && message.turnId ? [message.turnId] : []
))));
}
export function canonicalRunSnapshot(
messages: UIMessage[],
hasPendingToolCalls: boolean,
activeTurnId: string | null,
completionIdsProvided = false,
): CanonicalRunSnapshot {
return {
observedTurnIds: Array.from(new Set(messages.flatMap((message) => (
message.role === "user" && message.turnId ? [message.turnId] : []
)))),
hasPendingToolCalls,
activeTurnId,
completionIdsProvided,
};
}
export function persistedCanonicalRunState(body: WebuiThreadPersistedPayload): {
completedTurnIds: string[];
snapshot: CanonicalRunSnapshot;
} {
const messages = projectThreadEvents(body.events);
const suppliedCompletionIds = Array.isArray(body.completed_turn_ids) ? body.completed_turn_ids : null;
// The older protocol-1 host may omit active_turn_id. Its explicit pending
// flag still confirms idle; a missing flag cannot establish completion.
const snapshot = canonicalRunSnapshot(
messages,
body.has_pending_tool_calls !== false,
typeof body.active_turn_id === "string" ? body.active_turn_id : null,
suppliedCompletionIds !== null,
);
const completedTurnIds = suppliedCompletionIds?.filter(
(turnId) => typeof turnId === "string" && turnId.length > 0,
) ?? [];
// The gateway excludes incomplete transcript turns even when their display
// projection contains turn_end. Only older hosts need idle-state inference.
if (suppliedCompletionIds === null && !snapshot.hasPendingToolCalls && !snapshot.activeTurnId) {
completedTurnIds.push(...body.events.flatMap((event) => (
event.event === "turn_end" && event.turn_id ? [event.turn_id] : []
)));
completedTurnIds.push(...completedAssistantTurnIds(messages));
}
return { completedTurnIds: Array.from(new Set(completedTurnIds)), snapshot };
}
+111
View File
@@ -0,0 +1,111 @@
import { fetchWebuiThread } from "./api";
import type { NanobotClient } from "./nanobot-client";
import type { WebuiThreadPersistedPayload } from "./types";
import { webuiThreadCache } from "./webui-thread-cache";
interface LatestThreadRequest {
cached: WebuiThreadPersistedPayload | undefined;
controller: AbortController;
promise: Promise<WebuiThreadPersistedPayload | null>;
consumers: number;
settled: boolean;
shareable: boolean;
}
const requestsByClient = new WeakMap<NanobotClient, Map<string, LatestThreadRequest>>();
const INVALIDATED_THREAD_READ = Symbol("invalidated thread read");
function abortedRequest(): DOMException {
return new DOMException("The request was aborted", "AbortError");
}
/** Share only the canonical latest 40-event page within one authenticated host. */
export function fetchLatestWebuiThread(
client: NanobotClient,
token: string,
key: string,
signal?: AbortSignal,
): Promise<WebuiThreadPersistedPayload | null> {
if (signal?.aborted) return Promise.reject(abortedRequest());
const requests = requestsByClient.get(client) ?? new Map<string, LatestThreadRequest>();
requestsByClient.set(client, requests);
const requestKey = JSON.stringify([token, key]);
const cached = webuiThreadCache.get(key);
let request = requests.get(requestKey);
if (!request || !request.shareable || request.controller.signal.aborted || request.cached !== cached) {
const controller = new AbortController();
request = {
cached,
controller,
consumers: 0,
settled: false,
shareable: client.status === "open",
promise: fetchWebuiThread(token, key, {
limit: 40,
direction: "latest",
signal: controller.signal,
revision: cached?.revision,
cached,
}),
};
requests.set(requestKey, request);
const current = request;
const unsubscribeStatus = client.onStatus((status) => {
// Recovery must not join a read started before or during an outage.
if (status !== "open") current.shareable = false;
});
const unsubscribeSessionUpdate = client.onSessionUpdate((chatId, scope) => {
if (key === `websocket:${chatId}` && scope !== "metadata") {
current.controller.abort(INVALIDATED_THREAD_READ);
}
});
const unsubscribeRunCompletion = client.onRunCompletion((chatId) => {
if (key === `websocket:${chatId}`) current.controller.abort(INVALIDATED_THREAD_READ);
});
const finish = () => {
if (current.settled) return;
current.settled = true;
unsubscribeStatus();
unsubscribeSessionUpdate();
unsubscribeRunCompletion();
current.controller.signal.removeEventListener("abort", finish);
if (requests.get(requestKey) === current) requests.delete(requestKey);
};
current.controller.signal.addEventListener("abort", finish, { once: true });
void current.promise.then(finish, finish);
}
const current = request;
return new Promise((resolve, reject) => {
current.consumers += 1;
let active = true;
const release = () => {
if (!active) return;
active = false;
signal?.removeEventListener("abort", abort);
current.controller.signal.removeEventListener("abort", abort);
current.consumers -= 1;
if (current.consumers === 0 && !current.settled) current.controller.abort();
};
const abort = () => {
release();
if (current.controller.signal.reason === INVALIDATED_THREAD_READ) {
// Replace the stale page after the current notification finishes so
// all surviving consumers can join one read of its updated thread.
resolve(Promise.resolve().then(() => fetchLatestWebuiThread(client, token, key, signal)));
return;
}
reject(abortedRequest());
};
signal?.addEventListener("abort", abort, { once: true });
current.controller.signal.addEventListener("abort", abort, { once: true });
void current.promise.then((body) => {
if (!active) return;
release();
resolve(body);
}, (error: unknown) => {
if (!active) return;
release();
reject(error);
});
});
}
+21 -10
View File
@@ -70,6 +70,7 @@ function summarizeInboundWsPayload(ev: InboundEvent): unknown {
type Unsubscribe = () => void;
type EventHandler = (ev: InboundEvent) => void;
type StatusHandler = (status: ConnectionStatus) => void;
type RunCompletionHandler = (chatId: string) => void;
type RuntimeModelHandler = (modelName: string | null, modelPreset?: string | null) => void;
type SessionUpdateScope = "metadata" | "thread" | string;
type SessionUpdateHandler = (
@@ -171,6 +172,8 @@ export interface CanonicalRunSnapshot {
hasPendingToolCalls: boolean;
/** Exact active turn when supplied by a current gateway. */
activeTurnId?: string | null;
/** Supplied completion identities are authoritative for lifecycle turns. */
completionIdsProvided?: boolean;
}
type PendingMessageState = "queued" | "sent" | "unknown" | "accepted";
@@ -198,6 +201,7 @@ export class NanobotClient {
private sessionUpdateHandlers = new Set<SessionUpdateHandler>();
private sidebarStateUpdateHandlers = new Set<SidebarStateUpdateHandler>();
private runStatusHandlers = new Set<RunStatusHandler>();
private runCompletionHandlers = new Set<RunCompletionHandler>();
private errorHandlers = new Set<ErrorHandler>();
// chat_id -> handlers listening on it
private chatHandlers = new Map<string, Set<EventHandler>>();
@@ -360,6 +364,20 @@ export class NanobotClient {
return (this.unsettledRunTurnIdsByChatId.get(chatId)?.size ?? 0) > 0;
}
/** Observe terminal wire facts without subscribing to or attaching a chat. */
onRunCompletion(handler: RunCompletionHandler): Unsubscribe {
this.runCompletionHandlers.add(handler);
return () => this.runCompletionHandlers.delete(handler);
}
/** Durable runs that need a canonical disposition after transport recovery. */
getUnsettledRunChatIds(): string[] {
return Array.from(new Set([
...this.unsettledRunTurnIdsByChatId.keys(),
...this.runStartedAtByChatId.keys(),
])).filter((chatId) => !this.temporaryChatIds.has(chatId));
}
private normalizeMaxFrameBytes(value: number | undefined): number | undefined {
if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
return undefined;
@@ -375,10 +393,11 @@ export class NanobotClient {
snapshot?: CanonicalRunSnapshot,
): boolean {
if (completed.has(turnId)) return true;
const pending = this.pendingMessageSends.get(this.runSendKey(chatId, turnId));
if (snapshot?.completionIdsProvided && pending?.startsNewRun !== false) return false;
if (!snapshot || snapshot.activeTurnId === turnId) return false;
if (snapshot.hasPendingToolCalls) return false;
if (observed.has(turnId)) return true;
const pending = this.pendingMessageSends.get(this.runSendKey(chatId, turnId));
return pending?.state === "unknown" || pending?.state === "accepted";
}
@@ -770,6 +789,7 @@ export class NanobotClient {
if (closesCurrentRun && this.runStartedAtByChatId.delete(chatId)) {
this.emitRunStatus(chatId, null);
}
for (const handler of this.runCompletionHandlers) handler(chatId);
}
private recordGoalStatusForRunStrip(chatId: string, ev: InboundEvent): void {
@@ -1132,14 +1152,6 @@ export class NanobotClient {
for (const handler of this.statusHandlers) handler(status);
}
private clearRunStatusesForReconnect(): void {
if (this.runStartedAtByChatId.size === 0) return;
const chatIds = [...this.runStartedAtByChatId.keys()];
this.runStartedAtByChatId.clear();
this.runStartedAtByTurnKey.clear();
for (const chatId of chatIds) this.emitRunStatus(chatId, null);
}
private handleOpen(): void {
this.setStatus("open");
this.reconnectAttempts = 0;
@@ -1530,7 +1542,6 @@ export class NanobotClient {
}
private scheduleReconnect(): void {
this.clearRunStatusesForReconnect();
this.setStatus("reconnecting");
const attempt = this.reconnectAttempts++;
// Exponential backoff: 0.5s, 1s, 2s, 4s, capped.
+13
View File
@@ -5,6 +5,8 @@ import type { WebuiThreadPersistedPayload } from "./types";
/** Bounded canonical replay cache; the most recent snapshot also survives tab reloads. */
export class WebuiThreadCache extends MemoryLruCache<WebuiThreadPersistedPayload> {
private readonly listeners = new Map<string, Set<(body: WebuiThreadPersistedPayload) => void>>();
constructor(
maxBytes = 16 * 1024 * 1024,
maxEntries = 12,
@@ -31,6 +33,17 @@ export class WebuiThreadCache extends MemoryLruCache<WebuiThreadPersistedPayload
override set(key: string, body: WebuiThreadPersistedPayload): void {
super.set(key, body);
if (super.get(key)) writeReloadCache("thread", { key, body });
for (const listener of this.listeners.get(key) ?? []) listener(body);
}
subscribe(key: string, listener: (body: WebuiThreadPersistedPayload) => void): () => void {
const listeners = this.listeners.get(key) ?? new Set();
listeners.add(listener);
this.listeners.set(key, listeners);
return () => {
listeners.delete(listener);
if (listeners.size === 0) this.listeners.delete(key);
};
}
override delete(key: string): void {