Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions components/ChatMinimap.module.css
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,47 @@
user-select: text;
}

.loadEarlier {
display: grid;
grid-template-columns: 34px minmax(0, 1fr);
align-items: center;
width: 100%;
min-height: 32px;
padding: 0;
border: 0;
border-bottom: 1px solid color-mix(in srgb, var(--border) 68%, transparent);
background: transparent;
color: var(--text-muted);
font-family: inherit;
font-size: 13px;
font-weight: 500;
text-align: left;
cursor: pointer;
transition: background 100ms ease;
}

.loadEarlier:hover:not(:disabled) {
background: color-mix(in srgb, var(--text) 6%, transparent);
}

.loadEarlier:disabled {
color: var(--text-dim);
cursor: default;
}

.loadEarlierArrow {
display: flex;
align-items: center;
justify-content: center;
font-size: 12px;
line-height: 1;
}

.loadEarlierLabel {
padding-left: 6px;
line-height: 18px;
}

.turn {
position: relative;
display: grid;
Expand Down
26 changes: 26 additions & 0 deletions components/ChatMinimap.test.mjs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
import { registerHooks } from "node:module";
import test from "node:test";
import React from "react";
Expand All @@ -21,6 +22,7 @@ const jiti = createJiti(import.meta.url, {
tsconfigPaths: true,
});
const { AssistantOutline } = await jiti.import("./ChatMinimap.tsx");
const source = await readFile(new URL("./ChatMinimap.tsx", import.meta.url), "utf8");

test("renders math in headings without disabling heading navigation", () => {
const html = renderToStaticMarkup(
Expand All @@ -37,3 +39,27 @@ test("renders math in headings without disabling heading navigation", () => {
assert.match(html, /data-preview-heading-index="1"/);
assert.doesNotMatch(html, /disabled=""/);
});

test("renders the load-earlier row before the loaded turns", () => {
assert.match(source, /hasEarlierMessages: boolean/);
assert.match(source, /loadingEarlier: boolean/);
assert.match(source, /onLoadEarlier: \(\) => void \| Promise<void>/);

// The preview panel must render the row even when no turn is loaded yet,
// otherwise a page that ends inside one huge turn has no affordance at all.
assert.match(source, /minimapHovered && \(allNodes\.length > 0 \|\| hasEarlierMessages\)/);

const previewBox = source.slice(
source.indexOf("data-minimap-preview-box"),
source.indexOf("{allNodes.map((node) =>"),
);
assert.match(previewBox, /hasEarlierMessages && \(/);
assert.match(previewBox, /data-minimap-load-earlier/);
assert.match(previewBox, /disabled=\{loadingEarlier\}/);
assert.match(previewBox, /void onLoadEarlier\(\)/);
});

test("labels the load-earlier row from i18n and shows progress while it loads", () => {
assert.match(source, /t\("chatMinimap\.loadEarlier"\)/);
assert.match(source, /loadingEarlier \? t\("i18n\.loading"\) : t\("chatMinimap\.loadEarlier"\)/);
});
25 changes: 24 additions & 1 deletion components/ChatMinimap.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,12 @@ interface Props {
scrollContainer: RefObject<HTMLDivElement | null>;
messageRefs: RefObject<(HTMLDivElement | null)[]>;
onRevealHistory: () => void;
/** Whether the server has user turns older than the loaded page. */
hasEarlierMessages: boolean;
/** True while a page of older history is being fetched. */
loadingEarlier: boolean;
/** Fetch the previous page of older history into the chat. */
onLoadEarlier: () => void | Promise<void>;
}

const MINIMAP_WIDTH = 36;
Expand Down Expand Up @@ -233,6 +239,9 @@ export function ChatMinimap({
scrollContainer,
messageRefs,
onRevealHistory,
hasEarlierMessages,
loadingEarlier,
onLoadEarlier,
}: Props) {
const { t } = useI18n();
const [visible, setVisible] = useState(false);
Expand Down Expand Up @@ -674,7 +683,7 @@ export function ChatMinimap({
);
})}

{minimapHovered && allNodes.length > 0 && (
{minimapHovered && (allNodes.length > 0 || hasEarlierMessages) && (
<div
ref={previewBoxRef}
className={styles.preview}
Expand All @@ -683,6 +692,20 @@ export function ChatMinimap({
onMouseDown={(event) => event.stopPropagation()}
onMouseMove={(event) => event.stopPropagation()}
>
{hasEarlierMessages && (
<button
type="button"
className={styles.loadEarlier}
data-minimap-load-earlier=""
disabled={loadingEarlier}
onClick={() => { void onLoadEarlier(); }}
>
<span className={styles.loadEarlierArrow} aria-hidden="true">↑</span>
<span className={styles.loadEarlierLabel}>
{loadingEarlier ? t("i18n.loading") : t("chatMinimap.loadEarlier")}
</span>
</button>
)}
{allNodes.map((node) => {
const isLocated = nearestNodeIndex === node.index;
return (
Expand Down
43 changes: 43 additions & 0 deletions components/ChatWindow.minimap-history.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
import test from "node:test";

const source = await readFile(new URL("./ChatWindow.tsx", import.meta.url), "utf8");

test("shares one guarded older-page loader between the sentinel and the minimap", () => {
const loader = source.slice(
source.indexOf("const loadOlderPage = useCallback"),
source.indexOf("// IntersectionObserver on the sentinel div"),
);

assert.match(loader, /if \(loadingOlderRef\.current\) return/);
assert.match(loader, /if \(!hasEarlierMessages\) return/);
assert.match(loader, /const oldestId = historyCursor/);
assert.match(loader, /prevScrollDistanceRef\.current = captureScrollDistance/);
assert.match(loader, /loadingOlderRef\.current = true/);
assert.match(loader, /setLoadingEarlier\(true\)/);
assert.match(loader, /await loadContext\(sid, activeLeafId, oldestId\)/);
assert.match(
loader,
/finally \{[\s\S]*?loadingOlderRef\.current = false;[\s\S]*?setLoadingEarlier\(false\)/,
);

// The sentinel keeps its observer but delegates the fetch to the shared loader.
const observer = source.slice(
source.indexOf("// IntersectionObserver on the sentinel div"),
source.indexOf("// Keep the rendered window at least as large"),
);
assert.match(observer, /void loadOlderPage\(\)/);
assert.doesNotMatch(observer, /loadContext\(/);
});

test("passes older-history state and the loader to the minimap", () => {
const minimap = source.slice(
source.indexOf("<ChatMinimap\n"),
source.indexOf("onLoadEarlier={loadOlderPage}"),
);

assert.match(minimap, /hasEarlierMessages=\{hasEarlierMessages\}/);
assert.match(minimap, /loadingEarlier=\{loadingEarlier\}/);
assert.match(source, /onLoadEarlier=\{loadOlderPage\}/);
});
47 changes: 32 additions & 15 deletions components/ChatWindow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -468,6 +468,7 @@ export function ChatWindow({ session, searchTarget, onSearchTargetHandled, initi
const messageContentRef = useRef<HTMLDivElement | null>(null);
const prevScrollDistanceRef = useRef<number | null>(null);
const loadingOlderRef = useRef(false);
const [loadingEarlier, setLoadingEarlier] = useState(false);
const restoreStartedRef = useRef(false);
const pendingScrollRestoreRef = useRef(pendingScrollRestore);
pendingScrollRestoreRef.current = pendingScrollRestore;
Expand Down Expand Up @@ -626,6 +627,32 @@ export function ChatWindow({ session, searchTarget, onSearchTargetHandled, initi
onSearchTargetHandled?.(pendingSearchScroll);
}, [pendingSearchScroll, searchTarget, searchMessage, scrollContainerRef, scrollToMessage, onSearchTargetHandled]);

// Load one older page of history. Shared by the top sentinel (triggered by
// scrolling) and the minimap's "Load earlier" row so both paths keep a
// single in-flight guard and the same scroll-anchoring capture.
const loadOlderPage = useCallback(async () => {
// Skip while a page is already loading or nothing older exists.
if (loadingOlderRef.current) return;
if (!hasEarlierMessages) return;
const oldestId = historyCursor;
if (!oldestId) return;
const sid = session?.id ?? sessionIdRef.current;
if (!sid) return;
const container = scrollContainerRef.current;
if (container) {
prevScrollDistanceRef.current = captureScrollDistance(container.scrollHeight, container.scrollTop);
}
loadingOlderRef.current = true;
setLoadingEarlier(true);
try {
// loadContext handles prepend + scroll anchoring.
await loadContext(sid, activeLeafId, oldestId);
} finally {
loadingOlderRef.current = false;
setLoadingEarlier(false);
}
}, [activeLeafId, hasEarlierMessages, historyCursor, loadContext, scrollContainerRef, session?.id, sessionIdRef]);

// IntersectionObserver on the sentinel div at the top of the message list.
// When it becomes visible, load the next page of older messages.
useEffect(() => {
Expand All @@ -635,26 +662,13 @@ export function ChatWindow({ session, searchTarget, onSearchTargetHandled, initi
const observer = new IntersectionObserver(
(entries) => {
if (!entries[0]?.isIntersecting) return;
// No older history loaded yet: fetch the previous page from the server
// and prepend it (loadContext handles prepend + scroll anchoring).
// Skip while a page is already loading or nothing older exists.
if (loadingOlderRef.current) return;
if (!hasEarlierMessages) return;
const oldestId = historyCursor;
if (!oldestId) return;
const sid = session?.id ?? sessionIdRef.current;
if (!sid) return;
loadingOlderRef.current = true;
prevScrollDistanceRef.current = captureScrollDistance(container.scrollHeight, container.scrollTop);
void loadContext(sid, activeLeafId, oldestId).finally(() => {
loadingOlderRef.current = false;
});
void loadOlderPage();
},
{ root: container, threshold: 0 }
);
observer.observe(sentinel);
return () => observer.disconnect();
}, [historyCursor, hasEarlierMessages, session, activeLeafId, loadContext, sessionIdRef, scrollContainerRef]);
}, [loadOlderPage, scrollContainerRef]);

// Keep the rendered window at least as large as what's loaded, so prepended
// (older) pages stay visible instead of being sliced off the top.
Expand Down Expand Up @@ -1228,6 +1242,9 @@ export function ChatWindow({ session, searchTarget, onSearchTargetHandled, initi
scrollContainer={scrollContainerRef}
messageRefs={messageRefs}
onRevealHistory={revealHistoryForMinimap}
hasEarlierMessages={hasEarlierMessages}
loadingEarlier={loadingEarlier}
onLoadEarlier={loadOlderPage}
/>
)}
</>}
Expand Down
1 change: 1 addition & 0 deletions lib/i18n/messages/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -428,6 +428,7 @@ export const enLocale: LocalePlugin = {
"chat.imageNotSupportedBody": "The selected model ({model}) does not support image input. The attached images will likely be ignored.",
"chat.tokensSaved": "{saved} saved",
"chatMinimap.locateAssistant": "Locate assistant message",
"chatMinimap.loadEarlier": "Load earlier",
"i18n.close": "Close",
"i18n.copy": "Copy",
"i18n.copied": "Copied",
Expand Down
1 change: 1 addition & 0 deletions lib/i18n/messages/zh-CN.ts
Original file line number Diff line number Diff line change
Expand Up @@ -428,6 +428,7 @@ export const zhCNLocale: LocalePlugin = {
"chat.imageNotSupportedBody": "当前选择的模型({model})不支持图片输入,附加的图片可能会被忽略。",
"chat.tokensSaved": "节省 {saved}",
"chatMinimap.locateAssistant": "定位助手消息",
"chatMinimap.loadEarlier": "加载更早记录",
"i18n.close": "关闭",
"i18n.copy": "复制",
"i18n.copied": "已复制",
Expand Down
1 change: 1 addition & 0 deletions lib/i18n/messages/zh-TW.ts
Original file line number Diff line number Diff line change
Expand Up @@ -428,6 +428,7 @@ export const zhTWLocale: LocalePlugin = {
"chat.imageNotSupportedBody": "目前選擇的模型({model})不支援圖片輸入,附加的圖片可能會被忽略。",
"chat.tokensSaved": "已節省 {saved}",
"chatMinimap.locateAssistant": "定位助理訊息",
"chatMinimap.loadEarlier": "載入較早的記錄",
"i18n.close": "關閉",
"i18n.copy": "複製",
"i18n.copied": "已複製",
Expand Down