DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix
Bingxi Zhao (Frank)7009f7a98801
diff --git a/deeptutor_cli/chat.py b/deeptutor_cli/chat.pyindex 39a2bedbd..72be55742 100644--- a/deeptutor_cli/chat.py+++ b/deeptutor_cli/chat.py@@ -314,7 +314,7 @@ def _print_refs(state: ChatState) -> None:_print_literal(f" {label:<12}{value}")-def _print_literal(value: str, *, style: str | None = None) -> None:+def _print_literal(value: str, *, style: str = "") -> None:"""Print dynamic CLI text without interpreting it as Rich markup."""console.print(Text(value, style=style), highlight=False)diff --git a/web/app/(workspace)/home/[[...sessionId]]/page.tsx b/web/app/(workspace)/home/[[...sessionId]]/page.tsxindex 74c119ea1..f57a2db27 100644--- a/web/app/(workspace)/home/[[...sessionId]]/page.tsx+++ b/web/app/(workspace)/home/[[...sessionId]]/page.tsx@@ -96,7 +96,7 @@ import {} from "@/lib/research-types";import { listKnowledgeBases } from "@/lib/knowledge-api";import { getSubagentSettings } from "@/lib/subagents-api";-import { listLLMOptions, type LLMOption } from "@/lib/llm-options";+import { useLLMOptions } from "@/hooks/useLLMOptions";import {getEnabledOptionalTools,invalidateEnabledOptionalToolsCache,@@ -381,12 +381,13 @@ export default function ChatPage() {: new URLSearchParams(window.location.search).get("agent");}const agentPreselectDoneRef = useRef(false);- const [llmOptions, setLLMOptions] = useState<LLMOption[]>([]);- const [activeLLMDefault, setActiveLLMDefault] = useState<LLMSelection | null>(- null,- );- const [llmOptionsLoading, setLLMOptionsLoading] = useState(true);- const [llmOptionsError, setLLMOptionsError] = useState(false);+ const {+ options: llmOptions,+ activeDefault: activeLLMDefault,+ loading: llmOptionsLoading,+ error: llmOptionsError,+ refresh: refreshLLMOptions,+ } = useLLMOptions();const [capabilityConfigs, setCapabilityConfigs] =useState<CapabilityPlaygroundConfigMap>({});// User-toggleable tools the user has enabled in /settings/tools. This is@@ -1088,29 +1089,6 @@ export default function ChatPage() {void refreshUserEnabledTools();}, [refreshUserEnabledTools]);- const refreshLLMOptions = useCallback(- async (options?: { force?: boolean }) => {- setLLMOptionsLoading(true);- try {- const payload = await listLLMOptions({ force: options?.force });- setLLMOptions(payload.options);- setActiveLLMDefault(payload.active);- setLLMOptionsError(false);- } catch {- setLLMOptionsError(true);- setLLMOptions([]);- setActiveLLMDefault(null);- } finally {- setLLMOptionsLoading(false);- }- },- [],- );-- useEffect(() => {- void refreshLLMOptions();- }, [refreshLLMOptions]);-useEffect(() => {if (state.llmSelection || !activeLLMDefault) return;setLLMSelection(activeLLMDefault);@@ -1120,7 +1098,7 @@ export default function ChatPage() {if (typeof window === "undefined") return;const refresh = () => {void refreshKnowledgeBases({ force: true });- void refreshLLMOptions({ force: true });+ void refreshLLMOptions({ force: true, background: true });// Picks up toggles the user changed in another tab (/settings/tools).invalidateEnabledOptionalToolsCache();void refreshUserEnabledTools({ force: true });diff --git a/web/components/visualize/VisualizationViewer.tsx b/web/components/visualize/VisualizationViewer.tsxindex fed664ff4..cdef66a0f 100644--- a/web/components/visualize/VisualizationViewer.tsx+++ b/web/components/visualize/VisualizationViewer.tsx@@ -134,7 +134,8 @@ function HtmlRenderer({ html }: { html: string }) {);} else if (data.type === "dt:visualize-height" &&- typeof data.height === "number"+ typeof data.height === "number" &&+ Number.isFinite(data.height)) {setHeight(Math.min(2400, Math.max(240, Math.ceil(data.height) + 8)));}diff --git a/web/hooks/useLLMOptions.ts b/web/hooks/useLLMOptions.tsnew file mode 100644index 000000000..c755110ed--- /dev/null+++ b/web/hooks/useLLMOptions.ts@@ -0,0 +1,66 @@+"use client";++import { useCallback, useEffect, useReducer, useRef, useState } from "react";++import { listLLMOptions } from "@/lib/llm-options";+import {+ INITIAL_LLM_OPTIONS_STATE,+ reduceLLMOptionsState,+} from "@/lib/llm-options-state";+import { createSingleFlight } from "@/lib/single-flight";++interface RefreshOptions {+ force?: boolean;+ /** Keep the last usable catalog visible while synchronizing in the background. */+ background?: boolean;+}++/** Owns model-catalog loading independently from the chat page lifecycle. */+export function useLLMOptions() {+ const [state, dispatch] = useReducer(+ reduceLLMOptionsState,+ INITIAL_LLM_OPTIONS_STATE,+ );+ const latestRequestRef = useRef(0);+ const [loadOptions] = useState(() => createSingleFlight(listLLMOptions));+ const mountedRef = useRef(true);++ useEffect(() => {+ mountedRef.current = true;+ return () => {+ mountedRef.current = false;+ };+ }, []);++ const refresh = useCallback(async (options?: RefreshOptions) => {+ const requestId = ++latestRequestRef.current;+ dispatch({+ type: "refresh-started",+ background: options?.background ?? false,+ });++ // Browser lifecycle events commonly arrive as a focus/pageshow/visibility+ // cluster. Coalesce that cluster here, without changing the global cache's+ // force semantics for mutation-sensitive resources such as knowledge bases.+ try {+ const payload = await loadOptions({ force: options?.force });+ if (!mountedRef.current || requestId !== latestRequestRef.current) return;+ dispatch({ type: "refresh-succeeded", payload });+ } catch {+ if (!mountedRef.current || requestId !== latestRequestRef.current) return;+ dispatch({ type: "refresh-failed" });+ }+ }, [loadOptions]);++ useEffect(() => {+ void refresh();+ }, [refresh]);++ return {+ options: state.options,+ activeDefault: state.activeDefault,+ loading: state.status === "loading",+ error: state.status === "error",+ refresh,+ };+}diff --git a/web/lib/iframe-html.ts b/web/lib/iframe-html.tsindex e798c3863..a6000fc4d 100644--- a/web/lib/iframe-html.ts+++ b/web/lib/iframe-html.ts@@ -88,18 +88,80 @@ export function sanitizeIframeHtml(html: string): string {* via postMessage:* - `window.sendPrompt(text)` → posts a follow-up question; the host prefills* it into the composer (the widget analogue of an SVG node's data-prompt).- * - a ResizeObserver posts the content height so the host can grow the iframe- * to fit instead of clipping at a fixed height.+ * - observers post the current body content height so the host can grow and+ * shrink the iframe instead of retaining an old viewport height.*/-const BRIDGE_SCRIPT =- "<script data-dt-bridge>" +- "(function(){" +- 'window.sendPrompt=function(t){try{parent.postMessage({type:"dt:visualize-prompt",text:String(t||"")},"*")}catch(e){}};' +- 'function rh(){try{var b=document.body,h=Math.max(document.documentElement.scrollHeight,b?b.scrollHeight:0);parent.postMessage({type:"dt:visualize-height",height:h},"*")}catch(e){}}' +- 'if(typeof ResizeObserver!=="undefined"){var ro=new ResizeObserver(rh);document.addEventListener("DOMContentLoaded",function(){ro.observe(document.documentElement);rh()})}' +- 'document.addEventListener("DOMContentLoaded",rh);window.addEventListener("load",rh);' +- "})();" +- "<" ++const BRIDGE_SCRIPT = `<script data-dt-bridge>+(function () {+ window.sendPrompt = function (text) {+ try {+ parent.postMessage({+ type: "dt:visualize-prompt",+ text: String(text || "")+ }, "*");+ } catch (error) {}+ };++ function reportHeight() {+ try {+ var body = document.body;+ var root = document.documentElement;+ // root.scrollHeight is at least the iframe viewport height. Once the host+ // grows that viewport it becomes a historical floor, so body content is+ // the primary measurement and the root is only a defensive fallback.+ var height = body && body.scrollHeight > 0+ ? body.scrollHeight+ : root.scrollHeight;+ if (!height || !isFinite(height)) height = root.scrollHeight || 0;+ parent.postMessage({+ type: "dt:visualize-height",+ height: height+ }, "*");+ } catch (error) {}+ }++ var scheduledFrame = 0;+ function scheduleHeightReport() {+ if (scheduledFrame) return;+ var run = function () {+ scheduledFrame = 0;+ reportHeight();+ };+ scheduledFrame = typeof requestAnimationFrame === "function"+ ? requestAnimationFrame(run)+ : setTimeout(run, 0);+ }++ function startHeightObservers() {+ try {+ var body = document.body;+ if (body && typeof ResizeObserver !== "undefined") {+ var resizeObserver = new ResizeObserver(scheduleHeightReport);+ resizeObserver.observe(body);+ }+ if (body && typeof MutationObserver !== "undefined") {+ var mutationObserver = new MutationObserver(scheduleHeightReport);+ mutationObserver.observe(body, {+ attributes: true,+ characterData: true,+ childList: true,+ subtree: true+ });+ }+ scheduleHeightReport();+ } catch (error) {+ reportHeight();+ }+ }++ if (document.readyState === "loading") {+ document.addEventListener("DOMContentLoaded", startHeightObservers, { once: true });+ } else {+ startHeightObservers();+ }+ window.addEventListener("load", scheduleHeightReport);+})();+<` +"/script>";function injectBridge(html: string): string {diff --git a/web/lib/llm-options-state.ts b/web/lib/llm-options-state.tsnew file mode 100644index 000000000..6bbcac728--- /dev/null+++ b/web/lib/llm-options-state.ts@@ -0,0 +1,49 @@+import type { LLMOption, LLMOptionsResponse } from "@/lib/llm-options";+import type { LLMSelection } from "@/lib/unified-ws";++export type LLMOptionsStatus = "loading" | "ready" | "error";++export interface LLMOptionsState {+ options: LLMOption[];+ activeDefault: LLMSelection | null;+ status: LLMOptionsStatus;+}++export type LLMOptionsAction =+ | { type: "refresh-started"; background: boolean }+ | { type: "refresh-succeeded"; payload: LLMOptionsResponse }+ | { type: "refresh-failed" };++export const INITIAL_LLM_OPTIONS_STATE: LLMOptionsState = {+ options: [],+ activeDefault: null,+ status: "loading",+};++/**+ * State transitions for the model selector's stale-while-revalidate behavior.+ *+ * A page-return refresh is a catalog synchronization, not a model startup. It+ * therefore keeps the last usable catalog visible and only replaces it after a+ * successful response. Initial loading still has an explicit loading/error+ * state because there is no usable catalog to fall back to yet.+ */+export function reduceLLMOptionsState(+ state: LLMOptionsState,+ action: LLMOptionsAction,+): LLMOptionsState {+ switch (action.type) {+ case "refresh-started":+ return action.background ? state : { ...state, status: "loading" };+ case "refresh-succeeded":+ return {+ options: action.payload.options,+ activeDefault: action.payload.active,+ status: "ready",+ };+ case "refresh-failed":+ return state.options.length > 0+ ? { ...state, status: "ready" }+ : { ...state, status: "error" };+ }+}diff --git a/web/lib/single-flight.ts b/web/lib/single-flight.tsnew file mode 100644index 000000000..8b4c16d58--- /dev/null+++ b/web/lib/single-flight.ts@@ -0,0 +1,22 @@+/**+ * Wrap an async loader so concurrent calls share one in-flight request.+ * Arguments from later callers are intentionally ignored until that request+ * settles; the next call starts a fresh request with its own arguments.+ */+export function createSingleFlight<Args extends unknown[], Result>(+ loader: (...args: Args) => Promise<Result>,+): (...args: Args) => Promise<Result> {+ let inFlight: Promise<Result> | null = null;++ return (...args: Args) => {+ if (inFlight) return inFlight;++ const request = loader(...args);+ inFlight = request;+ const clear = () => {+ if (inFlight === request) inFlight = null;+ };+ void request.then(clear, clear);+ return request;+ };+}diff --git a/web/tests/iframe-html.test.ts b/web/tests/iframe-html.test.tsnew file mode 100644index 000000000..ec94a1c0b--- /dev/null+++ b/web/tests/iframe-html.test.ts@@ -0,0 +1,34 @@+import test from "node:test";+import assert from "node:assert/strict";++import { prepareIframeHtml } from "../lib/iframe-html";++function bridgeSource(): string {+ const prepared = prepareIframeHtml(+ "<!doctype html><html><head></head><body><main>content</main></body></html>",+ );+ const match = prepared.match(/<script data-dt-bridge>([\s\S]*?)<\/script>/);+ assert.ok(match, "prepared iframe HTML should contain the host bridge");+ return match[1];+}++test("iframe bridge measures current body content instead of historical viewport height", () => {+ const source = bridgeSource();++ assert.match(source, /body\.scrollHeight > 0/);+ assert.doesNotMatch(+ source,+ /Math\.max\(document\.documentElement\.scrollHeight/,+ );+});++test("iframe bridge observes layout and tab-content changes with coalescing", () => {+ const source = bridgeSource();++ assert.match(source, /new ResizeObserver\(scheduleHeightReport\)/);+ assert.match(source, /new MutationObserver\(scheduleHeightReport\)/);+ assert.match(source, /characterData: true/);+ assert.match(source, /childList: true/);+ assert.match(source, /subtree: true/);+ assert.match(source, /requestAnimationFrame\(run\)/);+});diff --git a/web/tests/llm-options-state.test.ts b/web/tests/llm-options-state.test.tsnew file mode 100644index 000000000..0a197e701--- /dev/null+++ b/web/tests/llm-options-state.test.ts@@ -0,0 +1,62 @@+import test from "node:test";+import assert from "node:assert/strict";++import {+ INITIAL_LLM_OPTIONS_STATE,+ reduceLLMOptionsState,+ type LLMOptionsState,+} from "../lib/llm-options-state";+import type { LLMOptionsResponse } from "../lib/llm-options";++const CATALOG: LLMOptionsResponse = {+ active: { profile_id: "profile-1", model_id: "model-1" },+ options: [+ {+ profile_id: "profile-1",+ model_id: "model-1",+ profile_name: "Primary",+ model_name: "Tutor",+ model: "tutor-v1",+ provider: "openai",+ is_active_default: true,+ },+ ],+};++function readyState(): LLMOptionsState {+ return reduceLLMOptionsState(INITIAL_LLM_OPTIONS_STATE, {+ type: "refresh-succeeded",+ payload: CATALOG,+ });+}++test("background model refresh keeps the current catalog visible", () => {+ const ready = readyState();+ const refreshing = reduceLLMOptionsState(ready, {+ type: "refresh-started",+ background: true,+ });++ assert.strictEqual(refreshing, ready);+ assert.equal(refreshing.status, "ready");+ assert.deepEqual(refreshing.options, CATALOG.options);+});++test("failed background model refresh preserves the last usable catalog", () => {+ const failed = reduceLLMOptionsState(readyState(), {+ type: "refresh-failed",+ });++ assert.equal(failed.status, "ready");+ assert.deepEqual(failed.options, CATALOG.options);+ assert.deepEqual(failed.activeDefault, CATALOG.active);+});++test("initial model refresh failure surfaces an error", () => {+ const failed = reduceLLMOptionsState(INITIAL_LLM_OPTIONS_STATE, {+ type: "refresh-failed",+ });++ assert.equal(failed.status, "error");+ assert.deepEqual(failed.options, []);+});diff --git a/web/tests/single-flight.test.ts b/web/tests/single-flight.test.tsnew file mode 100644index 000000000..68561908c--- /dev/null+++ b/web/tests/single-flight.test.ts@@ -0,0 +1,35 @@+import test from "node:test";+import assert from "node:assert/strict";++import { createSingleFlight } from "../lib/single-flight";++test("single-flight coalesces concurrent calls", async () => {+ let resolveLoader!: (value: string) => void;+ const calls: string[] = [];+ const load = createSingleFlight((argument: string) => {+ calls.push(argument);+ return new Promise<string>((resolve) => {+ resolveLoader = resolve;+ });+ });++ const first = load("focus");+ const second = load("pageshow");++ assert.strictEqual(second, first);+ assert.deepEqual(calls, ["focus"]);+ resolveLoader("models");+ assert.deepEqual(await Promise.all([first, second]), ["models", "models"]);+});++test("single-flight starts a fresh call after success or failure", async () => {+ let calls = 0;+ const load = createSingleFlight(async () => {+ calls += 1;+ if (calls === 1) throw new Error("temporary failure");+ return calls;+ });++ await assert.rejects(load(), /temporary failure/);+ assert.equal(await load(), 2);+});