The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): isolate keep-alive panes from the visible transcript
Brooklyn Nicholson60ba6024b5a0
diff --git a/apps/desktop/src/app/chat/index.tsx b/apps/desktop/src/app/chat/index.tsxindex afa9f3883ed..14651b7f727 100644--- a/apps/desktop/src/app/chat/index.tsx+++ b/apps/desktop/src/app/chat/index.tsx@@ -698,7 +698,7 @@ const ChatViewContent = memo(function ChatViewContent({</ErrorState></div>)}- {showChatBar && <ScrollToBottomButton />}+ {showChatBar && <ScrollToBottomButton sessionId={activeSessionId} />}{/* Vibe hearts rise from the composer only when no pet is out (elsethey play on the pet). Fired by the core `reaction` event. */}{!petPresent && (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.tsxindex f163ec84819..3d3d618c6d5 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@@ -23,14 +23,14 @@ afterEach(() => {// control's hidden (parked-at-bottom) state.describe('ScrollToBottomButton', () => {it('stays hidden while parked at the bottom', () => {- render(<ScrollToBottomButton />)+ render(<ScrollToBottomButton sessionId={null} />)expect(screen.queryByRole('button')).toBeNull()})it('is a plain jump-to-bottom control when scrolled up with no approval', () => {setThreadAtBottom(false)- render(<ScrollToBottomButton />)+ render(<ScrollToBottomButton sessionId={null} />)expect(screen.getByRole('button', { name: 'Scroll to bottom' })).toBeTruthy()expect(screen.queryByText('Approval needed')).toBeNull()@@ -39,7 +39,7 @@ describe('ScrollToBottomButton', () => {it('morphs into the approval pill when scrolled up with a pending approval', () => {pendingApproval()setThreadAtBottom(false)- render(<ScrollToBottomButton />)+ render(<ScrollToBottomButton sessionId={null} />)expect(screen.getByRole('button', { name: 'Approval needed' })).toBeTruthy()expect(screen.getByText('Approval needed')).toBeTruthy()@@ -47,7 +47,7 @@ describe('ScrollToBottomButton', () => {it('does not morph while a pending approval is still in view (at bottom)', () => {pendingApproval()- render(<ScrollToBottomButton />)+ render(<ScrollToBottomButton sessionId={null} />)// Parked at bottom → control hidden, so it can't claim "approval needed".expect(screen.queryByRole('button')).toBeNull()@@ -55,9 +55,9 @@ describe('ScrollToBottomButton', () => {it('re-arms sticky-bottom on click', () => {const handler = vi.fn()- const stop = onScrollToBottomRequest(handler)+ const stop = onScrollToBottomRequest(handler, 'sess-1')setThreadAtBottom(false)- render(<ScrollToBottomButton />)+ 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.tsxindex eaab1def046..85d01cb7008 100644--- a/apps/desktop/src/app/chat/scroll-to-bottom-button.tsx+++ b/apps/desktop/src/app/chat/scroll-to-bottom-button.tsx@@ -28,7 +28,7 @@ import { $threadJumpButtonVisible, requestScrollToBottom } from '@/store/thread-* `data-state`. `idle` (never-shown) stays silent so it can't flash on mount;* `in`/`out` only swap once it has actually appeared.*/-export function ScrollToBottomButton() {+export function ScrollToBottomButton({ sessionId }: { sessionId: string | null }) {const { t } = useI18n()const visible = useStore($threadJumpButtonVisible)const request = useStore($approvalRequest)@@ -59,7 +59,7 @@ export function ScrollToBottomButton() {data-state={state}onClick={() => {triggerHaptic('selection')- requestScrollToBottom()+ requestScrollToBottom(sessionId)}}style={{bottom: 'calc(var(--composer-measured-height) + 0.625rem)'diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/clarify-hydration.test.tsx b/apps/desktop/src/app/session/hooks/use-message-stream/clarify-hydration.test.tsxindex 2e1e1b31807..cc0ba10c295 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/clarify-hydration.test.tsx+++ b/apps/desktop/src/app/session/hooks/use-message-stream/clarify-hydration.test.tsx@@ -53,7 +53,7 @@ describe('clarify.request stream hydration', () => {beforeEach(() => {clearClarifyRequest()scrollToBottom.mockClear()- stopScrollListener = onScrollToBottomRequest(scrollToBottom)+ stopScrollListener = onScrollToBottomRequest(scrollToBottom, SID)})afterEach(() => {diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/input-requests.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/input-requests.tsindex 368de696607..bb5420816f5 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/input-requests.ts+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/input-requests.ts@@ -94,7 +94,7 @@ export function handleInputRequestEvent(ctx: GatewayEventContext): boolean {})if (sessionId === activeSessionIdRef.current) {- requestScrollToBottom()+ requestScrollToBottom(sessionId)}}@@ -142,7 +142,7 @@ export function handleInputRequestEvent(ctx: GatewayEventContext): boolean {})if (sessionId === activeSessionIdRef.current) {- requestScrollToBottom()+ requestScrollToBottom(sessionId)}}diff --git a/apps/desktop/src/components/assistant-ui/thread/index.tsx b/apps/desktop/src/components/assistant-ui/thread/index.tsxindex 188f3d1e255..fe0a1c73942 100644--- a/apps/desktop/src/components/assistant-ui/thread/index.tsx+++ b/apps/desktop/src/components/assistant-ui/thread/index.tsx@@ -175,6 +175,7 @@ export const Thread = memo(function Thread({components={messageComponents}emptyPlaceholder={emptyPlaceholder}loadingIndicator={loadingIndicator}+ sessionId={sessionId}sessionKey={sessionKey}/>{loading === 'session' && <CenteredThreadSpinner />}diff --git a/apps/desktop/src/components/assistant-ui/thread/list.test.ts b/apps/desktop/src/components/assistant-ui/thread/list.test.tsindex 2a88557167a..7518ea12b0e 100644--- a/apps/desktop/src/components/assistant-ui/thread/list.test.ts+++ b/apps/desktop/src/components/assistant-ui/thread/list.test.ts@@ -9,7 +9,10 @@ import {liveTailStart,type MessageGroup,resolveThreadScrollTarget,+ RUN_START_SNAP_THRESHOLD_PX,shouldClampTranscriptBudget,+ shouldRePinOnTranscriptReload,+ shouldSnapOnRunStart,subscribeToThreadForeground,transcriptBackfillFrameCount,transcriptPaneBudget@@ -329,3 +332,36 @@ describe('transcriptBackfillFrameCount', () => {expect(transcriptBackfillFrameCount()).toBeLessThanOrEqual(3)})})++describe('shouldSnapOnRunStart', () => {+ it('snaps when the viewport is already at the bottom', () => {+ expect(shouldSnapOnRunStart(0)).toBe(true)+ })++ it('snaps when the viewport is a line or two off the bottom', () => {+ expect(shouldSnapOnRunStart(RUN_START_SNAP_THRESHOLD_PX - 1)).toBe(true)+ })++ it('leaves a reader who has scrolled into history alone', () => {+ expect(shouldSnapOnRunStart(RUN_START_SNAP_THRESHOLD_PX)).toBe(false)+ expect(shouldSnapOnRunStart(400)).toBe(false)+ })+})++describe('shouldRePinOnTranscriptReload', () => {+ it('pins on a session switch even before the transcript has settled', () => {+ expect(shouldRePinOnTranscriptReload({ sessionSwitched: true, settledNonEmpty: false })).toBe(true)+ })++ it('pins on a session switch even when the prior session had settled', () => {+ expect(shouldRePinOnTranscriptReload({ sessionSwitched: true, settledNonEmpty: true })).toBe(true)+ })++ it('preserves the reader position on a same-session refresh after settling', () => {+ expect(shouldRePinOnTranscriptReload({ sessionSwitched: false, settledNonEmpty: true })).toBe(false)+ })++ it('pins on a cold-load arrival (same session, never settled non-empty)', () => {+ expect(shouldRePinOnTranscriptReload({ sessionSwitched: false, settledNonEmpty: false })).toBe(true)+ })+})diff --git a/apps/desktop/src/components/assistant-ui/thread/list.tsx b/apps/desktop/src/components/assistant-ui/thread/list.tsxindex d88a6dbec1d..b2c318721eb 100644--- a/apps/desktop/src/components/assistant-ui/thread/list.tsx+++ b/apps/desktop/src/components/assistant-ui/thread/list.tsx@@ -17,7 +17,7 @@ import {} from 'react'import { type GetTargetScrollTop, useStickToBottom } from 'use-stick-to-bottom'-import { usePaneLifecycle } from '@/components/pane-shell/pane-visibility'+import { usePaneLifecycle, usePaneVisible } from '@/components/pane-shell/pane-visibility'import { useI18n } from '@/i18n'import { messagePaintWeight } from '@/lib/render-weight'import { cn } from '@/lib/utils'@@ -25,8 +25,8 @@ import {onScrollToBottomRequest,onThreadEditClose,onThreadEditOpen,- resetThreadScroll,- setThreadAtBottom+ publishThreadAtBottom,+ resetPublishedThreadScroll} from '@/store/thread-scroll'import { isSecondaryWindow } from '@/store/windows'@@ -138,6 +138,28 @@ export const resolveThreadScrollTarget: GetTargetScrollTop = (targetScrollTop, {return remaining >= 0 && remaining <= SCROLL_TARGET_EPSILON_PX ? currentScrollTop : targetScrollTop}+/** Near-bottom slack for a run-start snap. Wider than the subpixel epsilon+ * use-stick-to-bottom uses for resize follow — a follow-up sent a line or two+ * off the bottom should still track, but a reader in history must not yank. */+export const RUN_START_SNAP_THRESHOLD_PX = 64++export function shouldSnapOnRunStart(+ remainingPx: number,+ thresholdPx = RUN_START_SNAP_THRESHOLD_PX+): boolean {+ return remainingPx < thresholdPx+}++// True when the pin-to-bottom settle should re-arm. A same-session refresh+// (transcript briefly emptied and repopulated under the same key) must keep+// the reader's position; only a session switch or a cold-load arrival re-pins.+export function shouldRePinOnTranscriptReload(opts: {+ sessionSwitched: boolean+ settledNonEmpty: boolean+}): boolean {+ return opts.sessionSwitched || !opts.settledNonEmpty+}+export function subscribeToThreadForeground(shouldReanchor: () => boolean, onReanchor: () => void): () => void {let frameId: number | null = nulllet framePending = false@@ -186,6 +208,7 @@ interface ThreadMessageListProps {components: ThreadMessageComponentsemptyPlaceholder?: ReactNodeloadingIndicator?: ReactNode+ sessionId?: string | nullsessionKey?: string | null}@@ -375,6 +398,7 @@ const ThreadMessageListInner: FC<ThreadMessageListProps> = ({components,emptyPlaceholder,loadingIndicator,+ sessionId = null,sessionKey}) => {// TWO signatures, deliberately split. The STRUCTURAL one (ids/roles/count)@@ -421,6 +445,7 @@ const ThreadMessageListInner: FC<ThreadMessageListProps> = ({const mountedPanes = useStore($mountedTranscriptPanes)const paneLifecycle = usePaneLifecycle()+ const paneVisible = usePaneVisible()// Hidden panes retain only a live-tail budget. Visible panes share the normal// screen budget; a reveal backfills older rows in bounded transition steps.const paneBudget = transcriptPaneBudget(mountedPanes, paneLifecycle === 'hot-hidden')@@ -469,6 +494,11 @@ const ThreadMessageListInner: FC<ThreadMessageListProps> = ({// Session the settle loop last armed for, so a re-arm within the same load// is distinguishable from a switch to a different transcript.const settleKeyRef = useRef(sessionKey)+ // True once the CURRENT session has settled with a non-empty transcript.+ // A same-session refresh must keep the reader's position; only a switch or+ // a cold-load arrival re-arms. Reset on switch so a mid-settle key change+ // cannot inherit the outgoing session's settled flag.+ const settledNonEmptyRef = useRef(false)// Record where the view should land once a prepend has grown the content,// measured from the BOTTOM so the added height doesn't invalidate it. Only a@@ -575,11 +605,14 @@ const ThreadMessageListInner: FC<ThreadMessageListProps> = ({? 'pt-[calc(var(--titlebar-height)+0.75rem)]': 'pt-[calc(var(--titlebar-height)-0.5rem)]'- useEffect(() => setThreadAtBottom(isAtBottom), [isAtBottom])- useEffect(() => () => resetThreadScroll(), [])+ useEffect(() => publishThreadAtBottom(isAtBottom, { paneVisible }), [isAtBottom, paneVisible])+ useEffect(() => () => resetPublishedThreadScroll({ paneVisible }), [paneVisible])// Floating jump button (outside this subtree) → return to the bottom.- useEffect(() => onScrollToBottomRequest(() => void scrollToBottom()), [scrollToBottom])+ useEffect(+ () => onScrollToBottomRequest(() => void scrollToBottom(), sessionId),+ [scrollToBottom, sessionId]+ )// 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@@ -620,8 +653,14 @@ const ThreadMessageListInner: FC<ThreadMessageListProps> = ({useEffect(() => onThreadEditOpen(beginEditHold), [beginEditHold])useEffect(() => onThreadEditClose(endEditHold), [endEditHold])useEffect(() => () => endEditHold(), [endEditHold])- // New run → snap to the latest turn.- useAuiEvent('thread.runStart', () => void scrollToBottom())+ // New run → snap to the latest turn only when already near the bottom.+ useAuiEvent('thread.runStart', () => {+ const el = scrollRef.current++ if (el && shouldSnapOnRunStart(el.scrollHeight - el.scrollTop - el.clientHeight)) {+ scrollToBottom()+ }+ })// Reset the cap and pin to bottom on mount + every session switch (messages// swap in place on a long-lived runtime, so sessionKey is the only signal).@@ -646,6 +685,19 @@ const ThreadMessageListInner: FC<ThreadMessageListProps> = ({return}+ const sessionSwitched = settleKeyRef.current !== sessionKey++ if (sessionSwitched) {+ settledNonEmptyRef.current = false+ }++ // Same-session refresh (transcript briefly cleared and repopulated) must+ // keep the reader's position. Run before stopScroll / scrollTop reset so+ // a refresh neither yanks the view nor clears the settled flag.+ if (!shouldRePinOnTranscriptReload({ sessionSwitched, settledNonEmpty: settledNonEmptyRef.current })) {+ return+ }+stopScroll()el.scrollTop = el.scrollHeightloadSettledRef.current = false@@ -653,7 +705,7 @@ const ThreadMessageListInner: FC<ThreadMessageListProps> = ({// An anchor captured for the OUTGOING transcript must not be applied to// this one — a switch owns the position outright. The empty→non-empty// re-arm is the SAME load, whose in-flight anchor is still correct.- if (settleKeyRef.current !== sessionKey) {+ if (sessionSwitched) {settleKeyRef.current = sessionKeyrestoreFromBottomRef.current = null}@@ -680,6 +732,7 @@ const ThreadMessageListInner: FC<ThreadMessageListProps> = ({// frames to minimize the settle-loop racing markdown paint on every switch.if (stableFrames >= 2 || ++frame > 15) {void scrollToBottom('instant')+ settledNonEmptyRef.current = hasGroupsloadSettledRef.current = truereturndiff --git a/apps/desktop/src/store/thread-scroll.test.ts b/apps/desktop/src/store/thread-scroll.test.tsnew file mode 100644index 00000000000..5fafa32a5d6--- /dev/null+++ b/apps/desktop/src/store/thread-scroll.test.ts@@ -0,0 +1,93 @@+import { afterEach, describe, expect, it, vi } from 'vitest'++import {+ $threadJumpButtonVisible,+ $threadScrolledUp,+ onScrollToBottomRequest,+ publishThreadAtBottom,+ requestScrollToBottom,+ resetPublishedThreadScroll,+ resetThreadScroll,+ setThreadAtBottom+} from './thread-scroll'++afterEach(() => {+ resetThreadScroll()+})++describe('publishThreadAtBottom', () => {+ it('lets the visible pane flash the jump pill when the thread leaves the bottom', () => {+ publishThreadAtBottom(false, { paneVisible: true })++ expect($threadJumpButtonVisible.get()).toBe(true)+ expect($threadScrolledUp.get()).toBe(true)+ })++ it('ignores stick-to-bottom misses from a hidden keep-alive pane', () => {+ setThreadAtBottom(true)++ publishThreadAtBottom(false, { paneVisible: false })++ expect($threadJumpButtonVisible.get()).toBe(false)+ expect($threadScrolledUp.get()).toBe(false)+ })++ it('keeps the visible pane\'s scrolled-up chrome when a hidden pane publishes', () => {+ publishThreadAtBottom(false, { paneVisible: true })++ publishThreadAtBottom(true, { paneVisible: false })++ expect($threadJumpButtonVisible.get()).toBe(true)+ expect($threadScrolledUp.get()).toBe(true)+ })+})++describe('resetPublishedThreadScroll', () => {+ it('clears the jump pill when the visible pane unmounts', () => {+ setThreadAtBottom(false)++ resetPublishedThreadScroll({ paneVisible: true })++ expect($threadJumpButtonVisible.get()).toBe(false)+ expect($threadScrolledUp.get()).toBe(false)+ })++ it('does not clear the visible pane when a hidden list unmounts', () => {+ setThreadAtBottom(false)++ resetPublishedThreadScroll({ paneVisible: false })++ expect($threadJumpButtonVisible.get()).toBe(true)+ expect($threadScrolledUp.get()).toBe(true)+ })+})++describe('requestScrollToBottom', () => {+ it('routes a scroll request only to its session', () => {+ const sessionA = vi.fn()+ const sessionB = vi.fn()+ const stopA = onScrollToBottomRequest(sessionA, 'session-a')+ const stopB = onScrollToBottomRequest(sessionB, 'session-b')++ requestScrollToBottom('session-b')++ expect(sessionA).not.toHaveBeenCalled()+ expect(sessionB).toHaveBeenCalledOnce()+ stopA()+ stopB()+ })++ it('does not let a late unmount clear a newer session\'s handler', () => {+ const first = vi.fn()+ const second = vi.fn()+ const stopFirst = onScrollToBottomRequest(first, 'session-a')+ const stopSecond = onScrollToBottomRequest(second, 'session-a')++ stopFirst()+ requestScrollToBottom('session-a')++ expect(first).not.toHaveBeenCalled()+ expect(second).toHaveBeenCalledOnce()+ stopSecond()+ })+})diff --git a/apps/desktop/src/store/thread-scroll.ts b/apps/desktop/src/store/thread-scroll.tsindex 976cf4b4e14..c896b7af27f 100644--- a/apps/desktop/src/store/thread-scroll.ts+++ b/apps/desktop/src/store/thread-scroll.ts@@ -8,6 +8,11 @@ import { atom, type WritableAtom } from 'nanostores'// `$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)@@ -28,18 +33,45 @@ export const setThreadAtBottom = (isAtBottom: boolean) => {export const resetThreadScroll = () => setThreadAtBottom(true)+export const publishThreadAtBottom = (isAtBottom: boolean, publisher: { paneVisible: boolean }): void => {+ if (!publisher.paneVisible) {+ return+ }++ setThreadAtBottom(isAtBottom)+}++export const resetPublishedThreadScroll = (publisher: { paneVisible: boolean }): void => {+ if (!publisher.paneVisible) {+ return+ }++ resetThreadScroll()+}+// Cross-component bridge: the jump button lives by the composer, the viewport's// `scrollToBottom` lives inside the thread. The bridge registers a handler; the// button fires it. Mirrors the composer focus/insert emitter pattern.-const handlers = new Set<() => void>()+const handlers = new Map<string | null, Set<() => void>>()++export const onScrollToBottomRequest = (handler: () => void, sessionId: string | null = null) => {+ const scoped = handlers.get(sessionId) ?? new Set<() => void>()-export const onScrollToBottomRequest = (handler: () => void) => {- handlers.add(handler)+ scoped.add(handler)+ handlers.set(sessionId, scoped)- return () => void handlers.delete(handler)+ return () => {+ scoped.delete(handler)++ if (scoped.size === 0) {+ handlers.delete(sessionId)+ }+ }}-export const requestScrollToBottom = () => handlers.forEach(handler => handler())+export const requestScrollToBottom = (sessionId: string | null = null) => {+ handlers.get(sessionId)?.forEach(handler => handler())+}// Inline edit grows a sticky human bubble. Fire on pointerdown so the viewport// escapes stick-to-bottom before focus/layout; close clears the edit flag when