Skip to content

The agent that grows with you

fix(desktop): reanchor transcript on window focus

Nicky Molina6f64a2c631bf
diff --git a/apps/desktop/e2e/mock-server.ts b/apps/desktop/e2e/mock-server.ts
index ce4665d1775..8de1af8aa4f 100644
--- a/apps/desktop/e2e/mock-server.ts
+++ b/apps/desktop/e2e/mock-server.ts
@@ -120,6 +120,9 @@ let _correctionSwitchIndex = 0
/** Per-server counter for the verify-on-stop script. */
let _verificationStopIndex = 0
+/** Per-server counter for the task-panel warm-resume script. */
+let _taskPanelResumeIndex = 0
+
/** User messages received by the mock, for E2E assertions on real submits. */
const _receivedUserTexts: string[] = []
@@ -131,6 +134,7 @@ function resetScriptIndex(): void {
_queueStopIndex = 0
_correctionSwitchIndex = 0
_verificationStopIndex = 0
+ _taskPanelResumeIndex = 0
_receivedUserTexts.length = 0
}
@@ -295,6 +299,41 @@ export const VERIFICATION_STOP_TEXT = 'I cannot provide fresh verification evide
export const BLOCKING_CLARIFY_TRIGGER = 'E2E_BLOCKING_CLARIFY_TRIGGER'
export const BLOCKING_CLARIFY_QUESTION = 'Keep this test turn running?'
+/**
+ * A long live response with a five-row todo card, held open by a foreground tool.
+ * The transcript is deliberately taller than the viewport so warm-session
+ * tests can detect when re-opening the session leaves it above the true bottom.
+ */
+export const TASK_PANEL_RESUME_TRIGGER = 'E2E_TASK_PANEL_RESUME_TRIGGER'
+export const TASK_PANEL_RESUME_TEXT = Array.from(
+ { length: 24 },
+ (_, index) => `Task-panel clearance line ${index + 1}: inspect the restored working session geometry.`,
+).join('\n\n')
+
+const TASK_PANEL_RESUME_SCRIPT: ScriptedTurn[] = [
+ {
+ text: TASK_PANEL_RESUME_TEXT,
+ toolCalls: [
+ {
+ name: 'todo',
+ args: {
+ todos: [
+ { id: 'design', content: 'Design the restored layout', status: 'completed' },
+ { id: 'implement', content: 'Implement the measured clearance', status: 'in_progress' },
+ { id: 'verify', content: 'Verify the latest message stays visible', status: 'pending' },
+ { id: 'review', content: 'Review the visual regression', status: 'pending' },
+ { id: 'ship', content: 'Ship the focused fix', status: 'pending' },
+ ],
+ },
+ },
+ {
+ name: 'terminal',
+ args: { command: 'sleep 60' },
+ },
+ ],
+ },
+]
+
const BLOCKING_CLARIFY_TURN: ScriptedTurn = {
text: '',
toolCalls: [{ name: 'clarify', args: { question: BLOCKING_CLARIFY_QUESTION, choices: ['Yes', 'No'] } }],
@@ -414,6 +453,7 @@ export function startMockServer(options: MockServerOptions = {}): Promise<MockSe
const isSidebarTrigger = userText.includes('E2E_SIDEBAR_TRIGGER')
const isSidebarCrossTrigger = userText.includes('E2E_SIDEBAR_CROSS')
const isQueueStopTrigger = userText.includes('E2E_QUEUE_STOP_TRIGGER')
+ const isTaskPanelResumeTrigger = userText.includes(TASK_PANEL_RESUME_TRIGGER)
const isVerificationStopTrigger = messages.some(
message => typeof message?.content === 'string' && message.content.includes(VERIFICATION_STOP_TRIGGER),
)
@@ -421,6 +461,29 @@ export function startMockServer(options: MockServerOptions = {}): Promise<MockSe
message => typeof message?.content === 'string' && message.content.includes(CORRECTION_SWITCH_TRIGGER),
)
+ if (isTaskPanelResumeTrigger) {
+ const turn =
+ TASK_PANEL_RESUME_SCRIPT[_taskPanelResumeIndex] ??
+ TASK_PANEL_RESUME_SCRIPT[TASK_PANEL_RESUME_SCRIPT.length - 1]
+ _taskPanelResumeIndex++
+ const respond = () => {
+ if (stream) {
+ streamScriptedTurn(res, model, turn)
+ } else {
+ nonStreamingScriptedTurn(res, model, turn)
+ }
+ }
+
+ if (holdThisCompletion) {
+ heldCompletionCount++
+ resolveHeldStreamStarted?.()
+ void heldStreamReleased.then(respond)
+ } else {
+ respond()
+ }
+ return
+ }
+
if (includesBlockingClarifyTrigger(parsed.messages)) {
if (stream) {
streamScriptedTurn(res, model, BLOCKING_CLARIFY_TURN)
diff --git a/apps/desktop/e2e/task-panel-clearance.spec.ts b/apps/desktop/e2e/task-panel-clearance.spec.ts
new file mode 100644
index 00000000000..19cf8d9541e
--- /dev/null
+++ b/apps/desktop/e2e/task-panel-clearance.spec.ts
@@ -0,0 +1,145 @@
+/**
+ * Regression coverage for returning to a working session as its task panel
+ * expands. The transcript must reconcile to the composer's full measured
+ * height without needing a manual scroll to repair the position.
+ */
+
+import { expect, test, type Page } from './test'
+
+import { type MockBackendFixture, setupMockBackend, waitForAppReady } from './fixtures'
+import { TASK_PANEL_RESUME_TRIGGER } from './mock-server'
+
+const SURFACE = '[data-composer-target]:visible'
+const PROMPT = `${TASK_PANEL_RESUME_TRIGGER}: keep the task panel expanded while this session is reopened.`
+
+function activeSurface(page: Page) {
+ return page.locator(SURFACE).last()
+}
+
+async function send(page: Page, text: string): Promise<void> {
+ const composer = activeSurface(page).locator('[contenteditable="true"]').first()
+
+ await composer.waitFor({ state: 'visible', timeout: 15_000 })
+ await composer.click()
+ await composer.type(text, { delay: 5 })
+ await page.keyboard.press('Enter')
+}
+
+async function openFreshDraft(page: Page): Promise<void> {
+ await page.locator('[data-slot="sidebar"] button[aria-label="New session"]').first().click()
+ await expect(activeSurface(page).locator('[data-slot="aui_thread-viewport"]')).not.toContainText(PROMPT)
+ await page.waitForTimeout(1_000)
+}
+
+async function reopenWorkingSession(page: Page): Promise<void> {
+ const sidebar = page.locator('[data-slot="sidebar"]')
+ const row = sidebar.getByRole('button', { name: /^(?:Session running|Needs your input|Working)\b/ }).first()
+
+ await row.waitFor({ state: 'visible', timeout: 30_000 })
+ await row.click()
+ await expect(activeSurface(page).locator('[data-slot="aui_thread-viewport"]')).toContainText(
+ 'Task-panel clearance line 24',
+ { timeout: 30_000 },
+ )
+}
+
+interface ClearanceMetrics {
+ composerHeight: number
+ distanceFromBottom: number
+ latestMessageBottom: number
+ statusPanelTop: number
+ viewportHeight: number
+}
+
+async function clearanceMetrics(page: Page): Promise<ClearanceMetrics> {
+ return activeSurface(page).evaluate(surface => {
+ const chatSurface = surface.closest<HTMLElement>('[data-chat-surface]')!
+ const viewport = surface.querySelector<HTMLElement>('[data-slot="aui_thread-viewport"]')!
+ const latest = Array.from(surface.querySelectorAll<HTMLElement>('[data-role="assistant"]')).at(-1)!
+ const status = surface.querySelector<HTMLElement>('[data-slot="composer-status-stack"]')!
+ const styles = getComputedStyle(chatSurface)
+
+ return {
+ composerHeight: Number.parseFloat(styles.getPropertyValue('--composer-measured-height')),
+ distanceFromBottom: viewport.scrollHeight - viewport.clientHeight - viewport.scrollTop,
+ latestMessageBottom: latest.getBoundingClientRect().bottom,
+ statusPanelTop: status.getBoundingClientRect().top,
+ viewportHeight: viewport.clientHeight,
+ }
+ })
+}
+
+test.describe('working-session task-panel clearance', () => {
+ let fixture: MockBackendFixture | null = null
+
+ test.beforeEach(async () => {
+ fixture = await setupMockBackend({
+ mockServer: { holdFirstCompletionContaining: TASK_PANEL_RESUME_TRIGGER },
+ })
+ await waitForAppReady(fixture, 120_000)
+ })
+
+ test.afterEach(async () => {
+ await fixture?.cleanup()
+ fixture = null
+ })
+
+ test('window focus reanchors a working session above the expanded task panel', async ({}, testInfo) => {
+ const page = fixture!.page
+
+ await send(page, PROMPT)
+ await fixture!.mock.waitForHeldCompletion()
+ await openFreshDraft(page)
+
+ // Re-open while the long response is still streaming. Its todo call lands
+ // afterward, so the already-visible composer grows only after the initial
+ // session-load scroll settle has finished.
+ fixture!.mock.releaseHeldStream()
+ await page.waitForTimeout(1_000)
+ await reopenWorkingSession(page)
+ await expect(activeSurface(page).getByText('Tasks 1/5')).toBeVisible({ timeout: 30_000 })
+
+ // Reproduce the stale geometry at the foreground boundary. Active turns
+ // disable Chromium's background throttling, so visibility can stay `visible`
+ // and window focus is the only foreground edge that can repair it.
+ await page.waitForTimeout(750)
+ const staleState = await activeSurface(page)
+ .locator('[data-slot="aui_thread-viewport"]')
+ .evaluate(viewport => {
+ // Grow scrollHeight before the observed thread-content node. This
+ // shifts the transcript behind the dock without resizing the observed
+ // node or synthesizing a user scroll (which must escape the lock).
+ const staleClearance = document.createElement('div')
+ staleClearance.style.height = '160px'
+ staleClearance.setAttribute('aria-hidden', 'true')
+ viewport.prepend(staleClearance)
+
+ const distance = viewport.scrollHeight - viewport.clientHeight - viewport.scrollTop
+ const surface = viewport.closest<HTMLElement>('[data-composer-target]')!
+ const latest = Array.from(surface.querySelectorAll<HTMLElement>('[data-role="assistant"]')).at(-1)!
+ const status = surface.querySelector<HTMLElement>('[data-slot="composer-status-stack"]')!
+
+ window.dispatchEvent(new Event('focus'))
+
+ return {
+ distance,
+ following: viewport.dataset.following,
+ latestMessageBottom: latest.getBoundingClientRect().bottom,
+ statusPanelTop: status.getBoundingClientRect().top,
+ visibility: document.visibilityState,
+ }
+ })
+
+ expect(staleState.visibility, JSON.stringify(staleState)).toBe('visible')
+ expect(staleState.following, JSON.stringify(staleState)).toBe('true')
+ expect(staleState.distance).toBeGreaterThan(100)
+ expect(staleState.latestMessageBottom, JSON.stringify(staleState)).toBeGreaterThan(staleState.statusPanelTop)
+ await page.waitForTimeout(1_000)
+ const metrics = await clearanceMetrics(page)
+ await page.screenshot({ path: testInfo.outputPath('task-panel-after-resume.png') })
+
+ expect(metrics.composerHeight, JSON.stringify(metrics)).toBeGreaterThanOrEqual(190)
+ expect(metrics.distanceFromBottom, JSON.stringify(metrics)).toBeLessThan(staleState.distance / 2)
+ expect(metrics.latestMessageBottom, JSON.stringify(metrics)).toBeLessThanOrEqual(metrics.statusPanelTop)
+ })
+})
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 c6dd3ff7b7b..93f14c8e52d 100644
--- a/apps/desktop/src/app/chat/composer/status-stack/index.tsx
+++ b/apps/desktop/src/app/chat/composer/status-stack/index.tsx
@@ -240,6 +240,7 @@ export function ComposerStatusStack({ queue, sessionId }: ComposerStatusStackPro
// bottom-anchored, so this grows upward over the thread without needing
// to be positioned — and it shares the dock's left edge for free.
className="flex max-h-[40vh] min-h-0 flex-col overflow-y-auto"
+ data-slot="composer-status-stack"
onPointerDownCapture={() => blurComposerInput()}
>
{/* The card paints the shared --composer-fill (rest / scrolled / focused
diff --git a/apps/desktop/src/components/assistant-ui/thread/list.test.ts b/apps/desktop/src/components/assistant-ui/thread/list.test.ts
index f6d6a77e027..8747bcc31ab 100644
--- a/apps/desktop/src/components/assistant-ui/thread/list.test.ts
+++ b/apps/desktop/src/components/assistant-ui/thread/list.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, it } from 'vitest'
+import { afterEach, describe, expect, it, vi } from 'vitest'
import {
buildGroups,
@@ -9,9 +9,82 @@ import {
liveTailStart,
type MessageGroup,
resolveThreadScrollTarget,
+ subscribeToThreadForeground,
transcriptPaneBudget
} from './list'
+afterEach(() => {
+ vi.restoreAllMocks()
+})
+
+describe('subscribeToThreadForeground', () => {
+ it('reanchors on focus when an active turn keeps document visibility pinned visible', () => {
+ const reanchor = vi.fn()
+
+ const raf = vi.spyOn(window, 'requestAnimationFrame').mockImplementation(callback => {
+ callback(0)
+
+ return 1
+ })
+
+ const unsubscribe = subscribeToThreadForeground(() => true, reanchor)
+
+ window.dispatchEvent(new Event('focus'))
+
+ expect(raf).toHaveBeenCalledOnce()
+ expect(reanchor).toHaveBeenCalledOnce()
+ unsubscribe()
+ })
+
+ it('leaves a scrolled-up reader in place when the window focuses', () => {
+ const reanchor = vi.fn()
+ const raf = vi.spyOn(window, 'requestAnimationFrame')
+ const unsubscribe = subscribeToThreadForeground(() => false, reanchor)
+
+ window.dispatchEvent(new Event('focus'))
+
+ expect(raf).not.toHaveBeenCalled()
+ expect(reanchor).not.toHaveBeenCalled()
+ unsubscribe()
+ })
+
+ it('drops a queued reanchor when the reader scrolls away before the frame', () => {
+ const frames: FrameRequestCallback[] = []
+ let following = true
+ const reanchor = vi.fn()
+
+ vi.spyOn(window, 'requestAnimationFrame').mockImplementation(callback => {
+ frames.push(callback)
+
+ return 7
+ })
+
+ const unsubscribe = subscribeToThreadForeground(() => following, reanchor)
+
+ window.dispatchEvent(new Event('focus'))
+ following = false
+ frames[0]?.(0)
+
+ expect(reanchor).not.toHaveBeenCalled()
+ unsubscribe()
+ })
+
+ it('cancels a queued reanchor when its thread unmounts', () => {
+ const cancel = vi.spyOn(window, 'cancelAnimationFrame')
+ const reanchor = vi.fn()
+
+ vi.spyOn(window, 'requestAnimationFrame').mockReturnValue(9)
+
+ const unsubscribe = subscribeToThreadForeground(() => true, reanchor)
+
+ window.dispatchEvent(new Event('focus'))
+ unsubscribe()
+
+ expect(cancel).toHaveBeenCalledWith(9)
+ expect(reanchor).not.toHaveBeenCalled()
+ })
+})
+
// Signature rows are `${index}:${id}:${role}:${weight}` (see the useAuiState
// selector in list.tsx).
const signature = (rows: [string, string, number][]) =>
diff --git a/apps/desktop/src/components/assistant-ui/thread/list.tsx b/apps/desktop/src/components/assistant-ui/thread/list.tsx
index b0d2c1cf3a1..9db5aedcb16 100644
--- a/apps/desktop/src/components/assistant-ui/thread/list.tsx
+++ b/apps/desktop/src/components/assistant-ui/thread/list.tsx
@@ -22,7 +22,6 @@ import { useI18n } from '@/i18n'
import { messagePaintWeight } from '@/lib/render-weight'
import { cn } from '@/lib/utils'
import {
- $threadScrolledUp,
onScrollToBottomRequest,
onThreadEditClose,
onThreadEditOpen,
@@ -125,6 +124,49 @@ export const resolveThreadScrollTarget: GetTargetScrollTop = (targetScrollTop, {
return remaining >= 0 && remaining <= SCROLL_TARGET_EPSILON_PX ? currentScrollTop : targetScrollTop
}
+export function subscribeToThreadForeground(shouldReanchor: () => boolean, onReanchor: () => void): () => void {
+ let frameId: number | null = null
+ let framePending = false
+
+ const onForeground = () => {
+ if (framePending || document.visibilityState !== 'visible' || !shouldReanchor()) {
+ return
+ }
+
+ framePending = true
+
+ const scheduledId = requestAnimationFrame(() => {
+ frameId = null
+ framePending = false
+
+ if (document.visibilityState === 'visible' && shouldReanchor()) {
+ onReanchor()
+ }
+ })
+
+ // Browser callbacks are asynchronous; the guard also keeps synchronous
+ // requestAnimationFrame test doubles from leaving a completed frame pending.
+ if (framePending) {
+ frameId = scheduledId
+ }
+ }
+
+ document.addEventListener('visibilitychange', onForeground)
+ window.addEventListener('focus', onForeground)
+
+ return () => {
+ document.removeEventListener('visibilitychange', onForeground)
+ window.removeEventListener('focus', onForeground)
+
+ if (frameId !== null) {
+ cancelAnimationFrame(frameId)
+ }
+
+ frameId = null
+ framePending = false
+ }
+}
+
interface ThreadMessageListProps {
clampToComposer: boolean
components: ThreadMessageComponents
@@ -526,21 +568,18 @@ const ThreadMessageListInner: FC<ThreadMessageListProps> = ({
useEffect(() => onScrollToBottomRequest(() => void scrollToBottom()), [scrollToBottom])
// Waking from display: hidden (HUD mode hides the main window; OS hide does
- // the same to any window): rAF and ResizeObserver were frozen the whole
- // time, so the virtualizer's measurements — and scrollTop itself — are
- // stale. If the user was following the bottom, re-anchor once visible;
- // leave a scrolled-up reader exactly where they were.
- useEffect(() => {
- const onVisible = () => {
- if (document.visibilityState === 'visible' && !$threadScrolledUp.get()) {
- requestAnimationFrame(() => void scrollToBottom())
- }
- }
-
- document.addEventListener('visibilitychange', onVisible)
-
- return () => document.removeEventListener('visibilitychange', onVisible)
- }, [scrollToBottom])
+ // the same to any window): rAF and ResizeObserver may have been frozen, so
+ // the virtualizer's measurements — and scrollTop itself — are stale. Active
+ // turns disable Chromium's background throttling, which can keep visibility
+ // pinned at `visible`; window focus is then the only foreground edge. If the
+ // user was following the bottom, re-anchor on either signal. Consult this
+ // thread's local state rather than the composer-facing global mirror, which
+ // can be overwritten by another mounted pane; leave a scrolled-up reader
+ // exactly where they were.
+ useEffect(
+ () => subscribeToThreadForeground(() => isAtBottom, () => void scrollToBottom()),
+ [isAtBottom, scrollToBottom]
+ )
const endEditHold = useCallback(() => {
scrollRef.current?.removeAttribute('data-editing')