refactor(chat): honest indeterminate session-loading overlay

Rework of the #578 loading overlay:
- Replace the simulated rAF percentage bar (which climbed to a fake 99%
  over ~24s, unrelated to real load progress) with an honest indeterminate
  spinner + 'Loading conversation…' message and an 8s 'Still loading…' hint.
- Collapse the null/loading/complete state machine to a single boolean and
  drop the artificial 400ms completion delay, so the conversation appears
  the moment the fetch resolves.
- Fix a stray ')' in the cancel button's className that voided its hover
  color, and remove the now-redundant width-transition/rAF conflict.
- Drop the dead 'server is taking too long' locale key (no timeout path
  uses it).

The AbortSignal plumbing (getSession/loadSession + cancel button) and the
Strict-Mode-safe initial-load ref are kept as-is.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Bingxi Zhao (Frank)
2026-06-23 21:04:33 +08:00
parent 37283e9124
commit 98805b46db
4 changed files with 27 additions and 103 deletions

View File

@@ -525,9 +525,7 @@ export default function ChatPage() {
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 [sessionLoading, setSessionLoading] = useState(false);
const loadAbortRef = useRef<AbortController | null>(null);
// Bridge ref: ``ChatComposer`` writes a prefill function into this on
// mount; ``ChatMessageList`` reads it via ``handlePrefillComposer`` so an
@@ -859,36 +857,36 @@ export default function ChatPage() {
router.replace("/home", { scroll: false });
}, [router]);
/** Abort in-flight load + navigates home. */
/** Abort in-flight load + navigate home. */
const cancelSessionLoad = useCallback(() => {
loadAbortRef.current?.abort();
loadAbortRef.current = null;
setSessionLoadingStage(null);
setSessionLoading(false);
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).
* otherwise the loading overlay stays until the API responds (no timeout).
*/
const startSessionLoad = useCallback(
(sid: string) => {
loadAbortRef.current?.abort();
const ctrl = new AbortController();
loadAbortRef.current = ctrl;
setSessionLoadingStage("loading");
setSessionLoading(true);
void loadSession(sid, ctrl.signal)
.then(() => {
if (!ctrl.signal.aborted) {
loadAbortRef.current = null;
setSessionLoadingStage("complete");
setSessionLoading(false);
}
})
.catch(() => {
if (!ctrl.signal.aborted) {
loadAbortRef.current = null;
setSessionLoadingStage(null);
setSessionLoading(false);
navigateToHome();
}
});
@@ -900,7 +898,7 @@ export default function ChatPage() {
// 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
// deliberately OMITTED from cleanup — cancelSessionLoad handles
// user-initiated cancellation.
useEffect(() => {
if (initialLoadRef.current) return;
@@ -915,14 +913,6 @@ export default function ChatPage() {
};
}, []); // 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(() => {
@@ -933,13 +923,13 @@ export default function ChatPage() {
loadAbortRef.current = null;
if (sessionIdParam) {
if (sessionIdParam === state.sessionId) {
setSessionLoadingStage(null);
setSessionLoading(false);
return;
}
startSessionLoad(sessionIdParam);
} else {
newSession();
setSessionLoadingStage(null);
setSessionLoading(false);
}
}, [sessionIdParam, startSessionLoad, newSession, state.sessionId]);
@@ -1841,11 +1831,8 @@ 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">
{sessionLoadingStage ? (
<SessionLoadingView
stage={sessionLoadingStage}
onCancel={cancelSessionLoad}
/>
{sessionLoading ? (
<SessionLoadingView 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">

View File

@@ -1,99 +1,51 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { useEffect, 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.
* Indeterminate loading overlay shown while a chat session is fetched from
* the server (e.g. when opening an entry from chat history). It replaces the
* misleading welcome screen during the load and lets the user cancel.
*
* The indicator is deliberately indeterminate: a session fetch reports no
* real progress, so a spinner is honest where a percentage bar would be
* fabricated. After a while we surface a reassurance hint.
*/
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;
// After this long with no response, reassure the user it is still working.
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]);
const timer = setTimeout(() => setShowHint(true), STILL_LOADING_AFTER_MS);
return () => clearTimeout(timer);
}, []);
return (
<div className="relative flex h-full flex-col items-center justify-center gap-5 px-6">
<div className="animate-fade-in relative flex h-full flex-col items-center justify-center gap-4 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)])"
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 */}
{/* Logo + spinner */}
<div className="flex items-center gap-3">
<img
src="/logo_black.png"
@@ -111,19 +63,6 @@ export default function SessionLoadingView({
{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)]">

View File

@@ -139,7 +139,6 @@
"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",

View File

@@ -139,7 +139,6 @@
"Loading": "加载中...",
"Loading conversation": "加载对话中…",
"Still loading…": "仍在加载中…",
"The server is taking too long to respond. Please check your connection and try again.": "服务器响应超时,请检查网络连接后重试。",
"Save": "保存",
"Cancel": "取消",
"Error": "错误",