Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

fix: leakage repair

Bingxi Zhao (Frank)538422493288
diff --git a/web/app/(workspace)/playground/page.tsx b/web/app/(workspace)/playground/page.tsx
index c20adc2ad..1e9aabf74 100644
--- a/web/app/(workspace)/playground/page.tsx
+++ b/web/app/(workspace)/playground/page.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useEffect, useMemo, useState } from "react";
+import { useEffect, useMemo, useRef, useState } from "react";
import {
BrainCircuit,
ChevronDown,
@@ -292,6 +292,7 @@ function ToolExecutor({ tool, knowledgeBases }: { tool: ToolInfo; knowledgeBases
const [result, setResult] = useState<ExecResult | null>(null);
const [error, setError] = useState<string | null>(null);
const [processLogs, setProcessLogs] = useState<string[]>([]);
+ const abortRef = useRef<AbortController | null>(null);
useEffect(() => {
setValues({});
@@ -300,12 +301,17 @@ function ToolExecutor({ tool, knowledgeBases }: { tool: ToolInfo; knowledgeBases
setProcessLogs([]);
}, [tool.name]);
+ useEffect(() => () => { abortRef.current?.abort(); }, []);
+
const setParam = (name: string, val: string) => setValues((p) => ({ ...p, [name]: val }));
const queryParam = params.find((p) => QUERY_PARAM_NAMES.has(p.name));
const otherParams = params.filter((p) => !QUERY_PARAM_NAMES.has(p.name));
const execute = async () => {
+ abortRef.current?.abort();
+ const controller = new AbortController();
+ abortRef.current = controller;
setExecuting(true);
setResult(null);
setError(null);
@@ -325,6 +331,7 @@ function ToolExecutor({ tool, knowledgeBases }: { tool: ToolInfo; knowledgeBases
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ params: coerced }),
+ signal: controller.signal,
});
if (!res.ok) {
@@ -372,9 +379,10 @@ function ToolExecutor({ tool, knowledgeBases }: { tool: ToolInfo; knowledgeBases
}
}
} catch (err: unknown) {
+ if (controller.signal.aborted) return;
setError(err instanceof Error ? err.message : String(err));
} finally {
- setExecuting(false);
+ if (!controller.signal.aborted) setExecuting(false);
}
};
@@ -615,6 +623,9 @@ function DeepQuestionTester({
const [messages, setMessages] = useState<TesterMessage[]>([]);
const [streaming, setStreaming] = useState(false);
const [uploadedPdf, setUploadedPdf] = useState<File | null>(null);
+ const abortRef = useRef<AbortController | null>(null);
+
+ useEffect(() => () => { abortRef.current?.abort(); }, []);
const updateLastAssistant = (updater: (msg: TesterMessage) => TesterMessage) => {
setMessages((prev) => {
@@ -651,6 +662,10 @@ function DeepQuestionTester({
const run = async () => {
if (!canRun || streaming) return;
+ abortRef.current?.abort();
+ const controller = new AbortController();
+ abortRef.current = controller;
+
const userContent =
config.mode === "custom"
? config.topic.trim()
@@ -698,6 +713,7 @@ function DeepQuestionTester({
config: requestConfig,
attachments,
}),
+ signal: controller.signal,
},
);
@@ -775,12 +791,13 @@ function DeepQuestionTester({
}
}
} catch (err: unknown) {
+ if (controller.signal.aborted) return;
updateLastAssistant((last) => ({
...last,
error: err instanceof Error ? err.message : String(err),
}));
} finally {
- setStreaming(false);
+ if (!controller.signal.aborted) setStreaming(false);
}
};
@@ -1003,6 +1020,9 @@ function DeepResearchTester({
const [messages, setMessages] = useState<TesterMessage[]>([]);
const [streaming, setStreaming] = useState(false);
const validation = useMemo(() => validateResearchConfig(config), [config]);
+ const abortRef = useRef<AbortController | null>(null);
+
+ useEffect(() => () => { abortRef.current?.abort(); }, []);
const updateLastAssistant = (updater: (msg: TesterMessage) => TesterMessage) => {
setMessages((prev) => {
@@ -1017,6 +1037,11 @@ function DeepResearchTester({
const run = async () => {
const content = input.trim();
if (!content || streaming || !validation.valid) return;
+
+ abortRef.current?.abort();
+ const controller = new AbortController();
+ abortRef.current = controller;
+
setMessages((prev) => [
...prev,
{ role: "user", content },
@@ -1037,6 +1062,7 @@ function DeepResearchTester({
language: i18n.language,
config: buildResearchWSConfig(config),
}),
+ signal: controller.signal,
},
);
@@ -1114,12 +1140,13 @@ function DeepResearchTester({
}
}
} catch (err: unknown) {
+ if (controller.signal.aborted) return;
updateLastAssistant((last) => ({
...last,
error: err instanceof Error ? err.message : String(err),
}));
} finally {
- setStreaming(false);
+ if (!controller.signal.aborted) setStreaming(false);
}
};
@@ -1241,6 +1268,9 @@ function CapabilityTester({
const [input, setInput] = useState("");
const [messages, setMessages] = useState<TesterMessage[]>([]);
const [streaming, setStreaming] = useState(false);
+ const abortRef = useRef<AbortController | null>(null);
+
+ useEffect(() => () => { abortRef.current?.abort(); }, []);
const updateLastAssistant = (updater: (msg: TesterMessage) => TesterMessage) => {
setMessages((prev) => {
@@ -1255,6 +1285,11 @@ function CapabilityTester({
const send = async () => {
const content = input.trim();
if (!content || streaming) return;
+
+ abortRef.current?.abort();
+ const controller = new AbortController();
+ abortRef.current = controller;
+
setMessages((prev) => [
...prev,
{ role: "user", content },
@@ -1275,6 +1310,7 @@ function CapabilityTester({
knowledge_bases: enabledTools.includes("rag") && knowledgeBase ? [knowledgeBase] : [],
language: i18n.language,
}),
+ signal: controller.signal,
},
);
@@ -1352,12 +1388,13 @@ function CapabilityTester({
}
}
} catch (err: unknown) {
+ if (controller.signal.aborted) return;
updateLastAssistant((last) => ({
...last,
error: err instanceof Error ? err.message : String(err),
}));
} finally {
- setStreaming(false);
+ if (!controller.signal.aborted) setStreaming(false);
}
};
diff --git a/web/components/notebook/SaveToNotebookModal.tsx b/web/components/notebook/SaveToNotebookModal.tsx
index 924ce616b..7755d494a 100644
--- a/web/components/notebook/SaveToNotebookModal.tsx
+++ b/web/components/notebook/SaveToNotebookModal.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useEffect, useMemo, useState } from "react";
+import { useEffect, useMemo, useRef, useState } from "react";
import { Loader2, X } from "lucide-react";
import { useTranslation } from "react-i18next";
import { apiUrl } from "@/lib/api";
@@ -70,9 +70,13 @@ export default function SaveToNotebookModal({
const [summaryPreview, setSummaryPreview] = useState("");
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState("");
+ const abortRef = useRef<AbortController | null>(null);
useEffect(() => {
- if (!open) return;
+ if (!open) {
+ abortRef.current?.abort();
+ return;
+ }
setTitle(payload?.title || "");
setSummaryPreview("");
setError("");
@@ -105,6 +109,9 @@ export default function SaveToNotebookModal({
const handleSave = async () => {
if (!payload || !canSave) return;
+ abortRef.current?.abort();
+ const controller = new AbortController();
+ abortRef.current = controller;
setIsLoading(true);
setError("");
setSummaryPreview("");
@@ -122,6 +129,7 @@ export default function SaveToNotebookModal({
metadata: payload.metadata || {},
kb_name: payload.kbName || null,
}),
+ signal: controller.signal,
});
if (!response.ok || !response.body) {
@@ -165,6 +173,7 @@ export default function SaveToNotebookModal({
throw new Error("Notebook save stream ended unexpectedly.");
} catch (err) {
+ if (controller.signal.aborted) return;
setError(err instanceof Error ? err.message : "Failed to save to notebook.");
setIsLoading(false);
}
diff --git a/web/context/UnifiedChatContext.tsx b/web/context/UnifiedChatContext.tsx
index 06d1ef3db..c2d2bd0fa 100644
--- a/web/context/UnifiedChatContext.tsx
+++ b/web/context/UnifiedChatContext.tsx
@@ -351,15 +351,19 @@ function reducer(state: ProviderState, action: Action): ProviderState {
},
};
}
- case "NEW_SESSION":
- return {
- ...state,
- selectedKey: action.key,
- sessions: {
- ...state.sessions,
- [action.key]: createSessionEntry(action.key),
- },
- };
+ case "NEW_SESSION": {
+ const MAX_CACHED_SESSIONS = 20;
+ let nextSessions = { ...state.sessions, [action.key]: createSessionEntry(action.key) };
+ const keys = Object.keys(nextSessions);
+ if (keys.length > MAX_CACHED_SESSIONS) {
+ const evictable = keys
+ .filter((k) => k !== action.key && nextSessions[k].status !== "running")
+ .sort((a, b) => nextSessions[a].updatedAt - nextSessions[b].updatedAt);
+ const toRemove = evictable.slice(0, keys.length - MAX_CACHED_SESSIONS);
+ for (const k of toRemove) delete nextSessions[k];
+ }
+ return { ...state, selectedKey: action.key, sessions: nextSessions };
+ }
default:
return state;
}
@@ -409,11 +413,22 @@ export function UnifiedChatProvider({ children }: { children: React.ReactNode })
>
>(new Map());
const draftCounterRef = useRef(0);
+ const retryTimersRef = useRef<Set<ReturnType<typeof setTimeout>>>(new Set());
useEffect(() => {
stateRef.current = state;
}, [state]);
+ useEffect(
+ () => () => {
+ runnersRef.current.forEach(({ client }) => client.disconnect());
+ runnersRef.current.clear();
+ retryTimersRef.current.forEach((id) => clearTimeout(id));
+ retryTimersRef.current.clear();
+ },
+ [],
+ );
+
const makeDraftKey = useCallback(() => {
draftCounterRef.current += 1;
return `draft_${Date.now()}_${draftCounterRef.current}`;
@@ -536,7 +551,11 @@ export function UnifiedChatProvider({ children }: { children: React.ReactNode })
dispatch({ type: "STREAM_END", key, status: "failed" });
return;
}
- window.setTimeout(() => dispatchToRunner(key, msg, attempt + 1), 200);
+ const timerId = window.setTimeout(() => {
+ retryTimersRef.current.delete(timerId);
+ dispatchToRunner(key, msg, attempt + 1);
+ }, 200);
+ retryTimersRef.current.add(timerId);
return;
}
runner.client.send(msg);
diff --git a/web/hooks/useChatAutoScroll.ts b/web/hooks/useChatAutoScroll.ts
index e2193e9e5..63e548453 100644
--- a/web/hooks/useChatAutoScroll.ts
+++ b/web/hooks/useChatAutoScroll.ts
@@ -51,7 +51,12 @@ export function useChatAutoScroll({
lastScrollTimeRef.current = performance.now();
}
}, THROTTLE_MS - elapsed);
- return;
+ return () => {
+ if (pendingRafRef.current) {
+ clearTimeout(pendingRafRef.current);
+ pendingRafRef.current = 0;
+ }
+ };
}
const raf = window.requestAnimationFrame(() => {