From 1fadcab73e754f1e65277af74be5b829b6524d0b Mon Sep 17 00:00:00 2001 From: Arga Fairuz Date: Wed, 18 Nov 2026 18:10:18 +0700 Subject: [PATCH] fix(chat): keep scroll position steady and make the prompt rail responsive Jumping to an old prompt from the navigation rail could take seconds with no feedback, then land in the wrong place. The rail's dots snapped to a new window the instant one was clicked, the active dot lagged behind what was on screen and stayed put after scrolling to the bottom, tooltips lingered half-faded, and on touch devices the rail could not be tapped at all. Scrolling through history stalled at the top or bottom until the user scrolled again, and the view jumped when items were revealed or trimmed. The jump paged back one 80-message request at a time, measured its target once while neighbours still rendered at a 200px content-visibility estimate, and could be overtaken by a later click. The dot window re-sliced around the new active dot in a single frame. The active dot was the rendered prompt nearest the viewport centre, so one already scrolled past could stay active, and when a long agent turn filled the rendered window with tool calls no prompt was found at all. Tooltips relied on leave events that never fire for removed or disabled elements, and iOS treats a tap that reveals hover content as hover only. Loading was driven solely by scroll events, so a load finishing while the reader sat at an edge triggered nothing; position was restored from scrollHeight deltas, trims had no compensation (Safari has no scroll anchoring), and streaming moved the virtual window to the end even while the reader was on older messages. The page API now takes until_id so a jump loads in one request; jumps carry a token, show a spinner on the control pressed, keep the dots still until they land and then slide them, and hold their target while layout settles. The active dot follows a reading line over every message's position in the whole list, so a prompt outside the rendered window still counts, and it is rechecked on layout changes. Hover is mouse-only and cleared when its element goes away; touch gets tap to jump, press-and-hold to preview and an accelerated, hysteresis-damped scrub. A ResizeObserver anchor keeper replaces native scroll anchoring, edges are re-checked after every load, older pages are prefetched, trims only drop off-screen items, sync leaves older windows in place, and tool results are fingerprinted cheaply. --- backend/chat/message-pages.test.ts | 17 + backend/chat/message-pages.ts | 8 +- backend/ws/messages/crud.ts | 4 +- .../chat/message/ChatMessages.svelte | 470 +++++++++---- .../chat/message/ChatNavigationRail.svelte | 623 +++++++++++++++--- frontend/stores/core/sessions.svelte.ts | 14 +- frontend/utils/chat/date-separator.ts | 5 +- frontend/utils/chat/virtual-scroll.svelte.ts | 43 +- 8 files changed, 943 insertions(+), 241 deletions(-) diff --git a/backend/chat/message-pages.test.ts b/backend/chat/message-pages.test.ts index a56d3391..26e67852 100644 --- a/backend/chat/message-pages.test.ts +++ b/backend/chat/message-pages.test.ts @@ -120,6 +120,23 @@ describe('getMessagePage', () => { expect(collected).toEqual(ids); }); + it('reaches back to a requested message in one page, contiguous with the loaded ones', () => { + const session = newSession(); + const ids = buildBranch(session, 12, 2); // 6 messages per turn + + const latest = getMessagePage(session, { minCount: 7 }); + const before = (latest.messages[0] as { messageId: string }).messageId; + const target = ids[7]; // inside turn 1, far older than one page + const page = getMessagePage(session, { beforeId: before, minCount: 7, untilId: target }); + const pageIds = page.messages.map((message) => (message as { messageId: string }).messageId); + + expect(pageIds).toContain(target); + const start = ids.indexOf(pageIds[0]); + expect(start).toBeLessThanOrEqual(7); + expect([...pageIds, ...latest.messages.map((m) => (m as { messageId: string }).messageId)]).toEqual(ids.slice(start)); + expect(page.hasMore).toBe(true); + }); + it('answers an empty page for a session with no messages, or an unknown cursor', () => { const session = newSession(); expect(getMessagePage(session)).toEqual({ messages: [], hasMore: false }); diff --git a/backend/chat/message-pages.ts b/backend/chat/message-pages.ts index 3e8856cf..54d0af84 100644 --- a/backend/chat/message-pages.ts +++ b/backend/chat/message-pages.ts @@ -88,10 +88,12 @@ function headOf(sessionId: string): string | null { /** * One page of the active branch, ending just before `beforeId` (or at the head * when absent). Holds at least `minCount` messages and always begins at a turn. + * With `untilId` it also reaches back to that message, so a jump to an old + * prompt is one request instead of a page-by-page walk. */ export function getMessagePage( sessionId: string, - options: { beforeId?: string; minCount?: number } = {} + options: { beforeId?: string; minCount?: number; untilId?: string } = {} ): MessagePage { const minCount = Math.max(1, options.minCount ?? DEFAULT_PAGE_SIZE); const byId = getDatabase().prepare('SELECT * FROM messages WHERE id = ? AND session_id = ?'); @@ -107,6 +109,7 @@ export function getMessagePage( const messages: UnifiedMessage[] = []; const boundary = new BoundaryTracker(); + let reachedUntil = !options.untilId; while (cursor) { const row = byId.get(cursor, sessionId) as DatabaseMessage | null; if (!row) { @@ -116,8 +119,9 @@ export function getMessagePage( const message = JSON.parse(row.data) as UnifiedMessage; messages.push(message); cursor = row.parent_message_id ?? null; + if (row.id === options.untilId) reachedUntil = true; const mayStartHere = boundary.add(message); - if (messages.length >= minCount && mayStartHere) break; + if (messages.length >= minCount && reachedUntil && mayStartHere) break; } return { diff --git a/backend/ws/messages/crud.ts b/backend/ws/messages/crud.ts index 5d4257bc..d1ffbd66 100644 --- a/backend/ws/messages/crud.ts +++ b/backend/ws/messages/crud.ts @@ -43,6 +43,8 @@ export const crudHandler = createRouter() session_id: t.String({ minLength: 1 }), /** Return the page that ends just before this message; omit for the latest. */ before_id: t.Optional(t.String()), + /** Also reach back to this message (a jump to an old prompt). */ + until_id: t.Optional(t.String()), /** Minimum page size; the page is extended back to the start of a turn. */ limit: t.Optional(t.Number({ minimum: 1, maximum: 500 })) }), @@ -52,7 +54,7 @@ export const crudHandler = createRouter() }) }, async ({ data }) => { requireSessionAccess(data.session_id); - return getMessagePage(data.session_id, { beforeId: data.before_id, minCount: data.limit }); + return getMessagePage(data.session_id, { beforeId: data.before_id, untilId: data.until_id, minCount: data.limit }); }) // Every user prompt on the active branch — the chat's navigation rail. diff --git a/frontend/components/chat/message/ChatMessages.svelte b/frontend/components/chat/message/ChatMessages.svelte index c1b2df58..48d8d40f 100644 --- a/frontend/components/chat/message/ChatMessages.svelte +++ b/frontend/components/chat/message/ChatMessages.svelte @@ -58,6 +58,7 @@ function resetView(count: number) { vs.reset(count); keyOffset = 0; + keptAnchor = null; } // ======================================== @@ -81,9 +82,12 @@ return filteredMessages.slice(vs.windowStart, vs.windowEnd); }); + /** Index in filteredMessages of the first rendered message. */ + const windowBase = $derived(vs.isActive ? vs.windowStart : 0); + // Add date separators to windowed messages (with global index offset for stable keys) const messagesWithDateSeparators = $derived.by((): DateSeparatorItem[] => { - return addDateSeparators(windowedMessages, keyOffset + (vs.isActive ? vs.windowStart : 0)); + return addDateSeparators(windowedMessages, keyOffset + windowBase); }); // Whether a message participates in the compact timeline rail (agent / reasoning) @@ -186,11 +190,12 @@ * anything on screen: the window and the keys shift by the number of items * added, in the same synchronous step as the insert, so the DOM is untouched * and the auto-scroll effect does not see "new messages". Returns how many - * list items were added. + * list items were added, or null when no page came back. With `untilId` the + * page reaches back to that message in the same request. */ - async function loadOlderPage(): Promise { - const page = await fetchOlderPage(); - if (!page) return 0; + async function loadOlderPage(untilId?: string): Promise { + const page = await fetchOlderPage(untilId); + if (!page) return null; const before = filteredMessages.length; if (applyOlderPage(page) === 0) return 0; const added = filteredMessages.length - before; @@ -202,23 +207,38 @@ return added; } - /** Page back until a message is loaded. True when it is (or already was). */ + /** + * Load back to a message. True when it is (or already was) loaded. Usually + * one request; a loop only because a page already in flight (a prefetch) is + * shared and may stop short of the message. + */ async function ensureMessageLoaded(messageId: string): Promise { - for (let guard = 0; guard < 1000 && !isMessageLoaded(messageId); guard++) { + for (let guard = 0; guard < 50 && !isMessageLoaded(messageId); guard++) { if (!sessionState.hasOlderMessages) return false; - const page = await fetchOlderPage(); - if (!page) return isMessageLoaded(messageId); - const before = filteredMessages.length; - if (applyOlderPage(page) > 0) { - const added = filteredMessages.length - before; - keyOffset -= added; - vs.prepend(added); - previousMessageCount = filteredMessages.length; - } + if ((await loadOlderPage(messageId)) === null) break; } return isMessageLoaded(messageId); } + /** + * Page the server in the background while the user is still a few screens + * away from the top, so the next page is usually there before they reach it. + * Applying it is invisible: the window shifts with the insert. + */ + let isPrefetchingOlder = false; + function prefetchOlderIfNear(el: HTMLElement) { + if (isPrefetchingOlder || !sessionState.hasOlderMessages) return; + const hiddenAbove = vs.isActive ? vs.windowStart : 0; + if (hiddenAbove > vs.bufferSize * 2) return; + if (el.scrollTop > Math.max(vs.loadMoreMargin * 3, el.clientHeight * 1.5)) return; + isPrefetchingOlder = true; + void loadOlderPage() + .catch(() => null) + .finally(() => { + isPrefetchingOlder = false; + }); + } + /** Index of a message in the rendered list, or -1. */ function indexOfMessage(messageId: string): number { return filteredMessages.findIndex((m) => 'messageId' in m && (m as { messageId?: string }).messageId === messageId); @@ -238,7 +258,7 @@ if (vs.isActive && vs.hasMoreAbove) { vs.expandUp(); } else if (sessionState.hasOlderMessages) { - if ((await loadOlderPage()) === 0) return; + if (!(await loadOlderPage())) return; if (vs.isActive && vs.hasMoreAbove) vs.expandUp(); } else { return; @@ -261,10 +281,25 @@ return messagesScrollEl ?? scrollContainer; } + /** + * Whether the reader is at the end of the chat: near the bottom of what is + * rendered AND nothing newer is held back by the window. Near the bottom of + * an older window is not "at the bottom" — following new messages from there + * would yank the window to the end. + */ + function isAtBottom(el: HTMLElement, threshold = 200): boolean { + if (vs.hasMoreBelow) return false; + return el.scrollTop + el.clientHeight >= el.scrollHeight - threshold; + } + // Auto-scroll to bottom when new messages arrive function scrollMessagesToBottom(smooth = true) { const el = getScrollEl(); if (el) { + // The anchor keeper must pin to the bottom while this (possibly smooth) + // scroll is still on its way there. + pinIntentUntil = Date.now() + 600; + keptPinned = true; // During streaming, always use instant scroll to avoid jitter // caused by smooth animation being outpaced by rapid DOM updates const useSmooth = smooth && !appState.isLoading; @@ -288,8 +323,7 @@ if (appState.isRestoring || suppressAutoScroll) return; const sid = sessionState.currentSession?.id; if (!sid) return; - const { scrollTop, scrollHeight, clientHeight } = el; - const atBottom = scrollTop + clientHeight >= scrollHeight - 200; + const atBottom = isAtBottom(el); if (atBottom) { setChatScroll(sid, { atBottom: true, anchorMessageId: null, anchorOffset: 0 }); } else { @@ -320,10 +354,7 @@ if (!el) return; // The lock has expired by now; refresh isUserAtBottom too so live // auto-scroll follows from the user's real position. - if (Date.now() >= scrollLockUntil) { - const { scrollTop, scrollHeight, clientHeight } = el; - isUserAtBottom = scrollTop + clientHeight >= scrollHeight - 200; - } + if (Date.now() >= scrollLockUntil) isUserAtBottom = isAtBottom(el); saveReadingPosition(el); }, 120); } @@ -344,36 +375,177 @@ flushWorkspaceSave(); } + // ======================================== + // ANCHOR KEEPER + // ======================================== + /** - * Grow the window upward over already-loaded items, keeping what is on - * screen in place (expand → restore scroll → trim). + * Keeps what the reader is looking at in place whenever the content changes + * size: the window revealing or trimming items at either end, an older page + * landing, markdown/code/images finishing their render, the panel resizing. + * + * The browser's own scroll anchoring is switched off (`overflow-anchor: + * none`) — Safari has none at all, and two mechanisms correcting the same + * scroll fight each other. Instead the first visible message is recorded on + * every scroll, and a ResizeObserver on the list puts it back at the same + * offset before the frame is painted. Changes below the anchor move nothing, + * so they cost nothing. A reader pinned to the bottom stays pinned instead. */ - function revealOlder(el: HTMLElement) { + let keptAnchor: { id: string; offset: number } | null = null; + let keptPinned = true; + /** A programmatic scroll to the bottom is in progress — keep pinning. */ + let pinIntentUntil = 0; + let listEl: HTMLElement | undefined = $state(); + + function captureAnchor(el: HTMLElement) { + keptPinned = Date.now() < pinIntentUntil || isAtBottom(el, 2); + keptAnchor = keptPinned ? null : captureChatAnchor(el); + } + + function keepAnchor() { + const el = getScrollEl(); + // The initial restore owns the scroll while it runs. + if (!el || !hasInitiallyScrolled || suppressAutoScroll) return; + // A position hold is running: keep ITS target, right away rather than + // on its next frame, so a change landing mid-frame never paints shifted. + if (releaseHold) { + if (heldTarget === 'bottom') { + if (el.scrollHeight - el.clientHeight - el.scrollTop > 1) el.scrollTop = el.scrollHeight; + } else if (heldTarget) { + const node = el.querySelector(`[data-message-id="${heldTarget.anchorId}"]`); + if (!node) return; + const delta = node.getBoundingClientRect().top - el.getBoundingClientRect().top - heldTarget.offset; + if (Math.abs(delta) > 1) el.scrollTop += delta; + } + return; + } + if (keptPinned) { + if (editModeState.isEditing) return; + if (el.scrollHeight - el.clientHeight - el.scrollTop > 1) el.scrollTop = el.scrollHeight; + return; + } + if (!keptAnchor) return; + const node = el.querySelector(`[data-message-id="${keptAnchor.id}"]`); + if (!node) return; + const delta = node.getBoundingClientRect().top - el.getBoundingClientRect().top - keptAnchor.offset; + if (Math.abs(delta) >= 1) el.scrollTop += delta; + } + + $effect(() => { + const el = messagesScrollEl; + const list = listEl; + if (!el || !list) return; + const observer = new ResizeObserver(() => keepAnchor()); + observer.observe(list); + observer.observe(el); + // The reader taking over cancels a pending pin to the bottom. + const takeOver = () => { + pinIntentUntil = 0; + }; + for (const type of ['wheel', 'touchstart', 'keydown'] as const) { + el.addEventListener(type, takeOver, { passive: true }); + } + return () => { + observer.disconnect(); + for (const type of ['wheel', 'touchstart', 'keydown'] as const) { + el.removeEventListener(type, takeOver); + } + }; + }); + + // ======================================== + // EDGES: REVEAL / LOAD MORE + // ======================================== + + /** + * Rendered items wholly beyond the viewport (plus a margin) at one end — + * the most the window may drop there without anything visible vanishing. + */ + function countOffscreen(el: HTMLElement, side: 'above' | 'below'): number { + const nodes = el.querySelectorAll('[data-vs-item]'); + const rect = el.getBoundingClientRect(); + const margin = vs.loadMoreMargin; + let count = 0; + if (side === 'below') { + for (let i = nodes.length - 1; i >= 0; i--) { + if (nodes[i].getBoundingClientRect().top <= rect.bottom + margin) break; + count++; + } + } else { + for (let i = 0; i < nodes.length; i++) { + if (nodes[i].getBoundingClientRect().bottom >= rect.top - margin) break; + count++; + } + } + return count; + } + + let isEdgeBusy = false; + + /** Run one window change, let it render, then look at the edges again. */ + async function runEdge(change: () => void) { + isEdgeBusy = true; + try { + change(); + await tick(); + await new Promise((resolve) => requestAnimationFrame(() => resolve())); + } finally { + isEdgeBusy = false; + } + checkEdges(); + } + + /** Fetch the next older page while the reader waits at the top. */ + async function loadOlderAtTop() { + isEdgeBusy = true; isLoadingOlder = true; + try { + await loadOlderPage(); + await tick(); + } catch { + // fetchOlderPage already logged it; the next scroll retries. + } finally { + isLoadingOlder = false; + isEdgeBusy = false; + } + checkEdges(); + } - const prevScrollHeight = el.scrollHeight; - const prevScrollTop = el.scrollTop; + /** + * Reveal or load whatever is next to the reader at either end. Called on + * every scroll AND after every load/reveal finishes: scrolling into the top + * while a page was still on its way left nothing to trigger the next step, + * so the chat sat stuck at the top until the user scrolled again. + */ + function checkEdges() { + const el = getScrollEl(); + if (!el || isEdgeBusy || !hasInitiallyScrolled || suppressAutoScroll) return; + const margin = vs.loadMoreMargin; + const { scrollTop, scrollHeight, clientHeight } = el; - const added = vs.expandUp(); - if (added > 0) { - // Phase 1: DOM updates with expanded window (no trim yet) - tick().then(() => { - requestAnimationFrame(() => { - // Restore scroll position based on content added at top - const heightAdded = el.scrollHeight - prevScrollHeight; - el.scrollTop = prevScrollTop + heightAdded; - // Lock scroll to prevent re-triggering from programmatic scroll - scrollLockUntil = Date.now() + 200; + prefetchOlderIfNear(el); - // Phase 2: trim bottom after scroll is settled - requestAnimationFrame(() => { - vs.trimBottom(); - setTimeout(() => { isLoadingOlder = false; }, 150); - }); + if (scrollTop <= margin) { + if (vs.isActive && vs.hasMoreAbove) { + const spare = countOffscreen(el, 'below'); + void runEdge(() => { + vs.expandUp(); + vs.trimBottom(spare); }); + return; + } + if (sessionState.hasOlderMessages) { + void loadOlderAtTop(); + return; + } + } + + if (vs.isActive && vs.hasMoreBelow && scrollHeight - scrollTop - clientHeight <= margin) { + const spare = countOffscreen(el, 'above'); + void runEdge(() => { + vs.expandDown(); + vs.trimTop(spare); }); - } else { - isLoadingOlder = false; } } @@ -382,59 +554,52 @@ const el = getScrollEl(); if (!el) return; + captureAnchor(el); + // While the lock is active we can't trust scroll events to reflect user // intent (they may be echoes of our own programmatic scroll), so leave - // isUserAtBottom and load-more untouched — but DO schedule a settle-capture - // so a real user scroll during the lock still updates the saved position. + // isUserAtBottom untouched — but DO schedule a settle-capture so a real + // user scroll during the lock still updates the saved position. if (Date.now() < scrollLockUntil) { scheduleReadingPositionSave(); + checkEdges(); return; } - const { scrollTop, scrollHeight, clientHeight } = el; - const threshold = 200; - isUserAtBottom = scrollTop + clientHeight >= scrollHeight - threshold; + isUserAtBottom = isAtBottom(el); // Remember this session's reading position (synchronous in the common, // unlocked case so a project switch immediately after still flushes it). saveReadingPosition(el); - const margin = vs.loadMoreMargin; - - // Load older messages when near top: first from the loaded list (reveal - // what the window trimmed), then from the server (the next older page). - if (scrollTop <= margin && !isLoadingOlder) { - if (vs.isActive && vs.hasMoreAbove) { - revealOlder(el); - } else if (sessionState.hasOlderMessages) { - isLoadingOlder = true; - loadOlderPage() - .then(async (added) => { - await tick(); - isLoadingOlder = false; - if (added > 0 && vs.hasMoreAbove) revealOlder(el); - }) - .catch(() => { - isLoadingOlder = false; - }); - } - } - - if (!vs.isActive) return; - - // Load newer messages when near bottom - const distanceFromBottom = scrollHeight - scrollTop - clientHeight; - if (distanceFromBottom <= margin && vs.hasMoreBelow) { - vs.expandDown(); - // Trim top immediately — removed content is above viewport - vs.trimTop(); - } + checkEdges(); } // ======================================== // AUTO-SCROLL & VIRTUAL SCROLL SYNC // ======================================== + /** + * A cheap stand-in for a tool result's size, enough to notice it arriving or + * growing. Serialising every result (screenshots included) on every streamed + * token and every loaded page was a large share of the chat's main-thread + * time once a session got long. + */ + function resultSignature(result: unknown): number { + const content = (result as { content?: unknown } | null)?.content ?? result; + if (typeof content === 'string') return content.length; + if (!Array.isArray(content)) return 1; + let size = content.length; + for (const part of content) { + const p = part as { text?: unknown; data?: unknown; source?: { data?: unknown } } | null; + if (typeof p?.text === 'string') size += p.text.length; + else if (typeof p?.data === 'string') size += p.data.length; + else if (typeof p?.source?.data === 'string') size += p.source.data.length; + else size += 1; + } + return size; + } + // Auto-scroll: track message count and partial message updates $effect(() => { const currentMessageCount = filteredMessages.length; @@ -446,7 +611,7 @@ if (isMessageCountDecreased) { resetView(currentMessageCount); } else if (isNewMessage) { - vs.sync(currentMessageCount, isUserAtBottom, appState.isLoading); + vs.sync(currentMessageCount, isUserAtBottom); } } @@ -482,7 +647,7 @@ for (const item of message.content) { if (item?.type !== 'tool_use') continue; if (item.result) { - currentToolResultsHash += `${item.id}:${JSON.stringify(item.result).length}|`; + currentToolResultsHash += `${item.id}:${resultSignature(item.result)}|`; } if (item.subActivities?.length) { currentSubAgentHash += `${item.id}:${item.subActivities.length}|`; @@ -598,18 +763,17 @@ const HOLD_POSITION_MS = 2000; let releaseHold: (() => void) | null = null; + /** What the running hold keeps in place (the anchor keeper applies it too). */ + let heldTarget: { anchorId: string; offset: number } | 'bottom' | null = null; /** * Keep a restored position in place while the layout finishes settling. * - * Aligning once is not enough: after it, messages above the anchor still - * resolve their real height (`content-visibility` lays them out at a 200px - * estimate until they near the viewport), and markdown, code blocks and - * images finish rendering. Chromium compensates for some of that with scroll - * anchoring; Safari has none. Either way the chat ended up somewhere near, - * but not at, the saved position. So the position is re-applied every frame - * for a short while, and given up the moment the user scrolls, clicks or - * types, or the session changes. + * Aligning once is not enough: after it, markdown, code blocks and images + * around the anchor finish rendering, and the window may reveal more items + * above it. So the position is re-applied every frame for a short while, + * and given up the moment the user scrolls, clicks or types, or the session + * changes — the anchor keeper takes over from there. * * `target` is the anchor to hold, or null to hold the bottom. */ @@ -624,7 +788,12 @@ el.removeEventListener(type, stop); window.removeEventListener(type, stop); } - if (releaseHold === stop) releaseHold = null; + if (releaseHold === stop) { + releaseHold = null; + heldTarget = null; + // Hand the position back to the anchor keeper. + captureAnchor(el); + } }; const step = () => { if (Date.now() > until || sessionState.currentSession?.id !== sessionId || editModeState.isEditing) { @@ -654,6 +823,7 @@ window.addEventListener(type, stop, { passive: true }); } releaseHold = stop; + heldTarget = target ?? 'bottom'; frame = requestAnimationFrame(step); } @@ -691,14 +861,11 @@ await tick(); // Align the anchor to its saved offset, then RE-ALIGN across several - // frames. Messages use `content-visibility: auto` with a 200px - // intrinsic-size estimate, so those above the anchor are laid out as - // short placeholders until they near the viewport — once they render - // at their real height (often far more than 200px for long messages) - // they shove the anchor away from where we just put it. Each pass - // re-measures and corrects until the position stabilizes, keeping the - // lock raised so these programmatic scrolls aren't mistaken for user - // input. + // frames: messages that just mounted are still settling their real + // height (markdown, code, images) and shove the anchor away from where + // we just put it. Each pass re-measures and corrects until the position + // stabilizes, keeping the lock raised so these programmatic scrolls + // aren't mistaken for user input. let aligned = false; for (let pass = 0; pass < 12; pass++) { await new Promise((resolve) => requestAnimationFrame(() => resolve())); @@ -757,6 +924,7 @@ .then(() => fillViewportIfShort()) .finally(() => { suppressAutoScroll = false; + checkEdges(); requestAnimationFrame(() => { isContentReady = true; }); @@ -777,6 +945,7 @@ .then(() => fillViewportIfShort()) .finally(() => { suppressAutoScroll = false; + checkEdges(); isContentReady = true; }); } else { @@ -857,33 +1026,46 @@ // NAV RAIL: JUMP TO USER MESSAGE // ======================================== + /** Where a jumped-to prompt lands, from the top of the list. */ + const NAV_JUMP_OFFSET = 24; + + /** The prompt a jump is on its way to — the rail shows it as loading. */ + let navPendingId = $state(null); + /** Bumped by every jump, so a slower earlier one never lands after a later one. */ + let navJumpToken = 0; + async function handleNavJump(item: NavItem) { const el = getScrollEl(); if (!el) return; - - // The prompt may be on a page that is not loaded yet. - if (!isMessageLoaded(item.messageId) && !(await ensureMessageLoaded(item.messageId))) return; - const index = indexOfMessage(item.messageId); - if (index < 0) return; - - // Lock scroll detection so jump doesn't flip isUserAtBottom incorrectly - scrollLockUntil = Date.now() + 400; - - const performScroll = () => { - const target = el.querySelector(`[data-message-id="${item.messageId}"]`); - if (target) { - const top = target.getBoundingClientRect().top - el.getBoundingClientRect().top + el.scrollTop - 24; - el.scrollTo({ top, behavior: 'auto' }); + const token = ++navJumpToken; + navPendingId = item.messageId; + try { + // The prompt may be on a page that is not loaded yet. + if (!isMessageLoaded(item.messageId) && !(await ensureMessageLoaded(item.messageId))) return; + if (token !== navJumpToken) return; + const index = indexOfMessage(item.messageId); + if (index < 0) return; + + if (vs.isActive && (index < vs.windowStart || index >= vs.windowEnd)) { + vs.ensureVisible(index); + await tick(); + if (token !== navJumpToken) return; } - }; - if (vs.isActive && (index < vs.windowStart || index >= vs.windowEnd)) { - vs.ensureVisible(index); - tick().then(() => { - requestAnimationFrame(performScroll); - }); - } else { - performScroll(); + const target = el.querySelector(`[data-message-id="${item.messageId}"]`); + if (!target) return; + // Lock scroll detection so the jump doesn't flip isUserAtBottom. + scrollLockUntil = Date.now() + 400; + pinIntentUntil = 0; + keptPinned = false; + isUserAtBottom = false; + el.scrollTop += target.getBoundingClientRect().top - el.getBoundingClientRect().top - NAV_JUMP_OFFSET; + // Messages around the target are still settling (markdown, code, + // images) and the window may reveal more above it: hold it in place + // until it is stable or the user takes over. + holdPosition(el, { anchorId: item.messageId, offset: NAV_JUMP_OFFSET }); + } finally { + if (token === navJumpToken) navPendingId = null; } } @@ -891,26 +1073,22 @@ const el = getScrollEl(); if (!el || filteredMessages.length === 0) return; + // Supersede a jump still loading, and any position being held. + navJumpToken++; + navPendingId = null; + releaseHold?.(); + const lastIndex = filteredMessages.length - 1; - // Re-scroll across frames: content-visibility'd items resolve their - // real height only after they come on-screen, growing scrollHeight. const performScroll = () => { scrollLockUntil = Date.now() + 600; - let attempts = 3; - const step = () => { - el.scrollTo({ top: el.scrollHeight, behavior: 'auto' }); - attempts--; - if (attempts > 0) { - requestAnimationFrame(step); - } else { - isUserAtBottom = true; - } - }; - step(); + el.scrollTop = el.scrollHeight; + isUserAtBottom = true; + // Late layout below is followed by the hold (and the anchor keeper after it). + holdPosition(el, null); }; - if (vs.isActive && (lastIndex < vs.windowStart || lastIndex >= vs.windowEnd)) { + if (vs.isActive && vs.hasMoreBelow) { vs.ensureVisible(lastIndex); tick().then(() => { requestAnimationFrame(performScroll); @@ -968,6 +1146,7 @@
+ right while the reading position was being aligned to them. + The wrapper is what the anchor keeper watches for size changes. --> +
{#each messagesWithDateSeparators as item (item.key)} -
+
{#if item.type === 'date'} {:else if item.type === 'message'} {@const messageId = 'messageId' in item.data ? item.data.messageId : undefined} {@const isLastUser = messageId === lastUserMessageId} {@const rail = railFlagsByKey.get(item.key)} -
+ +
{/if}
{/each} +
diff --git a/frontend/components/chat/message/ChatNavigationRail.svelte b/frontend/components/chat/message/ChatNavigationRail.svelte index 73335ffc..b51948b8 100644 --- a/frontend/components/chat/message/ChatNavigationRail.svelte +++ b/frontend/components/chat/message/ChatNavigationRail.svelte @@ -12,19 +12,35 @@ interface Props { scrollEl: HTMLElement | undefined; items: NavItem[]; + /** The prompt a jump is still loading (or scrolling) to. */ + pendingId: string | null; isUserAtBottom: boolean; onJump: (item: NavItem) => void; onJumpToBottom: () => void; } - const { scrollEl, items, isUserAtBottom, onJump, onJumpToBottom }: Props = $props(); + const { scrollEl, items, pendingId, isUserAtBottom, onJump, onJumpToBottom }: Props = $props(); type HoverKey = string | 'up' | 'down' | null; + type PendingSource = 'up' | 'down' | 'dot' | null; + + /** Mouse hover or keyboard focus only — touch never sets it (see the scrubber). */ let hovered = $state(null); let activeId = $state(null); let rafId = 0; let lockUntil = 0; let bandHeight = $state(0); + let bandEl: HTMLElement | undefined = $state(); + let pillEl: HTMLElement | undefined = $state(); + + /** What started the pending jump, so the spinner shows on the thing pressed. */ + let pendingSource = $state(null); + /** Spinner shown only for jumps that take a moment, so instant ones never flash. */ + let showPending = $state(false); + + /** Touch scrub in progress: the prompt under the gesture and where the finger is. */ + let scrub = $state<{ idx: number; y: number; cancel: boolean } | null>(null); + let previewHeight = $state(0); const activeIdx = $derived( activeId ? items.findIndex(i => i.messageId === activeId) : -1 @@ -42,7 +58,13 @@ ); // --- Windowing: cap visible dots to the available band height --- - const PER_DOT = 15; // px per dot row (line + py-1.5 + gap) + // + // Every dot is rendered in one column that slides behind a clipped viewport + // (translateY), so moving the window glides instead of re-slicing the list + // in one frame. While a jump is loading the window stays exactly where it + // was — the spinner sits on the dot that was pressed — and only moves once + // the jump has landed. + const PER_DOT = 15; // px per dot row (fixed row height) const CHROME = 68; // px for chevrons + pill/container padding const ELLIPSIS = 18; // px per ellipsis marker @@ -59,51 +81,112 @@ return Math.max(1, Math.min(items.length, Math.floor(forDots / PER_DOT))); }); + /** The dot the window centres on: the one being scrubbed to, else the active one. */ + const focusIdx = $derived(scrub ? scrub.idx : activeIdx); + + /** Window start held while a jump is on its way (null when free). */ + let frozenStart = $state(null); + const windowStart = $derived.by(() => { const total = items.length; if (!isWindowed) return 0; - const center = activeIdx === -1 ? total - 1 : activeIdx; + const maxStart = total - windowSize; + if (frozenStart !== null && !scrub) return Math.max(0, Math.min(frozenStart, maxStart)); + const center = focusIdx === -1 ? total - 1 : focusIdx; const start = center - Math.floor(windowSize / 2); - return Math.max(0, Math.min(start, total - windowSize)); + return Math.max(0, Math.min(start, maxStart)); + }); + + // Release the hold once nothing is pending — right away for a jump that + // needed no loading, when it lands for one that did. + $effect(() => { + if (frozenStart !== null && !pendingId) frozenStart = null; + }); + + /** Slide transitions are off until the rail has settled, and for a new chat. */ + let animate = $state(false); + const chatKey = $derived(items[0]?.messageId ?? ''); + $effect(() => { + chatKey; + animate = false; + let inner = 0; + const outer = requestAnimationFrame(() => { + inner = requestAnimationFrame(() => (animate = true)); + }); + return () => { + cancelAnimationFrame(outer); + cancelAnimationFrame(inner); + }; }); - const visibleItems = $derived(items.slice(windowStart, windowStart + windowSize)); + function isVisibleIdx(idx: number): boolean { + return idx >= windowStart && idx < windowStart + windowSize; + } const moreAbove = $derived(windowStart); + /** The dot whose tooltip is showing (mouse hover / keyboard focus), or -1. */ + const hoveredIdx = $derived.by(() => { + const key = hovered; + if (key === null || key === 'up' || key === 'down') return -1; + const idx = items.findIndex(i => i.messageId === key); + return isVisibleIdx(idx) ? idx : -1; + }); const moreBelow = $derived(items.length - (windowStart + windowSize)); const pageStep = $derived(Math.max(1, windowSize - 1)); + /** Keep the rail fully visible while it is doing something. */ + const isEngaged = $derived(scrub !== null || (pendingId !== null && showPending)); + + /** + * Where the reader's eye is: a prompt becomes active once its top crosses + * this line, and stays active through its replies until the next prompt + * crosses it. "Nearest to the middle of the viewport" switched late and + * unpredictably — a prompt already scrolled past could still be nearer than + * the one now on screen. + */ + const READING_LINE_RATIO = 0.3; + const READING_LINE_MAX_PX = 240; + function updateActive() { if (!scrollEl || items.length === 0) return; - if (Date.now() < lockUntil) return; + // A jump still on its way owns the highlight. + if (pendingId || Date.now() < lockUntil) return; - const scrollRect = scrollEl.getBoundingClientRect(); - const viewportCenter = scrollRect.height / 2; - const idSet = new Set(items.map(i => i.messageId)); + // Work in message positions, not prompt elements: a long agent turn can + // fill the whole rendered window with tool calls, leaving its prompt + // outside it — scanning only rendered prompts then found nothing and the + // highlight stayed wherever it was (e.g. after "scroll to bottom"). + const nodes = scrollEl.querySelectorAll('[data-msg-index]'); + if (nodes.length === 0) return; - let bestId: string | null = null; - let bestDist = Infinity; + const scrollRect = scrollEl.getBoundingClientRect(); + const line = scrollRect.top + Math.min(scrollRect.height * READING_LINE_RATIO, READING_LINE_MAX_PX); + const atEnd = scrollEl.scrollHeight - scrollEl.scrollTop - scrollEl.clientHeight < 4; - const nodes = scrollEl.querySelectorAll('[data-message-id]'); + // The message being read: the last one that has crossed the reading line, + // or — scrolled to the end — the last one on screen, since the final + // section can never reach the line. + let reading = -1; for (const el of nodes) { - const id = el.getAttribute('data-message-id'); - if (!id || !idSet.has(id)) continue; - - const rect = el.getBoundingClientRect(); - const relTop = rect.top - scrollRect.top; - const relBottom = relTop + rect.height; - - let dist: number; - if (viewportCenter < relTop) dist = relTop - viewportCenter; - else if (viewportCenter > relBottom) dist = viewportCenter - relBottom; - else dist = 0; - - if (dist < bestDist) { - bestDist = dist; - bestId = id; - } + const top = el.getBoundingClientRect().top; + if (top <= line || (atEnd && top < scrollRect.bottom)) reading = Number(el.dataset.msgIndex); + else break; } - - if (bestId) activeId = bestId; + // Nothing has crossed yet: the reader is still in the section before + // the first rendered message. + if (reading === -1) reading = Number(nodes[0].dataset.msgIndex) - 1; + + // The active prompt opens that section: the last loaded prompt at or + // before it, else the newest prompt older than everything loaded. + let next = -1; + let firstLoaded = items.length; + for (let i = 0; i < items.length; i++) { + const gi = items[i].globalIndex; + if (gi < 0) continue; + if (firstLoaded === items.length) firstLoaded = i; + if (gi <= reading) next = i; + } + if (next === -1) next = Math.max(0, firstLoaded - 1); + activeId = items[next].messageId; } function scheduleUpdate() { @@ -144,9 +227,61 @@ scheduleUpdate(); }); + // Content can move without a scroll event — the window swapping in other + // messages, replies finishing their render, a clamp at the end — so layout + // changes re-check too. + $effect(() => { + const el = scrollEl; + const list = el?.firstElementChild; + if (!el || !list) return; + const observer = new ResizeObserver(() => scheduleUpdate()); + observer.observe(list); + observer.observe(el); + return () => observer.disconnect(); + }); + + $effect(() => { + if (isUserAtBottom) scheduleUpdate(); + }); + + // Pending jump: show the spinner after a beat; once it lands, keep the + // highlight on the target a moment longer while the position settles. + $effect(() => { + if (!pendingId) { + showPending = false; + return; + } + const show = setTimeout(() => (showPending = true), 150); + return () => { + clearTimeout(show); + lockUntil = Date.now() + 300; + setTimeout(scheduleUpdate, 320); + }; + }); + + $effect(() => { + if (!pendingId) pendingSource = null; + }); + + // A hover whose element went away (the dot window moved, the chevron got + // disabled) never receives its leave event: drop it here instead of leaving + // a tooltip on screen. + $effect(() => { + const key = hovered; + if (key === null) return; + if (key === 'up') { + if (!canGoUp) hovered = null; + } else if (key === 'down') { + if (!canGoDown) hovered = null; + } else if (!isVisibleIdx(items.findIndex(i => i.messageId === key))) { + hovered = null; + } + }); + onMount(() => { return () => { if (rafId) cancelAnimationFrame(rafId); + endPress(); }; }); @@ -155,28 +290,269 @@ return clean.length > 120 ? clean.slice(0, 120) + '…' : clean; } - function jumpTo(item: NavItem) { + function jumpTo(item: NavItem, source: PendingSource = 'dot') { + // Hold the dots still for as long as the jump is loading. + frozenStart = windowStart; activeId = item.messageId; lockUntil = Date.now() + 700; + pendingSource = source; onJump(item); } + function jumpToBottom() { + // The end of the chat is the last prompt's section: show it right away + // rather than wait for the scroll to settle. + const last = items[items.length - 1]; + if (last) { + activeId = last.messageId; + lockUntil = Date.now() + 400; + setTimeout(scheduleUpdate, 420); + } + onJumpToBottom(); + } + function goUp() { - if (upTarget) jumpTo(upTarget); + if (isClickSuppressed()) return; + if (upTarget) jumpTo(upTarget, 'up'); } function goDown() { - if (downTarget) jumpTo(downTarget); + if (isClickSuppressed()) return; + if (downTarget) jumpTo(downTarget, 'down'); } // Page the window up/down by ~one window when an ellipsis marker is clicked function pageBy(delta: number) { + if (isClickSuppressed()) return; const total = items.length; if (total === 0) return; const center = activeIdx === -1 ? total - 1 : activeIdx; const target = Math.max(0, Math.min(total - 1, center + delta)); jumpTo(items[target]); } + + function clickDot(item: NavItem) { + if (isClickSuppressed()) return; + jumpTo(item); + } + + // --- Hover (mouse) and focus (keyboard) --- + + function hoverIn(event: PointerEvent, key: HoverKey) { + if (event.pointerType === 'mouse') hovered = key; + } + + function hoverOut(event: PointerEvent, key: HoverKey) { + if (event.pointerType === 'mouse' && hovered === key) hovered = null; + } + + function focusIn(event: FocusEvent, key: HoverKey) { + // Only keyboard focus: a clicked button keeps focus after the mouse has + // gone, which is what left tooltips lingering. + if ((event.currentTarget as HTMLElement).matches(':focus-visible')) hovered = key; + } + + function focusOut(key: HoverKey) { + if (hovered === key) hovered = null; + } + + // --- Touch: tap to jump, press-and-hold to preview, hold and slide to scrub --- + // + // The dots are a few pixels apart, far too close to aim at with a finger, + // so a scrub does not follow the dot under the finger. Finger travel maps + // to a number of prompts instead: a steady, generous step for the first + // few (fine control), growing for longer slides (reach across a long chat). + // Hysteresis stops the preview flickering at a step boundary, and turning + // back re-bases the slide so the fine steps return in the new direction. + + const HOLD_MS = 300; + const SLOP_PX = 8; + /** Finger travel per prompt for the first LINEAR_STEPS prompts. */ + const STEP_PX = 22; + const LINEAR_STEPS = 4; + const HYSTERESIS = 0.3; + /** Travel back against the slide that counts as turning around. */ + const TURN_PX = 6; + /** Slide this far left, away from the rail, and releasing cancels. */ + const CANCEL_PX = 72; + const SUPPRESS_CLICK_MS = 600; + + interface Press { + pointerId: number; + x0: number; + y0: number; + /** The dot pressed, or -1 when the press started on a chevron or ellipsis. */ + dotIdx: number; + timer: ReturnType | null; + scrubbing: boolean; + baseY: number; + baseIdx: number; + dir: number; + extremeY: number; + } + + let press: Press | null = null; + let suppressClickUntil = 0; + + function isClickSuppressed(): boolean { + return Date.now() < suppressClickUntil; + } + + function nearestDot(clientY: number): number { + if (!pillEl) return -1; + let best = -1; + let bestDist = Infinity; + for (const node of pillEl.querySelectorAll('[data-nav-idx]')) { + if (!isVisibleIdx(Number(node.dataset.navIdx))) continue; + const rect = node.getBoundingClientRect(); + const dist = Math.abs(rect.top + rect.height / 2 - clientY); + if (dist < bestDist) { + bestDist = dist; + best = Number(node.dataset.navIdx); + } + } + return bestDist <= PER_DOT ? best : -1; + } + + function onPressStart(event: PointerEvent) { + if (event.pointerType === 'mouse' || !event.isPrimary || items.length === 0) return; + endPress(); + hovered = null; + const onControl = (event.target as HTMLElement).closest('[data-nav-ctrl]') !== null; + const dotIdx = onControl ? -1 : nearestDot(event.clientY); + press = { + pointerId: event.pointerId, + x0: event.clientX, + y0: event.clientY, + dotIdx, + timer: setTimeout(() => startScrub(event.clientY), HOLD_MS), + scrubbing: false, + baseY: event.clientY, + baseIdx: 0, + dir: 0, + extremeY: event.clientY + }; + } + + function startScrub(clientY: number) { + if (!press || press.scrubbing) return; + if (press.timer) clearTimeout(press.timer); + press.timer = null; + press.scrubbing = true; + const center = activeIdx === -1 ? items.length - 1 : activeIdx; + press.baseIdx = press.dotIdx >= 0 ? press.dotIdx : center; + press.baseY = press.y0; + press.extremeY = clientY; + try { + pillEl?.setPointerCapture(press.pointerId); + } catch { + // The pointer is already gone; the up/cancel handler cleans up. + } + scrub = { idx: press.baseIdx, y: clientY, cancel: false }; + buzz(); + moveScrub(press.x0, clientY); + } + + /** Continuous prompt offset for a finger travel: linear first, then accelerating. */ + function travelToSteps(px: number): number { + const n = Math.abs(px) / STEP_PX; + const steps = n <= LINEAR_STEPS ? n : LINEAR_STEPS + (n - LINEAR_STEPS) * (1 + (n - LINEAR_STEPS) / LINEAR_STEPS); + return Math.sign(px) * steps; + } + + function moveScrub(clientX: number, clientY: number) { + if (!press || !scrub) return; + const last = items.length - 1; + + // Turning around re-bases the slide on the current prompt. + const moved = clientY - press.extremeY; + if (press.dir === 0) { + if (Math.abs(clientY - press.baseY) > 2) { + press.dir = Math.sign(clientY - press.baseY); + press.extremeY = clientY; + } + } else if (Math.sign(moved) === press.dir) { + press.extremeY = clientY; + } else if (Math.abs(moved) > TURN_PX) { + press.baseY = press.extremeY; + press.baseIdx = scrub.idx; + press.dir = -press.dir; + press.extremeY = clientY; + } + + const target = Math.max(0, Math.min(last, press.baseIdx + travelToSteps(clientY - press.baseY))); + let idx = Math.min(scrub.idx, last); + if (Math.abs(target - idx) >= 0.5 + HYSTERESIS) idx = Math.round(target); + const cancel = press.x0 - clientX > CANCEL_PX; + if (idx !== scrub.idx) buzz(); + scrub = { idx, y: clientY, cancel }; + } + + function onPressMove(event: PointerEvent) { + if (!press || event.pointerId !== press.pointerId) return; + if (!press.scrubbing) { + const dist = Math.hypot(event.clientX - press.x0, event.clientY - press.y0); + if (dist > SLOP_PX) startScrub(event.clientY); + return; + } + moveScrub(event.clientX, event.clientY); + } + + function onPressEnd(event: PointerEvent) { + if (!press || event.pointerId !== press.pointerId) return; + const ended = press; + const current = scrub; + endPress(); + if (ended.scrubbing) { + suppressClickUntil = Date.now() + SUPPRESS_CLICK_MS; + if (current && !current.cancel && items[current.idx]) jumpTo(items[current.idx]); + return; + } + // A tap on a dot jumps right away; a tap on a chevron or ellipsis is + // left to its own click handler. + if (ended.dotIdx >= 0 && items[ended.dotIdx]) { + suppressClickUntil = Date.now() + SUPPRESS_CLICK_MS; + jumpTo(items[ended.dotIdx]); + } + } + + function onPressCancel(event: PointerEvent) { + if (!press || event.pointerId !== press.pointerId) return; + if (press.scrubbing) suppressClickUntil = Date.now() + SUPPRESS_CLICK_MS; + endPress(); + } + + function endPress() { + if (press?.timer) clearTimeout(press.timer); + press = null; + scrub = null; + } + + function buzz() { + try { + navigator.vibrate?.(6); + } catch { + // Not allowed here — the preview change is feedback enough. + } + } + + function onContextMenu(event: Event) { + // A long press would otherwise open the browser's context menu. + if (press) event.preventDefault(); + } + + // --- Scrub preview card --- + + const scrubItem = $derived(scrub ? items[scrub.idx] ?? null : null); + const scrubPrev = $derived(scrub && scrub.idx > 0 ? items[scrub.idx - 1] : null); + const scrubNext = $derived(scrub && scrub.idx < items.length - 1 ? items[scrub.idx + 1] : null); + + const previewTop = $derived.by(() => { + if (!scrub || !bandEl) return 0; + const bandTop = bandEl.getBoundingClientRect().top; + const wanted = scrub.y - bandTop - previewHeight / 2; + return Math.max(0, Math.min(wanted, Math.max(0, bandHeight - previewHeight))); + }); {#snippet tooltip(item: NavItem)} @@ -191,77 +567,132 @@
{/snippet} +{#snippet spinner(size: string)} + +{/snippet} + {#if items.length >= 1}
+ + {/if} {#if !isUserAtBottom}