Skip to content

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

support lemonade & minor fixes

Bingxi Zhao (Frank)932987921b00
diff --git a/README.md b/README.md
index 496dfa59a..3d2826386 100644
--- a/README.md
+++ b/README.md
@@ -290,7 +290,7 @@ default. With auth enabled, add exact frontend origins:
```
<details>
-<summary><b>Connecting to Ollama / LM Studio / llama.cpp / vLLM on the host</b></summary>
+<summary><b>Connecting to Ollama / LM Studio / llama.cpp / vLLM / Lemonade on the host</b></summary>
Inside Docker, `localhost` is the container itself, not your host machine. To reach a model service running on the host, use the host gateway (recommended):
@@ -308,6 +308,7 @@ Then in **Settings → Models**, point the provider Base URL at `host.docker.int
- Ollama embedding: `http://host.docker.internal:11434/api/embed`
- LM Studio: `http://host.docker.internal:1234/v1`
- llama.cpp: `http://host.docker.internal:8080/v1`
+- Lemonade: `http://host.docker.internal:13305/api/v1`
Docker Desktop (macOS/Windows) usually resolves `host.docker.internal` without `--add-host`. On Linux, the flag is the portable way to create that hostname on modern Docker Engine.
diff --git a/deeptutor/services/provider_registry.py b/deeptutor/services/provider_registry.py
index 0a804c16c..a0a262bf5 100644
--- a/deeptutor/services/provider_registry.py
+++ b/deeptutor/services/provider_registry.py
@@ -379,6 +379,16 @@ PROVIDERS: tuple[ProviderSpec, ...] = (
detect_by_base_keyword="8080",
default_api_base="http://localhost:8080/v1",
),
+ ProviderSpec(
+ name="lemonade",
+ keywords=("lemonade",),
+ env_key="LEMONADE_API_KEY",
+ display_name="Lemonade",
+ backend="openai_compat",
+ is_local=True,
+ detect_by_base_keyword="13305",
+ default_api_base="http://localhost:13305/api/v1",
+ ),
ProviderSpec(
name="ovms",
keywords=("openvino", "ovms"),
diff --git a/site/src/content/docs/docs/get-started/providers.md b/site/src/content/docs/docs/get-started/providers.md
index b5183e0cf..e64e8daff 100644
--- a/site/src/content/docs/docs/get-started/providers.md
+++ b/site/src/content/docs/docs/get-started/providers.md
@@ -3,7 +3,7 @@ title: Provider Configuration
---
-DeepTutor currently ships 32 LLM provider bindings, 12 embedding provider bindings, and 7 active search providers (plus an explicit `none` option). Configure them through the Web Settings page, `deeptutor init`, `data/user/settings/model_catalog.json`, or process environment variables. Project-root `.env` files are not auto-loaded by the runtime.
+DeepTutor currently ships 33 LLM provider bindings, 12 embedding provider bindings, and 7 active search providers (plus an explicit `none` option). Configure them through the Web Settings page, `deeptutor init`, `data/user/settings/model_catalog.json`, or process environment variables. Project-root `.env` files are not auto-loaded by the runtime.
## LLM Providers
@@ -21,6 +21,7 @@ DeepTutor currently ships 32 LLM provider bindings, 12 embedding provider bindin
| Gemini | `gemini` | `https://generativelanguage.googleapis.com/v1beta/openai/`|
| GitHub Copilot | `github_copilot` | `https://api.githubcopilot.com` |
| Groq | `groq` | `https://api.groq.com/openai/v1` |
+| Lemonade | `lemonade` | `http://localhost:13305/api/v1` |
| llama.cpp | `llama_cpp` | `http://localhost:8080/v1` |
| LM Studio | `lm_studio` | `http://localhost:1234/v1` |
| MiniMax | `minimax` | `https://api.minimax.io/v1` |
@@ -155,3 +156,12 @@ LLM_MODEL=your-model-name
LLM_HOST=http://localhost:8080/v1
LLM_API_KEY=not-needed
```
+
+### Lemonade
+
+```dotenv
+LLM_BINDING=lemonade
+LLM_MODEL=your-model-name
+LLM_HOST=http://localhost:13305/api/v1
+LLM_API_KEY=not-needed
+```
diff --git a/site/src/content/docs/zh-cn/docs/get-started/providers.md b/site/src/content/docs/zh-cn/docs/get-started/providers.md
index d50fbb049..1019d74e9 100644
--- a/site/src/content/docs/zh-cn/docs/get-started/providers.md
+++ b/site/src/content/docs/zh-cn/docs/get-started/providers.md
@@ -3,7 +3,7 @@ title: Provider 配置
---
-DeepTutor 当前内置 32 个 LLM provider 绑定、12 个 embedding provider 绑定和 7 个激活的搜索 provider(外加显式的 `none` 选项)。可以通过 Web 设置页面、`deeptutor init`、`data/user/settings/model_catalog.json` 或进程环境变量来配置。项目根目录的 `.env` 文件**不会**被运行时自动加载。
+DeepTutor 当前内置 33 个 LLM provider 绑定、12 个 embedding provider 绑定和 7 个激活的搜索 provider(外加显式的 `none` 选项)。可以通过 Web 设置页面、`deeptutor init`、`data/user/settings/model_catalog.json` 或进程环境变量来配置。项目根目录的 `.env` 文件**不会**被运行时自动加载。
## LLM Providers
@@ -21,6 +21,7 @@ DeepTutor 当前内置 32 个 LLM provider 绑定、12 个 embedding provider
| Gemini | `gemini` | `https://generativelanguage.googleapis.com/v1beta/openai/`|
| GitHub Copilot | `github_copilot` | `https://api.githubcopilot.com` |
| Groq | `groq` | `https://api.groq.com/openai/v1` |
+| Lemonade | `lemonade` | `http://localhost:13305/api/v1` |
| llama.cpp | `llama_cpp` | `http://localhost:8080/v1` |
| LM Studio | `lm_studio` | `http://localhost:1234/v1` |
| MiniMax | `minimax` | `https://api.minimax.io/v1` |
@@ -155,3 +156,12 @@ LLM_MODEL=your-model-name
LLM_HOST=http://localhost:8080/v1
LLM_API_KEY=not-needed
```
+
+### Lemonade
+
+```dotenv
+LLM_BINDING=lemonade
+LLM_MODEL=your-model-name
+LLM_HOST=http://localhost:13305/api/v1
+LLM_API_KEY=not-needed
+```
diff --git a/web/app/(workspace)/book/components/BookChatPanel.tsx b/web/app/(workspace)/book/components/BookChatPanel.tsx
index 58138523d..1c67fcd64 100644
--- a/web/app/(workspace)/book/components/BookChatPanel.tsx
+++ b/web/app/(workspace)/book/components/BookChatPanel.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useEffect, useRef, useState } from "react";
+import { useEffect, useLayoutEffect, useRef, useState } from "react";
import type {
ChangeEvent,
ClipboardEvent,
@@ -178,7 +178,11 @@ export default function BookChatPanel({
};
}, [book?.id, page?.id, initialSessionId, open]);
- useEffect(() => {
+ // Pin-to-bottom in layout phase (not in a post-paint effect): the
+ // assignment lands before the browser commits the frame so the
+ // viewer never sees the "new content at the old scrollTop" flash
+ // that an ordinary ``useEffect`` would produce during fast streams.
+ useLayoutEffect(() => {
if (scrollerRef.current) {
scrollerRef.current.scrollTop = scrollerRef.current.scrollHeight;
}
@@ -433,7 +437,11 @@ export default function BookChatPanel({
</button>
</header>
- <div ref={scrollerRef} className="flex-1 overflow-y-auto px-4 py-3">
+ <div
+ ref={scrollerRef}
+ data-chat-scroll-root="true"
+ className="flex-1 overflow-y-auto px-4 py-3"
+ >
{messages.length === 0 ? (
<div className="rounded-2xl border border-dashed border-[var(--border)] bg-[var(--background)]/50 p-4 text-xs leading-5 text-[var(--muted-foreground)]">
{t(
@@ -480,6 +488,7 @@ export default function BookChatPanel({
<AssistantResponse
content={m.content}
className="text-sm leading-relaxed"
+ isStreaming={Boolean(m.streaming)}
/>
) : (
<div className="whitespace-pre-wrap break-words">
diff --git a/web/app/globals.css b/web/app/globals.css
index 11875c2f2..ada7be33c 100644
--- a/web/app/globals.css
+++ b/web/app/globals.css
@@ -238,6 +238,29 @@
background: var(--muted-foreground);
}
+/* ─── Streaming surfaces ───
+ Every scroll container that wraps an LLM-streaming surface (chat,
+ trace card, quiz follow-up, book chat, …) opts into this contract
+ by carrying ``data-chat-scroll-root="true"``.
+
+ ``overflow-anchor: none``
+ Disables the browser's automatic scroll anchoring. Anchoring tries
+ to keep an in-viewport element fixed in screen space when content
+ above it grows; for a chat surface this fights ``useChatAutoScroll``
+ every time a code block / KaTeX block / dynamic viewer mounts and
+ reflows the message list. Without this rule the page visibly jitters
+ during fast streams.
+
+ ``scroll-behavior: auto``
+ The hook intentionally never animates ``scrollTop``. If a global
+ ``scroll-behavior: smooth`` ever lands (theme, base reset, browser
+ experiment), a smooth animation racing against the next-frame pin
+ reintroduces the exact stutter this rule is here to prevent. */
+[data-chat-scroll-root="true"] {
+ overflow-anchor: none;
+ scroll-behavior: auto;
+}
+
/* ─── Prose: base ─── */
.prose {
@apply font-serif text-[15px];
diff --git a/web/components/chat/home/ChatMessages.tsx b/web/components/chat/home/ChatMessages.tsx
index 27194f2cb..ee7f6197e 100644
--- a/web/components/chat/home/ChatMessages.tsx
+++ b/web/components/chat/home/ChatMessages.tsx
@@ -272,7 +272,7 @@ const AssistantMessage = memo(function AssistantMessage({
status={outlineStatus}
/>
{showResearchBody ? (
- <AssistantResponse content={msg.content} />
+ <AssistantResponse content={msg.content} isStreaming={isStreaming} />
) : null}
</>
) : mathAnimatorResult ? (
@@ -290,7 +290,7 @@ const AssistantMessage = memo(function AssistantMessage({
per-question markdown — the pipeline trims that out of
``msg.content`` since the QuizViewer renders the cards
themselves. */}
- {msg.content ? <AssistantResponse content={msg.content} /> : null}
+ {msg.content ? <AssistantResponse content={msg.content} isStreaming={isStreaming} /> : null}
<QuizViewer
questions={quizQuestions}
sessionId={sessionId}
@@ -305,7 +305,7 @@ const AssistantMessage = memo(function AssistantMessage({
// iteration's text sits below.
messageSegments.map((seg) =>
seg.kind === "text" ? (
- <AssistantResponse key={seg.key} content={seg.text} />
+ <AssistantResponse key={seg.key} content={seg.text} isStreaming={isStreaming} />
) : (
<AskUserOptions
key={seg.key}
@@ -318,7 +318,7 @@ const AssistantMessage = memo(function AssistantMessage({
),
)
) : (
- <AssistantResponse content={msg.content} />
+ <AssistantResponse content={msg.content} isStreaming={isStreaming} />
)}
{/* Non-default branches (quiz, math animator, visualize) keep
ask_user below the body. The default branch inlines the card
diff --git a/web/components/common/AssistantResponse.tsx b/web/components/common/AssistantResponse.tsx
index a0ae5ec5e..1d7bee8e3 100644
--- a/web/components/common/AssistantResponse.tsx
+++ b/web/components/common/AssistantResponse.tsx
@@ -1,24 +1,36 @@
"use client";
-import { Fragment, useMemo } from "react";
+import { Fragment, memo, useMemo } from "react";
import MarkdownRenderer from "@/components/common/MarkdownRenderer";
import ModelThinkingCard from "@/components/common/ModelThinkingCard";
import { hasVisibleMarkdownContent } from "@/lib/markdown-display";
import { parseModelThinkingSegments } from "@/lib/think-segments";
+import { useSmoothStreamText } from "@/hooks/useSmoothStreamText";
interface AssistantResponseProps {
content: string;
className?: string;
+ /**
+ * When true, the renderer drives the visible text through a rAF
+ * typewriter (``useSmoothStreamText``) so the markdown grows at a
+ * steady, frame-aligned pace even when the upstream LLM emits
+ * uneven chunks. Pass ``false`` for completed turns and any non-
+ * streaming surface — the hook short-circuits to a pass-through
+ * in that case.
+ */
+ isStreaming?: boolean;
}
-export default function AssistantResponse({
+function AssistantResponseImpl({
content,
className = "text-[14px] leading-[1.75]",
+ isStreaming = false,
}: AssistantResponseProps) {
+ const displayContent = useSmoothStreamText(content, isStreaming);
const segments = useMemo(
- () => parseModelThinkingSegments(content),
- [content],
+ () => parseModelThinkingSegments(displayContent),
+ [displayContent],
);
// Decide whether the message has anything worth rendering. We consider both
@@ -73,3 +85,11 @@ export default function AssistantResponse({
</div>
);
}
+
+// Memoize so completed messages don't re-parse markdown when an
+// unrelated streaming sibling updates the parent — the streaming
+// message gets a fresh ``msg.content`` per delta and re-renders
+// naturally, but every other bubble keeps its previous render output.
+const AssistantResponse = memo(AssistantResponseImpl);
+AssistantResponse.displayName = "AssistantResponse";
+export default AssistantResponse;
diff --git a/web/components/quiz/QuizFollowupTabBody.tsx b/web/components/quiz/QuizFollowupTabBody.tsx
index b1a031b05..7c265b5f4 100644
--- a/web/components/quiz/QuizFollowupTabBody.tsx
+++ b/web/components/quiz/QuizFollowupTabBody.tsx
@@ -14,7 +14,7 @@
* intact and is reflected in the QuizViewer follow-up badge.
*/
-import { useEffect, useMemo, useRef } from "react";
+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef } from "react";
import { Sparkles } from "lucide-react";
import { useTranslation } from "react-i18next";
import MarkdownRenderer from "@/components/common/MarkdownRenderer";
@@ -24,6 +24,7 @@ import {
extractMessageSegments,
} from "@/components/chat/home/AskUserOptions";
import { TraceSurface } from "@/components/chat/home/TracePanels";
+import { useSmoothStreamText } from "@/hooks/useSmoothStreamText";
import {
type QuizFollowupTabContext,
useFollowupThread,
@@ -50,11 +51,32 @@ export default function QuizFollowupTabBody({
const controller = useQuizFollowupController();
const thread = useFollowupThread(context.questionKey);
const threadEndRef = useRef<HTMLDivElement | null>(null);
+ const scrollerRef = useRef<HTMLDivElement | null>(null);
+ const shouldFollowRef = useRef(true);
- useEffect(() => {
- threadEndRef.current?.scrollIntoView({ behavior: "smooth", block: "end" });
+ // Pin-to-bottom autoscroll: direct ``scrollTop = scrollHeight`` in
+ // layout phase, no smooth animation. ``scrollIntoView`` with
+ // ``behavior: 'smooth'`` was the previous strategy here, but it
+ // races against the next-frame layout update during fast streams
+ // (the in-flight animation interrupts itself when a new delta
+ // lands and grows the container again), producing the visible
+ // jitter we're trying to eliminate. The pin pattern matches what
+ // ``useChatAutoScroll`` does on the main chat surface so the two
+ // surfaces feel identical mid-stream.
+ useLayoutEffect(() => {
+ if (!shouldFollowRef.current) return;
+ const el = scrollerRef.current;
+ if (!el) return;
+ el.scrollTop = el.scrollHeight;
}, [thread.messages, thread.isStreaming]);
+ const handleScroll = useCallback(() => {
+ const el = scrollerRef.current;
+ if (!el) return;
+ shouldFollowRef.current =
+ el.scrollHeight - el.scrollTop - el.clientHeight < 80;
+ }, []);
+
// Hydrate prior chat history when the tab opens and the notebook
// entry has a persisted ``followup_session_id``. Skipped when the
// in-memory thread is already populated (page reload while the
@@ -121,8 +143,17 @@ export default function QuizFollowupTabBody({
</div>
</div>
- {/* Scrollable body: pinned context + chat thread. */}
- <div className="flex-1 overflow-y-auto px-4 py-3">
+ {/* Scrollable body: pinned context + chat thread.
+ ``data-chat-scroll-root`` opts this surface into the global
+ ``overflow-anchor: none`` + ``scroll-behavior: auto`` rule
+ (see app/globals.css) so the manual pin isn't fought by the
+ browser's built-in scroll anchoring. */}
+ <div
+ ref={scrollerRef}
+ onScroll={handleScroll}
+ data-chat-scroll-root="true"
+ className="flex-1 overflow-y-auto px-4 py-3"
+ >
<div className="mx-auto flex max-w-[640px] flex-col gap-3">
<div className="rounded-md border border-[var(--border)]/70 bg-[var(--background)]/70 px-3 py-2">
<div className="mb-1 text-[10px] font-semibold uppercase tracking-wider text-[var(--muted-foreground)]">
@@ -286,6 +317,11 @@ function AssistantThreadMessage({
[message.events],
);
const hasInlineAskUser = segments.some((s) => s.kind === "ask_user");
+ // Smooth the trailing-text growth via the shared rAF typewriter so
+ // the markdown renderer sees a steadily-growing string instead of
+ // bursty deltas. Off when ``isStreaming`` is false — the hook
+ // short-circuits to a pure pass-through in that case.
+ const smoothedContent = useSmoothStreamText(message.content, isStreaming);
return (
<div className="flex flex-col gap-1.5">
@@ -313,9 +349,9 @@ function AssistantThreadMessage({
/>
),
)
- ) : message.content ? (
+ ) : smoothedContent ? (
<div className="text-[13px] leading-[1.6] text-[var(--foreground)]">
- <MarkdownRenderer content={message.content} variant="compact" />
+ <MarkdownRenderer content={smoothedContent} variant="compact" />
</div>
) : null}
</div>
diff --git a/web/hooks/useChatAutoScroll.ts b/web/hooks/useChatAutoScroll.ts
index 3ec9fe2ba..bc2136315 100644
--- a/web/hooks/useChatAutoScroll.ts
+++ b/web/hooks/useChatAutoScroll.ts
@@ -1,6 +1,6 @@
"use client";
-import { useCallback, useEffect, useRef } from "react";
+import { useCallback, useEffect, useLayoutEffect, useRef } from "react";
interface AutoScrollOptions {
hasMessages: boolean;
@@ -11,8 +11,42 @@ interface AutoScrollOptions {
lastEventCount?: number;
}
-const THROTTLE_MS = 80;
-
+/**
+ * "Pin to bottom" autoscroll, designed for jitter-free LLM streaming.
+ *
+ * The implementation deliberately collapses what used to be three
+ * separate scroll paths (a throttled timer, a rAF tick, a smooth-vs-
+ * instant branch on stream state) into one: a single
+ * ``useLayoutEffect`` that assigns ``scrollTop = scrollHeight`` while
+ * ``autoFollow`` is true. That is the only writer to ``scrollTop``
+ * during streaming, which removes all the races that previously made
+ * the viewport visibly stutter — smooth-scroll animation interrupted
+ * by the next delta's instant snap, throttle + rAF firing within the
+ * same frame, the browser's built-in scroll anchoring tugging back at
+ * the manual pin while mid-stream code blocks / KaTeX / dynamic
+ * viewers reflow above the cursor, etc.
+ *
+ * Three companion mechanisms keep behaviour correct in edge cases:
+ *
+ * - ``handleScroll`` watches the user's scroll position. The instant
+ * they move more than 80px above the bottom we release the pin so
+ * they can browse history without being yanked back. Scrolling
+ * back near the bottom re-arms it.
+ * - ``composerHeight`` changes (e.g. when the composer grows for a
+ * multi-line draft) re-pin once via a layout effect so the freshly-
+ * revealed content stays on screen.
+ * - A short post-stream window watches for ``childList`` mutations.
+ * Several capability viewers (MathAnimator, Quiz, Visualize) are
+ * loaded via ``next/dynamic({ssr:false})`` and only mount after the
+ * final result event lands; if the user is still pinned we follow
+ * those late-mounting heights downward.
+ *
+ * The scroll container must also opt into ``overflow-anchor: none``
+ * (set globally on ``[data-chat-scroll-root="true"]``). Without it,
+ * the browser's default scroll-anchoring tries to keep an in-viewport
+ * element fixed in screen space when content above it grows — which
+ * fights this hook every time a code block expands.
+ */
export function useChatAutoScroll({
hasMessages,
isStreaming,
@@ -24,79 +58,80 @@ export function useChatAutoScroll({
const containerRef = useRef<HTMLDivElement>(null);
const endRef = useRef<HTMLDivElement>(null);
const shouldAutoScrollRef = useRef(true);
- const lastScrollTimeRef = useRef(0);
- const pendingRafRef = useRef(0);
- const scrollToBottom = useCallback((behavior: ScrollBehavior) => {
+ const pinToBottom = useCallback(() => {
const container = containerRef.current;
if (!container) return;
- container.scrollTo({
- top: container.scrollHeight,
- behavior,
- });
+ // Direct assignment, not ``scrollTo({behavior})``. The browser
+ // applies it synchronously inside the same layout pass which
+ // means the user never sees the in-between frame where new
+ // content has rendered but the scroll position is still stale.
+ container.scrollTop = container.scrollHeight;
}, []);
- useEffect(() => {
- if (!shouldAutoScrollRef.current) return;
-
- const now = performance.now();
- const elapsed = now - lastScrollTimeRef.current;
-
- if (isStreaming && elapsed < THROTTLE_MS) {
- if (pendingRafRef.current) return;
- pendingRafRef.current = window.setTimeout(() => {
- pendingRafRef.current = 0;
- if (shouldAutoScrollRef.current) {
- scrollToBottom("instant");
- lastScrollTimeRef.current = performance.now();
- }
- }, THROTTLE_MS - elapsed);
- return () => {
- if (pendingRafRef.current) {
- clearTimeout(pendingRafRef.current);
- pendingRafRef.current = 0;
- }
- };
- }
-
- const raf = window.requestAnimationFrame(() => {
- scrollToBottom(isStreaming ? "instant" : "smooth");
- lastScrollTimeRef.current = performance.now();
- });
-
- return () => {
- window.cancelAnimationFrame(raf);
- if (pendingRafRef.current) {
- clearTimeout(pendingRafRef.current);
- pendingRafRef.current = 0;
- }
- };
+ // Primary pin: runs in layout phase after every render that bumps
+ // message count / streaming content / events / composer height /
+ // mount. ``useLayoutEffect`` (not ``useEffect``) is required so the
+ // assignment happens before the browser paints — otherwise the
+ // viewer briefly shows the new layout at the old scroll position
+ // and we observe a flash.
+ useLayoutEffect(() => {
+ if (!hasMessages || !shouldAutoScrollRef.current) return;
+ pinToBottom();
}, [
+ pinToBottom,
+ hasMessages,
isStreaming,
- lastEventCount,
- lastMessageContent,
messageCount,
- scrollToBottom,
+ lastMessageContent,
+ lastEventCount,
+ composerHeight,
]);
+ // Companion pin: a frame-aligned rAF loop that runs ONLY while the
+ // turn is streaming. ``useLayoutEffect`` above already pins on every
+ // page-level state change (new delta, new event, new message), but
+ // there is a class of height growth that doesn't bubble up to the
+ // page:
+ //
+ // 1. ``useSmoothStreamText`` advances the visible markdown inside
+ // a child component between WebSocket deltas. Those frames
+ // grow the inner content but the page's deps don't change, so
+ // the layout effect above doesn't re-fire on them.
+ // 2. KaTeX, code blocks, Mermaid, and the late-mount viewer
+ // ``next/dynamic`` chunks all change the height of the message
+ // area asynchronously when they finish hydrating mid-stream.
+ //
+ // We can't use ``ResizeObserver`` on the scroll container itself
+ // because it observes border-box, not scrollHeight; overflow growth
+ // doesn't fire it. A short rAF loop scoped strictly to the
+ // streaming window costs ~60 cheap pins per second (each pin is a
+ // single attribute write, no React work) and is the simplest way
+ // to stay glued to the bottom edge regardless of WHY the inner
+ // content height changed.
useEffect(() => {
- if (!hasMessages || !shouldAutoScrollRef.current) return;
- const raf = window.requestAnimationFrame(() => {
- scrollToBottom("instant");
- });
- return () => window.cancelAnimationFrame(raf);
- }, [composerHeight, hasMessages, scrollToBottom]);
-
- // After streaming ends, dynamically-loaded components (e.g. MathAnimatorViewer
- // via next/dynamic) may render and grow the content height. Detect that and
- // scroll to bottom so the user can see the full result.
+ if (!isStreaming || !hasMessages) return;
+ let rafId = 0;
+ const tick = () => {
+ if (shouldAutoScrollRef.current) {
+ const container = containerRef.current;
+ if (container) container.scrollTop = container.scrollHeight;
+ }
+ rafId = requestAnimationFrame(tick);
+ };
+ rafId = requestAnimationFrame(tick);
+ return () => cancelAnimationFrame(rafId);
+ }, [isStreaming, hasMessages]);
+
+ // After streaming ends, capability viewers loaded via ``next/dynamic``
+ // (MathAnimatorViewer, QuizViewer, VisualizationViewer, RichCodeBlock,
+ // Mermaid …) finish hydrating and grow the content height. The user
+ // expects to land at the bottom so they see the full result.
//
- // This observer used to run for the entire lifetime of the conversation,
- // which meant any post-stream DOM change — including the user expanding a
- // trace `<details>` row to read it — was treated as "new content arrived"
- // and pulled the user back to the bottom. We now gate it to a short window
- // right after `isStreaming` flips false, which is when late-mounting
- // dynamic components actually settle.
+ // The observer is intentionally short-lived (4s after stream stop):
+ // a longer window would mis-classify post-turn user interactions
+ // (expanding a trace ``<details>``, clicking a citation) as
+ // "streaming-style growth" and rip them back to the bottom.
const POST_STREAM_AUTOSCROLL_WINDOW_MS = 4000;
useEffect(() => {
if (isStreaming) return;
@@ -116,7 +151,7 @@ export function useChatAutoScroll({
if (performance.now() > deadline) return;
const curHeight = container.scrollHeight;
if (curHeight > prevHeight && shouldAutoScrollRef.current) {
- scrollToBottom("instant");
+ pinToBottom();
}
prevHeight = curHeight;
});
@@ -134,7 +169,7 @@ export function useChatAutoScroll({
mo.disconnect();
if (rafId) cancelAnimationFrame(rafId);
};
- }, [hasMessages, isStreaming, scrollToBottom]);
+ }, [hasMessages, isStreaming, pinToBottom]);
const handleScroll = useCallback(() => {
const container = containerRef.current;
@@ -144,6 +179,14 @@ export function useChatAutoScroll({
shouldAutoScrollRef.current = distanceFromBottom < 80;
}, []);
+ // ``scrollToBottom`` is preserved as a public escape hatch (e.g. an
+ // imperative "jump to latest" button) but kept ``instant`` so it
+ // never animates against an active stream.
+ const scrollToBottom = useCallback((_behavior: ScrollBehavior) => {
+ void _behavior;
+ pinToBottom();
+ }, [pinToBottom]);
+
return {
containerRef,
endRef,
diff --git a/web/hooks/useSmoothStreamText.ts b/web/hooks/useSmoothStreamText.ts
new file mode 100644
index 000000000..3b305d8ec
--- /dev/null
+++ b/web/hooks/useSmoothStreamText.ts
@@ -0,0 +1,141 @@
+"use client";
+
+import { useEffect, useRef, useState } from "react";
+
+interface SmoothStreamOptions {
+ /**
+ * Cap on visible chars revealed per rAF frame.
+ * The reveal speed adapts to the current backlog so a long pause that
+ * suddenly delivers a 2KB chunk doesn't take 30 seconds to type out:
+ * each frame reveals max(MIN_CHARS_PER_FRAME, backlog / catchUpDivisor),
+ * up to ``maxCharsPerFrame``.
+ */
+ maxCharsPerFrame?: number;
+ /** Minimum chars revealed per frame so the cursor always advances. */
+ minCharsPerFrame?: number;
+ /** Larger = slower reveal relative to backlog. ~5 feels natural. */
+ catchUpDivisor?: number;
+ /**
+ * When ``false``, the hook is a pass-through: the smoother is disabled
+ * and ``displayContent`` always equals ``content``. Useful so callers
+ * can keep the same render path for both streaming and idle messages.
+ */
+ enabled?: boolean;
+}
+
+/**
+ * Decouples the visible markdown growth rate from the WebSocket delta
+ * cadence so the user perceives smooth, "typewriter"-style streaming
+ * regardless of how bursty the upstream LLM chunks are.
+ *
+ * Mechanics:
+ * - While ``isStreaming`` is true and the incoming ``content`` is
+ * longer than what we've shown, a single ``requestAnimationFrame``
+ * loop advances the cursor towards ``content.length``.
+ * - When ``isStreaming`` flips false, we snap to the full ``content``
+ * on the next frame so the finished message lands instantly. This
+ * also handles short messages where the smoother would otherwise
+ * leave a few trailing chars unrevealed at stream end.
+ * - When ``content`` shrinks (regenerate / edit-branch path resets
+ * the streaming bubble) we snap back to the new length. Otherwise
+ * the cursor would briefly display stale tail text.
+ *
+ * The hook is intentionally generic: it knows nothing about markdown
+ * or assistant turns, so it can be reused for any streaming surface
+ * (chat, quiz follow-up, book chat, memory workbench, …).
+ */
+export function useSmoothStreamText(
+ content: string,
+ isStreaming: boolean,
+ options: SmoothStreamOptions = {},
+): string {
+ const {
+ maxCharsPerFrame = 120,
+ minCharsPerFrame = 2,
+ catchUpDivisor = 5,
+ enabled = true,
+ } = options;
+
+ const [shown, setShown] = useState<string>(content);
+ const shownLenRef = useRef<number>(content.length);
+ const rafRef = useRef<number>(0);
+
+ useEffect(() => {
+ if (!enabled) {
+ // Disabled mode: act as a pure pass-through.
+ if (shownLenRef.current !== content.length || shown !== content) {
+ shownLenRef.current = content.length;
+ setShown(content);
+ }
+ return;
+ }
+
+ // Snap to full content the moment streaming stops so the user never
+ // sees a half-revealed tail at the end of the turn.
+ if (!isStreaming) {
+ if (rafRef.current) {
+ cancelAnimationFrame(rafRef.current);
+ rafRef.current = 0;
+ }
+ if (shownLenRef.current !== content.length || shown !== content) {
+ shownLenRef.current = content.length;
+ setShown(content);
+ }
+ return;
+ }
+
+ // Content shrank (regenerate / branch switch): snap back to avoid
+ // a phantom tail from the previous stream.
+ if (shownLenRef.current > content.length) {
+ shownLenRef.current = content.length;
+ setShown(content);
+ return;
+ }
+
+ if (shownLenRef.current >= content.length) {
+ // Caught up — wait for the next delta to re-arm the loop.
+ return;
+ }
+
+ const step = () => {
+ rafRef.current = 0;
+ const target = content.length;
+ const current = shownLenRef.current;
+ if (current >= target) return;
+ const backlog = target - current;
+ const advance = Math.min(
+ maxCharsPerFrame,
+ Math.max(minCharsPerFrame, Math.ceil(backlog / catchUpDivisor)),
+ );
+ const next = Math.min(target, current + advance);
+ shownLenRef.current = next;
+ setShown(content.slice(0, next));
+ if (next < target) {
+ rafRef.current = requestAnimationFrame(step);
+ }
+ };
+
+ if (!rafRef.current) {
+ rafRef.current = requestAnimationFrame(step);
+ }
+
+ return () => {
+ if (rafRef.current) {
+ cancelAnimationFrame(rafRef.current);
+ rafRef.current = 0;
+ }
+ };
+ // ``shown`` is intentionally omitted from deps — including it would
+ // restart the loop after every advance and we'd lose the rAF chain.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [
+ content,
+ isStreaming,
+ enabled,
+ maxCharsPerFrame,
+ minCharsPerFrame,
+ catchUpDivisor,
+ ]);
+
+ return shown;
+}