Skip to content

The agent that grows with you

fix(desktop): preserve reading intent across history and pane changes

brooklyn!3ccad12c0ae1
diff --git a/apps/desktop/src/app/chat/composer/index.tsx b/apps/desktop/src/app/chat/composer/index.tsx
index 9c1b4ed3819..cb0a16cb379 100644
--- a/apps/desktop/src/app/chat/composer/index.tsx
+++ b/apps/desktop/src/app/chat/composer/index.tsx
@@ -16,7 +16,7 @@ import { PR_COMMENT_URL_RE } from '@/lib/chat-runtime'
import { sanitizeComposerInput } from '@/lib/composer-input-sanitize'
import { DATA_IMAGE_URL_RE } from '@/lib/embedded-images'
import { triggerHaptic } from '@/lib/haptics'
-import { useStoresSelector } from '@/lib/use-session-slice'
+import { useStoreSelector, useStoresSelector } from '@/lib/use-session-slice'
import { cn } from '@/lib/utils'
import { interceptsTypedVoiceStop } from '@/lib/voice-stop-word'
import { sessionCompacting } from '@/store/compaction'
@@ -28,7 +28,7 @@ import { sessionBlockingPrompt } from '@/store/prompts'
import { toggleReview } from '@/store/review'
import { $gatewayState } from '@/store/session'
import { $botChatSessionIds, $sessionStates, $sessionTiles, isBotChatSession } from '@/store/session-states'
-import { $threadScrolledUp } from '@/store/thread-scroll'
+import { $threadScrolledUpBySession } from '@/store/thread-scroll'
import { $autoSpeakReplies } from '@/store/voice-prefs'
import { useTheme } from '@/themes'
@@ -80,7 +80,7 @@ import {
normalizeComposerEditorDom,
RICH_INPUT_SLOT
} from './rich-editor'
-import { useComposerScope } from './scope'
+import { useComposerScope, useComposerSurfaceId } from './scope'
import { ComposerStatusStack } from './status-stack'
import { CodingStatusRow } from './status-stack/coding-row'
import { SuggestionPills } from './suggestion-pills'
@@ -175,7 +175,13 @@ export function ChatBar({
const scope = useComposerScope()
const attachments = useStore(scope.attachments.$attachments)
const compacting = useStore(useMemo(() => sessionCompacting(sessionId ?? null), [sessionId]))
- const scrolledUp = useStore($threadScrolledUp)
+ const surfaceId = useComposerSurfaceId()
+ const scrollSessionId = sessionId ?? surfaceId
+
+ const scrolledUp = useStoreSelector($threadScrolledUpBySession, map =>
+ Boolean(scrollSessionId && map[scrollSessionId])
+ )
+
const autoSpeak = useStore($autoSpeakReplies)
// The turn is parked on the user (clarify / approval / sudo / secret). Esc must
// not interrupt it — there's nothing actively running to stop, and stopping
diff --git a/apps/desktop/src/app/chat/composer/status-stack/index.test.tsx b/apps/desktop/src/app/chat/composer/status-stack/index.test.tsx
index 63d18f0af70..19849105039 100644
--- a/apps/desktop/src/app/chat/composer/status-stack/index.test.tsx
+++ b/apps/desktop/src/app/chat/composer/status-stack/index.test.tsx
@@ -3,7 +3,7 @@ import { MemoryRouter } from 'react-router'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { I18nProvider } from '@/i18n'
-import { $threadScrolledUp, resetThreadScroll } from '@/store/thread-scroll'
+import { resetThreadScroll, setThreadAtBottom } from '@/store/thread-scroll'
import { ComposerStatusStack } from './index'
@@ -17,19 +17,20 @@ vi.stubGlobal('ResizeObserver', TestResizeObserver)
describe('ComposerStatusStack scroll treatment', () => {
beforeEach(() => {
- $threadScrolledUp.set(true)
+ setThreadAtBottom(false, 'sess-a')
})
afterEach(() => {
cleanup()
- resetThreadScroll()
+ resetThreadScroll('sess-a')
})
it('dims only the status content while keeping the dock card opaque', () => {
const view = render(
<MemoryRouter>
<I18nProvider configClient={null} initialLocale="en">
- <ComposerStatusStack queue={<div>Queued task</div>} sessionId={null} />
+ <ComposerStatusStack queue={<div>Queued task</div>} sessionId="sess-a" />
+ <ComposerStatusStack queue={<div>Sibling task</div>} sessionId="sess-b" />
</I18nProvider>
</MemoryRouter>
)
@@ -42,5 +43,6 @@ describe('ComposerStatusStack scroll treatment', () => {
expect(dimmedContent).not.toBeNull()
expect(dimmedContent).not.toBe(card)
expect(card?.contains(dimmedContent)).toBe(true)
+ expect(screen.getByText('Sibling task').closest('.opacity-30')).toBeNull()
})
})
diff --git a/apps/desktop/src/app/chat/composer/status-stack/index.tsx b/apps/desktop/src/app/chat/composer/status-stack/index.tsx
index 877150cedd5..104689fc030 100644
--- a/apps/desktop/src/app/chat/composer/status-stack/index.tsx
+++ b/apps/desktop/src/app/chat/composer/status-stack/index.tsx
@@ -3,6 +3,7 @@ import { type ReactNode, useEffect, useMemo } from 'react'
import { useNavigate } from 'react-router'
import { blurComposerInput } from '@/app/chat/composer/focus'
+import { useComposerSurfaceId } from '@/app/chat/composer/scope'
import { AGENTS_ROUTE } from '@/app/routes'
import type { SubmitTextOptions } from '@/app/session/hooks/use-prompt-actions/utils'
import { BillingBanner } from '@/components/billing-banner'
@@ -15,7 +16,7 @@ import { Codicon } from '@/components/ui/codicon'
import { GlyphSpinner } from '@/components/ui/glyph-spinner'
import { Tip, TipKeybindLabel } from '@/components/ui/tooltip'
import { type Translations, useI18n } from '@/i18n'
-import { useSessionSlice } from '@/lib/use-session-slice'
+import { useSessionSlice, useStoreSelector } from '@/lib/use-session-slice'
import { cn } from '@/lib/utils'
import { $billingBlock } from '@/store/billing-block'
import {
@@ -30,7 +31,7 @@ import {
import { $freeTierRoute, $freeTierStatus, freeTierStripPending } from '@/store/free-tier'
import { $previewStatusBySession, dismissPreviewArtifact } from '@/store/preview-status'
import { $sessionControlBySession, refreshSessionControl } from '@/store/session-control'
-import { $threadScrolledUp } from '@/store/thread-scroll'
+import { $threadScrolledUpBySession } from '@/store/thread-scroll'
import { openSessionInNewWindow } from '@/store/windows'
import { PreviewStatusRow } from './preview-row'
@@ -107,7 +108,13 @@ export function ComposerStatusStack({ onSubmit, queue, sessionId }: ComposerStat
const previews = useSessionSlice($previewStatusBySession, sessionId)
const controlEntry = useSessionValue($sessionControlBySession, sessionId)
- const scrolledUp = useStore($threadScrolledUp)
+ const surfaceId = useComposerSurfaceId()
+ const scrollSessionId = sessionId ?? surfaceId
+
+ const scrolledUp = useStoreSelector($threadScrolledUpBySession, map =>
+ Boolean(scrollSessionId && map[scrollSessionId])
+ )
+
const billing = useStore($billingBlock)
const freeTierStatus = useStore($freeTierStatus)
const freeTierRoute = useStore($freeTierRoute)
diff --git a/apps/desktop/src/app/chat/index.tsx b/apps/desktop/src/app/chat/index.tsx
index 899596a3a60..c7e529d6077 100644
--- a/apps/desktop/src/app/chat/index.tsx
+++ b/apps/desktop/src/app/chat/index.tsx
@@ -234,7 +234,7 @@ function useMessagesWhileVisible($messages: ReadableAtom<ChatMessage[]>): ChatMe
* of re-rendering them by element identity and the stream's render cost stays
* confined to the streaming message's own subtree.
*/
-function ChatRuntimeBoundary({
+export function ChatRuntimeBoundary({
busy,
children,
onCancel,
@@ -306,38 +306,54 @@ function ChatRuntimeBoundary({
const tailState = storedId && transcriptTailStates ? transcriptTailState(storedId, tailProfile) : undefined
const restBackfillAvailable = Boolean(tailState?.possiblyTruncated)
- const expandWindow = useCallback(() => {
- // The store window still holds older messages: growing pages is enough.
- // Otherwise the whole in-memory transcript is already materialized — if
- // the REST tail hydration was truncated, fetch the next older page and
- // PREPEND it to the session store before growing, so the grown window has
- // something older to show. Fire-and-forget: the prepend lands through the
- // session-state write path and re-renders this boundary.
- if (
- !windowStateRef.current.get(runtimeIdRef.current ?? '')?.state.window.windowed &&
- runtimeId &&
- storedId &&
- transcriptBackfillAvailable(storedId, tailProfile)
- ) {
- void backfillOlderTranscriptPage({
- storedSessionId: storedId,
- profile: tailProfile,
- // Stale-response guard: a session switch remounts/re-keys this view;
- // checking the live atoms (not captured props) discards a page that
- // resolves after the user moved on — same pattern as isCurrentResume.
- isCurrent: () => view.$storedId.get() === storedId && view.$runtimeId.get() === runtimeId,
- applyOlderPage: olderPage => {
- sessionTileDelegate()?.updateSession(runtimeId, state => {
- const merged = mergeOlderTranscriptPage(state.messages, olderPage)
-
- return merged === state.messages ? state : { ...state, messages: merged }
- })
- }
- })
- }
+ const expandWindow = useCallback(
+ async (beforePrepend?: () => void) => {
+ // Network latency is not scroll intent. Capture at arrival, immediately
+ // before the store prepend, and only grow a window that has a page to show.
+ if (
+ !windowStateRef.current.get(runtimeIdRef.current ?? '')?.state.window.windowed &&
+ runtimeId &&
+ storedId &&
+ transcriptBackfillAvailable(storedId, tailProfile)
+ ) {
+ let grew = false
+ await backfillOlderTranscriptPage({
+ storedSessionId: storedId,
+ profile: tailProfile,
+ // Stale-response guard: a session switch remounts/re-keys this view;
+ // checking the live atoms (not captured props) discards a page that
+ // resolves after the user moved on — same pattern as isCurrentResume.
+ isCurrent: () => view.$storedId.get() === storedId && view.$runtimeId.get() === runtimeId,
+ applyOlderPage: olderPage => {
+ const current = view.$messages.get()
+
+ if (mergeOlderTranscriptPage(current, olderPage) === current) {
+ return
+ }
+
+ beforePrepend?.()
+ setWindowPages(pages => pages + 1)
+ sessionTileDelegate()?.updateSession(runtimeId, state => {
+ const merged = mergeOlderTranscriptPage(state.messages, olderPage)
+ grew = merged !== state.messages
+
+ return grew ? { ...state, messages: merged } : state
+ })
+ }
+ })
+
+ // Exhaustion and overlapping-only pages have no structural publication.
+ // Do not leave the list waiting for a commit that will never arrive.
+ return grew
+ }
- setWindowPages(pages => pages + 1)
- }, [runtimeId, storedId, tailProfile, view])
+ beforePrepend?.()
+ setWindowPages(pages => pages + 1)
+
+ return true
+ },
+ [runtimeId, storedId, tailProfile, view]
+ )
const olderAvailable = windowed || restBackfillAvailable
@@ -726,6 +742,7 @@ const ChatViewContent = memo(function ChatViewContent({
onCancel={haltRun}
onDismissError={onDismissError}
onRestoreToMessage={onRestoreToMessage}
+ scrollProfile={modelOptionsProfile || activeGatewayProfile}
sessionId={activeSessionId}
sessionKey={threadKey}
/>
diff --git a/apps/desktop/src/app/chat/runtime-backfill.test.tsx b/apps/desktop/src/app/chat/runtime-backfill.test.tsx
new file mode 100644
index 00000000000..1a04b502c92
--- /dev/null
+++ b/apps/desktop/src/app/chat/runtime-backfill.test.tsx
@@ -0,0 +1,112 @@
+import { act, render } from '@testing-library/react'
+import { atom } from 'nanostores'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { stubThreadEnvironment } from '@/components/assistant-ui/test-utils'
+import { type TranscriptWindowValue, useTranscriptWindow } from '@/components/assistant-ui/thread/transcript-window'
+import type * as HermesApi from '@/hermes'
+import type { ChatMessage } from '@/lib/chat-messages'
+import type * as SessionStates from '@/store/session-states'
+import { $transcriptTailBySessionId, recordTranscriptTail } from '@/store/transcript-tail'
+
+import { PRIMARY_SESSION_VIEW, SessionViewProvider } from './session-view'
+import { _resetTranscriptBackfillForTests } from './transcript-backfill'
+
+import { ChatRuntimeBoundary } from '.'
+
+vi.mock('@/hermes', async importOriginal => ({
+ ...(await importOriginal<typeof HermesApi>()),
+ getOlderSessionMessages: vi.fn()
+}))
+vi.mock('@/store/session-states', async importOriginal => ({
+ ...(await importOriginal<typeof SessionStates>()),
+ sessionTileDelegate: vi.fn()
+}))
+const { getOlderSessionMessages } = await import('@/hermes')
+const { sessionTileDelegate } = await import('@/store/session-states')
+stubThreadEnvironment()
+
+const message = (id: string): ChatMessage => ({ id, role: 'user', parts: [{ type: 'text', text: id }] })
+
+beforeEach(() => {
+ $transcriptTailBySessionId.set({})
+ _resetTranscriptBackfillForTests()
+ vi.mocked(getOlderSessionMessages).mockReset()
+})
+
+describe('runtime older-page expansion', () => {
+ it.each([true, false])(
+ 'captures only a page that adds history, after its network wait (adds rows: %s)',
+ async addsRows => {
+ const $messages = atom([message('tail')])
+
+ const view = {
+ ...PRIMARY_SESSION_VIEW,
+ $messages,
+ $runtimeId: atom<string | null>('runtime'),
+ $storedId: atom<string | null>('stored')
+ }
+
+ recordTranscriptTail('stored', {
+ messages: Array.from({ length: 120 }, (_, index) => ({
+ id: index + 120,
+ role: 'user' as const,
+ content: 'tail',
+ timestamp: index + 2000
+ })),
+ pagination: { limit: 120, offset: 0, order: 'latest', returned: 120 }
+ })
+ let resolvePage!: (value: unknown) => void
+ vi.mocked(getOlderSessionMessages).mockReturnValue(
+ new Promise(resolve => {
+ resolvePage = resolve
+ }) as never
+ )
+ const events: string[] = []
+ vi.mocked(sessionTileDelegate).mockReturnValue({
+ updateSession: (_id: string, update: (state: { messages: ChatMessage[] }) => { messages: ChatMessage[] }) => {
+ events.push('apply')
+ $messages.set(update({ messages: $messages.get() }).messages)
+ }
+ } as never)
+ let window!: TranscriptWindowValue
+
+ function Observe() {
+ window = useTranscriptWindow()
+
+ return null
+ }
+
+ render(
+ <SessionViewProvider value={view}>
+ <ChatRuntimeBoundary
+ busy={false}
+ onCancel={() => {}}
+ onEdit={async () => {}}
+ onReload={async () => {}}
+ onThreadMessagesChange={() => {}}
+ suppressMessages={false}
+ >
+ <Observe />
+ </ChatRuntimeBoundary>
+ </SessionViewProvider>
+ )
+ let pending: unknown
+ act(() => {
+ pending = window.expandWindow(() => events.push('anchor'))
+ })
+ expect(pending).toBeInstanceOf(Promise)
+ expect(events).toEqual([])
+ await act(async () => {
+ resolvePage({
+ session_id: 'stored',
+ messages: addsRows ? [{ id: 1, role: 'user', content: 'older', timestamp: 1000 }] : [],
+ pagination: { limit: 120, offset: 120, order: 'latest', returned: 1 }
+ })
+ expect(await pending).toBe(addsRows)
+ })
+ expect(events).toEqual(addsRows ? ['anchor', 'apply'] : [])
+ expect($messages.get()).toHaveLength(addsRows ? 2 : 1)
+ }
+ )
+})
diff --git a/apps/desktop/src/app/chat/scroll-to-bottom-button.test.tsx b/apps/desktop/src/app/chat/scroll-to-bottom-button.test.tsx
index 16b173c8f75..dc94fee8034 100644
--- a/apps/desktop/src/app/chat/scroll-to-bottom-button.test.tsx
+++ b/apps/desktop/src/app/chat/scroll-to-bottom-button.test.tsx
@@ -10,6 +10,7 @@ import {
setThreadAtBottom
} from '@/store/thread-scroll'
+import { ComposerSurfaceProvider } from './composer/scope'
import { ScrollToBottomButton } from './scroll-to-bottom-button'
function pendingApproval() {
@@ -20,23 +21,79 @@ function pendingApproval() {
afterEach(() => {
cleanup()
clearAllPrompts()
- resetThreadScroll()
+
+ for (const id of ['sess-1', 'sess-a', 'sess-b', 'tile-runtime', 'surface-a', 'surface-b']) {
+ resetThreadScroll(id)
+ }
+
$activeSessionId.set(null)
})
// `getByRole('button')` excludes aria-hidden nodes, so "queryByRole null" is the
// control's hidden (parked-at-bottom) state.
describe('ScrollToBottomButton', () => {
+ it('isolates pre-runtime panes using their existing composer surface identity', () => {
+ setThreadAtBottom(false, 'surface-a')
+ publishThreadMessagesBelow(4, { paneVisible: true, sessionId: 'surface-a' })
+ const first = vi.fn()
+ const second = vi.fn()
+ const stopFirst = onScrollToBottomRequest(first, 'surface-a')
+ const stopSecond = onScrollToBottomRequest(second, 'surface-b')
+ render(
+ <>
+ <ComposerSurfaceProvider value="surface-a">
+ <ScrollToBottomButton sessionId={null} />
+ </ComposerSurfaceProvider>
+ <ComposerSurfaceProvider value="surface-b">
+ <ScrollToBottomButton sessionId={null} />
+ </ComposerSurfaceProvider>
+ </>
+ )
+
+ expect(screen.getAllByRole('button')).toHaveLength(1)
+ fireEvent.click(screen.getByRole('button', { name: 'Scroll to bottom · 4 messages' }))
+ expect(first).toHaveBeenCalledOnce()
+ expect(second).not.toHaveBeenCalled()
+ stopFirst()
+ stopSecond()
+ })
+
+ it('does not light a sibling pane when only one visible session scrolls up', () => {
+ setThreadAtBottom(false, 'sess-a')
+ render(<ScrollToBottomButton sessionId="sess-b" />)
+
+ expect(screen.queryByRole('button')).toBeNull()
+ })
+
+ it("keeps each visible pane's message count when its sibling publishes or unmounts", () => {
+ setThreadAtBottom(false, 'sess-a')
+ setThreadAtBottom(false, 'sess-b')
+ publishThreadMessagesBelow(12, { paneVisible: true, sessionId: 'sess-a' })
+ publishThreadMessagesBelow(3, { paneVisible: true, sessionId: 'sess-b' })
+ render(
+ <>
+ <ScrollToBottomButton sessionId="sess-a" />
+ <ScrollToBottomButton sessionId="sess-b" />
+ </>
+ )
+
+ expect(screen.getByRole('button', { name: 'Scroll to bottom · 12 messages' })).toBeTruthy()
+ expect(screen.getByRole('button', { name: 'Scroll to bottom · 3 messages' })).toBeTruthy()
+ act(() => resetThreadScroll('sess-b'))
+ expect(screen.getByRole('button', { name: 'Scroll to bottom · 12 messages' })).toBeTruthy()
+ expect(screen.queryByRole('button', { name: 'Scroll to bottom · 3 messages' })).toBeNull()
+ })
+
it('stays hidden while parked at the bottom', () => {
- render(<ScrollToBottomButton sessionId={null} />)
+ render(<ScrollToBottomButton sessionId="sess-1" />)
expect(screen.queryByRole('button')).toBeNull()
})
it('shows the messages below the viewport when scrolled up with no approval', () => {
- setThreadAtBottom(false)
- publishThreadMessagesBelow(12, { paneVisible: true })
- render(<ScrollToBottomButton sessionId={null} />)
+ setThreadAtBottom(false, 'sess-1')
+ publishThreadMessagesBelow(12, { paneVisible: true, sessionId: 'sess-1' })
+ render(<ScrollToBottomButton sessionId="sess-1" />)
expect(screen.getByRole('button', { name: 'Scroll to bottom · 12 messages' }).textContent).toBe('12 messages')
expect(screen.queryByText('Approval needed')).toBeNull()
@@ -44,7 +101,7 @@ describe('ScrollToBottomButton', () => {
it('morphs into the approval pill when scrolled up with a pending approval', () => {
pendingApproval()
- setThreadAtBottom(false)
+ setThreadAtBottom(false, 'sess-1')
render(<ScrollToBottomButton sessionId="sess-1" />)
expect(screen.getByRole('button', { name: 'Approval needed' })).toBeTruthy()
@@ -53,7 +110,7 @@ describe('ScrollToBottomButton', () => {
it('does not morph while a pending approval is still in view (at bottom)', () => {
pendingApproval()
- render(<ScrollToBottomButton sessionId={null} />)
+ render(<ScrollToBottomButton sessionId="sess-1" />)
// Parked at bottom → control hidden, so it can't claim "approval needed".
expect(screen.queryByRole('button')).toBeNull()
@@ -61,7 +118,8 @@ describe('ScrollToBottomButton', () => {
it('labels uncounted content without zero and follows only its own approval', () => {
pendingApproval()
- setThreadAtBottom(false)
+ setThreadAtBottom(false, 'sess-1')
+ setThreadAtBottom(false, 'tile-runtime')
const view = render(<ScrollToBottomButton sessionId="tile-runtime" />)
expect(screen.getByRole('button', { name: 'Scroll to bottom' }).textContent).toBe('Scroll to bottom')
@@ -78,7 +136,7 @@ describe('ScrollToBottomButton', () => {
it('re-arms sticky-bottom on click', () => {
const handler = vi.fn()
const stop = onScrollToBottomRequest(handler, 'sess-1')
- setThreadAtBottom(false)
+ setThreadAtBottom(false, 'sess-1')
render(<ScrollToBottomButton sessionId="sess-1" />)
fireEvent.click(screen.getByRole('button'))
diff --git a/apps/desktop/src/app/chat/scroll-to-bottom-button.tsx b/apps/desktop/src/app/chat/scroll-to-bottom-button.tsx
index 4ff648315d0..589e50e1772 100644
--- a/apps/desktop/src/app/chat/scroll-to-bottom-button.tsx
+++ b/apps/desktop/src/app/chat/scroll-to-bottom-button.tsx
@@ -6,9 +6,16 @@ import { Codicon } from '@/components/ui/codicon'
import { AnimatedInt } from '@/components/ui/diff-count'
import { useI18n } from '@/i18n'
import { triggerHaptic } from '@/lib/haptics'
+import { useStoreSelector } from '@/lib/use-session-slice'
import { cn } from '@/lib/utils'
import { sessionApprovalRequest } from '@/store/prompts'
-import { $threadJumpButtonVisible, $threadMessagesBelow, requestScrollToBottom } from '@/store/thread-scroll'
+import {
+ $threadJumpButtonVisibleBySession,
+ $threadMessagesBelowBySession,
+ requestScrollToBottom
+} from '@/store/thread-scroll'
+
+import { useComposerSurfaceId } from './composer/scope'
/**
* Floating "jump to bottom" control. Sits centered just above the composer,
@@ -33,8 +40,17 @@ import { $threadJumpButtonVisible, $threadMessagesBelow, requestScrollToBottom }
*/
export function ScrollToBottomButton({ sessionId }: { sessionId: string | null }) {
const { t } = useI18n()
- const visible = useStore($threadJumpButtonVisible)
- const count = useStore($threadMessagesBelow)
+ const surfaceId = useComposerSurfaceId()
+ const scrollSessionId = sessionId ?? surfaceId
+
+ const visible = useStoreSelector($threadJumpButtonVisibleBySession, map =>
+ Boolean(scrollSessionId && map[scrollSessionId])
+ )
+
+ const count = useStoreSelector($threadMessagesBelowBySession, map =>
+ scrollSessionId ? (map[scrollSessionId] ?? 0) : 0
+ )
+
const reducedMotion = useReducedMotion()
const request = useStore(useMemo(() => sessionApprovalRequest(sessionId), [sessionId]))
// Scrolled away while an approval is pending → the inline Run/Reject bar is
@@ -71,7 +87,7 @@ export function ScrollToBottomButton({ sessionId }: { sessionId: string | null }
data-state={state}
onClick={() => {
triggerHaptic('selection')
- requestScrollToBottom(sessionId)
+ requestScrollToBottom(scrollSessionId)
}}
style={{
bottom: 'calc(var(--composer-measured-height) + 1rem)'
diff --git a/apps/desktop/src/app/chat/transcript-backfill.test.ts b/apps/desktop/src/app/chat/transcript-backfill.test.ts
index 733c114cc62..c8d327a58a7 100644
--- a/apps/desktop/src/app/chat/transcript-backfill.test.ts
+++ b/apps/desktop/src/app/chat/transcript-backfill.test.ts
@@ -289,6 +289,38 @@ describe('backfillOlderTranscriptPage', () => {
expect(transcriptTailState('stored-1')).toMatchObject({ nextOffset: 120, possiblyTruncated: true })
})
+ it('discards an older page when the same session tail was replaced during the fetch', async () => {
+ truncatedTail()
+ let resolvePage!: (value: unknown) => void
+ vi.mocked(getOlderSessionMessages).mockReturnValue(
+ new Promise(resolve => {
+ resolvePage = resolve
+ }) as never
+ )
+ const applyOlderPage = vi.fn()
+
+ const pending = backfillOlderTranscriptPage({
+ storedSessionId: 'stored-1',
+ isCurrent: () => true,
+ applyOlderPage
+ })
+
+ // Rewind/revalidation replaced the display tail without changing the route.
+ recordTranscriptTail('stored-1', {
+ messages: [row(900, 'replacement')],
+ pagination: { limit: 120, offset: 0, order: 'latest', returned: 1 }
+ })
+ resolvePage({
+ messages: [row(1, 'stale older row')],
+ pagination: { limit: 120, offset: 120, order: 'latest', returned: 1 },
+ session_id: 'stored-1'
+ })
+
+ expect(await pending).toBe(false)
+ expect(applyOlderPage).not.toHaveBeenCalled()
+ expect(transcriptTailState('stored-1')).toMatchObject({ nextOffset: 1, possiblyTruncated: false })
+ })
+
it('shares one in-flight fetch per stored session', async () => {
truncatedTail()
diff --git a/apps/desktop/src/app/chat/transcript-backfill.ts b/apps/desktop/src/app/chat/transcript-backfill.ts
index c7151ec59fb..ca354ce3209 100644
--- a/apps/desktop/src/app/chat/transcript-backfill.ts
+++ b/apps/desktop/src/app/chat/transcript-backfill.ts
@@ -147,10 +147,10 @@ export function backfillOlderTranscriptPage(request: BackfillRequest): Promise<b
return false
}
- // Session switched while the page was in flight: discard it entirely.
- // The bookkeeping stays untouched so a later re-visit (which re-records
- // the tail on hydration anyway) starts from consistent state.
- if (!request.isCurrent()) {
+ // A route can stay put while rewind or revalidation replaces its tail.
+ // This page belongs to the exact tail generation we fetched against, not
+ // merely the same stored id. Never graft it onto a newer display history.
+ if (!request.isCurrent() || transcriptTailState(storedSessionId, profile) !== tail) {
return false
}
diff --git a/apps/desktop/src/components/assistant-ui/thread/index.tsx b/apps/desktop/src/components/assistant-ui/thread/index.tsx
index fe0a1c73942..d16f924c24b 100644
--- a/apps/desktop/src/components/assistant-ui/thread/index.tsx
+++ b/apps/desktop/src/components/assistant-ui/thread/index.tsx
@@ -45,6 +45,7 @@ interface ThreadProps {
onRestoreToMessage?: (messageId: string, target?: RestoreMessageTarget) => Promise<void> | void
sessionId?: string | null
sessionKey?: string | null
+ scrollProfile?: string
}
// memo'd on purpose, and load-bearing for session-switch cost. ChatView
@@ -65,6 +66,7 @@ export const Thread = memo(function Thread({
onDismissError,
onRestoreToMessage,
sessionId = null,
+ scrollProfile,
sessionKey
}: ThreadProps) {
const { t } = useI18n()
@@ -175,6 +177,7 @@ export const Thread = memo(function Thread({
components={messageComponents}
emptyPlaceholder={emptyPlaceholder}
loadingIndicator={loadingIndicator}
+ scrollProfile={scrollProfile}
sessionId={sessionId}
sessionKey={sessionKey}
/>
diff --git a/apps/desktop/src/components/assistant-ui/thread/list-restore-composer-resize.test.tsx b/apps/desktop/src/components/assistant-ui/thread/list-restore-composer-resize.test.tsx
new file mode 100644
index 00000000000..b937bd87912
--- /dev/null
+++ b/apps/desktop/src/components/assistant-ui/thread/list-restore-composer-resize.test.tsx
@@ -0,0 +1,209 @@
+import { AssistantRuntimeProvider, type ThreadMessage, useExternalStoreRuntime } from '@assistant-ui/react'
+import { act, render } from '@testing-library/react'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { rescopeConnectionScopedStores } from '@/lib/connection-scoped'
+import { setActiveProfile } from '@/store/profile'
+import { saveThreadScrollPosition, threadScrollTargetTop } from '@/store/thread-scroll'
+
+import { stubThreadEnvironment, stubThreadViewportSize } from '../test-utils'
+
+import { Thread } from '.'
+
+const observers = new Set<{ fire: () => void }>()
+
+class TestResizeObserver {
+ private readonly callback: ResizeObserverCallback
+
+ constructor(callback: ResizeObserverCallback) {
+ this.callback = callback
+ observers.add(this)
+ }
+
+ disconnect() {
+ observers.delete(this)
+ }
+
+ fire() {
+ const target = document.body
+ this.callback(
+ [
+ {
+ borderBoxSize: [],
+ contentBoxSize: [],
+ contentRect: {
+ bottom: 1,
+ height: 1,
+ left: 0,
+ right: 1,
+ toJSON: () => ({}),
+ top: 0,
+ width: 1,
+ x: 0,
+ y: 0
+ } as DOMRect,
+ devicePixelContentBoxSize: [],
+ target
+ } as ResizeObserverEntry
+ ],
+ this as unknown as ResizeObserver
+ )
+ }
+
+ observe() {}
+ unobserve() {}
+}
+
+stubThreadEnvironment()
+vi.stubGlobal('ResizeObserver', TestResizeObserver)
+stubThreadViewportSize()
+
+const SCROLL_H = 5000
+const CLIENT_H = 600
+const FROM_BOTTOM = 800
+const VIEWPORT_SLOT = 'aui_thread-viewport'
+const CLEARANCE_SLOT = 'aui_composer-clearance'
+
+let viewportScrollHeight = SCROLL_H
+let viewportClientHeight = CLIENT_H
+let clearanceHeight = 120
+
+Object.defineProperty(HTMLElement.prototype, 'scrollHeight', {
+ configurable: true,
+ get() {
+ return viewportScrollHeight
+ }
+})
+Object.defineProperty(HTMLElement.prototype, 'clientHeight', {
+ configurable: true,
+ get() {
+ if (this.getAttribute?.('data-slot') === CLEARANCE_SLOT) {
+ return clearanceHeight
+ }
+
+ return viewportClientHeight
+ }
+})
+
+beforeEach(() => {
+ viewportScrollHeight = SCROLL_H
+ viewportClientHeight = CLIENT_H
+ clearanceHeight = 120
+ observers.clear()
+ window.localStorage.clear()
+ setActiveProfile('default')
+ rescopeConnectionScopedStores(null)
+})
+
+function viewportEl(container: HTMLElement): HTMLElement {
+ const el = container.querySelector(`[data-slot="${VIEWPORT_SLOT}"]`) as HTMLElement | null
+ expect(el).toBeTruthy()
+
+ return el!
+}
+
+function fireContentResizes() {
+ act(() => {
+ for (const observer of [...observers]) {
+ observer.fire()
+ }
+ })
+}
+
+async function settleScroll(ticks = 3) {
+ await act(async () => {
+ for (let tick = 0; tick < ticks; tick += 1) {
+ await new Promise<void>(resolve => window.setTimeout(resolve, 0))
+ }
+ })
+}
+
+const createdAt = new Date('2026-08-01T00:00:00.000Z')
+
+function sessionMessages(key: string, turns = 1): ThreadMessage[] {
+ return Array.from({ length: turns }, (_, index) => [
+ {
+ id: `u-${key}-${index}`,
+ role: 'user',
+ content: [{ type: 'text', text: `message ${index} in ${key}` }],
+ attachments: [],
+ createdAt,
+ metadata: { custom: {} }
+ } as ThreadMessage,
+ {
+ id: `a-${key}-${index}`,
+ role: 'assistant',
+ content: [{ type: 'text', text: `response ${index} in ${key}` }],
+ status: { type: 'complete', reason: 'stop' },
+ createdAt,
+ metadata: { unstable_state: null, unstable_annotations: [], unstable_data: [], steps: [], custom: {} }
+ } as ThreadMessage
+ ]).flat()
+}
+
+function ScrollHarness({ messages, sessionKey }: { messages: ThreadMessage[]; sessionKey: string | null }) {
+ const runtime = useExternalStoreRuntime<ThreadMessage>({
+ isRunning: false,
+ messages,
+ onNew: async () => {}
+ })
+
+ return (
+ <AssistantRuntimeProvider runtime={runtime}>
+ <Thread clampToComposer sessionKey={sessionKey} />
+ </AssistantRuntimeProvider>
+ )
+}
+
+describe('list post-settle restore vs composer-only resize', () => {
+ it('follows pre-settle async layout before the next animation frame can paint', () => {
+ const raf = vi.spyOn(globalThis, 'requestAnimationFrame').mockImplementation(() => 0)
+
+ try {
+ const { container, unmount } = render(<ScrollHarness messages={sessionMessages('cold')} sessionKey="cold" />)
+ const vp = viewportEl(container)
+ viewportScrollHeight += 146
+ fireContentResizes()
+ expect(vp.scrollTop).toBe(viewportScrollHeight - CLIENT_H)
+ unmount()
+ } finally {
+ raf.mockRestore()
+ }
+ })
+
+ it('does not rewrite scrollTop when only composer clearance grows; content growth still restores', async () => {
+ saveThreadScrollPosition('a', { fromBottom: FROM_BOTTOM, kind: 'offset' })
+
+ const { container } = render(<ScrollHarness messages={sessionMessages('a')} sessionKey="a" />)
+ const vp = viewportEl(container)
+
+ await settleScroll()
+
+ const restoredTop = SCROLL_H - CLIENT_H - FROM_BOTTOM
+ expect(vp.scrollTop).toBe(restoredTop)
+
+ const userRoot = container.querySelector('[data-slot="aui_user-message-root"]')
+ expect(userRoot).toBeTruthy()
+ expect(container.querySelector(`[data-slot="${CLEARANCE_SLOT}"]`)).toBeTruthy()
+
+ // Composer-only: clearance + viewport box move together; transcript rows do not.
+ viewportScrollHeight = SCROLL_H + 80
+ viewportClientHeight = CLIENT_H - 80
+ clearanceHeight = 200
+ fireContentResizes()
+
+ expect(vp.scrollTop).toBe(restoredTop)
+ expect(container.querySelector('[data-slot="aui_user-message-root"]')).toBe(userRoot)
+
+ // CONTROL: real transcript growth must still re-pin the frozen fromBottom.
+ viewportScrollHeight = SCROLL_H + 80 + 600
+ fireContentResizes()
+
+ expect(vp.scrollTop).toBe(
+ threadScrollTargetTop(
+ { fromBottom: FROM_BOTTOM, kind: 'offset' },
+ { clientHeight: viewportClientHeight, scrollHeight: viewportScrollHeight }
+ )
+ )
+ })
+})
diff --git a/apps/desktop/src/components/assistant-ui/thread/list-session-scroll.test.tsx b/apps/desktop/src/components/assistant-ui/thread/list-session-scroll.test.tsx
index ad1b6a57d30..6ca349e85c3 100644
--- a/apps/desktop/src/components/assistant-ui/thread/list-session-scroll.test.tsx
+++ b/apps/desktop/src/components/assistant-ui/thread/list-session-scroll.test.tsx
@@ -1,13 +1,21 @@
import { AssistantRuntimeProvider, type ThreadMessage, useExternalStoreRuntime } from '@assistant-ui/react'
-import { act, render } from '@testing-library/react'
-import { beforeEach, describe, expect, it } from 'vitest'
+import { act, render, waitFor } from '@testing-library/react'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { PaneLifecycleContext, PaneVisibleContext } from '@/components/pane-shell/pane-visibility'
import { rescopeConnectionScopedStores } from '@/lib/connection-scoped'
import { setActiveProfile } from '@/store/profile'
-import { saveThreadScrollPosition } from '@/store/thread-scroll'
+import {
+ getThreadScrollPosition,
+ requestScrollToBottom,
+ saveThreadScrollPosition,
+ threadScrollStorageKey
+} from '@/store/thread-scroll'
import { stubThreadEnvironment, stubThreadViewportSize } from '../test-utils'
+import { TranscriptWindowProvider, type TranscriptWindowValue } from './transcript-window'
+
import { Thread } from '.'
stubThreadEnvironment()
@@ -80,9 +88,12 @@ function sessionMessages(key: string, turns = 1): ThreadMessage[] {
interface ScrollHarnessProps {
messages: ThreadMessage[]
sessionKey: string | null
+ scrollProfile?: string
+ sessionId?: string | null
+ window?: TranscriptWindowValue
}
-function ScrollHarness({ messages, sessionKey }: ScrollHarnessProps) {
+function ScrollHarness({ messages, sessionKey, scrollProfile, sessionId, window }: ScrollHarnessProps) {
const runtime = useExternalStoreRuntime<ThreadMessage>({
isRunning: false,
messages,
@@ -91,7 +102,9 @@ function ScrollHarness({ messages, sessionKey }: ScrollHarnessProps) {
return (
<AssistantRuntimeProvider runtime={runtime}>
- <Thread sessionKey={sessionKey} />
+ <TranscriptWindowProvider value={window ?? { olderAvailable: false, expandWindow: () => {} }}>
+ <Thread scrollProfile={scrollProfile} sessionId={sessionId} sessionKey={sessionKey} />
+ </TranscriptWindowProvider>
</AssistantRuntimeProvider>
)
}
@@ -131,42 +144,517 @@ describe('list session-scroll restore', () => {
}
})
+ it.each([0, 800])('restores a kept-alive pane after hidden layout drift (offset %i)', async offset => {
+ if (offset) {
+ saveThreadScrollPosition('a', { fromBottom: offset, kind: 'offset' })
+ }
+ const messages = sessionMessages('a')
+
+ const pane = (visible: boolean) => (
+ <PaneVisibleContext.Provider value={visible}>
+ <PaneLifecycleContext.Provider value={visible ? 'visible' : 'hot-hidden'}>
+ <ScrollHarness messages={messages} sessionKey="a" />
+ </PaneLifecycleContext.Provider>
+ </PaneVisibleContext.Provider>
+ )
+
+ const { container, rerender } = render(pane(true))
+ await settleScroll()
+ const vp = viewportEl(container)
+ expect(vp.scrollTop).toBe(SCROLL_H - CLIENT_H - offset)
+ rerender(pane(false))
+ // A hidden pane's smaller render budget / background refresh changes its
+ // layout. These browser scroll events are not a new reading position.
+ act(() => {
+ vp.scrollTop = 300
+ vp.dispatchEvent(new Event('scroll'))
+ })
+ await settleScroll()
+ rerender(pane(true))
+ await settleScroll()
+ expect(vp.scrollTop).toBe(SCROLL_H - CLIENT_H - offset)
+ })
+
+ it.each([0, 800])('preserves position through repeated reveals with late resize (offset %i)', async offset => {
+ const previousObserver = globalThis.ResizeObserver
+ const observers = new Set<{ callback: ResizeObserverCallback; targets: Set<Element> }>()
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ targets = new Set<Element>()
+ constructor(public callback: ResizeObserverCallback) {
+ observers.add(this)
+ }
+ observe(target: Element) {
+ this.targets.add(target)
+ }
+ unobserve(target: Element) {
+ this.targets.delete(target)
+ }
+ disconnect() {
+ this.targets.clear()
+ }
+ }
+ )
+
+ if (offset) {
+ saveThreadScrollPosition('a', { fromBottom: offset, kind: 'offset' })
+ }
+ const messages = sessionMessages('a')
+ let runtimeId: string | null = null
+
+ const pane = (visible: boolean) => (
+ <PaneVisibleContext.Provider value={visible}>
+ <PaneLifecycleContext.Provider value={visible ? 'visible' : 'hot-hidden'}>
+ <ScrollHarness messages={messages} sessionId={runtimeId} sessionKey="a" />
+ </PaneLifecycleContext.Provider>
+ </PaneVisibleContext.Provider>
+ )
+
+ const { container, rerender, unmount } = render(pane(true))
+
+ try {
+ const vp = viewportEl(container)
+ await settleScroll(10)
+
+ for (let round = 0; round < 4; round++) {
+ if (round === 2) {
+ runtimeId = 'runtime-a'
+ rerender(pane(true))
+ await settleScroll(3)
+ }
+
+ // Deferred markdown finishes after the initial restore handed off.
+ // Switch away in the same frame, before the library's queued follow.
+ act(() => {
+ scrollHeightValue += 1000
+
+ for (const observer of observers) {
+ const targets = [...observer.targets].filter(el => el.getAttribute('data-slot') === 'aui_thread-content')
+
+ if (targets.length) {
+ observer.callback(
+ targets.map(target => ({
+ target,
+ contentRect: { height: scrollHeightValue }
+ })) as ResizeObserverEntry[],
+ observer as unknown as ResizeObserver
+ )
+ }
+ }
+ })
+ rerender(pane(false))
+ await settleScroll(10)
+ rerender(pane(true))
+ await settleScroll(10)
+ expect(vp.scrollTop).toBeGreaterThanOrEqual(scrollHeightValue - CLIENT_H - offset - 1)
+ expect(vp.scrollTop).toBeLessThanOrEqual(scrollHeightValue - CLIENT_H - offset)
+ }
+
+ // User input ends resize protection; a real reading position still wins.
+ act(() => {
+ vp.dispatchEvent(new Event('pointerdown'))
+ vp.scrollTop -= 800
+ vp.dispatchEvent(new Event('scroll'))
+ })
+ await settleScroll(10)
+ const readingTop = vp.scrollTop
+ rerender(pane(false))
+ await settleScroll(10)
+ rerender(pane(true))
+ await settleScroll(10)
+ expect(vp.scrollTop).toBe(readingTop)
+ // Returning to the latest message must replace the old reading target,
+ // including late resizes after the jump cancelled offset restoration.
+ act(() => requestScrollToBottom(runtimeId))
+ await settleScroll(10)
+ expect(vp.scrollTop).toBeGreaterThanOrEqual(scrollHeightValue - CLIENT_H - 1)
+ act(() => vp.dispatchEvent(new Event('scroll')))
+
+ for (let round = 0; round < 3; round++) {
+ act(() => {
+ scrollHeightValue += 1000
+
+ for (const observer of observers) {
+ const targets = [...observer.targets].filter(el => el.getAttribute('data-slot') === 'aui_thread-content')
+
+ if (targets.length) {
+ observer.callback(
+ targets.map(target => ({
+ target,
+ contentRect: { height: scrollHeightValue }
+ })) as ResizeObserverEntry[],
+ observer as unknown as ResizeObserver
+ )
+ }
+ }
+ })
+ rerender(pane(false))
+ await settleScroll(10)
+ rerender(pane(true))
+ await settleScroll(10)
+ expect(vp.scrollTop).toBeGreaterThanOrEqual(scrollHeightValue - CLIENT_H - 1)
+ }
+ } finally {
+ unmount()
+ vi.stubGlobal('ResizeObserver', previousObserver)
+ }
+ })
+
+ it.each([true, false])('keeps scroll ownership when profile switches before visibility: %s', async profileFirst => {
+ saveThreadScrollPosition('a', { fromBottom: 800, kind: 'offset' })
+ const ownerKey = threadScrollStorageKey()
+ const messages = sessionMessages('a')
+
+ const pane = (visible: boolean) => (
+ <PaneVisibleContext.Provider value={visible}>
+ <PaneLifecycleContext.Provider value={visible ? 'visible' : 'hot-hidden'}>
+ <ScrollHarness messages={messages} sessionKey="a" />
+ </PaneLifecycleContext.Provider>
+ </PaneVisibleContext.Provider>
+ )
+
+ const { container, rerender } = render(pane(true))
+ await settleScroll(10)
+ const vp = viewportEl(container)
+
+ if (profileFirst) {
+ setActiveProfile('pr-bot')
+ }
+ rerender(pane(false))
+
+ if (!profileFirst) {
+ setActiveProfile('pr-bot')
+ }
+ const otherKey = threadScrollStorageKey()
+ await settleScroll(10)
+ // The selected global profile can still belong to the other Bot when the
+ // default Bot's kept-alive pane reveals. Its transcript owner did not change.
+ rerender(pane(true))
+ await settleScroll(10)
+ expect(vp.scrollTop).toBe(SCROLL_H - CLIENT_H - 800)
+ act(() => requestScrollToBottom())
+ await settleScroll(10)
+ rerender(pane(false))
+ await settleScroll(10)
+ expect(getThreadScrollPosition('a', ownerKey)).toEqual({ kind: 'bottom' })
+ expect(getThreadScrollPosition('a', otherKey)).toBeUndefined()
+ act(() => window.dispatchEvent(new Event('beforeunload')))
+ expect(getThreadScrollPosition('a', otherKey)).toBeUndefined()
+ setActiveProfile('default')
+ rerender(pane(true))
+ await settleScroll(10)
+ expect(vp.scrollTop).toBeGreaterThanOrEqual(SCROLL_H - CLIENT_H - 1)
+ })
+
+ it('restores remounted Bots from their explicit owners while a different profile is active', async () => {
+ const defaultKey = threadScrollStorageKey('default')
+ const otherKey = threadScrollStorageKey('pr-bot')
+ saveThreadScrollPosition('default-chat', { fromBottom: 800, kind: 'offset' }, defaultKey)
+ setActiveProfile('pr-bot')
+
+ const pane = (bot: string, epoch = 0) => (
+ <ScrollHarness
+ key={`${bot}:${epoch}`}
+ messages={sessionMessages(bot)}
+ scrollProfile={bot}
+ sessionKey={`${bot}-chat`}
+ />
+ )
+
+ const { container, rerender } = render(pane('default'))
+ await settleScroll(10)
+ expect(viewportEl(container).scrollTop).toBe(SCROLL_H - CLIENT_H - 800)
+ act(() => requestScrollToBottom())
+ await settleScroll(10)
+ act(() => window.dispatchEvent(new Event('beforeunload')))
+ expect(getThreadScrollPosition('default-chat', defaultKey)).toEqual({ kind: 'bottom' })
+ expect(getThreadScrollPosition('default-chat', otherKey)).toBeUndefined()
+
+ for (let round = 0; round < 3; round++) {
+ rerender(pane('pr-bot', round))
+ await settleScroll(10)
+ rerender(pane('default', round + 1))
+ await settleScroll(10)
+ expect(viewportEl(container).scrollTop).toBeGreaterThanOrEqual(SCROLL_H - CLIENT_H - 1)
+ }
+
+ expect(getThreadScrollPosition('default-chat', otherKey)).toBeUndefined()
+ })
+
+ it('re-arms restoration when a mounted transcript resolves a different owner profile', async () => {
+ saveThreadScrollPosition('a', { fromBottom: 800, kind: 'offset' }, threadScrollStorageKey('default'))
+ setActiveProfile('pr-bot')
+ const messages = sessionMessages('a')
+ const { container, rerender } = render(<ScrollHarness messages={messages} sessionKey="a" />)
+ await settleScroll(10)
+ rerender(<ScrollHarness messages={messages} scrollProfile="default" sessionKey="a" />)
+ await settleScroll(10)
+ expect(viewportEl(container).scrollTop).toBe(SCROLL_H - CLIENT_H - 800)
+ })
+
+ it('keeps bottom intent when content grows before a prepend and runtime binding', async () => {
+ const messages = sessionMessages('a', 60).map(message => ({
+ ...message,
+ content: [{ type: 'text', text: 'x'.repeat(5000) }] as const
+ }))
+
+ const { container, rerender, getByText } = render(<ScrollHarness messages={messages} sessionKey="a" />)
+ await settleScroll(20)
+ const vp = viewportEl(container)
+ expect(vp.scrollTop).toBeGreaterThanOrEqual(SCROLL_H - CLIENT_H - 1)
+ // Layout grew before the library's next-frame bottom follow, matching a
+ // delayed budget commit. A prepend must anchor the intended bottom.
+ scrollHeightValue += 3700
+ act(() => getByText('Show earlier messages').click())
+ rerender(<ScrollHarness messages={messages} sessionId="runtime-a" sessionKey="a" />)
+ await settleScroll(10)
+ expect(vp.scrollTop).toBeGreaterThanOrEqual(scrollHeightValue - CLIENT_H - 1)
+ })
+
it('keeps a clamped cold offset parked until the transcript is tall enough', async () => {
+ const pendingHistory = { olderAvailable: true, expandWindow: () => new Promise<boolean>(() => {}) }
saveThreadScrollPosition('b', { fromBottom: 800, kind: 'offset' })
scrollHeightValue = CLIENT_H
- const { container, rerender } = render(<ScrollHarness messages={[]} sessionKey="b" />)
+ const { container, rerender } = render(<ScrollHarness messages={[]} sessionKey="b" window={pendingHistory} />)
const vp = viewportEl(container)
await settleScroll()
scrollHeightValue = 1000
- rerender(<ScrollHarness messages={sessionMessages('b')} sessionKey="b" />)
+ rerender(<ScrollHarness messages={sessionMessages('b')} sessionKey="b" window={pendingHistory} />)
await settleScroll(20)
expect(vp.scrollTop).toBe(0)
- rerender(<ScrollHarness messages={sessionMessages('b', 2)} sessionKey="b" />)
+ rerender(<ScrollHarness messages={sessionMessages('b', 2)} sessionKey="b" window={pendingHistory} />)
await settleScroll()
expect(vp.scrollTop).toBe(0)
scrollHeightValue = 2000
- rerender(<ScrollHarness messages={sessionMessages('b', 3)} sessionKey="b" />)
+ rerender(<ScrollHarness messages={sessionMessages('b', 3)} sessionKey="b" window={pendingHistory} />)
await settleScroll()
expect(vp.scrollTop).toBe(2000 - CLIENT_H - 800)
saveThreadScrollPosition('c', { fromBottom: 800, kind: 'offset' })
scrollHeightValue = 1000
- rerender(<ScrollHarness messages={sessionMessages('c')} sessionKey="c" />)
+ rerender(<ScrollHarness messages={sessionMessages('c')} sessionKey="c" window={pendingHistory} />)
await settleScroll(20)
act(() => vp.dispatchEvent(new WheelEvent('wheel', { deltaY: -200, bubbles: true })))
scrollHeightValue = 2000
- rerender(<ScrollHarness messages={sessionMessages('c', 3)} sessionKey="c" />)
+ rerender(<ScrollHarness messages={sessionMessages('c', 3)} sessionKey="c" window={pendingHistory} />)
await settleScroll()
// jsdom has no native scroll anchoring; the browser probe checks the
// resulting reader position. Here the abandoned target must not return.
expect(vp.scrollTop).not.toBe(2000 - CLIENT_H - 800)
})
+
+ it('applies the load target in the commit that prepends rows, before another animation frame', async () => {
+ const raf = vi.spyOn(globalThis, 'requestAnimationFrame').mockImplementation(() => 0)
+
+ try {
+ const { container, rerender } = render(<ScrollHarness messages={sessionMessages('commit')} sessionKey="commit" />)
+ const vp = viewportEl(container)
+ expect(vp.scrollTop).toBe(SCROLL_H - CLIENT_H)
+ scrollHeightValue += 2000
+ rerender(<ScrollHarness messages={sessionMessages('commit', 2)} sessionKey="commit" />)
+ // Runtime publication is timer-batched; animation frames remain frozen.
+ await waitFor(() => expect(container.querySelectorAll('[data-slot="aui_message-group"]').length).toBe(2))
+ expect(vp.scrollTop).toBe(scrollHeightValue - CLIENT_H)
+ } finally {
+ raf.mockRestore()
+ }
+ })
+
+ it.each(['exhausted', 'failed'] as const)('releases an unreachable restore when history is %s', async outcome => {
+ saveThreadScrollPosition('lost', { fromBottom: 9000, kind: 'offset' })
+ const expandWindow = vi.fn(async () => false)
+ const history = { olderAvailable: outcome === 'failed', expandWindow }
+
+ const { container, getByText } = render(
+ <ScrollHarness messages={sessionMessages('lost')} sessionKey="lost" window={history} />
+ )
+
+ // Separate acts let the stepped budget and parked-target effects commit.
+ for (let step = 0; step < 5; step++) {
+ await settleScroll(20)
+ }
+ act(() => window.dispatchEvent(new Event('beforeunload')))
+ expect(getThreadScrollPosition('lost')).toEqual({ kind: 'offset', fromBottom: SCROLL_H - CLIENT_H })
+ expect(viewportEl(container).scrollTop).toBe(0)
+
+ if (outcome === 'failed') {
+ expect(expandWindow).toHaveBeenCalledTimes(1)
+ act(() => getByText('Show earlier messages').click())
+ await settleScroll(10)
+ expect(expandWindow).toHaveBeenCalledTimes(2)
+ }
+ })
+
+ it('lets downward wheel intent cancel a clamped restore before delayed history arrives', async () => {
+ saveThreadScrollPosition('cancel', { fromBottom: 9000, kind: 'offset' })
+ const history = { olderAvailable: true, expandWindow: () => new Promise<boolean>(() => {}) }
+
+ const { container, rerender } = render(
+ <ScrollHarness messages={sessionMessages('cancel')} sessionKey="cancel" window={history} />
+ )
+
+ await settleScroll(20)
+ const vp = viewportEl(container)
+ act(() => vp.dispatchEvent(new WheelEvent('wheel', { deltaY: 200, bubbles: true })))
+ scrollHeightValue = 12000
+ rerender(<ScrollHarness messages={sessionMessages('cancel', 2)} sessionKey="cancel" window={history} />)
+ await settleScroll(10)
+ expect(vp.scrollTop).not.toBe(12000 - CLIENT_H - 9000)
+ })
+
+ it('captures the current reader at async page arrival and ignores an outgoing page after switching', async () => {
+ let finish!: (applied: boolean) => void
+ let capture: (() => void) | undefined
+
+ const expandWindow = vi.fn((before?: () => void) => {
+ capture = before
+
+ return new Promise<boolean>(resolve => {
+ finish = resolve
+ })
+ })
+
+ const history = { olderAvailable: true, expandWindow }
+
+ const { container, rerender, getByText } = render(
+ <ScrollHarness messages={sessionMessages('arrival')} sessionKey="arrival" window={history} />
+ )
+
+ await settleScroll(10)
+ const vp = viewportEl(container)
+ act(() => {
+ vp.dispatchEvent(new Event('pointerdown'))
+ vp.scrollTop = 300
+ vp.dispatchEvent(new Event('scroll'))
+ getByText('Show earlier messages').click()
+ })
+ await settleScroll(10)
+ act(() => {
+ vp.scrollTop = 800
+ vp.dispatchEvent(new Event('scroll'))
+ capture?.()
+ scrollHeightValue += 2000
+ rerender(<ScrollHarness messages={sessionMessages('arrival', 2)} sessionKey="arrival" window={history} />)
+ finish(true)
+ })
+ await settleScroll(10)
+ expect(vp.scrollTop).toBe(2800)
+ act(() => getByText('Show earlier messages').click())
+ rerender(<ScrollHarness messages={sessionMessages('next')} sessionKey="next" />)
+ await settleScroll(10)
+ const nextTop = vp.scrollTop
+ act(() => {
+ capture?.()
+ finish(true)
+ })
+ await settleScroll(10)
+ expect(vp.scrollTop).toBe(nextTop)
+ })
+
+ it('waits for a history page before requesting another or spending the restore budget', async () => {
+ saveThreadScrollPosition('async', { fromBottom: 9000, kind: 'offset' })
+ let finish!: (applied: boolean) => void
+ let beforePrepend: (() => void) | undefined
+
+ const expandWindow = vi.fn((capture?: () => void) => {
+ beforePrepend = capture
+
+ return new Promise<boolean>(resolve => {
+ finish = resolve
+ })
+ })
+
+ const window = { olderAvailable: true, expandWindow }
+
+ const { container, rerender } = render(
+ <ScrollHarness messages={sessionMessages('async')} sessionKey="async" window={window} />
+ )
+
+ await waitFor(() => expect(expandWindow).toHaveBeenCalled())
+ expect(expandWindow).toHaveBeenCalledTimes(1)
+ await settleScroll(120)
+ expect(expandWindow).toHaveBeenCalledTimes(1)
+ expect(viewportEl(container).scrollTop).toBe(0)
+ act(() => {
+ beforePrepend?.()
+ finish(true)
+ })
+ // RPC completion can precede the runtime's batched publication.
+ await settleScroll(20)
+ expect(expandWindow).toHaveBeenCalledTimes(1)
+ act(() => {
+ scrollHeightValue = 12000
+ rerender(<ScrollHarness messages={sessionMessages('async', 3)} sessionKey="async" window={window} />)
+ finish(true)
+ })
+ await settleScroll(20)
+ expect(viewportEl(container).scrollTop).toBe(12000 - CLIENT_H - 9000)
+ expect(expandWindow).toHaveBeenCalledTimes(1)
+ })
+
+ it('spends pages to regrow toward a saved offset the mounted window cannot cover', async () => {
+ // Heavy turns so the transcript is windowed by the render budget; a saved
+ // offset far below the mounted window must auto-spend pages (the same
+ // Show-earlier path) instead of stranding at the clamped top.
+ const heavy = 'x'.repeat(5000)
+
+ const messages = Array.from({ length: 60 }, (_, i) => [
+ {
+ id: `u-${i}`,
+ role: 'user',
+ content: [{ type: 'text', text: heavy }],
+ attachments: [],
+ createdAt,
+ metadata: { custom: {} }
+ } as ThreadMessage,
+ {
+ id: `a-${i}`,
+ role: 'assistant',
+ content: [{ type: 'text', text: heavy }],
+ status: { type: 'complete', reason: 'stop' },
+ createdAt,
+ metadata: { unstable_state: null, unstable_annotations: [], unstable_data: [], steps: [], custom: {} }
+ } as ThreadMessage
+ ]).flat()
+
+ // Control: no saved offset — the default window stays capped.
+ const ctl = render(<ScrollHarness messages={messages} sessionKey="ctl" />)
+
+ const stableGroups = async (container: HTMLElement) => {
+ let count = container.querySelectorAll('[data-slot="aui_message-group"]').length
+
+ for (let round = 0; round < 25; round += 1) {
+ await settleScroll(10)
+ const next = container.querySelectorAll('[data-slot="aui_message-group"]').length
+
+ if (next === count) {
+ return count
+ }
+
+ count = next
+ }
+
+ return count
+ }
+
+ const ctlGroups = await stableGroups(ctl.container)
+ ctl.unmount()
+
+ // Deep saved offset — the regrow effect spends pages toward it.
+ saveThreadScrollPosition('regrow', { fromBottom: 999999, kind: 'offset' })
+ const deep = render(<ScrollHarness messages={messages} sessionKey="regrow" />)
+ const deepGroups = await stableGroups(deep.container)
+
+ expect(ctlGroups).toBeGreaterThan(0)
+ expect(deepGroups).toBeGreaterThan(ctlGroups)
+ })
})
diff --git a/apps/desktop/src/components/assistant-ui/thread/list.tsx b/apps/desktop/src/components/assistant-ui/thread/list.tsx
index edd63de406f..a934eea87fa 100644
--- a/apps/desktop/src/components/assistant-ui/thread/list.tsx
+++ b/apps/desktop/src/components/assistant-ui/thread/list.tsx
@@ -17,6 +17,7 @@ import {
} from 'react'
import { type GetTargetScrollTop, useStickToBottom } from 'use-stick-to-bottom'
+import { useComposerSurfaceId } from '@/app/chat/composer/scope'
import { usePaneLifecycle, usePaneVisible } from '@/components/pane-shell/pane-visibility'
import { useI18n } from '@/i18n'
import { messagePaintWeight } from '@/lib/render-weight'
@@ -30,7 +31,9 @@ import {
publishThreadAtBottom,
resetPublishedThreadScroll,
saveThreadScrollPosition,
+ shouldReapplyFrozenThreadScrollOffset,
THREAD_SCROLL_BOTTOM,
+ type ThreadScrollRestoreResizeMetrics,
type ThreadScrollState,
threadScrollStateFromMetrics,
threadScrollStorageKey,
@@ -138,6 +141,12 @@ export const shouldAnchorBeforePrepend = (settled: boolean, target: ThreadScroll
// still well under the measured 780ms single-jump freeze.
const BACKFILL_STEP = 290
+// Auto-spent budget pages while a parked reading offset waits for the tree
+// to cover it (see the grow effect). The real bound is the transcript
+// itself; this only stops a truncated-window fetch that never lands from
+// re-arming forever.
+const PARKED_OFFSET_MAX_PAGES = 96
+
export const transcriptBackfillFrameCount = (
firstPaint = FIRST_PAINT_BUDGET,
step = BACKFILL_STEP,
@@ -224,6 +233,7 @@ interface ThreadMessageListProps {
loadingIndicator?: ReactNode
sessionId?: string | null
sessionKey?: string | null
+ scrollProfile?: string
}
// Group each user message with the assistant turn(s) that follow it so the
@@ -414,6 +424,7 @@ const ThreadMessageListInner: FC<ThreadMessageListProps> = ({
emptyPlaceholder,
loadingIndicator,
sessionId = null,
+ scrollProfile,
sessionKey
}) => {
// TWO signatures, deliberately split. The STRUCTURAL one (ids/roles/count)
@@ -516,6 +527,15 @@ const ThreadMessageListInner: FC<ThreadMessageListProps> = ({
// step may anchor while the load is still unsettled.
const loadTargetRef = useRef<ThreadScrollState>(THREAD_SCROLL_BOTTOM)
const cancelRestoreRef = useRef<(() => void) | null>(null)
+ const applyRestoreRef = useRef<(() => void) | null>(null)
+ // Pages auto-spent toward the current parked offset; reset at each park.
+ const autoGrowPagesRef = useRef(0)
+ // Bumped when the settle loop parks an offset, so the grow effect below
+ // re-runs with fresh state even when no other dependency changed.
+ const [restoreGrowTick, setRestoreGrowTick] = useState(0)
+ const windowRequestRef = useRef<object | null>(null)
+ const windowCommitRef = useRef<string | null>(null)
+ const jumpRestoreRef = useRef<(() => void) | null>(null)
const isRunning = useAuiState(s => s.thread.isRunning)
// Session the settle loop last armed for, so a re-arm within the same load
// is distinguishable from a switch to a different transcript.
@@ -537,7 +557,9 @@ const ThreadMessageListInner: FC<ThreadMessageListProps> = ({
return
}
- restoreFromBottomRef.current = el.scrollHeight - el.scrollTop
+ // Preserve bottom intent rather than a temporary gap before resize-follow.
+ restoreFromBottomRef.current =
+ liveScrollStateRef.current.kind === 'bottom' ? el.clientHeight : el.scrollHeight - el.scrollTop
anchorHeightRef.current = el.scrollHeight
}, [scrollRef])
@@ -644,11 +666,29 @@ const ThreadMessageListInner: FC<ThreadMessageListProps> = ({
? 'pt-[calc(var(--titlebar-height)+0.75rem)]'
: 'pt-[calc(var(--titlebar-height)-0.5rem)]'
- useEffect(() => publishThreadAtBottom(isAtBottom, { paneVisible }), [isAtBottom, paneVisible])
- useEffect(() => () => resetPublishedThreadScroll({ paneVisible }), [paneVisible])
+ const surfaceId = useComposerSurfaceId()
+ const scrollSessionId = sessionId ?? surfaceId
+ useEffect(
+ () => publishThreadAtBottom(isAtBottom, { paneVisible, sessionId: scrollSessionId }),
+ [isAtBottom, paneVisible, scrollSessionId]
+ )
+ useEffect(
+ () => () => resetPublishedThreadScroll({ paneVisible, sessionId: scrollSessionId }),
+ [paneVisible, scrollSessionId]
+ )
// Floating jump button (outside this subtree) → return to the bottom.
- useEffect(() => onScrollToBottomRequest(() => void scrollToBottom(), sessionId), [scrollToBottom, sessionId])
+ useEffect(
+ () =>
+ onScrollToBottomRequest(() => {
+ if (jumpRestoreRef.current) {
+ jumpRestoreRef.current()
+ } else {
+ void scrollToBottom()
+ }
+ }, scrollSessionId),
+ [scrollToBottom, scrollSessionId]
+ )
// Waking from display: hidden (HUD mode hides the main window; OS hide does
// the same to any window): rAF and ResizeObserver may have been frozen, so
@@ -705,6 +745,21 @@ const ThreadMessageListInner: FC<ThreadMessageListProps> = ({
// highlight, the budget backfill) changes scrollHeight WITHOUT a scroll
// event, so a scroll-only cache records a stale offset (the gap #70478's
// review threads flagged). Both legs write stateFromMetrics(el).
+ // Bind persistence to this transcript, not whichever Bot most recently
+ // changed the global profile. Visibility changes do not transfer ownership.
+ const [scrollOwner, setScrollOwner] = useState(() => ({
+ sessionKey,
+ profile: scrollProfile,
+ storageKey: threadScrollStorageKey(scrollProfile)
+ }))
+
+ if (scrollOwner.sessionKey !== sessionKey || scrollOwner.profile !== scrollProfile) {
+ setScrollOwner({ sessionKey, profile: scrollProfile, storageKey: threadScrollStorageKey(scrollProfile) })
+ }
+
+ const scrollStorageKey = scrollOwner.storageKey
+ const restoredStorageKeyRef = useRef(scrollStorageKey)
+
const liveScrollStateRef = useRef<ThreadScrollState>(THREAD_SCROLL_BOTTOM)
// Key the restore loop has already applied to the current transcript — the
// record gate: an instance records only the state it actually showed under
@@ -717,7 +772,7 @@ const ThreadMessageListInner: FC<ThreadMessageListProps> = ({
const el = scrollRef.current
const content = contentRef.current
- if (!el || !content) {
+ if (!el || !content || !paneVisible) {
return
}
@@ -733,7 +788,7 @@ const ThreadMessageListInner: FC<ThreadMessageListProps> = ({
el.removeEventListener('scroll', update)
observer.disconnect()
}
- }, [contentRef, scrollRef])
+ }, [contentRef, paneVisible, scrollRef])
// Persist the live position on app close, so a reading position survives a
// quit without a session switch (the switch cleanup below only runs on
@@ -741,7 +796,7 @@ const ThreadMessageListInner: FC<ThreadMessageListProps> = ({
// settled gate — a close mid-settle must not persist transient clamped
// metrics.
useEffect(() => {
- const storageKey = threadScrollStorageKey()
+ const storageKey = scrollStorageKey
const flush = () => {
if (sessionKey && loadSettledRef.current && restoredContentKeyRef.current === sessionKey) {
@@ -752,7 +807,7 @@ const ThreadMessageListInner: FC<ThreadMessageListProps> = ({
window.addEventListener('beforeunload', flush)
return () => window.removeEventListener('beforeunload', flush)
- }, [sessionKey])
+ }, [scrollStorageKey, sessionKey])
// Reset the cap and restore the remembered scroll state on mount + every
// session switch (messages swap in place on a long-lived runtime, so
@@ -784,11 +839,29 @@ const ThreadMessageListInner: FC<ThreadMessageListProps> = ({
return
}
+ // A kept-alive Bot pane can shrink its render budget or refresh messages
+ // while hidden. Preserve its last visible position, not that background
+ // layout, and re-arm the normal restore loop when the pane is revealed.
+ // The outgoing visible effect's cleanup has already saved its position.
+ if (!paneVisible) {
+ loadSettledRef.current = false
+ restoredContentKeyRef.current = null
+ restoreFromBottomRef.current = null
+
+ return
+ }
+
// Cleanup belongs to the subscription owner, not the newly active globals.
- const storageKey = threadScrollStorageKey()
- const sessionSwitched = settleKeyRef.current !== sessionKey
+ const storageKey = scrollStorageKey
+ const sessionSwitched = settleKeyRef.current !== sessionKey || restoredStorageKeyRef.current !== storageKey
+ restoredStorageKeyRef.current = storageKey
- const plan = planThreadScrollRestore(restoredContentKeyRef.current, sessionKey, hasGroups, loadSettledRef.current)
+ const plan = planThreadScrollRestore(
+ sessionSwitched ? undefined : restoredContentKeyRef.current,
+ sessionKey,
+ hasGroups,
+ loadSettledRef.current
+ )
restoredContentKeyRef.current = plan.gate
@@ -829,7 +902,7 @@ const ThreadMessageListInner: FC<ThreadMessageListProps> = ({
}
const remembered = sessionKey ? getThreadScrollPosition(sessionKey, storageKey) : undefined
- const target = remembered ?? THREAD_SCROLL_BOTTOM
+ let target = remembered ?? THREAD_SCROLL_BOTTOM
// The previous session's parting state must not leak into this one: from
// here every scroll/RO event describes the restored session.
@@ -837,7 +910,12 @@ const ThreadMessageListInner: FC<ThreadMessageListProps> = ({
loadTargetRef.current = target
stopScroll()
- el.scrollTop = threadScrollTargetTop(target, el)
+
+ applyRestoreRef.current = () => {
+ el.scrollTop = threadScrollTargetTop(target, el)
+ }
+
+ applyRestoreRef.current()
loadSettledRef.current = false
// An anchor captured for the OUTGOING transcript must not be applied to
@@ -889,6 +967,9 @@ const ThreadMessageListInner: FC<ThreadMessageListProps> = ({
// effect flips settled once it consumes the parked value.
restoreFromBottomRef.current = target.fromBottom + node.clientHeight
anchorHeightRef.current = height
+ // Wake paging even when the current render budget has stopped growing.
+ autoGrowPagesRef.current = 0
+ setRestoreGrowTick(tick => tick + 1)
} else {
loadSettledRef.current = true
}
@@ -903,9 +984,34 @@ const ThreadMessageListInner: FC<ThreadMessageListProps> = ({
// Quiet frames are not layout completion: deferred Markdown and intrinsic
// row measurements can change height after the initial settle. Retain the
- // restored offset through those resizes until input or a live run takes over.
+ // restored target through those resizes until input or a live run takes over.
+ // Bottom needs the same protection: the library follows on the next frame,
+ // but a switch in this frame would otherwise persist the temporary gap.
+ const restoreResizeMetrics = (): ThreadScrollRestoreResizeMetrics => {
+ const clearance = contentRef.current?.querySelector('[data-slot="aui_composer-clearance"]')
+
+ return {
+ clearanceHeight: clearance instanceof HTMLElement ? clearance.clientHeight : 0,
+ clientHeight: el.clientHeight,
+ scrollHeight: el.scrollHeight
+ }
+ }
+
+ let lastRestoreMetrics = restoreResizeMetrics()
+
const resizeObserver = new ResizeObserver(() => {
- if (target.kind === 'offset' && loadSettledRef.current) {
+ const next = restoreResizeMetrics()
+ const previous = lastRestoreMetrics
+ lastRestoreMetrics = next
+
+ // ResizeObserver runs before paint; waiting for the next settle rAF
+ // exposes a frame at the old offset when deferred markdown grows.
+ // Reading offsets still ignore composer-only resizes once settled.
+ if (
+ !loadSettledRef.current ||
+ target.kind === 'bottom' ||
+ shouldReapplyFrozenThreadScrollOffset(target, true, previous, next)
+ ) {
el.scrollTop = threadScrollTargetTop(target, el)
liveScrollStateRef.current = threadScrollStateFromMetrics(el)
}
@@ -916,6 +1022,7 @@ const ThreadMessageListInner: FC<ThreadMessageListProps> = ({
}
const cancelRestore = () => {
+ applyRestoreRef.current = null
resizeObserver.disconnect()
cancelAnimationFrame(rafId)
@@ -935,27 +1042,48 @@ const ThreadMessageListInner: FC<ThreadMessageListProps> = ({
const onWheel = (event: WheelEvent) => {
resizeObserver.disconnect()
- if (event.deltaY < 0) {
+ if (event.deltaY !== 0) {
cancelRestore()
}
}
- const unsubscribeJump = onScrollToBottomRequest(cancelRestore, sessionId)
+ jumpRestoreRef.current = () => {
+ cancelRestore()
+ // A jump replaces reading intent, including an in-flight prepend anchor.
+ // Re-arm resize protection: deferred markdown may grow after this click.
+ target = THREAD_SCROLL_BOTTOM
+ restoreFromBottomRef.current = null
+ liveScrollStateRef.current = target
+
+ applyRestoreRef.current = () => {
+ el.scrollTop = threadScrollTargetTop(target, el)
+ }
+
+ loadSettledRef.current = true
+ el.scrollTop = threadScrollTargetTop(target, el)
+
+ if (contentRef.current) {
+ resizeObserver.observe(contentRef.current)
+ }
+ void scrollToBottom('instant')
+ }
+
el.addEventListener('wheel', onWheel, { passive: true })
el.addEventListener('pointerdown', cancelRestore, { passive: true })
el.addEventListener('keydown', cancelRestore)
return () => {
cancelRestoreRef.current = null
+ applyRestoreRef.current = null
resizeObserver.disconnect()
- unsubscribeJump()
+ jumpRestoreRef.current = null
el.removeEventListener('wheel', onWheel)
el.removeEventListener('pointerdown', cancelRestore)
el.removeEventListener('keydown', cancelRestore)
cancelAnimationFrame(rafId)
record()
}
- }, [contentRef, hasGroups, scrollRef, scrollToBottom, sessionId, sessionKey, stopScroll])
+ }, [contentRef, hasGroups, paneVisible, scrollRef, scrollStorageKey, scrollToBottom, sessionKey, stopScroll])
// A thread can mount with a run already active, without a runStart event.
useEffect(() => {
@@ -964,6 +1092,67 @@ const ThreadMessageListInner: FC<ThreadMessageListProps> = ({
}
}, [hasGroups, isRunning, sessionKey])
+ // A window request owns no position while in flight. Capture at application
+ // time, when the reader may be somewhere else. A session/visibility change
+ // invalidates the callback, including an old promise resolving after reveal.
+ useLayoutEffect(
+ () => () => {
+ windowRequestRef.current = null
+ windowCommitRef.current = null
+ },
+ [paneVisible, scrollStorageKey, sessionKey]
+ )
+
+ const releaseParkedRestore = useCallback(() => {
+ if (!loadSettledRef.current && restoreFromBottomRef.current != null) {
+ cancelRestoreRef.current?.()
+ restoreFromBottomRef.current = null
+ }
+ }, [])
+
+ const growWindow = useCallback(async () => {
+ if (!paneVisible || windowRequestRef.current || windowCommitRef.current != null) {
+ return
+ }
+
+ const request = {}
+ windowRequestRef.current = request
+ let captured = false
+
+ try {
+ const applied = await expandWindow(() => {
+ if (windowRequestRef.current !== request) {
+ return
+ }
+
+ captured = true
+ windowCommitRef.current = structuralSignature
+ anchorBeforePrepend()
+ setRenderBudget(budget => budget + paneBudget)
+ })
+
+ if (windowRequestRef.current === request) {
+ if (applied === false || !captured) {
+ windowCommitRef.current = null
+ releaseParkedRestore()
+ } else {
+ autoGrowPagesRef.current += 1
+ }
+ }
+ } catch {
+ // The existing Show earlier button remains the explicit retry path.
+ if (windowRequestRef.current === request) {
+ windowCommitRef.current = null
+ releaseParkedRestore()
+ }
+ } finally {
+ if (windowRequestRef.current === request) {
+ windowRequestRef.current = null
+ setRestoreGrowTick(tick => tick + 1)
+ }
+ }
+ }, [anchorBeforePrepend, expandWindow, paneBudget, paneVisible, releaseParkedRestore, structuralSignature])
+
// Prepend an older page while preserving the on-screen position. The user is
// scrolled up (reading history) so the stick-to-bottom lock is escaped and
// won't fight this manual restore. Spend the already-materialized DOM page
@@ -976,15 +1165,13 @@ const ThreadMessageListInner: FC<ThreadMessageListProps> = ({
return
}
- anchorBeforePrepend()
- // Both paths grow the DOM budget by one pane page. Windowed rows are older
- // than the current page, so expand-without-grow paints nothing.
- setRenderBudget(budget => budget + paneBudget)
-
if (action === 'window') {
- expandWindow()
+ void growWindow()
+ } else {
+ anchorBeforePrepend()
+ setRenderBudget(budget => budget + paneBudget)
}
- }, [anchorBeforePrepend, expandWindow, hiddenCount, olderAvailable, paneBudget])
+ }, [anchorBeforePrepend, growWindow, hiddenCount, olderAvailable, paneBudget])
// Scroll/wheel at the top edge pages older turns through the same showEarlier
// path as the button. Wheel is required because browsers emit no `scroll`
@@ -1027,6 +1214,17 @@ const ThreadMessageListInner: FC<ThreadMessageListProps> = ({
const el = scrollRef.current
const restoreFromBottom = restoreFromBottomRef.current
+ if (windowCommitRef.current === structuralSignature) {
+ return
+ }
+
+ windowCommitRef.current = null
+
+ // Apply load intent in the commit, without spending an unchanged anchor.
+ if (paneVisible && (restoreFromBottom == null || liveScrollStateRef.current.kind === 'bottom')) {
+ applyRestoreRef.current?.()
+ }
+
if (
el &&
restoreFromBottom != null &&
@@ -1040,7 +1238,57 @@ const ThreadMessageListInner: FC<ThreadMessageListProps> = ({
loadSettledRef.current = true
}
// renderBudget covers DOM pages; groups.length covers store-window expands.
- }, [scrollRef, renderBudget, groups.length])
+ }, [scrollRef, renderBudget, structuralSignature, paneVisible])
+
+ // Regrow toward a parked reading offset through the existing paging path.
+ // Keep its target intact until reachable; exhaustion releases it at the
+ // nearest available position rather than leaving restoration stuck forever.
+ useLayoutEffect(() => {
+ const el = scrollRef.current
+ const restoreFromBottom = restoreFromBottomRef.current
+
+ if (!el || restoreFromBottom == null || el.scrollHeight >= restoreFromBottom) {
+ return
+ }
+
+ // Wait for the stepped backfill to top out first: while it is still
+ // climbing the tree may cover the offset on its own, and racing it would
+ // only hoard pages. A hidden pane stays put entirely — its budget is
+ // clamped to the live tail and the reveal re-runs this effect.
+ if (renderBudget < paneBudget || !paneVisible) {
+ return
+ }
+
+ const action = resolveShowEarlierAction(hiddenCount, olderAvailable)
+
+ if (!action || autoGrowPagesRef.current >= PARKED_OFFSET_MAX_PAGES) {
+ releaseParkedRestore()
+
+ return
+ }
+
+ if (windowRequestRef.current) {
+ return
+ }
+
+ if (action === 'window') {
+ void growWindow()
+ } else {
+ autoGrowPagesRef.current += 1
+ startTransition(() => setRenderBudget(budget => budget + paneBudget))
+ }
+ }, [
+ restoreGrowTick,
+ scrollRef,
+ renderBudget,
+ groups.length,
+ hiddenCount,
+ olderAvailable,
+ paneBudget,
+ growWindow,
+ paneVisible,
+ releaseParkedRestore
+ ])
// The row array is memoized on the inputs the rows actually read. This
// component re-renders on every isAtBottom flip — and use-stick-to-bottom
@@ -1064,7 +1312,7 @@ const ThreadMessageListInner: FC<ThreadMessageListProps> = ({
[visibleGroups, components, structuralSignature, tailStart]
)
- useMessagesBelow({ contentRef, scrollRef, isAtBottom, paneVisible, rows, sessionKey })
+ useMessagesBelow({ contentRef, scrollRef, isAtBottom, paneVisible, rows, sessionKey, sessionId: scrollSessionId })
useStickyPromptClip({ contentRef, scrollRef, paneVisible, rows })
return (
diff --git a/apps/desktop/src/components/assistant-ui/thread/transcript-window.tsx b/apps/desktop/src/components/assistant-ui/thread/transcript-window.tsx
index cfeb965f40f..d70d9659c6b 100644
--- a/apps/desktop/src/components/assistant-ui/thread/transcript-window.tsx
+++ b/apps/desktop/src/components/assistant-ui/thread/transcript-window.tsx
@@ -3,8 +3,10 @@ import { createContext, type ReactNode, useContext } from 'react'
export interface TranscriptWindowValue {
/** Store holds older messages the runtime window has not materialized. */
olderAvailable: boolean
- /** Pull one more page of older messages out of the session store. */
- expandWindow: () => void
+ /** Pull a page, capturing the reader immediately before the prepend commits.
+ * A remote page resolves false on failure; callers can retry without growing
+ * an empty render window or holding the reader still during network I/O. */
+ expandWindow: (beforePrepend?: () => void) => void | Promise<boolean>
}
const TranscriptWindowContext = createContext<TranscriptWindowValue>({
diff --git a/apps/desktop/src/components/assistant-ui/thread/use-messages-below.test.tsx b/apps/desktop/src/components/assistant-ui/thread/use-messages-below.test.tsx
index 8afa098b6a6..ae58614ee97 100644
--- a/apps/desktop/src/components/assistant-ui/thread/use-messages-below.test.tsx
+++ b/apps/desktop/src/components/assistant-ui/thread/use-messages-below.test.tsx
@@ -1,7 +1,7 @@
import { act, cleanup, renderHook } from '@testing-library/react'
import { afterEach, describe, expect, it, vi } from 'vitest'
-import { $threadMessagesBelow, resetThreadScroll } from '@/store/thread-scroll'
+import { $threadMessagesBelowBySession, resetThreadScroll } from '@/store/thread-scroll'
import { countMessagesBelow, useMessagesBelow } from './use-messages-below'
@@ -35,7 +35,7 @@ function transcript() {
afterEach(() => {
cleanup()
- resetThreadScroll()
+ resetThreadScroll('runtime-a')
vi.restoreAllMocks()
vi.unstubAllGlobals()
})
@@ -106,30 +106,36 @@ describe('messages below the viewport', () => {
isAtBottom: false,
paneVisible: true,
rows: null,
- sessionKey: 'a'
+ sessionKey: 'stored-a',
+ sessionId: 'runtime-a'
}
const { rerender } = renderHook(props => useMessagesBelow(props), { initialProps: options })
flush()
- expect($threadMessagesBelow.get()).toBe(1)
+ expect($threadMessagesBelowBySession.get()['runtime-a'] ?? 0).toBe(1)
+
+ // Another visible pane reaching bottom must not erase this reader's count.
+ const sibling = renderHook(() => useMessagesBelow({ ...options, sessionId: 'runtime-b', isAtBottom: true }))
+ expect($threadMessagesBelowBySession.get()['runtime-a']).toBe(1)
+ sibling.unmount()
assistantRect.mockReturnValue(rect(200, 500))
viewport.dispatchEvent(new Event('scroll'))
flush()
- expect($threadMessagesBelow.get()).toBe(0)
+ expect($threadMessagesBelowBySession.get()['runtime-a'] ?? 0).toBe(0)
assistantRect.mockReturnValue(rect(200, 900))
resize?.([], {} as ResizeObserver)
flush()
- expect($threadMessagesBelow.get()).toBe(1)
+ expect($threadMessagesBelowBySession.get()['runtime-a'] ?? 0).toBe(1)
rerender({ ...options, paneVisible: false })
assistantRect.mockReturnValue(rect(200, 500))
viewport.dispatchEvent(new Event('scroll'))
flush()
- expect($threadMessagesBelow.get()).toBe(1)
+ expect($threadMessagesBelowBySession.get()['runtime-a'] ?? 0).toBe(1)
rerender({ ...options, isAtBottom: true })
- expect($threadMessagesBelow.get()).toBe(0)
+ expect($threadMessagesBelowBySession.get()['runtime-a'] ?? 0).toBe(0)
})
})
diff --git a/apps/desktop/src/components/assistant-ui/thread/use-messages-below.ts b/apps/desktop/src/components/assistant-ui/thread/use-messages-below.ts
index 11571b5bb3e..fb2a637fe35 100644
--- a/apps/desktop/src/components/assistant-ui/thread/use-messages-below.ts
+++ b/apps/desktop/src/components/assistant-ui/thread/use-messages-below.ts
@@ -12,6 +12,7 @@ interface MessagesBelowOptions {
paneVisible: boolean
rows: ReactNode
sessionKey: string | null | undefined
+ sessionId: string | null
}
/** Only measure inside the viewport's turn; leave skipped off-screen content asleep. */
@@ -52,7 +53,8 @@ export function useMessagesBelow({
isAtBottom,
paneVisible,
rows,
- sessionKey
+ sessionKey,
+ sessionId
}: MessagesBelowOptions) {
useEffect(() => {
if (!paneVisible) {
@@ -60,7 +62,7 @@ export function useMessagesBelow({
}
if (isAtBottom) {
- publishThreadMessagesBelow(0, { paneVisible })
+ publishThreadMessagesBelow(0, { paneVisible, sessionId })
return
}
@@ -76,7 +78,7 @@ export function useMessagesBelow({
const measure = () => {
frame = 0
- publishThreadMessagesBelow(countMessagesBelow(viewport, content), { paneVisible })
+ publishThreadMessagesBelow(countMessagesBelow(viewport, content), { paneVisible, sessionId })
}
const schedule = () => {
@@ -96,5 +98,5 @@ export function useMessagesBelow({
viewport.removeEventListener('scroll', schedule)
observer.disconnect()
}
- }, [contentRef, scrollRef, isAtBottom, paneVisible, rows, sessionKey])
+ }, [contentRef, scrollRef, isAtBottom, paneVisible, rows, sessionKey, sessionId])
}
diff --git a/apps/desktop/src/store/thread-scroll-restore.test.ts b/apps/desktop/src/store/thread-scroll-restore.test.ts
new file mode 100644
index 00000000000..eced33ebda9
--- /dev/null
+++ b/apps/desktop/src/store/thread-scroll-restore.test.ts
@@ -0,0 +1,51 @@
+import { describe, expect, it } from 'vitest'
+
+import {
+ shouldReapplyFrozenThreadScrollOffset,
+ threadScrollTargetTop,
+ threadScrollTranscriptHeight
+} from './thread-scroll'
+
+const OFFSET = { fromBottom: 800, kind: 'offset' as const }
+const BOTTOM = { kind: 'bottom' as const }
+
+describe('shouldReapplyFrozenThreadScrollOffset', () => {
+ it('does not re-pin a frozen offset when only composer clearance / viewport box resized', () => {
+ const previous = { clearanceHeight: 120, clientHeight: 600, scrollHeight: 5000 }
+ const next = { clearanceHeight: 200, clientHeight: 520, scrollHeight: 5080 }
+
+ expect(threadScrollTranscriptHeight(previous)).toBe(threadScrollTranscriptHeight(next))
+ expect(shouldReapplyFrozenThreadScrollOffset(OFFSET, true, previous, next)).toBe(false)
+
+ // Blind re-apply (the v0.21.1 post-settle RO) would rewrite scrollTop.
+ expect(threadScrollTargetTop(OFFSET, previous)).not.toBe(threadScrollTargetTop(OFFSET, next))
+ })
+
+ it('does not rewrite when a settled offset sees a no-op / same-transcript resize', () => {
+ const metrics = { clearanceHeight: 120, clientHeight: 600, scrollHeight: 5000 }
+
+ expect(shouldReapplyFrozenThreadScrollOffset(OFFSET, true, metrics, metrics)).toBe(false)
+ })
+
+ it('re-pins when transcript content height grew (streaming, prepend, markdown)', () => {
+ const previous = { clearanceHeight: 120, clientHeight: 600, scrollHeight: 5000 }
+ const next = { clearanceHeight: 120, clientHeight: 600, scrollHeight: 5600 }
+
+ expect(shouldReapplyFrozenThreadScrollOffset(OFFSET, true, previous, next)).toBe(true)
+ expect(threadScrollTargetTop(OFFSET, next)).toBe(5600 - 600 - 800)
+ })
+
+ it('leaves kind:bottom / following restore alone', () => {
+ const previous = { clearanceHeight: 120, clientHeight: 600, scrollHeight: 5000 }
+ const next = { clearanceHeight: 120, clientHeight: 600, scrollHeight: 5600 }
+
+ expect(shouldReapplyFrozenThreadScrollOffset(BOTTOM, true, previous, next)).toBe(false)
+ })
+
+ it('does not re-pin while the session-switch settle loop is still running', () => {
+ const previous = { clearanceHeight: 120, clientHeight: 600, scrollHeight: 5000 }
+ const next = { clearanceHeight: 120, clientHeight: 600, scrollHeight: 5600 }
+
+ expect(shouldReapplyFrozenThreadScrollOffset(OFFSET, false, previous, next)).toBe(false)
+ })
+})
diff --git a/apps/desktop/src/store/thread-scroll.test.ts b/apps/desktop/src/store/thread-scroll.test.ts
index cfd1ecab5ee..f6ef1f6dac9 100644
--- a/apps/desktop/src/store/thread-scroll.test.ts
+++ b/apps/desktop/src/store/thread-scroll.test.ts
@@ -1,10 +1,12 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
- $threadJumpButtonVisible,
- $threadScrolledUp,
+ $threadJumpButtonVisibleBySession,
+ $threadMessagesBelowBySession,
+ $threadScrolledUpBySession,
onScrollToBottomRequest,
publishThreadAtBottom,
+ publishThreadMessagesBelow,
requestScrollToBottom,
resetPublishedThreadScroll,
resetThreadScroll,
@@ -12,53 +14,90 @@ import {
} from './thread-scroll'
afterEach(() => {
- resetThreadScroll()
+ resetThreadScroll('session-a')
+ resetThreadScroll('session-b')
})
describe('publishThreadAtBottom', () => {
it('lets the visible pane flash the jump pill when the thread leaves the bottom', () => {
- publishThreadAtBottom(false, { paneVisible: true })
+ publishThreadAtBottom(false, { paneVisible: true, sessionId: 'session-a' })
- expect($threadJumpButtonVisible.get()).toBe(true)
- expect($threadScrolledUp.get()).toBe(true)
+ expect(Boolean($threadJumpButtonVisibleBySession.get()['session-a'])).toBe(true)
+ expect(Boolean($threadScrolledUpBySession.get()['session-a'])).toBe(true)
})
it('ignores stick-to-bottom misses from a hidden keep-alive pane', () => {
- setThreadAtBottom(true)
+ setThreadAtBottom(true, 'session-a')
- publishThreadAtBottom(false, { paneVisible: false })
+ publishThreadAtBottom(false, { paneVisible: false, sessionId: 'session-a' })
- expect($threadJumpButtonVisible.get()).toBe(false)
- expect($threadScrolledUp.get()).toBe(false)
+ expect(Boolean($threadJumpButtonVisibleBySession.get()['session-a'])).toBe(false)
+ expect(Boolean($threadScrolledUpBySession.get()['session-a'])).toBe(false)
})
it("keeps the visible pane's scrolled-up chrome when a hidden pane publishes", () => {
- publishThreadAtBottom(false, { paneVisible: true })
+ publishThreadAtBottom(false, { paneVisible: true, sessionId: 'session-a' })
- publishThreadAtBottom(true, { paneVisible: false })
+ publishThreadAtBottom(true, { paneVisible: false, sessionId: 'session-a' })
- expect($threadJumpButtonVisible.get()).toBe(true)
- expect($threadScrolledUp.get()).toBe(true)
+ expect(Boolean($threadJumpButtonVisibleBySession.get()['session-a'])).toBe(true)
+ expect(Boolean($threadScrolledUpBySession.get()['session-a'])).toBe(true)
})
})
describe('resetPublishedThreadScroll', () => {
+ it('resets only the unmounting session, including its message count', () => {
+ for (const sessionId of ['session-a', 'session-b']) {
+ publishThreadAtBottom(false, { paneVisible: true, sessionId })
+ publishThreadMessagesBelow(7, { paneVisible: true, sessionId })
+ }
+
+ resetPublishedThreadScroll({ paneVisible: true, sessionId: 'session-a' })
+
+ expect($threadJumpButtonVisibleBySession.get()['session-a']).toBeUndefined()
+ expect($threadScrolledUpBySession.get()['session-a']).toBeUndefined()
+ expect($threadMessagesBelowBySession.get()['session-a']).toBeUndefined()
+ expect($threadJumpButtonVisibleBySession.get()['session-b']).toBe(true)
+ expect($threadScrolledUpBySession.get()['session-b']).toBe(true)
+ expect($threadMessagesBelowBySession.get()['session-b']).toBe(7)
+ })
+
+ it('preserves mirror references on no-op ticks, hidden publications, and missing identities', () => {
+ publishThreadAtBottom(false, { paneVisible: true, sessionId: 'session-a' })
+ publishThreadMessagesBelow(7, { paneVisible: true, sessionId: 'session-a' })
+ const flags = $threadScrolledUpBySession.get()
+ const jump = $threadJumpButtonVisibleBySession.get()
+ const counts = $threadMessagesBelowBySession.get()
+
+ publishThreadAtBottom(false, { paneVisible: true, sessionId: 'session-a' })
+ publishThreadMessagesBelow(7, { paneVisible: true, sessionId: 'session-a' })
+ publishThreadMessagesBelow(0, { paneVisible: false, sessionId: 'session-a' })
+ resetPublishedThreadScroll({ paneVisible: false, sessionId: 'session-a' })
+ publishThreadAtBottom(false, { paneVisible: true, sessionId: null })
+ publishThreadMessagesBelow(12, { paneVisible: true, sessionId: null })
+ resetThreadScroll(null)
+
+ expect($threadScrolledUpBySession.get()).toBe(flags)
+ expect($threadJumpButtonVisibleBySession.get()).toBe(jump)
+ expect($threadMessagesBelowBySession.get()).toBe(counts)
+ })
+
it('clears the jump pill when the visible pane unmounts', () => {
- setThreadAtBottom(false)
+ setThreadAtBottom(false, 'session-a')
- resetPublishedThreadScroll({ paneVisible: true })
+ resetPublishedThreadScroll({ paneVisible: true, sessionId: 'session-a' })
- expect($threadJumpButtonVisible.get()).toBe(false)
- expect($threadScrolledUp.get()).toBe(false)
+ expect(Boolean($threadJumpButtonVisibleBySession.get()['session-a'])).toBe(false)
+ expect(Boolean($threadScrolledUpBySession.get()['session-a'])).toBe(false)
})
it('does not clear the visible pane when a hidden list unmounts', () => {
- setThreadAtBottom(false)
+ setThreadAtBottom(false, 'session-a')
- resetPublishedThreadScroll({ paneVisible: false })
+ resetPublishedThreadScroll({ paneVisible: false, sessionId: 'session-a' })
- expect($threadJumpButtonVisible.get()).toBe(true)
- expect($threadScrolledUp.get()).toBe(true)
+ expect(Boolean($threadJumpButtonVisibleBySession.get()['session-a'])).toBe(true)
+ expect(Boolean($threadScrolledUpBySession.get()['session-a'])).toBe(true)
})
})
diff --git a/apps/desktop/src/store/thread-scroll.ts b/apps/desktop/src/store/thread-scroll.ts
index 41397f1c6d7..f8754c28212 100644
--- a/apps/desktop/src/store/thread-scroll.ts
+++ b/apps/desktop/src/store/thread-scroll.ts
@@ -9,58 +9,79 @@ import { $activeProfile, normalizeProfileKey } from '@/store/profile'
// subtree, so ThreadMessageList mirrors it into these atoms for the composer,
// status stack, and floating jump button — all of which render OUTSIDE the thread.
//
-// `$threadScrolledUp` dims the composer / status stack; `$threadJumpButtonVisible`
-// shows the floating jump control. Both track `!isAtBottom` today, but stay
-// separate so their thresholds can diverge again without touching consumers.
-//
-// Keep-alive tabs stay mounted with a real layout box, so only the on-screen
-// pane may publish or reset this composer-facing mirror. Jump-to-bottom
-// requests are keyed by session so a click (or an input-request snap) cannot
-// scroll every mounted transcript.
-export const $threadScrolledUp = atom(false)
-export const $threadJumpButtonVisible = atom(false)
-export const $threadMessagesBelow = atom(0)
-
-export const publishThreadMessagesBelow = (count: number, publisher: { paneVisible: boolean }): void => {
- if (publisher.paneVisible && $threadMessagesBelow.get() !== count) {
- $threadMessagesBelow.set(count)
+// Each session owns its live chrome, including when two split panes are visible.
+// Hidden keep-alive panes may neither publish nor reset a visible pane's state.
+// Keep the flags separate so their thresholds can diverge without changing consumers.
+export const $threadScrolledUpBySession = atom<Record<string, boolean>>({})
+export const $threadJumpButtonVisibleBySession = atom<Record<string, boolean>>({})
+export const $threadMessagesBelowBySession = atom<Record<string, number>>({})
+
+export const publishThreadMessagesBelow = (
+ count: number,
+ publisher: { paneVisible: boolean; sessionId?: string | null }
+): void => {
+ if (publisher.paneVisible) {
+ setSessionValue($threadMessagesBelowBySession, publisher.sessionId, count, 0)
}
}
-// Skip no-op writes so subscribers don't churn on every scroll tick.
-const setter = (target: WritableAtom<boolean>) => (value: boolean) => {
- if (target.get() !== value) {
- target.set(value)
+// Skip no-op writes and remove default entries so scroll ticks don't churn subscribers.
+// Missing identities are not a shared bucket: callers use their existing surface id
+// until a runtime session exists.
+function setSessionValue<T extends boolean | number>(
+ target: WritableAtom<Record<string, T>>,
+ sessionId: string | null | undefined,
+ value: T,
+ empty: T
+): void {
+ if (!sessionId) {
+ return
+ }
+
+ const current = target.get()
+
+ if ((current[sessionId] ?? empty) === value) {
+ return
}
-}
-const setScrolledUp = setter($threadScrolledUp)
-const setJumpButtonVisible = setter($threadJumpButtonVisible)
+ const next = { ...current }
-export const setThreadAtBottom = (isAtBottom: boolean) => {
- setScrolledUp(!isAtBottom)
- setJumpButtonVisible(!isAtBottom)
+ if (value === empty) {
+ delete next[sessionId]
+ } else {
+ next[sessionId] = value
+ }
+
+ target.set(next)
+}
+
+export const setThreadAtBottom = (isAtBottom: boolean, sessionId: string | null = null) => {
+ setSessionValue($threadScrolledUpBySession, sessionId, !isAtBottom, false)
+ setSessionValue($threadJumpButtonVisibleBySession, sessionId, !isAtBottom, false)
}
-export const resetThreadScroll = () => {
- setThreadAtBottom(true)
- $threadMessagesBelow.set(0)
+export const resetThreadScroll = (sessionId: string | null = null) => {
+ setThreadAtBottom(true, sessionId)
+ setSessionValue($threadMessagesBelowBySession, sessionId, 0, 0)
}
-export const publishThreadAtBottom = (isAtBottom: boolean, publisher: { paneVisible: boolean }): void => {
+export const publishThreadAtBottom = (
+ isAtBottom: boolean,
+ publisher: { paneVisible: boolean; sessionId?: string | null }
+): void => {
if (!publisher.paneVisible) {
return
}
- setThreadAtBottom(isAtBottom)
+ setThreadAtBottom(isAtBottom, publisher.sessionId)
}
-export const resetPublishedThreadScroll = (publisher: { paneVisible: boolean }): void => {
+export const resetPublishedThreadScroll = (publisher: { paneVisible: boolean; sessionId?: string | null }): void => {
if (!publisher.paneVisible) {
return
}
- resetThreadScroll()
+ resetThreadScroll(publisher.sessionId)
}
// Cross-component bridge: the jump button lives by the composer, the viewport's
@@ -158,6 +179,43 @@ export function threadScrollTargetTop(
return state.kind === 'bottom' ? max : Math.max(0, max - state.fromBottom)
}
+// Composer metrics write --composer-measured-height onto the chat surface,
+// which grows [data-slot="aui_composer-clearance"] and can shrink the
+// clampToComposer viewport. The post-settle restore ResizeObserver sees that
+// as a content resize and used to re-pin a frozen fromBottom — rewriting
+// scrollTop on every keystroke. Transcript height is scrollHeight minus the
+// clearance spacer, so composer-only layout is distinguishable from real
+// message/prepend/streaming growth.
+export type ThreadScrollRestoreResizeMetrics = {
+ clearanceHeight: number
+ clientHeight: number
+ scrollHeight: number
+}
+
+export function threadScrollTranscriptHeight(
+ metrics: Pick<ThreadScrollRestoreResizeMetrics, 'clearanceHeight' | 'scrollHeight'>
+): number {
+ return Math.max(0, metrics.scrollHeight - Math.max(0, metrics.clearanceHeight))
+}
+
+/**
+ * Post-settle restore RO may re-pin a frozen offset only when transcript
+ * rows actually changed height. Composer clearance / viewport-box resizes
+ * and no-op RO deliveries must not rewrite scrollTop.
+ */
+export function shouldReapplyFrozenThreadScrollOffset(
+ target: ThreadScrollState,
+ settled: boolean,
+ previous: Pick<ThreadScrollRestoreResizeMetrics, 'clearanceHeight' | 'scrollHeight'>,
+ next: Pick<ThreadScrollRestoreResizeMetrics, 'clearanceHeight' | 'scrollHeight'>
+): boolean {
+ if (target.kind !== 'offset' || !settled) {
+ return false
+ }
+
+ return Math.round(threadScrollTranscriptHeight(previous)) !== Math.round(threadScrollTranscriptHeight(next))
+}
+
// Storage is scoped per profile with the same `.profile.<encoded>` suffix the
// app's other persisted session state uses (session.ts profileNavigationKey),
// so two profiles can never read or evict each other's reading positions.