DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(partners): restore focus and reconnect after tab inactivity (#886)
Bingxi Zhao7820b050f0d5
diff --git a/web/components/partners/PartnerChat.tsx b/web/components/partners/PartnerChat.tsxindex 9c0c9964e..ebd70e8d5 100644--- a/web/components/partners/PartnerChat.tsx+++ b/web/components/partners/PartnerChat.tsx@@ -25,6 +25,7 @@ import {resumePartnerSession,} from "@/lib/partners-api";import { freshPartnerSessionKey } from "@/lib/partner-session";+import { ReconnectingWebSocket } from "@/lib/reconnecting-websocket";import type { ExportableMessage } from "@/lib/chat-export";import type { StreamEvent } from "@/lib/unified-ws";import { docIconFor, formatBytes, isSvgFilename } from "@/lib/doc-attachments";@@ -224,7 +225,7 @@ export default function PartnerChat({events: StreamEvent[];content: string;} | null>(null);- const wsRef = useRef<WebSocket | null>(null);+ const connectionRef = useRef<ReconnectingWebSocket | null>(null);// Mirror the active session into a ref so the socket's onopen (which closes// over the effect's first render) attaches to the CURRENT session.const sessionKeyRef = useRef(sessionKey);@@ -255,11 +256,19 @@ export default function PartnerChat({const tryAttach = useCallback(() => {if (attachedRef.current) return;if (!historyReadyRef.current || !sessionKeyRef.current) return;- if (wsRef.current?.readyState !== WebSocket.OPEN) return;+ const connection = connectionRef.current;+ if (!connection?.connected) return;attachedRef.current = true;- wsRef.current.send(- JSON.stringify({ action: "attach", session_key: sessionKeyRef.current }),- );+ if (+ !connection.send(+ JSON.stringify({+ action: "attach",+ session_key: sessionKeyRef.current,+ }),+ )+ ) {+ attachedRef.current = false;+ }}, []);// Restore the active session's history (scoped to it — the cross-channel@@ -270,6 +279,7 @@ export default function PartnerChat({if (!sessionKey) return;let cancelled = false;historyReadyRef.current = false;+ attachedRef.current = false;void getPartnerHistory(partnerId, {sessionKey,limit: 60,@@ -306,8 +316,8 @@ export default function PartnerChat({useEffect(() => {if (!running) {- wsRef.current?.close();- wsRef.current = null;+ connectionRef.current?.stop();+ connectionRef.current = null;setConnected(false);setStreaming(false);setDraft(null);@@ -315,19 +325,8 @@ export default function PartnerChat({}attachedRef.current = false;- const ws = new WebSocket(wsUrl(`/api/v1/partners/${partnerId}/ws`));- wsRef.current = ws;- ws.onopen = () => {- setConnected(true);- // Reattach to an in-flight turn (survives a page refresh): the server- // replays its buffered stream, so a mid-answer reload keeps streaming.- // Sequenced after history load via tryAttach so the replay isn't- // clobbered by the history replace.- tryAttach();- };-// Authoritative live-turn accumulator. Lives in the effect scope so- // socket handlers can mutate it cheaply; renders see snapshots only.+ // connection handlers can mutate it cheaply; renders see snapshots only.let live: { events: StreamEvent[]; content: string } | null = null;const publish = () => {setDraft(@@ -335,12 +334,17 @@ export default function PartnerChat({);};- ws.onmessage = (e) => {- const data = JSON.parse(e.data) as {+ const handleMessage = (message: MessageEvent) => {+ let data: {type: string;content?: string;event?: StreamEvent;};+ try {+ data = JSON.parse(String(message.data));+ } catch {+ return;+ }if (data.type === "resuming") {// Server is about to replay an in-flight turn (after a refresh).live = { events: [], content: "" };@@ -349,11 +353,15 @@ export default function PartnerChat({return;}if (data.type === "user_echo") {- // The question that opened the replayed turn (not yet persisted).- setMessages((msgs) => [- ...msgs,- { role: "user", content: data.content ?? "" },- ]);+ // Reconnects replay the active question. Keep the optimistic row that+ // is already present in this mounted page instead of duplicating it.+ const content = data.content ?? "";+ setMessages((msgs) => {+ const last = msgs[msgs.length - 1];+ return last?.role === "user" && last.content === content+ ? msgs+ : [...msgs, { role: "user", content }];+ });return;}if (data.type === "stream_event" && data.event) {@@ -419,14 +427,48 @@ export default function PartnerChat({}};- ws.onclose = () => {- setConnected(false);- setStreaming(false);+ const connection = new ReconnectingWebSocket(+ wsUrl(`/api/v1/partners/${partnerId}/ws`),+ {+ onOpen: () => {+ setConnected(true);+ attachedRef.current = false;+ // Reattach after every reconnect so the server can replay an+ // in-flight turn. tryAttach waits for history before doing so.+ tryAttach();+ },+ onMessage: handleMessage,+ onDisconnect: () => {+ setConnected(false);+ setStreaming(false);+ },+ },+ {+ shouldReconnect: () =>+ document.visibilityState === "visible" && navigator.onLine !== false,+ },+ );+ connectionRef.current = connection;++ const wakeWhenActive = () => {+ if (+ document.visibilityState === "visible" &&+ navigator.onLine !== false+ ) {+ connection.wake();+ }};+ window.addEventListener("focus", wakeWhenActive);+ window.addEventListener("online", wakeWhenActive);+ document.addEventListener("visibilitychange", wakeWhenActive);+ connection.start();return () => {- ws.close();- wsRef.current = null;+ window.removeEventListener("focus", wakeWhenActive);+ window.removeEventListener("online", wakeWhenActive);+ document.removeEventListener("visibilitychange", wakeWhenActive);+ connection.stop();+ if (connectionRef.current === connection) connectionRef.current = null;};}, [partnerId, running, tryAttach]);@@ -446,11 +488,9 @@ export default function PartnerChat({}, [messages, onMessagesChange]);const sendStop = useCallback(() => {- if (wsRef.current?.readyState === WebSocket.OPEN) {- wsRef.current.send(- JSON.stringify({ action: "stop", session_key: sessionKey }),- );- }+ connectionRef.current?.send(+ JSON.stringify({ action: "stop", session_key: sessionKey }),+ );}, [sessionKey]);// Escape interrupts a streaming answer. Bound on `window` rather than the@@ -578,7 +618,7 @@ export default function PartnerChat({const handleSend = useCallback((content: string, attachments: PartnerPendingAttachment[]) => {- if (streaming || !running) return;+ if (streaming || !running) return false;// A new user-authored turn explicitly returns to live-follow mode.// During the answer, the shared hook releases that mode as soon as the@@ -588,16 +628,15 @@ export default function PartnerChat({attachments.length === 0 ? parseClientCommand(content) : null;if (command) {void runClientCommand(command.command, command.arg);- return;+ return false;}- if (!wsRef.current || wsRef.current.readyState !== WebSocket.OPEN) return;const visibleContent =content ||(attachments.every((item) => item.type === "image")? t("Please analyze the attached image(s)."): t("Please use the attached file(s)."));- wsRef.current.send(+ const sent = connectionRef.current?.send(JSON.stringify({content: visibleContent,session_key: sessionKey,@@ -609,6 +648,7 @@ export default function PartnerChat({})),}),);+ if (!sent) return false;setMessages((msgs) => [...msgs,{@@ -620,6 +660,7 @@ export default function PartnerChat({setDraft({ events: [], content: "" });setStreaming(true);scrollToBottom("instant");+ return true;},[sessionKey,diff --git a/web/components/partners/PartnerComposer.tsx b/web/components/partners/PartnerComposer.tsxindex 57ddc8513..9e13f3b8d 100644--- a/web/components/partners/PartnerComposer.tsx+++ b/web/components/partners/PartnerComposer.tsx@@ -45,7 +45,8 @@ export const PartnerComposer = memo(function PartnerComposer({streaming,placeholder,}: {- onSend: (content: string, attachments: PartnerPendingAttachment[]) => void;+ /** Returns true when sending starts an asynchronous streamed response. */+ onSend: (content: string, attachments: PartnerPendingAttachment[]) => boolean;onStop?: () => void;disabled?: boolean;streaming?: boolean;@@ -65,6 +66,8 @@ export const PartnerComposer = memo(function PartnerComposer({const [showHelp, setShowHelp] = useState(false);const textareaRef = useRef<HTMLTextAreaElement | null>(null);const fileInputRef = useRef<HTMLInputElement | null>(null);+ const restoreFocusOnReturnRef = useRef(false);+ const restoreFocusAfterSendRef = useRef(false);const dragCounterRef = useRef(0);const errorTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);const { isComposingRef, onCompositionStart, onCompositionEnd } =@@ -72,6 +75,48 @@ export const PartnerComposer = memo(function PartnerComposer({useAutoSizedTextarea(textareaRef, input, { min: 24, max: 180 });+ const focusTextarea = useCallback(() => {+ requestAnimationFrame(() => {+ if (!disabled && !streaming) textareaRef.current?.focus();+ });+ }, [disabled, streaming]);++ useEffect(() => {+ const rememberFocus = () => {+ restoreFocusOnReturnRef.current =+ document.activeElement === textareaRef.current;+ };+ const restoreFocus = () => {+ if (+ restoreFocusOnReturnRef.current &&+ document.visibilityState === "visible"+ ) {+ focusTextarea();+ }+ };++ window.addEventListener("blur", rememberFocus);+ window.addEventListener("focus", restoreFocus);+ document.addEventListener("visibilitychange", restoreFocus);+ return () => {+ window.removeEventListener("blur", rememberFocus);+ window.removeEventListener("focus", restoreFocus);+ document.removeEventListener("visibilitychange", restoreFocus);+ };+ }, [focusTextarea]);++ useEffect(() => {+ if (disabled || streaming) return;+ if (+ !restoreFocusAfterSendRef.current &&+ !restoreFocusOnReturnRef.current+ ) {+ return;+ }+ restoreFocusAfterSendRef.current = false;+ focusTextarea();+ }, [disabled, focusTextarea, streaming]);+// Slash commands (same 5 the IM channels expose) — fetched once; the palette// is partner-independent so no id is needed.useEffect(() => {@@ -102,13 +147,16 @@ export const PartnerComposer = memo(function PartnerComposer({const slashOpen = !slashClosed && slashMatches.length > 0;const boundedSlashIndex = Math.min(slashIndex, slashMatches.length - 1);- const acceptCommand = useCallback((command: PartnerCommandInfo) => {- // Arg-taking commands keep the menu out of the way with a trailing space;- // zero-arg ones are left ready to send.- setInput(command.arg_hint ? `${command.command} ` : command.command);- setSlashClosed(true);- requestAnimationFrame(() => textareaRef.current?.focus());- }, []);+ const acceptCommand = useCallback(+ (command: PartnerCommandInfo) => {+ // Arg-taking commands keep the menu out of the way with a trailing+ // space; zero-arg ones are left ready to send.+ setInput(command.arg_hint ? `${command.command} ` : command.command);+ setSlashClosed(true);+ focusTextarea();+ },+ [focusTextarea],+ );const showAttachmentError = useCallback((message: string) => {setAttachmentError(message);@@ -196,11 +244,15 @@ export const PartnerComposer = memo(function PartnerComposer({const submit = useCallback(() => {const content = input.trim();if ((!content && attachments.length === 0) || disabled) return;- onSend(content, attachments);+ const awaitsResponse = onSend(content, attachments);setInput("");setAttachments([]);- requestAnimationFrame(() => textareaRef.current?.focus());- }, [attachments, disabled, input, onSend]);+ if (awaitsResponse) {+ restoreFocusAfterSendRef.current = true;+ } else {+ focusTextarea();+ }+ }, [attachments, disabled, focusTextarea, input, onSend]);const handleKeyDown = useCallback((e: React.KeyboardEvent<HTMLTextAreaElement>) => {diff --git a/web/lib/reconnecting-websocket.ts b/web/lib/reconnecting-websocket.tsnew file mode 100644index 000000000..6632c187b--- /dev/null+++ b/web/lib/reconnecting-websocket.ts@@ -0,0 +1,194 @@+const CONNECTING = 0+const OPEN = 1++const DEFAULT_BASE_RETRY_MS = 250+const DEFAULT_MAX_RETRY_MS = 8_000+const DEFAULT_STALE_CONNECTING_MS = 10_000++export function reconnectDelayMs(+ attempt: number,+ baseDelayMs = DEFAULT_BASE_RETRY_MS,+ maxDelayMs = DEFAULT_MAX_RETRY_MS+): number {+ return Math.min(baseDelayMs * 2 ** Math.max(0, attempt), maxDelayMs)+}++interface RetryScheduler {+ set(callback: () => void, delayMs: number): unknown+ clear(handle: unknown): void+}++interface ReconnectingWebSocketHandlers {+ onOpen?: () => void+ onMessage: (event: MessageEvent) => void+ onDisconnect?: () => void+ onError?: (error: unknown) => void+}++interface ReconnectingWebSocketOptions {+ createSocket?: (url: string) => WebSocket+ shouldReconnect?: () => boolean+ scheduler?: RetryScheduler+ now?: () => number+ baseRetryMs?: number+ maxRetryMs?: number+ staleConnectingMs?: number+}++const defaultScheduler: RetryScheduler = {+ set: (callback, delayMs) => setTimeout(callback, delayMs),+ clear: handle => clearTimeout(handle as ReturnType<typeof setTimeout>),+}++/**+ * Owns one browser WebSocket and keeps it alive across transient disconnects.+ *+ * The class deliberately knows nothing about React or the wire protocol. A+ * caller can pause retries while its page is hidden, then call `wake()` on+ * focus/visibility/online events for an immediate connection attempt.+ */+export class ReconnectingWebSocket {+ private socket: WebSocket | null = null+ private retryHandle: unknown = null+ private retryAttempt = 0+ private connectingSince = 0+ private stopped = true++ private readonly createSocket: (url: string) => WebSocket+ private readonly shouldReconnect: () => boolean+ private readonly scheduler: RetryScheduler+ private readonly now: () => number+ private readonly baseRetryMs: number+ private readonly maxRetryMs: number+ private readonly staleConnectingMs: number++ constructor(+ private readonly url: string,+ private readonly handlers: ReconnectingWebSocketHandlers,+ options: ReconnectingWebSocketOptions = {}+ ) {+ this.createSocket = options.createSocket ?? (url => new WebSocket(url))+ this.shouldReconnect = options.shouldReconnect ?? (() => true)+ this.scheduler = options.scheduler ?? defaultScheduler+ this.now = options.now ?? Date.now+ this.baseRetryMs = options.baseRetryMs ?? DEFAULT_BASE_RETRY_MS+ this.maxRetryMs = options.maxRetryMs ?? DEFAULT_MAX_RETRY_MS+ this.staleConnectingMs = options.staleConnectingMs ?? DEFAULT_STALE_CONNECTING_MS+ }++ get connected(): boolean {+ return this.socket?.readyState === OPEN+ }++ start(): void {+ if (!this.stopped) return+ this.stopped = false+ if (this.shouldReconnect()) this.open()+ }++ /** Try immediately after the browser becomes active or comes back online. */+ wake(): void {+ if (this.stopped || !this.shouldReconnect()) return+ this.clearRetry()+ this.retryAttempt = 0++ if (this.socket?.readyState === OPEN) return+ if (+ this.socket?.readyState === CONNECTING &&+ this.now() - this.connectingSince < this.staleConnectingMs+ ) {+ return+ }++ this.releaseSocket()+ this.open()+ }++ send(payload: string): boolean {+ if (!this.socket || this.socket.readyState !== OPEN) return false+ try {+ this.socket.send(payload)+ return true+ } catch (error) {+ this.handlers.onError?.(error)+ this.socket.close()+ return false+ }+ }++ stop(): void {+ if (this.stopped) return+ this.stopped = true+ this.clearRetry()+ this.releaseSocket()+ this.retryAttempt = 0+ }++ private open(): void {+ if (this.stopped || (this.socket && this.socket.readyState <= OPEN)) {+ return+ }++ let socket: WebSocket+ try {+ socket = this.createSocket(this.url)+ } catch (error) {+ this.handlers.onError?.(error)+ this.scheduleRetry()+ return+ }++ this.socket = socket+ this.connectingSince = this.now()+ socket.onopen = () => {+ if (this.socket !== socket || this.stopped) return+ this.retryAttempt = 0+ this.handlers.onOpen?.()+ }+ socket.onmessage = event => {+ if (this.socket === socket && !this.stopped) {+ this.handlers.onMessage(event)+ }+ }+ socket.onerror = error => {+ if (this.socket === socket && !this.stopped) {+ this.handlers.onError?.(error)+ }+ }+ socket.onclose = () => {+ if (this.socket !== socket) return+ this.socket = null+ this.handlers.onDisconnect?.()+ this.scheduleRetry()+ }+ }++ private scheduleRetry(): void {+ if (this.stopped || this.retryHandle !== null || !this.shouldReconnect()) {+ return+ }+ const delayMs = reconnectDelayMs(this.retryAttempt, this.baseRetryMs, this.maxRetryMs)+ this.retryAttempt += 1+ this.retryHandle = this.scheduler.set(() => {+ this.retryHandle = null+ if (this.shouldReconnect()) this.open()+ }, delayMs)+ }++ private clearRetry(): void {+ if (this.retryHandle === null) return+ this.scheduler.clear(this.retryHandle)+ this.retryHandle = null+ }++ private releaseSocket(): void {+ const socket = this.socket+ this.socket = null+ if (!socket) return+ socket.onopen = null+ socket.onmessage = null+ socket.onerror = null+ socket.onclose = null+ if (socket.readyState <= OPEN) socket.close()+ }+}diff --git a/web/tests/reconnecting-websocket.test.ts b/web/tests/reconnecting-websocket.test.tsnew file mode 100644index 000000000..548cfbec2--- /dev/null+++ b/web/tests/reconnecting-websocket.test.ts@@ -0,0 +1,163 @@+import test from 'node:test'+import assert from 'node:assert/strict'+import { readFileSync } from 'node:fs'+import path from 'node:path'+import { ReconnectingWebSocket, reconnectDelayMs } from '../lib/reconnecting-websocket'++class FakeSocket {+ readyState = 0+ sent: string[] = []+ onopen: ((event: Event) => void) | null = null+ onmessage: ((event: MessageEvent) => void) | null = null+ onerror: ((event: Event) => void) | null = null+ onclose: ((event: CloseEvent) => void) | null = null++ open(): void {+ this.readyState = 1+ this.onopen?.({} as Event)+ }++ drop(): void {+ this.readyState = 3+ this.onclose?.({} as CloseEvent)+ }++ close(): void {+ if (this.readyState !== 3) this.drop()+ }++ send(payload: string): void {+ this.sent.push(payload)+ }+}++function createHarness(shouldReconnect: () => boolean = () => true) {+ const sockets: FakeSocket[] = []+ const scheduled: Array<{+ callback: () => void+ delayMs: number+ cancelled: boolean+ }> = []+ let now = 0+ const client = new ReconnectingWebSocket(+ 'ws://partner.test',+ { onMessage: () => {} },+ {+ createSocket: () => {+ const socket = new FakeSocket()+ sockets.push(socket)+ return socket as unknown as WebSocket+ },+ shouldReconnect,+ now: () => now,+ scheduler: {+ set: (callback, delayMs) => {+ const task = { callback, delayMs, cancelled: false }+ scheduled.push(task)+ return task+ },+ clear: handle => {+ ;(handle as (typeof scheduled)[number]).cancelled = true+ },+ },+ }+ )+ return {+ client,+ sockets,+ scheduled,+ setNow: (value: number) => {+ now = value+ },+ }+}++test('reconnect delay grows exponentially and remains bounded', () => {+ assert.deepEqual(+ [0, 1, 2, 3, 8].map(attempt => reconnectDelayMs(attempt, 250, 2_000)),+ [250, 500, 1_000, 2_000, 2_000]+ )+})++test('unexpected closes reconnect without creating concurrent sockets', () => {+ const { client, sockets, scheduled } = createHarness()+ client.start()+ client.start()+ assert.equal(sockets.length, 1)++ sockets[0].open()+ sockets[0].drop()+ assert.equal(scheduled[0].delayMs, 250)++ scheduled[0].callback()+ assert.equal(sockets.length, 2)+ sockets[1].drop()+ assert.equal(scheduled[1].delayMs, 500)+})++test('wake reconnects immediately when a hidden page becomes active', () => {+ let active = true+ const { client, sockets, scheduled } = createHarness(() => active)+ client.start()+ sockets[0].open()+ active = false+ sockets[0].drop()+ assert.equal(scheduled.length, 0, 'hidden pages should not spin retry timers')++ active = true+ client.wake()+ assert.equal(sockets.length, 2)+})++test('a retry timer that fires in the background waits for wake', () => {+ let active = true+ const { client, sockets, scheduled } = createHarness(() => active)+ client.start()+ sockets[0].open()+ sockets[0].drop()++ active = false+ scheduled[0].callback()+ assert.equal(sockets.length, 1)++ active = true+ client.wake()+ assert.equal(sockets.length, 2)+})++test('wake replaces only a stale connecting socket', () => {+ const { client, sockets, setNow } = createHarness()+ client.start()+ setNow(9_999)+ client.wake()+ assert.equal(sockets.length, 1)++ setNow(10_001)+ client.wake()+ assert.equal(sockets.length, 2)+ assert.equal(sockets[0].readyState, 3)+})++test('stop cancels pending retries and closes without reconnecting', () => {+ const { client, sockets, scheduled } = createHarness()+ client.start()+ sockets[0].open()+ sockets[0].drop()+ client.stop()++ assert.equal(scheduled[0].cancelled, true)+ scheduled[0].callback()+ assert.equal(sockets.length, 1)+})++test('partner composer restores focus after streaming and page return', () => {+ const source = readFileSync(+ path.resolve(process.cwd(), 'components/partners/PartnerComposer.tsx'),+ 'utf8'+ )++ assert.match(source, /restoreFocusAfterSendRef\.current = true/)+ assert.match(source, /if \(disabled \|\| streaming/)+ assert.match(source, /window\.addEventListener\("blur", rememberFocus\)/)+ assert.match(source, /document\.addEventListener\("visibilitychange", restoreFocus\)/)+})