Skip to content

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

feat(web): unify turn lifecycle feedback

Bingxi Zhao (Frank)68bb0d108df7
diff --git a/web/components/reading/workspace/ReadingCompanion.tsx b/web/components/reading/workspace/ReadingCompanion.tsx
index 3e92a9d14..c7d55e931 100644
--- a/web/components/reading/workspace/ReadingCompanion.tsx
+++ b/web/components/reading/workspace/ReadingCompanion.tsx
@@ -45,6 +45,8 @@ import SessionViewerPanel, {
import { ChatViewerBridges } from "@/components/chat/home/ChatViewerBridges";
import Tooltip from "@/components/common/Tooltip";
import { useUnifiedChat } from "@/features/chat/compat/UnifiedChatFacade";
+import { TurnStatusBar } from "@/features/chat/components/turn";
+import { turnViewState } from "@/features/chat/model/turn-state";
import { useChatAutoScroll } from "@/hooks/useChatAutoScroll";
import { useMeasuredHeight } from "@/hooks/useMeasuredHeight";
import { useResearchOutlineContinuation } from "@/hooks/useResearchOutlineContinuation";
@@ -52,6 +54,7 @@ import { buildChatOutline } from "@/lib/chat-outline";
import { downloadChatMarkdown } from "@/lib/chat-export";
import { setReadingViewport } from "@/lib/reading-turn-state";
import { workspaceActionNeedsConfiguration } from "@/lib/workspace-mode";
+import { hasPendingAskUser } from "@/lib/ask-user-state";
import {
fetchReadingAskHint,
fetchReadingOpeners,
@@ -113,6 +116,7 @@ export function ReadingCompanion({
const {
state,
submitUserReply,
+ cancelStreamingTurn,
regenerateLastMessage,
deleteTurn,
editMessage,
@@ -150,6 +154,14 @@ export function ReadingCompanion({
const { ref: composerBoxRef, height: composerHeight } =
useMeasuredHeight<HTMLDivElement>();
const lastMessage = state.messages[state.messages.length - 1];
+ const awaitingUserReply = hasPendingAskUser(lastMessage?.events);
+ const activeTurnViewState = turnViewState({
+ status: awaitingUserReply
+ ? "waiting_input"
+ : state.isStreaming
+ ? "running"
+ : undefined,
+ });
const {
containerRef: messagesContainerRef,
endRef: messagesEndRef,
@@ -569,6 +581,13 @@ export function ReadingCompanion({
ref={composerBoxRef}
className="shrink-0 border-t border-[var(--border)] bg-[var(--card)] pt-3 dark:border-[var(--border)] dark:bg-[var(--secondary)]"
>
+ <TurnStatusBar
+ state={activeTurnViewState}
+ stage={state.currentStage || undefined}
+ onCancel={cancelStreamingTurn}
+ onAnswer={() => prefillInputRef.current?.("")}
+ className="mx-4 mb-2"
+ />
{selection && (
<div className="mx-4 mb-2 flex items-start gap-2 rounded-xl border border-[var(--border)] bg-[var(--card)] px-2.5 py-2 dark:border-[var(--border)] dark:bg-[var(--card)]">
<Highlighter
diff --git a/web/components/space/learning/MasteryStudy.tsx b/web/components/space/learning/MasteryStudy.tsx
index 396288215..b0b9ee0d5 100644
--- a/web/components/space/learning/MasteryStudy.tsx
+++ b/web/components/space/learning/MasteryStudy.tsx
@@ -21,12 +21,15 @@ import SessionViewerPanel, {
type SessionViewerPanelHandle,
} from "@/components/chat/home/SessionViewerPanel";
import { useUnifiedChat } from "@/features/chat/compat/UnifiedChatFacade";
+import { TurnStatusBar } from "@/features/chat/components/turn";
+import { turnViewState } from "@/features/chat/model/turn-state";
import { useChatAutoScroll } from "@/hooks/useChatAutoScroll";
import { useMasteryStudySession } from "@/hooks/useMasteryStudySession";
import { useMeasuredHeight } from "@/hooks/useMeasuredHeight";
import { useResearchOutlineContinuation } from "@/hooks/useResearchOutlineContinuation";
import { fetchMasteryAskHint, type MasteryTopic } from "@/lib/learning-api";
import { consumePendingPrompt } from "@/lib/pending-prompt";
+import { hasPendingAskUser } from "@/lib/ask-user-state";
import { workspaceActionNeedsConfiguration } from "@/lib/workspace-mode";
import { topicDisplayName, type Translate } from "./format";
@@ -81,6 +84,7 @@ export function MasteryStudy({
state,
sendMessage,
submitUserReply,
+ cancelStreamingTurn,
regenerateLastMessage,
deleteTurn,
editMessage,
@@ -101,6 +105,14 @@ export function MasteryStudy({
const { ref: composerBoxRef, height: composerHeight } =
useMeasuredHeight<HTMLDivElement>();
const lastMessage = state.messages[state.messages.length - 1];
+ const awaitingUserReply = hasPendingAskUser(lastMessage?.events);
+ const activeTurnViewState = turnViewState({
+ status: awaitingUserReply
+ ? "waiting_input"
+ : state.isStreaming
+ ? "running"
+ : undefined,
+ });
const {
containerRef: messagesContainerRef,
endRef: messagesEndRef,
@@ -467,6 +479,13 @@ export function MasteryStudy({
ref={composerBoxRef}
className="shrink-0 bg-[var(--background)]"
>
+ <TurnStatusBar
+ state={activeTurnViewState}
+ stage={state.currentStage || undefined}
+ onCancel={cancelStreamingTurn}
+ onAnswer={() => prefillInputRef.current?.("")}
+ className="mx-4 mb-2"
+ />
<MasteryComposer
placeholder={t("Ask your tutor about “{{waypoint}}”…", {
waypoint: waypoint.name,
diff --git a/web/features/chat/components/ChatWorkspace.tsx b/web/features/chat/components/ChatWorkspace.tsx
index 8fdd45229..92b2a0857 100644
--- a/web/features/chat/components/ChatWorkspace.tsx
+++ b/web/features/chat/components/ChatWorkspace.tsx
@@ -10,6 +10,8 @@ import {
useState,
} from "react";
import { useChatRouteSession } from "@/features/chat/controllers/useChatRouteSession";
+import { turnViewState } from "@/features/chat/model/turn-state";
+import { TurnStatusBar } from "@/features/chat/components/turn";
import {
GraduationCap,
@@ -1012,6 +1014,13 @@ export default function ChatWorkspace() {
quiz card would appear below the fold, under the composer, and the
conversation looked stalled. Re-arm the pin and land on the card. */
const awaitingUserReply = hasPendingAskUser(lastMessage?.events);
+ const activeTurnViewState = turnViewState({
+ status: awaitingUserReply
+ ? "waiting_input"
+ : state.isStreaming
+ ? "running"
+ : undefined,
+ });
// Read inside ``handleSend`` without adding a dependency that would rebuild
// the callback (and so the composer) on every streamed event.
const awaitingUserReplyRef = useRef(awaitingUserReply);
@@ -2500,6 +2509,15 @@ export default function ChatWorkspace() {
</div>
)}
+ <div className="mx-auto w-full max-w-[960px] px-6">
+ <TurnStatusBar
+ state={activeTurnViewState}
+ stage={state.currentStage || undefined}
+ onCancel={cancelStreamingTurn}
+ onAnswer={() => prefillInputRef.current?.("")}
+ className="mb-2"
+ />
+ </div>
<ChatComposer
composerRef={composerRef}
capMenuRef={capMenuRef}
diff --git a/web/features/chat/components/turn/ProtocolMismatchNotice.tsx b/web/features/chat/components/turn/ProtocolMismatchNotice.tsx
new file mode 100644
index 000000000..b71ef6f38
--- /dev/null
+++ b/web/features/chat/components/turn/ProtocolMismatchNotice.tsx
@@ -0,0 +1,36 @@
+"use client";
+
+import { useTranslation } from "react-i18next";
+import { Button, InlineAlert } from "@/shared/ui";
+
+export interface ProtocolMismatchNoticeProps {
+ clientVersion: string;
+ serverVersion?: string;
+ onReload?: () => void;
+}
+
+export function ProtocolMismatchNotice({
+ clientVersion,
+ serverVersion,
+ onReload,
+}: ProtocolMismatchNoticeProps) {
+ const { t } = useTranslation();
+ return (
+ <InlineAlert
+ tone="danger"
+ title={t("Frontend update required")}
+ action={
+ onReload ? (
+ <Button size="sm" variant="secondary" onClick={onReload}>
+ {t("Reload")}
+ </Button>
+ ) : null
+ }
+ >
+ {t("This page uses protocol {{clientVersion}}, but the server reports {{serverVersion}}.", {
+ clientVersion,
+ serverVersion: serverVersion || t("an incompatible version"),
+ })}
+ </InlineAlert>
+ );
+}
diff --git a/web/features/chat/components/turn/TurnFailureActions.tsx b/web/features/chat/components/turn/TurnFailureActions.tsx
new file mode 100644
index 000000000..9f527182f
--- /dev/null
+++ b/web/features/chat/components/turn/TurnFailureActions.tsx
@@ -0,0 +1,39 @@
+"use client";
+
+import { useTranslation } from "react-i18next";
+import { Button } from "@/shared/ui";
+import type { TurnViewState } from "../../model/turn-state";
+
+export interface TurnFailureActionsProps {
+ state: TurnViewState;
+ onRegenerate?: () => void;
+ onShowDetails?: () => void;
+ compact?: boolean;
+}
+
+export function TurnFailureActions({
+ state,
+ onRegenerate,
+ onShowDetails,
+ compact = false,
+}: TurnFailureActionsProps) {
+ const { t } = useTranslation();
+ if (state.kind !== "retryable_failure" && state.kind !== "terminal_failure") {
+ return null;
+ }
+
+ return (
+ <div className="flex shrink-0 items-center gap-2">
+ {onShowDetails ? (
+ <Button size="sm" variant="ghost" onClick={onShowDetails}>
+ {t("View details")}
+ </Button>
+ ) : null}
+ {state.kind === "retryable_failure" && onRegenerate ? (
+ <Button size="sm" variant="secondary" onClick={onRegenerate}>
+ {compact ? t("Retry") : t("Regenerate response")}
+ </Button>
+ ) : null}
+ </div>
+ );
+}
diff --git a/web/features/chat/components/turn/TurnStatusBar.tsx b/web/features/chat/components/turn/TurnStatusBar.tsx
new file mode 100644
index 000000000..bd20655f3
--- /dev/null
+++ b/web/features/chat/components/turn/TurnStatusBar.tsx
@@ -0,0 +1,170 @@
+"use client";
+
+import {
+ AlertCircle,
+ CheckCircle2,
+ CircleStop,
+ Clock3,
+ Loader2,
+ MessageCircleQuestion,
+ RefreshCw,
+ RotateCcw,
+ WifiOff,
+ XCircle,
+ type LucideIcon,
+} from "lucide-react";
+import { useTranslation } from "react-i18next";
+import { Button, StatusChip, cn, type StatusTone } from "@/shared/ui";
+import {
+ turnPrimaryAction,
+ type TurnPrimaryAction,
+ type TurnViewState,
+} from "../../model/turn-state";
+import { TurnFailureActions } from "./TurnFailureActions";
+
+interface Presentation {
+ label: string;
+ detail?: string;
+ tone: StatusTone;
+ icon: LucideIcon;
+ spin?: boolean;
+}
+
+export interface TurnStatusBarProps {
+ state: TurnViewState;
+ stage?: string;
+ className?: string;
+ showSettled?: boolean;
+ onCancel?: () => void;
+ onAnswer?: () => void;
+ onReconnect?: () => void;
+ onRegenerate?: () => void;
+ onShowDetails?: () => void;
+}
+
+export function TurnStatusBar({
+ state,
+ stage,
+ className,
+ showSettled = false,
+ onCancel,
+ onAnswer,
+ onReconnect,
+ onRegenerate,
+ onShowDetails,
+}: TurnStatusBarProps) {
+ const { t } = useTranslation();
+ const presentation = present(state, t);
+ const action = turnPrimaryAction(state);
+ const settled = state.kind === "idle" || state.kind === "completed";
+
+ if (settled && !showSettled) return null;
+
+ return (
+ <>
+ <div
+ data-turn-state={state.kind}
+ className={cn(
+ "flex min-h-11 items-center gap-3 rounded-xl border border-border bg-card px-3 py-2 text-sm shadow-sm",
+ className,
+ )}
+ >
+ <StatusChip
+ tone={presentation.tone}
+ icon={
+ <presentation.icon
+ aria-hidden
+ className={cn("h-3.5 w-3.5", presentation.spin && "animate-spin")}
+ />
+ }
+ >
+ {presentation.label}
+ </StatusChip>
+ <p className="min-w-0 flex-1 truncate text-xs text-muted-foreground">
+ {stage || presentation.detail}
+ </p>
+ <PrimaryAction
+ action={action}
+ onCancel={onCancel}
+ onAnswer={onAnswer}
+ onReconnect={onReconnect}
+ />
+ <TurnFailureActions
+ state={state}
+ compact
+ onRegenerate={onRegenerate}
+ onShowDetails={onShowDetails}
+ />
+ </div>
+ <span className="sr-only" role="status" aria-live="polite" aria-atomic="true">
+ {presentation.label}
+ </span>
+ </>
+ );
+}
+
+function PrimaryAction({
+ action,
+ onCancel,
+ onAnswer,
+ onReconnect,
+}: {
+ action: TurnPrimaryAction;
+ onCancel?: () => void;
+ onAnswer?: () => void;
+ onReconnect?: () => void;
+}) {
+ const { t } = useTranslation();
+ if (action === "cancel" && onCancel) {
+ return (
+ <Button size="sm" variant="ghost" onClick={onCancel} icon={<CircleStop aria-hidden className="h-4 w-4" />}>
+ {t("Stop")}
+ </Button>
+ );
+ }
+ if (action === "answer" && onAnswer) {
+ return (
+ <Button size="sm" variant="secondary" onClick={onAnswer}>
+ {t("Answer")}
+ </Button>
+ );
+ }
+ if (action === "reconnect" && onReconnect) {
+ return (
+ <Button size="sm" variant="secondary" onClick={onReconnect} icon={<RefreshCw aria-hidden className="h-4 w-4" />}>
+ {t("Reconnect")}
+ </Button>
+ );
+ }
+ return null;
+}
+
+function present(
+ state: TurnViewState,
+ t: (key: string) => string,
+): Presentation {
+ switch (state.kind) {
+ case "idle":
+ return { label: t("Ready"), detail: t("Ask a question when you're ready."), tone: "neutral", icon: CheckCircle2 };
+ case "connecting":
+ return { label: t("Connecting"), detail: t("Opening a secure connection…"), tone: "info", icon: Loader2, spin: true };
+ case "queued":
+ return { label: t("Queued"), detail: t("Your request is waiting for a worker."), tone: "info", icon: Clock3 };
+ case "running":
+ return { label: t("Working"), detail: t("The tutor is preparing a response."), tone: "info", icon: Loader2, spin: true };
+ case "waiting_input":
+ return { label: t("Waiting for your answer"), detail: t("Reply below to continue this turn."), tone: "warning", icon: MessageCircleQuestion };
+ case "cancelling":
+ return { label: t("Stopping"), detail: t("Finishing the current operation safely…"), tone: "warning", icon: Loader2, spin: true };
+ case "recovering":
+ return { label: t("Reconnecting"), detail: t("Your response is safe. Restoring the live connection…"), tone: "warning", icon: WifiOff };
+ case "completed":
+ return { label: t("Completed"), detail: t("The response is complete."), tone: "success", icon: CheckCircle2 };
+ case "cancelled":
+ return { label: t("Stopped"), detail: t("This turn was stopped."), tone: "neutral", icon: XCircle };
+ case "retryable_failure":
+ return { label: t("Response interrupted"), detail: state.failure.message, tone: "danger", icon: RotateCcw };
+ case "terminal_failure":
+ return { label: t("Turn failed"), detail: state.failure.message, tone: "danger", icon: AlertCircle };
+ }
+}
diff --git a/web/features/chat/components/turn/index.ts b/web/features/chat/components/turn/index.ts
new file mode 100644
index 000000000..a3488f032
--- /dev/null
+++ b/web/features/chat/components/turn/index.ts
@@ -0,0 +1,6 @@
+export { ProtocolMismatchNotice } from "./ProtocolMismatchNotice";
+export type { ProtocolMismatchNoticeProps } from "./ProtocolMismatchNotice";
+export { TurnFailureActions } from "./TurnFailureActions";
+export type { TurnFailureActionsProps } from "./TurnFailureActions";
+export { TurnStatusBar } from "./TurnStatusBar";
+export type { TurnStatusBarProps } from "./TurnStatusBar";
diff --git a/web/locales/en/app.json b/web/locales/en/app.json
index 4a6338616..6963e469f 100644
--- a/web/locales/en/app.json
+++ b/web/locales/en/app.json
@@ -4520,5 +4520,35 @@
"Notes could not be loaded.": "Notes could not be loaded.",
"Note was not saved.": "Note was not saved.",
"Note was not deleted.": "Note was not deleted.",
- "Video learning panels": "Video learning panels"
+ "Video learning panels": "Video learning panels",
+ "Ready": "Ready",
+ "Ask a question when you're ready.": "Ask a question when you're ready.",
+ "Connecting": "Connecting",
+ "Opening a secure connection…": "Opening a secure connection…",
+ "Queued": "Queued",
+ "Your request is waiting for a worker.": "Your request is waiting for a worker.",
+ "Working": "Working",
+ "The tutor is preparing a response.": "The tutor is preparing a response.",
+ "Waiting for your answer": "Waiting for your answer",
+ "Reply below to continue this turn.": "Reply below to continue this turn.",
+ "Stopping": "Stopping",
+ "Finishing the current operation safely…": "Finishing the current operation safely…",
+ "Reconnecting": "Reconnecting",
+ "Your response is safe. Restoring the live connection…": "Your response is safe. Restoring the live connection…",
+ "Completed": "Completed",
+ "The response is complete.": "The response is complete.",
+ "Stopped": "Stopped",
+ "This turn was stopped.": "This turn was stopped.",
+ "Response interrupted": "Response interrupted",
+ "Turn failed": "Turn failed",
+ "View details": "View details",
+ "Retry": "Retry",
+ "Regenerate response": "Regenerate response",
+ "Stop": "Stop",
+ "Answer": "Answer",
+ "Reconnect": "Reconnect",
+ "Frontend update required": "Frontend update required",
+ "Reload": "Reload",
+ "This page uses protocol {{clientVersion}}, but the server reports {{serverVersion}}.": "This page uses protocol {{clientVersion}}, but the server reports {{serverVersion}}.",
+ "an incompatible version": "an incompatible version"
}
diff --git a/web/locales/zh/app.json b/web/locales/zh/app.json
index 260dbcce1..c3b98b2b5 100644
--- a/web/locales/zh/app.json
+++ b/web/locales/zh/app.json
@@ -4520,5 +4520,35 @@
"Notes could not be loaded.": "无法加载笔记。",
"Note was not saved.": "笔记未保存。",
"Note was not deleted.": "笔记未删除。",
- "Video learning panels": "视频学习面板"
+ "Video learning panels": "视频学习面板",
+ "Ready": "就绪",
+ "Ask a question when you're ready.": "准备好后即可开始提问。",
+ "Connecting": "正在连接",
+ "Opening a secure connection…": "正在建立安全连接…",
+ "Queued": "正在排队",
+ "Your request is waiting for a worker.": "请求正在等待可用的 Worker。",
+ "Working": "正在处理",
+ "The tutor is preparing a response.": "导师正在准备回答。",
+ "Waiting for your answer": "等待你的回答",
+ "Reply below to continue this turn.": "请在下方回答以继续本轮对话。",
+ "Stopping": "正在停止",
+ "Finishing the current operation safely…": "正在安全结束当前操作…",
+ "Reconnecting": "正在重新连接",
+ "Your response is safe. Restoring the live connection…": "回答进度已保留,正在恢复实时连接…",
+ "Completed": "已完成",
+ "The response is complete.": "回答已完成。",
+ "Stopped": "已停止",
+ "This turn was stopped.": "本轮对话已停止。",
+ "Response interrupted": "回答被中断",
+ "Turn failed": "本轮失败",
+ "View details": "查看详情",
+ "Retry": "重试",
+ "Regenerate response": "重新生成回答",
+ "Stop": "停止",
+ "Answer": "回答",
+ "Reconnect": "重新连接",
+ "Frontend update required": "需要更新前端",
+ "Reload": "重新加载",
+ "This page uses protocol {{clientVersion}}, but the server reports {{serverVersion}}.": "当前页面使用协议 {{clientVersion}},但服务端报告为 {{serverVersion}}。",
+ "an incompatible version": "不兼容版本"
}
diff --git a/web/tests/integration/turn-status.spec.tsx b/web/tests/integration/turn-status.spec.tsx
new file mode 100644
index 000000000..324fe08a9
--- /dev/null
+++ b/web/tests/integration/turn-status.spec.tsx
@@ -0,0 +1,89 @@
+import { render, screen } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { describe, expect, it, vi } from "vitest";
+import {
+ ProtocolMismatchNotice,
+ TurnStatusBar,
+} from "@/features/chat/components/turn";
+import type { TurnViewState } from "@/features/chat/model/turn-state";
+import { initI18n } from "@/i18n/init";
+
+initI18n("en");
+
+const states: TurnViewState[] = [
+ { kind: "idle" },
+ { kind: "connecting" },
+ { kind: "queued" },
+ { kind: "running" },
+ { kind: "waiting_input" },
+ { kind: "cancelling" },
+ { kind: "recovering" },
+ { kind: "completed" },
+ { kind: "cancelled" },
+ {
+ kind: "retryable_failure",
+ failure: { code: "worker_lost", message: "Worker moved", retryable: true },
+ },
+ {
+ kind: "terminal_failure",
+ failure: { code: "rejected", message: "Request rejected", retryable: false },
+ },
+];
+
+describe("turn lifecycle UI", () => {
+ it.each(states)("renders the $kind state without changing the shared layout", (state) => {
+ const { container } = render(<TurnStatusBar state={state} showSettled />);
+ expect(container.querySelector(`[data-turn-state="${state.kind}"]`)).toBeVisible();
+ });
+
+ it("connects lifecycle actions to their exact semantics", async () => {
+ const user = userEvent.setup();
+ const onCancel = vi.fn();
+ const { rerender } = render(
+ <TurnStatusBar state={{ kind: "running" }} onCancel={onCancel} />,
+ );
+ await user.click(screen.getByRole("button", { name: "Stop" }));
+ expect(onCancel).toHaveBeenCalledOnce();
+
+ const onRegenerate = vi.fn();
+ rerender(
+ <TurnStatusBar
+ state={{
+ kind: "retryable_failure",
+ failure: { code: "worker_lost", message: "Moved", retryable: true },
+ }}
+ onRegenerate={onRegenerate}
+ />,
+ );
+ await user.click(screen.getByRole("button", { name: "Retry" }));
+ expect(onRegenerate).toHaveBeenCalledOnce();
+ });
+
+ it("announces lifecycle changes without announcing noisy stage updates", () => {
+ const { rerender } = render(
+ <TurnStatusBar state={{ kind: "running" }} stage="Searching sources" />,
+ );
+ const liveRegion = screen.getByRole("status");
+ expect(liveRegion).toHaveTextContent("Working");
+ expect(liveRegion).not.toHaveTextContent("Searching sources");
+ rerender(<TurnStatusBar state={{ kind: "recovering" }} stage="Attempt 2" />);
+ expect(liveRegion).toHaveTextContent("Reconnecting");
+ expect(liveRegion).not.toHaveTextContent("Attempt 2");
+ });
+
+ it("shows a safe protocol mismatch notice and reload action", async () => {
+ const onReload = vi.fn();
+ const user = userEvent.setup();
+ render(
+ <ProtocolMismatchNotice
+ clientVersion="2.0"
+ serverVersion="3.0"
+ onReload={onReload}
+ />,
+ );
+ expect(screen.getByRole("alert")).toHaveTextContent("2.0");
+ expect(screen.getByRole("alert")).toHaveTextContent("3.0");
+ await user.click(screen.getByRole("button", { name: "Reload" }));
+ expect(onReload).toHaveBeenCalledOnce();
+ });
+});