Skip to content

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

feat: 聊天历史加载动画支持

LunaireReveriece188919d9a9
diff --git a/web/app/(workspace)/home/[[...sessionId]]/page.tsx b/web/app/(workspace)/home/[[...sessionId]]/page.tsx
index 389787b44..cbe33d575 100644
--- a/web/app/(workspace)/home/[[...sessionId]]/page.tsx
+++ b/web/app/(workspace)/home/[[...sessionId]]/page.tsx
@@ -35,6 +35,7 @@ import type { SelectedHistorySession } from "@/components/chat/HistorySessionPic
import type { SelectedQuestionEntry } from "@/components/chat/QuestionBankPicker";
import ChatComposer from "@/components/chat/home/ChatComposer";
import { ChatMessageList } from "@/components/chat/home/ChatMessages";
+import SessionLoadingView from "@/components/chat/home/SessionLoadingView";
// Imported eagerly so the drawer shell is always mounted off-screen —
// clicking a chip becomes a single CSS class flip, no chunk fetch + double
// render. The heavy renderers inside still load lazily.
@@ -515,6 +516,12 @@ export default function ChatPage() {
const spaceMenuRef = useRef<HTMLDivElement>(null);
const spaceBtnRef = useRef<HTMLButtonElement>(null);
const initialLoadRef = useRef(false);
+ // Session-loading overlay: shown while navigating from chat-history →
+ // session detail. Holds an AbortController so the user can cancel.
+ const [sessionLoadingStage, setSessionLoadingStage] = useState<
+ null | "loading" | "complete"
+ >(null);
+ const loadAbortRef = useRef<AbortController | null>(null);
// Bridge ref: ``ChatComposer`` writes a prefill function into this on
// mount; ``ChatMessageList`` reads it via ``handlePrefillComposer`` so an
// ``AskUserOptions`` chip click can drop text into the composer textarea.
@@ -840,32 +847,94 @@ export default function ChatPage() {
}
}, []);
/* ---- URL-driven session loading ---- */
+
+ const navigateToHome = useCallback(() => {
+ router.replace("/home", { scroll: false });
+ }, [router]);
+
+ /** Abort in-flight load + navigates home. */
+ const cancelSessionLoad = useCallback(() => {
+ loadAbortRef.current?.abort();
+ loadAbortRef.current = null;
+ setSessionLoadingStage(null);
+ navigateToHome();
+ }, [navigateToHome]);
+
+ /**
+ * Shared helper: kick off a load. The user can cancel via the ✕ button;
+ * otherwise the loading screen stays until the API responds (no timeout).
+ */
+ const startSessionLoad = useCallback(
+ (sid: string) => {
+ loadAbortRef.current?.abort();
+ const ctrl = new AbortController();
+ loadAbortRef.current = ctrl;
+ setSessionLoadingStage("loading");
+
+ void loadSession(sid, ctrl.signal)
+ .then(() => {
+ if (!ctrl.signal.aborted) {
+ loadAbortRef.current = null;
+ setSessionLoadingStage("complete");
+ }
+ })
+ .catch(() => {
+ if (!ctrl.signal.aborted) {
+ loadAbortRef.current = null;
+ setSessionLoadingStage(null);
+ navigateToHome();
+ }
+ });
+ },
+ [loadSession, navigateToHome],
+ );
+
+ // Initial mount — load the session from the URL.
+ // Uses a ref-based flag so Strict Mode double-mount doesn't break the flow:
+ // when React tears down + re-mounts in dev, we reset initialLoadRef in
+ // cleanup so the second mount restarts the load cleanly. The abort is
+ // deliberately OMITTED from cleanup — cancelSessionLoad / timeout handle
+ // user-initiated cancellation.
useEffect(() => {
if (initialLoadRef.current) return;
initialLoadRef.current = true;
if (sessionIdParam) {
- void loadSession(sessionIdParam).catch(() => {
- router.replace("/home", { scroll: false });
- });
+ startSessionLoad(sessionIdParam);
} else {
newSession();
}
+ return () => {
+ initialLoadRef.current = false;
+ };
}, []); // eslint-disable-line react-hooks/exhaustive-deps
+ // Clear "complete" after a short fade
+ useEffect(() => {
+ if (sessionLoadingStage === "complete") {
+ const t = setTimeout(() => setSessionLoadingStage(null), 400);
+ return () => clearTimeout(t);
+ }
+ }, [sessionLoadingStage]);
+
// When URL param changes (sidebar navigation), load the corresponding session
const prevSessionIdParam = useRef(sessionIdParam);
useEffect(() => {
if (sessionIdParam === prevSessionIdParam.current) return;
prevSessionIdParam.current = sessionIdParam;
+ // Abort any in-flight session load from the previous param
+ loadAbortRef.current?.abort();
+ loadAbortRef.current = null;
if (sessionIdParam) {
- if (sessionIdParam === state.sessionId) return;
- void loadSession(sessionIdParam).catch(() => {
- router.replace("/home", { scroll: false });
- });
+ if (sessionIdParam === state.sessionId) {
+ setSessionLoadingStage(null);
+ return;
+ }
+ startSessionLoad(sessionIdParam);
} else {
newSession();
+ setSessionLoadingStage(null);
}
- }, [sessionIdParam, loadSession, newSession, router, state.sessionId]);
+ }, [sessionIdParam, startSessionLoad, newSession, state.sessionId]);
// When a new session_id is assigned by the server, update the URL
useEffect(() => {
@@ -1705,7 +1774,12 @@ export default function ChatPage() {
</div>
</div>
<div className="mx-auto flex w-full max-w-[960px] flex-1 min-h-0 flex-col overflow-hidden px-6">
- {!hasMessages ? (
+ {sessionLoadingStage ? (
+ <SessionLoadingView
+ stage={sessionLoadingStage}
+ onCancel={cancelSessionLoad}
+ />
+ ) : !hasMessages ? (
<div className="flex flex-1 min-h-0 flex-col items-center justify-end pb-14 animate-fade-in">
<div className="flex items-center justify-center gap-4">
<img
diff --git a/web/components/chat/home/SessionLoadingView.tsx b/web/components/chat/home/SessionLoadingView.tsx
new file mode 100644
index 000000000..b2497e658
--- /dev/null
+++ b/web/components/chat/home/SessionLoadingView.tsx
@@ -0,0 +1,135 @@
+"use client";
+
+import { useEffect, useRef, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { Loader2, X } from "lucide-react";
+
+/**
+ * Loading overlay shown while a chat session is being fetched from the
+ * server. Progress is cosmetic but asymptotically approaches 99 % so
+ * the user sees continuous activity. Completion jumps to 100 % and fades.
+ */
+interface SessionLoadingViewProps {
+ stage: "loading" | "complete";
+ onCancel?: () => void;
+}
+
+// ---- timing constants ----
+const FAST_MS = 600; // 0 → 45 % (quick)
+const SLOW_MS = 4000; // 45 → 90 % (eased)
+const TAIL_MS = 20_000; // 90 → 99 % (asymptotic)
+const FAST_PEAK = 45;
+const SLOW_PEAK = 90;
+const TAIL_ASYM = 99;
+
+const STILL_LOADING_AFTER_MS = 8000;
+
+export default function SessionLoadingView({
+ stage,
+ onCancel,
+}: SessionLoadingViewProps) {
+ const { t } = useTranslation();
+ const [progress, setProgress] = useState(0);
+ const [showHint, setShowHint] = useState(false);
+ const startRef = useRef<number>(0);
+ const rafRef = useRef<number>(0);
+ const hintTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+
+ useEffect(() => {
+ if (stage === "complete") {
+ setProgress(100);
+ setShowHint(false);
+ if (hintTimerRef.current) clearTimeout(hintTimerRef.current);
+ return;
+ }
+
+ // Reset
+ startRef.current = Date.now();
+ setProgress(0);
+ setShowHint(false);
+ if (hintTimerRef.current) clearTimeout(hintTimerRef.current);
+ hintTimerRef.current = setTimeout(
+ () => setShowHint(true),
+ STILL_LOADING_AFTER_MS,
+ );
+
+ const tick = () => {
+ const elapsed = Date.now() - startRef.current;
+ let value: number;
+
+ if (elapsed <= FAST_MS) {
+ value = (elapsed / FAST_MS) * FAST_PEAK;
+ } else if (elapsed <= FAST_MS + SLOW_MS) {
+ const t2 = (elapsed - FAST_MS) / SLOW_MS; // 0…1
+ value =
+ FAST_PEAK + (SLOW_PEAK - FAST_PEAK) * (1 - Math.pow(1 - t2, 2));
+ } else {
+ const t3 = (elapsed - FAST_MS - SLOW_MS) / TAIL_MS; // 0 → 1
+ value = SLOW_PEAK + (TAIL_ASYM - SLOW_PEAK) * (1 - 1 / (1 + 3 * t3));
+ }
+
+ setProgress(Math.min(Math.round(value), 99));
+ rafRef.current = requestAnimationFrame(tick);
+ };
+ rafRef.current = requestAnimationFrame(tick);
+
+ return () => {
+ cancelAnimationFrame(rafRef.current);
+ if (hintTimerRef.current) clearTimeout(hintTimerRef.current);
+ };
+ }, [stage]);
+
+ return (
+ <div className="relative flex h-full flex-col items-center justify-center gap-5 px-6">
+ {/* Cancel button — top-right */}
+ {onCancel ? (
+ <button
+ type="button"
+ aria-label={t("Cancel")}
+ onClick={onCancel}
+ className="absolute end-3 top-3 inline-flex h-8 w-8 items-center justify-center rounded-lg text-[var(--muted-foreground)] transition hover:bg-[var(--muted)] hover:text-[var(--foreground)])"
+ >
+ <X className="h-4 w-4" />
+ </button>
+ ) : null}
+
+ {/* Logo */}
+ <div className="flex items-center gap-3">
+ <img
+ src="/logo_black.png"
+ alt="DeepTutor"
+ width={32}
+ height={32}
+ className="h-8 w-8 select-none"
+ draggable={false}
+ />
+ <Loader2 className="h-5 w-5 animate-spin text-[var(--primary)]" />
+ </div>
+
+ {/* Primary message */}
+ <p className="text-sm font-medium text-[var(--foreground)]">
+ {t("Loading conversation")}
+ </p>
+
+ {/* Progress bar */}
+ <div className="flex w-56 items-center gap-3">
+ <div className="h-1.5 flex-1 overflow-hidden rounded-full bg-[var(--muted)]">
+ <div
+ className="h-full rounded-full bg-[var(--primary)] transition-[width] duration-300 ease-out"
+ style={{ width: `${progress}%` }}
+ />
+ </div>
+ <span className="w-8 text-right text-[11px] tabular-nums text-[var(--muted-foreground)]">
+ {progress}%
+ </span>
+ </div>
+
+ {/* Slow-load hint */}
+ {showHint ? (
+ <p className="animate-fade-in text-[12px] text-[var(--muted-foreground)]">
+ {t("Still loading…")}
+ </p>
+ ) : null}
+ </div>
+ );
+}
diff --git a/web/context/UnifiedChatContext.tsx b/web/context/UnifiedChatContext.tsx
index 27f69bfee..acd48eb20 100644
--- a/web/context/UnifiedChatContext.tsx
+++ b/web/context/UnifiedChatContext.tsx
@@ -766,7 +766,7 @@ interface ChatContextValue {
switchBranch: (parentMessageId: number | null, childId: number) => void;
renameSessionTitle: (title: string) => Promise<void>;
newSession: () => void;
- loadSession: (sessionId: string) => Promise<void>;
+ loadSession: (sessionId: string, signal?: AbortSignal) => Promise<void>;
selectedSessionId: string | null;
sessionStatuses: Record<string, SessionStatusSnapshot>;
sidebarRefreshToken: number;
@@ -1212,8 +1212,8 @@ export function UnifiedChatProvider({
);
const loadSession = useCallback(
- async (sessionId: string) => {
- const session = await getSession(sessionId);
+ async (sessionId: string, signal?: AbortSignal) => {
+ const session = await getSession(sessionId, signal);
const activeTurn = Array.isArray(session.active_turns)
? session.active_turns[0]
: undefined;
diff --git a/web/lib/session-api.ts b/web/lib/session-api.ts
index ca783b8c3..dd464f82a 100644
--- a/web/lib/session-api.ts
+++ b/web/lib/session-api.ts
@@ -156,9 +156,13 @@ export async function listSessions(
);
}
-export async function getSession(sessionId: string): Promise<SessionDetail> {
+export async function getSession(
+ sessionId: string,
+ signal?: AbortSignal,
+): Promise<SessionDetail> {
const response = await apiFetch(apiUrl(`/api/v1/sessions/${sessionId}`), {
cache: "no-store",
+ signal,
});
return expectJson<SessionDetail>(response);
}
diff --git a/web/locales/en/app.json b/web/locales/en/app.json
index cce9264c6..6f7c3a276 100644
--- a/web/locales/en/app.json
+++ b/web/locales/en/app.json
@@ -137,6 +137,9 @@
"Notebooks": "Notebooks",
"Settings": "Settings",
"Loading": "Loading...",
+ "Loading conversation": "Loading conversation…",
+ "Still loading…": "Still loading…",
+ "The server is taking too long to respond. Please check your connection and try again.": "The server is taking too long to respond. Please check your connection and try again.",
"Save": "Save",
"Cancel": "Cancel",
"Error": "Error",
diff --git a/web/locales/zh/app.json b/web/locales/zh/app.json
index 65814a06d..58e08a827 100644
--- a/web/locales/zh/app.json
+++ b/web/locales/zh/app.json
@@ -137,6 +137,9 @@
"Notebooks": "笔记本",
"Settings": "设置",
"Loading": "加载中...",
+ "Loading conversation": "加载对话中…",
+ "Still loading…": "仍在加载中…",
+ "The server is taking too long to respond. Please check your connection and try again.": "服务器响应超时,请检查网络连接后重试。",
"Save": "保存",
"Cancel": "取消",
"Error": "错误",