DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat(web): add multi-worker turn runtime client
Bingxi Zhao (Frank)1115cdbb928d
diff --git a/web/features/chat/transport/TurnRuntimeClient.ts b/web/features/chat/transport/TurnRuntimeClient.tsnew file mode 100644index 000000000..2689f6705--- /dev/null+++ b/web/features/chat/transport/TurnRuntimeClient.ts@@ -0,0 +1,264 @@+import type { ClientCommand, ServerEvent, StreamEvent } from "@/contracts/generated/turn-protocol";+import { buildPing, buildResumeTurn } from "@/contracts/parse/turn-command";+import { parseTurnEvent } from "@/contracts/parse/turn-event";++import {+ browserSocketFactory,+ SOCKET_CONNECTING,+ SOCKET_OPEN,+ type TurnSocket,+ type TurnSocketFactory,+} from "./socket";+import { reconnectDelay, shouldReconnect } from "./reconnect-policy";++export type RuntimeConnectionState = "idle" | "connecting" | "connected" | "recovering" | "stopped";++export interface RuntimeScheduler {+ setTimeout(callback: () => void, delay: number): unknown;+ clearTimeout(handle: unknown): void;+}++export interface TurnRuntimeClientOptions {+ url?: string;+ socketFactory?: TurnSocketFactory;+ scheduler?: RuntimeScheduler;+ random?: () => number;+ maxBufferedGap?: number;+ onEvent: (event: ServerEvent) => void;+ onStateChange?: (state: RuntimeConnectionState) => void;+ onDiagnostic?: (diagnostic: string) => void;+ onReconcile?: (cursor: { turnId: string; afterSeq: number }) => void;+}++interface PendingCommand {+ command: ClientCommand;+ acknowledgedAfter: number;+ sentGeneration: number;+}++const defaultScheduler: RuntimeScheduler = {+ setTimeout: (callback, delay) => globalThis.setTimeout(callback, delay),+ clearTimeout: (handle) => globalThis.clearTimeout(handle as ReturnType<typeof setTimeout>),+};++export class TurnRuntimeClient {+ private readonly options: Required<+ Pick<TurnRuntimeClientOptions, "url" | "socketFactory" | "scheduler" | "random" | "maxBufferedGap">+ > &+ Omit<+ TurnRuntimeClientOptions,+ "url" | "socketFactory" | "scheduler" | "random" | "maxBufferedGap"+ >;+ private socket: TurnSocket | null = null;+ private reconnectHandle: unknown = null;+ private reconnectAttempt = 0;+ private generation = 0;+ private stopped = false;+ private pageVisible = true;+ private turnId: string | null = null;+ private lastSeq = 0;+ private buffered = new Map<number, StreamEvent>();+ private pending: PendingCommand[] = [];+ private connectionState: RuntimeConnectionState = "idle";++ constructor(options: TurnRuntimeClientOptions) {+ this.options = {+ url: "/api/v1/ws",+ socketFactory: browserSocketFactory,+ scheduler: defaultScheduler,+ random: Math.random,+ maxBufferedGap: 32,+ ...options,+ };+ }++ get state(): RuntimeConnectionState {+ return this.connectionState;+ }++ get cursor(): { turnId: string | null; afterSeq: number } {+ return { turnId: this.turnId, afterSeq: this.lastSeq };+ }++ connect(): void {+ if (this.stopped) this.stopped = false;+ if (this.socket && this.socket.readyState <= SOCKET_OPEN) return;+ this.clearReconnect();+ this.setState(this.turnId ? "recovering" : "connecting");+ const socket = this.options.socketFactory(this.options.url);+ this.socket = socket;++ socket.addEventListener("open", () => this.handleOpen(socket));+ socket.addEventListener("message", (event) => this.handleMessage(socket, event.data));+ socket.addEventListener("close", () => this.handleClose(socket));+ socket.addEventListener("error", () => {+ if (socket === this.socket) this.options.onDiagnostic?.("turn socket error; awaiting close");+ });+ }++ setResumeCursor(turnId: string | null, afterSeq: number): void {+ if (!Number.isInteger(afterSeq) || afterSeq < 0) throw new TypeError("afterSeq is invalid");+ this.turnId = turnId?.trim() || null;+ this.lastSeq = afterSeq;+ this.buffered.clear();+ }++ setPageVisible(visible: boolean): void {+ this.pageVisible = visible;+ if (visible && !this.stopped && !this.socket) this.manualRetry();+ }++ send(command: ClientCommand, options: { durable?: boolean } = {}): void {+ const durable = options.durable ?? command.type !== "ping";+ if (!durable) {+ this.sendNow(command);+ return;+ }+ const pending: PendingCommand = {+ command,+ acknowledgedAfter: this.lastSeq,+ sentGeneration: -1,+ };+ this.pending.push(pending);+ this.flushPending();+ }++ cancel(command: ClientCommand): void {+ this.send(command);+ }++ ping(): void {+ this.send(buildPing(), { durable: false });+ }++ manualRetry(): void {+ if (this.stopped) return;+ this.reconnectAttempt = 0;+ if (this.socket?.readyState === SOCKET_CONNECTING) return;+ this.socket?.close();+ this.socket = null;+ this.connect();+ }++ stop(): void {+ this.stopped = true;+ this.clearReconnect();+ const socket = this.socket;+ this.socket = null;+ socket?.close(1000, "client stopped");+ this.pending = [];+ this.buffered.clear();+ this.setState("stopped");+ }++ private handleOpen(socket: TurnSocket): void {+ if (socket !== this.socket || this.stopped) return;+ this.generation += 1;+ this.reconnectAttempt = 0;+ this.setState("connected");+ if (this.turnId) {+ this.sendNow(buildResumeTurn({ turnId: this.turnId, afterSeq: this.lastSeq }));+ }+ this.flushPending();+ }++ private handleMessage(socket: TurnSocket, raw: unknown): void {+ if (socket !== this.socket || this.stopped) return;+ const parsed = parseTurnEvent(raw);+ if (!parsed.ok) {+ if (parsed.reason !== "heartbeat") this.options.onDiagnostic?.(parsed.diagnostic);+ return;+ }+ const event = parsed.value;+ if (event.type === "active_turn_info") {+ if (event.turn_id) this.turnId = event.turn_id;+ this.options.onEvent(event);+ return;+ }+ if (event.type === "pong") return;+ this.acceptStreamEvent(event as StreamEvent);+ }++ private acceptStreamEvent(event: StreamEvent): void {+ const seq = event.seq ?? 0;+ if (event.turn_id) this.turnId = event.turn_id;+ if (seq <= this.lastSeq) return;+ const gap = seq - this.lastSeq;+ if (gap > 1) {+ if (gap <= this.options.maxBufferedGap) {+ this.buffered.set(seq, event);+ } else if (this.turnId) {+ this.options.onDiagnostic?.(`turn event gap exceeded buffer; after_seq=${this.lastSeq}`);+ this.options.onReconcile?.({ turnId: this.turnId, afterSeq: this.lastSeq });+ }+ return;+ }++ this.emitInOrder(event);+ let next = this.buffered.get(this.lastSeq + 1);+ while (next) {+ this.buffered.delete(this.lastSeq + 1);+ this.emitInOrder(next);+ next = this.buffered.get(this.lastSeq + 1);+ }+ }++ private emitInOrder(event: StreamEvent): void {+ this.lastSeq = event.seq ?? this.lastSeq;+ this.pending = this.pending.filter((item) => this.lastSeq <= item.acknowledgedAfter);+ this.options.onEvent(event);+ }++ private handleClose(socket: TurnSocket): void {+ if (socket !== this.socket) return;+ this.socket = null;+ if (this.stopped) return;+ this.setState(this.turnId ? "recovering" : "connecting");+ this.scheduleReconnect();+ }++ private scheduleReconnect(): void {+ if (+ !shouldReconnect({+ attempt: this.reconnectAttempt,+ activeTurnId: this.turnId,+ pageVisible: this.pageVisible,+ })+ ) {+ this.setState("idle");+ return;+ }+ const delay = reconnectDelay(this.reconnectAttempt, this.options.random);+ this.reconnectAttempt += 1;+ this.reconnectHandle = this.options.scheduler.setTimeout(() => {+ this.reconnectHandle = null;+ this.connect();+ }, delay);+ }++ private flushPending(): void {+ if (!this.socket || this.socket.readyState !== SOCKET_OPEN) return;+ for (const pending of this.pending) {+ if (pending.sentGeneration === this.generation) continue;+ this.sendNow(pending.command);+ pending.sentGeneration = this.generation;+ }+ }++ private sendNow(command: ClientCommand): void {+ if (!this.socket || this.socket.readyState !== SOCKET_OPEN) return;+ this.socket.send(JSON.stringify(command));+ }++ private clearReconnect(): void {+ if (this.reconnectHandle === null) return;+ this.options.scheduler.clearTimeout(this.reconnectHandle);+ this.reconnectHandle = null;+ }++ private setState(state: RuntimeConnectionState): void {+ if (this.connectionState === state) return;+ this.connectionState = state;+ this.options.onStateChange?.(state);+ }+}diff --git a/web/features/chat/transport/reconnect-policy.ts b/web/features/chat/transport/reconnect-policy.tsnew file mode 100644index 000000000..04c299b59--- /dev/null+++ b/web/features/chat/transport/reconnect-policy.ts@@ -0,0 +1,18 @@+const BASE_DELAY_MS = 250;+const MAX_DELAY_MS = 8_000;+const IDLE_ATTEMPT_LIMIT = 5;++export function reconnectDelay(attempt: number, random: () => number = Math.random): number {+ const exponential = Math.min(MAX_DELAY_MS, BASE_DELAY_MS * 2 ** Math.max(0, attempt));+ const jitter = 0.8 + Math.min(1, Math.max(0, random())) * 0.4;+ return Math.round(exponential * jitter);+}++export function shouldReconnect(input: {+ attempt: number;+ activeTurnId: string | null;+ pageVisible: boolean;+}): boolean {+ if (!input.pageVisible && !input.activeTurnId) return false;+ return Boolean(input.activeTurnId) || input.attempt < IDLE_ATTEMPT_LIMIT;+}diff --git a/web/features/chat/transport/socket.ts b/web/features/chat/transport/socket.tsnew file mode 100644index 000000000..8450d81cb--- /dev/null+++ b/web/features/chat/transport/socket.ts@@ -0,0 +1,22 @@+export interface SocketMessageEvent {+ data: unknown;+}++export interface TurnSocket {+ readonly readyState: number;+ send(data: string): void;+ close(code?: number, reason?: string): void;+ addEventListener(+ type: "open" | "message" | "close" | "error",+ listener: (event: SocketMessageEvent) => void,+ ): void;+}++export type TurnSocketFactory = (url: string) => TurnSocket;++export const SOCKET_CONNECTING = 0;+export const SOCKET_OPEN = 1;++export function browserSocketFactory(url: string): TurnSocket {+ return new WebSocket(url) as unknown as TurnSocket;+}diff --git a/web/tests/turn-runtime-client.test.ts b/web/tests/turn-runtime-client.test.tsnew file mode 100644index 000000000..5508c660e--- /dev/null+++ b/web/tests/turn-runtime-client.test.ts@@ -0,0 +1,173 @@+import assert from "node:assert/strict";+import test from "node:test";++import { buildCancelTurn, buildSubmitUserReply } from "../contracts/parse/turn-command";+import { TurnRuntimeClient, type RuntimeScheduler } from "../features/chat/transport/TurnRuntimeClient";+import { SOCKET_CONNECTING, SOCKET_OPEN, type TurnSocket } from "../features/chat/transport/socket";++class FakeSocket implements TurnSocket {+ readyState = SOCKET_CONNECTING;+ sent: Record<string, unknown>[] = [];+ private listeners = new Map<string, Array<(event: { data: unknown }) => void>>();++ addEventListener(type: string, listener: (event: { data: unknown }) => void): void {+ const rows = this.listeners.get(type) ?? [];+ rows.push(listener);+ this.listeners.set(type, rows);+ }++ send(data: string): void {+ this.sent.push(JSON.parse(data) as Record<string, unknown>);+ }++ close(): void {+ this.readyState = 3;+ this.emit("close");+ }++ open(): void {+ this.readyState = SOCKET_OPEN;+ this.emit("open");+ }++ message(value: unknown): void {+ this.emit("message", { data: typeof value === "string" ? value : JSON.stringify(value) });+ }++ private emit(type: string, event: { data: unknown } = { data: undefined }): void {+ for (const listener of this.listeners.get(type) ?? []) listener(event);+ }+}++class FakeScheduler implements RuntimeScheduler {+ tasks: Array<() => void> = [];+ setTimeout(callback: () => void): unknown {+ this.tasks.push(callback);+ return callback;+ }+ clearTimeout(handle: unknown): void {+ this.tasks = this.tasks.filter((task) => task !== handle);+ }+ runNext(): void {+ this.tasks.shift()?.();+ }+}++function stream(seq: number, type = "content"): Record<string, unknown> {+ return {+ type,+ turn_id: "turn-1",+ session_id: "session-1",+ seq,+ timestamp: seq,+ content: `token-${seq}`,+ metadata: {},+ };+}++function harness() {+ const sockets: FakeSocket[] = [];+ const scheduler = new FakeScheduler();+ const events: Array<{ type?: string; seq?: number }> = [];+ const states: string[] = [];+ const diagnostics: string[] = [];+ const reconciliations: unknown[] = [];+ const client = new TurnRuntimeClient({+ socketFactory: () => {+ const socket = new FakeSocket();+ sockets.push(socket);+ return socket;+ },+ scheduler,+ random: () => 0.5,+ maxBufferedGap: 3,+ onEvent: (event) => events.push(event),+ onStateChange: (state) => states.push(state),+ onDiagnostic: (value) => diagnostics.push(value),+ onReconcile: (cursor) => reconciliations.push(cursor),+ });+ return { client, diagnostics, events, reconciliations, scheduler, sockets, states };+}++test("reconnect resumes from the persisted cursor through a different worker", () => {+ const { client, scheduler, sockets, states } = harness();+ client.setResumeCursor("turn-1", 8);+ client.connect();+ sockets[0].open();+ assert.equal(sockets[0].sent[0].type, "resume_from");+ assert.equal(sockets[0].sent[0].seq, 8);++ sockets[0].close();+ assert.equal(states.at(-1), "recovering");+ scheduler.runNext();+ sockets[1].open();+ assert.equal(sockets[1].sent[0].seq, 8);+});++test("duplicates are dropped and bounded out-of-order events are restored", () => {+ const { client, events, sockets } = harness();+ client.connect();+ sockets[0].open();+ sockets[0].message(stream(2));+ sockets[0].message(stream(1));+ sockets[0].message(stream(1));+ assert.deepEqual(events.map((event) => event.seq), [1, 2]);+});++test("large sequence gaps request reconciliation instead of emitting", () => {+ const { client, events, reconciliations, sockets } = harness();+ client.setResumeCursor("turn-1", 1);+ client.connect();+ sockets[0].open();+ sockets[0].message(stream(8));+ assert.equal(events.length, 0);+ assert.deepEqual(reconciliations, [{ turnId: "turn-1", afterSeq: 1 }]);+});++test("heartbeats and invalid or future frames never become chat events", () => {+ const { client, diagnostics, events, sockets } = harness();+ client.connect();+ sockets[0].open();+ sockets[0].message({ type: "pong" });+ sockets[0].message({ type: "future", content: "private" });+ sockets[0].message("not json");+ assert.equal(events.length, 0);+ assert.equal(diagnostics.length, 2);+ assert.doesNotMatch(diagnostics.join(" "), /private/);+});++test("cancel stays connected and a waiting-input reply survives only unacknowledged reconnects", () => {+ const { client, scheduler, sockets } = harness();+ client.setResumeCursor("turn-1", 2);+ client.connect();+ sockets[0].open();+ client.cancel(buildCancelTurn("turn-1"));+ client.send(buildSubmitUserReply({ turnId: "turn-1", text: "continue" }));+ assert.equal(sockets[0].readyState, SOCKET_OPEN);++ sockets[0].close();+ scheduler.runNext();+ sockets[1].open();+ assert.equal(sockets[1].sent.filter((item) => item.type === "submit_user_reply").length, 1);+ sockets[1].message(stream(3));++ sockets[1].close();+ scheduler.runNext();+ sockets[2].open();+ assert.equal(sockets[2].sent.filter((item) => item.type === "submit_user_reply").length, 0);+});++test("stopping cancels retries and idle hidden sessions do not reconnect", () => {+ const { client, scheduler, sockets } = harness();+ client.connect();+ sockets[0].open();+ client.setPageVisible(false);+ sockets[0].close();+ assert.equal(scheduler.tasks.length, 0);++ client.setPageVisible(true);+ assert.equal(sockets.length, 2);+ client.stop();+ assert.equal(client.state, "stopped");+ assert.equal(scheduler.tasks.length, 0);+});