Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(inbox): preserve scroll position when returning from chat (#1913)

Call White3ed478d2b354
diff --git a/ui/e2e/inbox-return/README.md b/ui/e2e/inbox-return/README.md
new file mode 100644
index 000000000..41a8d6472
--- /dev/null
+++ b/ui/e2e/inbox-return/README.md
@@ -0,0 +1,34 @@
+# Inbox Return Regression
+
+Run `npm run test:inbox-return` from `ui/`.
+
+This backend-free suite renders the production `InboxPage` with an in-memory
+Inbox provider and a routed Chat placeholder. Its shell mirrors the production
+mobile internal scroll owner and desktop document scrolling. Browser history
+and the Chat Back button both return to the original Inbox entry.
+
+The invariant is that returning from a conversation preserves the reader's
+neighborhood within the already loaded Inbox window. A surviving visible row
+keeps its offset; disappearing unread rows fall back to their nearest remaining
+neighbors, subject to the new scroll limits. New activity and delayed layout or
+read updates must not reclaim scrolling after the reader resumes input.
+
+The suite covers repeated returns, bottom-up unread triage, removed anchors,
+additional loaded pages, new activity, delayed mark-read updates, content reflow,
+fresh navigation, and a later Search return without replaying a consumed Chat
+snapshot. Component tests additionally cover empty intermediate
+renders, all visible rows disappearing, every supported input cancellation,
+expiration, and Strict Mode lifecycle replay. Consumption and cancellation both
+prevent the shared snapshot from leaking into a later Inbox remount, while the
+current visit retains its local copy for delayed layout corrections.
+
+All API requests are blocked. No Avibe instance, credentials, or persisted
+messages are used. Screenshots and failure traces are written under
+`e2e/.artifacts/inbox-return/`.
+
+For full-service verification, proxy the worktree's Vite server to the existing
+local Incus regression instance with `VIBE_UI_BACKEND`. Use existing conversations
+and confirm their IDs and loaded row counts survive a history return. Do not
+repurpose a remote instance or restart the user's host service. Native iOS Safari
+edge-swipe recognition is a separate device check; Chromium exercises its
+history-POP navigation result, not Safari's gesture recognizer.
diff --git a/ui/e2e/inbox-return/fixture.html b/ui/e2e/inbox-return/fixture.html
new file mode 100644
index 000000000..6b1ba1b69
--- /dev/null
+++ b/ui/e2e/inbox-return/fixture.html
@@ -0,0 +1,12 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <title>Inbox Return Regression</title>
+ </head>
+ <body>
+ <div id="root"></div>
+ <script type="module" src="./fixture.tsx"></script>
+ </body>
+</html>
diff --git a/ui/e2e/inbox-return/fixture.tsx b/ui/e2e/inbox-return/fixture.tsx
new file mode 100644
index 000000000..b85af998a
--- /dev/null
+++ b/ui/e2e/inbox-return/fixture.tsx
@@ -0,0 +1,104 @@
+import { StrictMode, useCallback, useEffect, useState } from 'react';
+import { createRoot } from 'react-dom/client';
+import { HashRouter, Route, Routes, useLocation, useNavigate, useParams } from 'react-router-dom';
+import { ArrowLeft } from 'lucide-react';
+import { InboxPage } from '../../src/components/workbench/InboxPage';
+import { ApiProvider, type InboxSession } from '../../src/context/ApiContext';
+import { WorkbenchInboxContext } from '../../src/context/WorkbenchInboxContext';
+import { InstanceAuthorizationContext } from '../../src/context/InstanceAuthorizationContext';
+import { ToastContext } from '../../src/context/ToastContext';
+import { WindowManagerContext, type WindowManagerValue } from '../../src/context/WindowManagerContext';
+import { OWNER_INSTANCE_CAPABILITIES } from '../../src/lib/sessionInfo';
+import { APP_SHELL_SCROLL_ID } from '../../src/lib/mobileProjectsListMemory';
+import '../../src/i18n';
+import '../../src/index.css';
+
+const noop = () => {};
+const activateFeed = () => noop;
+const makeRow = (id: number): InboxSession => ({
+ session_id: `session-${id}`, title: `Conversation ${id}`, scope_id: null,
+ project_id: 'fixture', project_name: 'Regression', last_activity_at: '2026-09-06T00:00:00Z',
+ last_message_author: 'agent', replied: false,
+ preview_text: `Completed review ${id}.\nThe conversation is ready to read.`,
+ preview_at: null, unread_count: 1, unread: true,
+});
+const history = Array.from({ length: 90 }, (_, index) => makeRow(index + 1));
+const params = new URLSearchParams(window.location.search);
+const delay = Number(params.get('delay') ?? 0);
+
+function Chat({ markRead, addActivity }: { markRead: (id: string) => Promise<void>; addActivity: () => void }) {
+ const { sessionId } = useParams();
+ const navigate = useNavigate();
+ useEffect(() => {
+ void markRead(sessionId!);
+ }, [markRead, sessionId]);
+ return <div className="flex h-full flex-col gap-4 p-4" data-testid="chat-detail">
+ <button type="button" aria-label="Back" className="size-10" onClick={() => navigate(-1)}><ArrowLeft /></button>
+ <div>{sessionId}</div>
+ <button type="button" onClick={addActivity}>New activity</button>
+ <button type="button" onClick={() => navigate('/inbox')}>New Inbox entry</button>
+ </div>;
+}
+
+function Search() {
+ const navigate = useNavigate();
+ return <div data-testid="search-detail">
+ <button type="button" aria-label="Back" onClick={() => navigate(-1)}><ArrowLeft /></button>
+ </div>;
+}
+
+export function Fixture() {
+ const location = useLocation();
+ const chat = location.pathname.startsWith('/chat/');
+ const [sessions, setSessions] = useState(history.slice(0, 60));
+ const [unread, setUnread] = useState(Object.fromEntries(history.map((row) => [row.session_id, 1])));
+ const markRead = useCallback(async (id: string) => {
+ if (delay > 0) await new Promise((resolve) => setTimeout(resolve, delay));
+ setUnread((prev) => {
+ if (!(id in prev)) return prev;
+ const next = { ...prev };
+ delete next[id];
+ return next;
+ });
+ }, []);
+ const addActivity = () => {
+ setSessions((prev) => prev.some((row) => row.session_id === 'session-100') ? prev : [makeRow(100), ...prev]);
+ setUnread((prev) => ({ ...prev, 'session-100': 1 }));
+ };
+ return <WorkbenchInboxContext.Provider value={{
+ inboxSessions: sessions, unreadBySession: unread, totalUnread: Object.keys(unread).length,
+ unreadSessions: Object.keys(unread).length, nextCursor: sessions.length < 90 ? 'next' : null,
+ loading: false, loadingMore: false, refresh: async () => {},
+ loadMore: async () => { setSessions(history); }, markRead, activateFeed,
+ }}>
+ <div className="flex h-dvh flex-col overflow-hidden bg-background text-foreground md:block md:h-auto md:overflow-visible">
+ {!chat && <header className="h-16 shrink-0 border-b border-border px-4 py-5 md:hidden">Inbox</header>}
+ <main id={APP_SHELL_SCROLL_ID} className={chat
+ ? 'min-h-0 flex-1 overflow-hidden md:overflow-visible'
+ : 'min-h-0 flex-1 overflow-y-auto pb-[88px] md:overflow-visible md:pb-0'}>
+ <div className={chat ? 'h-full' : 'px-4 py-5 md:px-10 md:py-8'}>
+ <Routes>
+ <Route path="/inbox" element={<InboxPage />} />
+ <Route path="/chat/:sessionId" element={<Chat markRead={markRead} addActivity={addActivity} />} />
+ <Route path="/search" element={<Search />} />
+ </Routes>
+ </div>
+ </main>
+ </div>
+ </WorkbenchInboxContext.Provider>;
+}
+
+createRoot(document.getElementById('root')!).render(
+ <StrictMode><HashRouter>
+ <InstanceAuthorizationContext.Provider value={{
+ remote: false, instanceKind: null, instanceRole: 'owner',
+ capabilities: { ...OWNER_INSTANCE_CAPABILITIES, can_read_instance: false },
+ }}>
+ <ToastContext.Provider value={{ showToast: noop }}><ApiProvider>
+ <WindowManagerContext.Provider value={{ focusedId: null, focusCanvas: noop } as WindowManagerValue}>
+ <Fixture />
+ </WindowManagerContext.Provider>
+ </ApiProvider></ToastContext.Provider>
+ </InstanceAuthorizationContext.Provider>
+ </HashRouter></StrictMode>,
+);
diff --git a/ui/e2e/inbox-return/return.spec.ts b/ui/e2e/inbox-return/return.spec.ts
new file mode 100644
index 000000000..627890635
--- /dev/null
+++ b/ui/e2e/inbox-return/return.spec.ts
@@ -0,0 +1,137 @@
+import { expect, test, type Page } from '@playwright/test';
+import { copy } from '../support/copy';
+
+const row = (page: Page, id: number) => page.locator(`[data-inbox-session-id="session-${id}"]`);
+const rows = (page: Page) => page.locator('[data-inbox-session-id]');
+const position = (page: Page) => page.evaluate(() => {
+ const shell = document.getElementById('app-shell-scroll')!;
+ const owner = getComputedStyle(shell).overflowY === 'visible' ? document.scrollingElement! : shell;
+ return { top: owner.scrollTop, max: owner.scrollHeight - owner.clientHeight };
+});
+const scrollTo = (page: Page, top: number) => page.evaluate((value) => {
+ const shell = document.getElementById('app-shell-scroll')!;
+ const owner = getComputedStyle(shell).overflowY === 'visible' ? document.scrollingElement! : shell;
+ owner.scrollTop = value;
+}, top);
+const alignTop = (page: Page, id: number) => row(page, id).evaluate((el) => {
+ const shell = document.getElementById('app-shell-scroll')!;
+ const documentScrolls = getComputedStyle(shell).overflowY === 'visible';
+ const owner = documentScrolls ? document.scrollingElement! : shell;
+ owner.scrollTop += el.getBoundingClientRect().top - (documentScrolls ? 0 : shell.getBoundingClientRect().top);
+});
+const open = async (page: Page, query = '') => {
+ await page.route('**/api/**', (route) => route.fulfill({ status: 503, json: { error: 'No backend in this fixture' } }));
+ await page.goto(`/e2e/inbox-return/fixture.html${query}#/inbox`);
+ await expect(rows(page)).toHaveCount(60);
+};
+const enter = async (page: Page, id: number) => {
+ await row(page, id).getByRole('button', { name: copy('workbench.inbox.openSession') }).click();
+ await expect(page.getByTestId('chat-detail')).toBeVisible();
+};
+
+test('returns to the same reading position through browser history and the Back button', async ({ page }, testInfo) => {
+ await open(page);
+ await page.getByRole('button', { name: copy('workbench.inbox.filterAll'), exact: true }).click();
+ for (const browserBack of [true, false, true]) {
+ await row(page, 50).scrollIntoViewIfNeeded();
+ const before = await position(page);
+ const offset = await row(page, 50).evaluate((el) => el.getBoundingClientRect().top);
+ await enter(page, 50);
+ if (browserBack) await page.goBack();
+ else await page.getByRole('button', { name: 'Back', exact: true }).click();
+ await expect(rows(page)).toHaveCount(60);
+ await expect.poll(async () => Math.abs((await position(page)).top - before.top)).toBeLessThan(1);
+ expect(Math.abs(await row(page, 50).evaluate((el) => el.getBoundingClientRect().top) - offset)).toBeLessThan(1);
+ }
+ await page.screenshot({ path: testInfo.outputPath('inbox-return.png'), scale: 'css' });
+});
+
+test('keeps bottom-up unread triage near the remaining bottom after each read', async ({ page }) => {
+ await open(page);
+ for (const id of [60, 59, 58]) {
+ await scrollTo(page, (await position(page)).max);
+ await enter(page, id);
+ await page.goBack();
+ await expect(row(page, id)).toHaveCount(0);
+ await expect(rows(page)).toHaveCount(id - 1);
+ await expect.poll(async () => {
+ const p = await position(page);
+ return Math.abs(p.max - p.top);
+ }).toBeLessThan(1);
+ expect((await position(page)).top).toBeGreaterThan(1000);
+ }
+});
+
+test('restores a surviving visible row when the opened unread conversation disappears', async ({ page }) => {
+ await open(page);
+ await alignTop(page, 40);
+ const before = await row(page, 41).evaluate((el) => el.getBoundingClientRect().top);
+ await enter(page, 40);
+ await page.goBack();
+ await expect(row(page, 40)).toHaveCount(0);
+ await expect.poll(async () => Math.abs(await row(page, 41).evaluate((el) => el.getBoundingClientRect().top) - before)).toBeLessThan(1);
+});
+
+test('preserves the read neighborhood across new activity and loaded additional pages', async ({ page }) => {
+ await open(page);
+ await page.getByRole('button', { name: copy('workbench.inbox.loadMore'), exact: true }).click();
+ await expect(rows(page)).toHaveCount(90);
+ await page.getByRole('button', { name: copy('workbench.inbox.filterAll'), exact: true }).click();
+ await row(page, 80).scrollIntoViewIfNeeded();
+ const before = await row(page, 80).evaluate((el) => el.getBoundingClientRect().top);
+ await enter(page, 80);
+ await page.getByRole('button', { name: 'New activity', exact: true }).click();
+ await page.goBack();
+ await expect(rows(page)).toHaveCount(91);
+ await expect.poll(async () => Math.abs(await row(page, 80).evaluate((el) => el.getBoundingClientRect().top) - before)).toBeLessThan(1);
+});
+
+test('keeps a late mark-read update anchored until the user resumes scrolling', async ({ page }) => {
+ await open(page, '?delay=800');
+ await alignTop(page, 40);
+ const before = await row(page, 41).evaluate((el) => el.getBoundingClientRect().top);
+ await enter(page, 40);
+ await page.goBack();
+ await expect(row(page, 40)).toHaveCount(1);
+ await expect(row(page, 40)).toHaveCount(0);
+ await expect.poll(async () => Math.abs(await row(page, 41).evaluate((el) => el.getBoundingClientRect().top) - before)).toBeLessThan(1);
+ await row(page, 1).evaluate((el) => { el.style.minHeight = '500px'; });
+ await expect.poll(async () => Math.abs(await row(page, 41).evaluate((el) => el.getBoundingClientRect().top) - before)).toBeLessThan(1);
+ await page.locator('#app-shell-scroll').dispatchEvent('wheel', { deltaY: -1 });
+ await scrollTo(page, 900);
+ await row(page, 2).evaluate((el) => { el.style.minHeight = '500px'; });
+ // Native browser anchoring may move the offset after a resize; it must not
+ // be forced back into the old reading neighborhood near conversation 40.
+ await page.waitForTimeout(150);
+ expect((await position(page)).top).toBeLessThan(2000);
+});
+
+test('a fresh Inbox navigation does not inherit an older history entry position', async ({ page }) => {
+ await open(page);
+ await row(page, 40).scrollIntoViewIfNeeded();
+ await enter(page, 40);
+ await page.getByRole('button', { name: 'New Inbox entry', exact: true }).click();
+ await expect(rows(page)).toHaveCount(59);
+ expect((await position(page)).top).toBe(0);
+});
+
+test('does not reuse an old Chat position when a later Search visit returns', async ({ page, isMobile }) => {
+ await open(page);
+ await page.getByRole('button', { name: copy('workbench.inbox.filterAll'), exact: true }).click();
+ await row(page, 50).scrollIntoViewIfNeeded();
+ const before = await position(page);
+ await enter(page, 50);
+ await page.goBack();
+ await expect.poll(async () => Math.abs((await position(page)).top - before.top)).toBeLessThan(1);
+ await page.locator('#app-shell-scroll').dispatchEvent('wheel', { deltaY: -1 });
+ await scrollTo(page, 0);
+ if (isMobile) await page.getByText(copy('workbench.search.entry'), { exact: true }).click();
+ else await page.evaluate(() => { window.location.hash = '/search'; });
+ await expect(page.getByTestId('search-detail')).toBeVisible();
+ await page.goBack();
+ await expect(rows(page)).toHaveCount(60);
+ await expect.poll(async () => (await position(page)).top).toBe(0);
+ await row(page, 1).evaluate((el) => { el.style.minHeight = '500px'; });
+ await page.waitForTimeout(150);
+ expect((await position(page)).top).toBe(0);
+});
diff --git a/ui/e2e/inbox-return/tsconfig.json b/ui/e2e/inbox-return/tsconfig.json
new file mode 100644
index 000000000..6091c849c
--- /dev/null
+++ b/ui/e2e/inbox-return/tsconfig.json
@@ -0,0 +1,9 @@
+{
+ "extends": "../../tsconfig.app.json",
+ "compilerOptions": { "types": ["vite/client", "node"] },
+ "include": [
+ "*.ts", "*.tsx", "../../playwright.inbox-return.config.ts",
+ "../../src/components/workbench/InboxPage.test.tsx", "../../agentation.d.ts"
+ ],
+ "exclude": []
+}
diff --git a/ui/package.json b/ui/package.json
index 8361a6fdf..316b1790b 100644
--- a/ui/package.json
+++ b/ui/package.json
@@ -20,6 +20,7 @@
"e2e": "playwright test",
"e2e:headed": "playwright test --headed",
"test:chat-paging": "tsc -p e2e/chat-paging/tsconfig.json --noEmit && playwright test --config playwright.chat-paging.config.ts",
+ "test:inbox-return": "tsc -p e2e/inbox-return/tsconfig.json --noEmit && playwright test --config playwright.inbox-return.config.ts",
"validate:catalog": "node scripts/validate-scenario-catalog.mjs",
"validate:theme": "node scripts/validate-theme.mjs"
},
diff --git a/ui/playwright.config.ts b/ui/playwright.config.ts
index 822ef2a67..fd704869a 100644
--- a/ui/playwright.config.ts
+++ b/ui/playwright.config.ts
@@ -16,7 +16,7 @@ import { BASE_URL } from './e2e/support/env';
export default defineConfig({
testDir: './e2e',
- testIgnore: '**/chat-paging/**',
+ testIgnore: ['**/chat-paging/**', '**/inbox-return/**'],
outputDir: './e2e/.artifacts/test-results',
// Every spec mutates shared instance state (sources, agent modes, the
// runtime switch). Parallel workers would race on it, so the suite is serial
diff --git a/ui/playwright.inbox-return.config.ts b/ui/playwright.inbox-return.config.ts
new file mode 100644
index 000000000..64224362f
--- /dev/null
+++ b/ui/playwright.inbox-return.config.ts
@@ -0,0 +1,18 @@
+import { defineConfig, devices } from '@playwright/test';
+
+export default defineConfig({
+ testDir: './e2e/inbox-return',
+ outputDir: './e2e/.artifacts/inbox-return',
+ workers: 1,
+ retries: 0,
+ use: { baseURL: 'http://127.0.0.1:5199', locale: 'en-US', trace: 'retain-on-failure' },
+ webServer: {
+ command: 'npm run dev -- --host 127.0.0.1 --port 5199 --strictPort',
+ env: { VIBE_UI_BACKEND: 'http://127.0.0.1:9' },
+ url: 'http://127.0.0.1:5199/e2e/inbox-return/fixture.html',
+ },
+ projects: [
+ { name: 'desktop', use: { ...devices['Desktop Chrome'] } },
+ { name: 'mobile', use: { ...devices['iPhone 13'], browserName: 'chromium' } },
+ ],
+});
diff --git a/ui/src/components/workbench/InboxPage.test.tsx b/ui/src/components/workbench/InboxPage.test.tsx
new file mode 100644
index 000000000..a7f8374f1
--- /dev/null
+++ b/ui/src/components/workbench/InboxPage.test.tsx
@@ -0,0 +1,281 @@
+/* @vitest-environment jsdom */
+
+import { StrictMode } from 'react';
+import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { MemoryRouter, Route, Routes, useNavigate } from 'react-router-dom';
+import type { InboxSession } from '../../context/ApiContext';
+import { INBOX_REVERT_AFTER_MS, writeInboxFilter } from '../../lib/inboxFilterMemory';
+import { APP_SHELL_SCROLL_ID } from '../../lib/mobileProjectsListMemory';
+import { InboxPage } from './InboxPage';
+
+const feed = vi.hoisted(() => ({
+ inboxSessions: [] as InboxSession[],
+ unreadBySession: {} as Record<string, number>,
+ loading: false,
+ nextCursor: 'next-page',
+ refresh: vi.fn(),
+ loadMore: vi.fn(),
+ markRead: vi.fn(),
+}));
+vi.mock('../../context/WorkbenchInboxContext', () => ({
+ useWorkbenchInbox: () => ({
+ ...feed,
+ totalUnread: Object.keys(feed.unreadBySession).length,
+ unreadSessions: Object.keys(feed.unreadBySession).length,
+ loadingMore: false,
+ }),
+}));
+vi.mock('../../context/InstanceAuthorizationContext', () => ({
+ useInstanceAuthorization: () => ({ capabilities: { can_chat: true, can_read_instance: false } }),
+}));
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+vi.mock('../ui/markdown', () => ({ Markdown: ({ content }: { content: string }) => <p>{content}</p> }));
+
+const row = (id: number): InboxSession => ({
+ session_id: `session-${id}`, title: `Session ${id}`, scope_id: null,
+ project_id: null, project_name: null, last_activity_at: '2026-09-06T00:00:00Z',
+ last_message_author: 'agent', replied: false, preview_text: `Reply ${id}`,
+ preview_at: null, unread_count: 1, unread: true,
+});
+
+let shell: HTMLDivElement;
+let rowHeight: number;
+let entry = 0;
+let resizeCallbacks: Set<() => void>;
+
+function Chat() {
+ const navigate = useNavigate();
+ return <>
+ <button onClick={() => navigate(-1)}>Back</button>
+ <button onClick={() => navigate('/inbox')}>New Inbox entry</button>
+ </>;
+}
+
+function mount() {
+ const key = `inbox-${++entry}`;
+ const app = () => <StrictMode><MemoryRouter initialEntries={[{ pathname: '/inbox', key }]}>
+ <Routes>
+ <Route path="/inbox" element={<InboxPage />} />
+ <Route path="/chat/:sessionId" element={<Chat />} />
+ <Route path="/search" element={<Chat />} />
+ </Routes>
+ </MemoryRouter></StrictMode>;
+ const view = render(app(), { container: shell });
+ return { ...view, update: () => view.rerender(app()) };
+}
+
+const article = (id: number) => shell.querySelector<HTMLElement>(`[data-inbox-session-id="session-${id}"]`)!;
+const offset = (id: number) => article(id).getBoundingClientRect().top - shell.getBoundingClientRect().top;
+const open = (id: number) => {
+ fireEvent.click(within(article(id)).getByRole('button', { name: /workbench.inbox.openSession/ }));
+ expect(shell.scrollTop).toBe(0); // Chat's shorter layout clamps the shared scroll owner.
+};
+const back = () => fireEvent.click(screen.getByText('Back'));
+
+beforeEach(() => {
+ writeInboxFilter('unread', 0);
+ feed.inboxSessions = Array.from({ length: 70 }, (_, index) => row(index + 1));
+ feed.unreadBySession = Object.fromEntries(feed.inboxSessions.map((s) => [s.session_id, 1]));
+ feed.loading = false;
+ feed.refresh.mockClear();
+ feed.loadMore.mockClear();
+ rowHeight = 160;
+ shell = document.createElement('div');
+ shell.id = APP_SHELL_SCROLL_ID;
+ shell.style.overflowY = 'auto';
+ document.body.appendChild(shell);
+ let top = 0;
+ const max = () => Math.max(0, shell.querySelectorAll('article').length * rowHeight + 200 - 600);
+ Object.defineProperties(shell, {
+ scrollTop: { configurable: true, get: () => { top = Math.min(top, max()); return top; },
+ set: (next: number) => { top = Math.max(0, Math.min(next, max())); } },
+ clientHeight: { configurable: true, value: 600 },
+ scrollHeight: { configurable: true, get: () => max() + 600 },
+ });
+ vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function (this: HTMLElement) {
+ const index = Array.from(shell.querySelectorAll('article')).indexOf(this);
+ const y = this === shell ? 64 : 64 + 200 + Math.max(0, index) * rowHeight - shell.scrollTop;
+ const height = this === shell ? 600 : rowHeight;
+ return { x: 0, y, top: y, bottom: y + height, left: 0, right: 390, width: 390, height, toJSON: () => ({}) };
+ });
+ resizeCallbacks = new Set();
+ vi.stubGlobal('ResizeObserver', class {
+ callback: () => void;
+ constructor(callback: () => void) { this.callback = callback; }
+ observe() { resizeCallbacks.add(this.callback); }
+ disconnect() { resizeCallbacks.delete(this.callback); }
+ });
+});
+
+afterEach(() => {
+ cleanup();
+ shell.remove();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+});
+
+describe('Inbox return position', () => {
+ it('keeps the loaded window and reading position on repeated history returns', () => {
+ mount();
+ for (const id of [65, 64, 63]) {
+ shell.scrollTop = 9900;
+ const before = offset(id);
+ open(id);
+ back();
+ expect(offset(id)).toBe(before);
+ expect(shell.querySelectorAll('article')).toHaveLength(70);
+ }
+ expect(feed.refresh).not.toHaveBeenCalled();
+ expect(feed.loadMore).not.toHaveBeenCalled();
+ });
+
+ it('anchors a surviving visible conversation when read rows disappear', () => {
+ mount();
+ shell.scrollTop = 650;
+ const before = offset(4);
+ open(3);
+ delete feed.unreadBySession['session-3'];
+ back();
+ expect(article(3)).toBeNull();
+ expect(offset(4)).toBe(before);
+ expect(shell.scrollTop).toBe(490);
+ });
+
+ it('does not replay a consumed Chat snapshot after a later Search return', () => {
+ mount();
+ shell.scrollTop = 650;
+ open(3);
+ back();
+ expect(shell.scrollTop).toBe(650);
+ // A successful restore must consume the shared snapshot even without an
+ // input event. Its local copy still handles layout corrections in this visit.
+ shell.scrollTop = 300;
+ fireEvent.click(screen.getByRole('button', { name: /workbench.search.entry/ }));
+ expect(shell.scrollTop).toBe(0);
+ back();
+ expect(shell.scrollTop).toBe(0);
+ });
+
+ it('uses the nearest surviving neighbor when every visible row disappears', () => {
+ mount();
+ shell.scrollTop = 650;
+ open(3);
+ for (let id = 3; id <= 7; id++) delete feed.unreadBySession[`session-${id}`];
+ back();
+ expect(offset(8)).toBe(shell.clientHeight - rowHeight);
+ expect(shell.scrollTop).toBeGreaterThan(0);
+ });
+
+ it('clamps to the new bottom when the last unread conversation is removed', () => {
+ mount();
+ shell.scrollTop = shell.scrollHeight;
+ open(70);
+ delete feed.unreadBySession['session-70'];
+ back();
+ expect(shell.scrollTop).toBe(shell.scrollHeight - shell.clientHeight);
+ expect(shell.scrollTop).toBeGreaterThan(0);
+ });
+
+ it('preserves the anchor when new activity inserts conversations above it', () => {
+ mount();
+ shell.scrollTop = 650;
+ const before = offset(3);
+ open(3);
+ feed.inboxSessions = [row(90), ...feed.inboxSessions];
+ feed.unreadBySession['session-90'] = 1;
+ back();
+ expect(offset(3)).toBe(before);
+ expect(shell.scrollTop).toBe(810);
+ });
+
+ it('waits for rows and corrects late layout changes without overriding user input', () => {
+ const view = mount();
+ shell.scrollTop = 650;
+ const before = offset(3);
+ open(3);
+ const sessions = feed.inboxSessions;
+ feed.inboxSessions = [];
+ feed.loading = true;
+ back();
+ expect(shell.scrollTop).toBe(0);
+ feed.inboxSessions = sessions;
+ feed.loading = false;
+ // A parent context update renders the page even though the route is unchanged.
+ view.update();
+ expect(offset(3)).toBe(before);
+ rowHeight = 190;
+ act(() => resizeCallbacks.forEach((callback) => callback()));
+ expect(offset(3)).toBe(before);
+ fireEvent.wheel(shell);
+ shell.scrollTop = 300;
+ rowHeight = 210;
+ act(() => resizeCallbacks.forEach((callback) => callback()));
+ expect(shell.scrollTop).toBe(300);
+ });
+
+ it.each(['wheel', 'touchstart', 'pointerdown', 'keydown'])('respects %s input before delayed rows return', (event) => {
+ const view = mount();
+ shell.scrollTop = 650;
+ open(3);
+ const sessions = feed.inboxSessions;
+ feed.inboxSessions = [];
+ back();
+ fireEvent(shell, new Event(event, { bubbles: true }));
+ // Resize can occur before the next React commit; it must not reclaim scrolling.
+ act(() => resizeCallbacks.forEach((callback) => callback()));
+ expect(resizeCallbacks.size).toBe(0);
+ feed.inboxSessions = sessions;
+ view.update();
+ expect(shell.scrollTop).toBe(0);
+ fireEvent.click(screen.getByRole('button', { name: /workbench.search.entry/ }));
+ back();
+ expect(shell.scrollTop).toBe(0);
+ });
+
+ it('does not restore another history entry, even with the same filter', () => {
+ mount();
+ shell.scrollTop = 650;
+ open(3);
+ fireEvent.click(screen.getByText('New Inbox entry'));
+ expect(shell.scrollTop).toBe(0);
+ });
+
+ it('does not restore an expired return even when the filter is unchanged', () => {
+ mount();
+ shell.scrollTop = 650;
+ open(3);
+ const now = Date.now();
+ vi.spyOn(Date, 'now').mockReturnValue(now + INBOX_REVERT_AFTER_MS + 1);
+ back();
+ expect(shell.scrollTop).toBe(0);
+ });
+
+ it('does not apply the previous filter position to a different filter', () => {
+ mount();
+ shell.scrollTop = 650;
+ open(3);
+ writeInboxFilter('all', 0);
+ back();
+ expect(shell.scrollTop).toBe(0);
+ });
+
+ it('starts at the top when the entire old reading neighborhood is gone', () => {
+ mount();
+ shell.scrollTop = 650;
+ open(3);
+ feed.inboxSessions = Array.from({ length: 30 }, (_, index) => row(index + 100));
+ feed.unreadBySession = Object.fromEntries(feed.inboxSessions.map((s) => [s.session_id, 1]));
+ back();
+ expect(shell.scrollTop).toBe(0);
+ });
+
+ it('leaves an Inbox opened from the top at the top when new rows arrive', () => {
+ mount();
+ open(1);
+ feed.inboxSessions = [row(90), ...feed.inboxSessions];
+ feed.unreadBySession['session-90'] = 1;
+ back();
+ expect(shell.scrollTop).toBe(0);
+ });
+});
diff --git a/ui/src/components/workbench/InboxPage.tsx b/ui/src/components/workbench/InboxPage.tsx
index d23714b09..5072e1347 100644
--- a/ui/src/components/workbench/InboxPage.tsx
+++ b/ui/src/components/workbench/InboxPage.tsx
@@ -1,6 +1,6 @@
-import { useCallback, useEffect, useMemo, useState } from 'react';
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
+import { useLocation, useNavigate } from 'react-router-dom';
import { ArrowRight, CheckCheck, Filter, Inbox, Loader2, MessageSquareReply, RefreshCw, Search } from 'lucide-react';
import clsx from 'clsx';
@@ -11,6 +11,7 @@ import { formatRelativeTime } from '../../lib/relativeTime';
import { Markdown } from '../ui/markdown';
import { Button } from '../ui/button';
import { WebPushControl } from './WebPushControl';
+import { useInboxScrollRestoration } from './useInboxScrollRestoration';
import {
readInboxFilter,
writeInboxFilter,
@@ -22,6 +23,8 @@ import {
export const InboxPage: React.FC = () => {
const { t } = useTranslation();
const navigate = useNavigate();
+ const location = useLocation();
+ const listRef = useRef<HTMLDivElement>(null);
const {
capabilities,
} = useInstanceAuthorization();
@@ -97,7 +100,10 @@ export const InboxPage: React.FC = () => {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [filter, inboxSessions, unreadBySession]);
+ const capturePosition = useInboxScrollRestoration(listRef, location.key, filter, visible);
+
const openSession = (s: InboxSession) => {
+ capturePosition();
navigate(`/chat/${encodeURIComponent(s.session_id)}`);
};
@@ -117,7 +123,7 @@ export const InboxPage: React.FC = () => {
const showEmpty = visible.length === 0 && (filter === 'unread' ? unreadSessions === 0 : !hasMore);
return (
- <div className="mx-auto flex w-full max-w-4xl flex-col gap-6 py-2">
+ <div ref={listRef} className="mx-auto flex w-full max-w-4xl flex-col gap-6 py-2">
{/* Header */}
<div className="flex flex-wrap items-center gap-4">
<div className="flex size-12 shrink-0 items-center justify-center rounded-2xl border border-mint/30 bg-mint/[0.08] text-mint-ink shadow-glow-md-mint">
@@ -238,6 +244,7 @@ export const InboxPage: React.FC = () => {
return (
<article
key={s.session_id}
+ data-inbox-session-id={s.session_id}
className={clsx(
'flex flex-col gap-3 rounded-xl border p-4 transition',
unread > 0
diff --git a/ui/src/components/workbench/useInboxScrollRestoration.ts b/ui/src/components/workbench/useInboxScrollRestoration.ts
new file mode 100644
index 000000000..d0ce38ee4
--- /dev/null
+++ b/ui/src/components/workbench/useInboxScrollRestoration.ts
@@ -0,0 +1,116 @@
+import { useCallback, useLayoutEffect, useRef, type RefObject } from 'react';
+import { INBOX_REVERT_AFTER_MS, type InboxFilter } from '../../lib/inboxFilterMemory';
+import { APP_SHELL_SCROLL_ID, writeAppShellScrollTop } from '../../lib/mobileProjectsListMemory';
+
+type Snapshot = {
+ entryKey: string;
+ filter: InboxFilter;
+ savedAt: number;
+ scrollTop: number;
+ anchors: { id: string; top: number }[];
+};
+
+// One Inbox -> Chat return, tied to its history entry, not every future visit.
+// Keep only geometry and IDs; the Inbox provider already owns the loaded pages.
+let saved: Snapshot | null = null;
+
+function scrollOwner(root: HTMLElement): HTMLElement | null {
+ const shell = root.closest<HTMLElement>(`#${APP_SHELL_SCROLL_ID}`);
+ return shell && getComputedStyle(shell).overflowY !== 'visible'
+ ? shell
+ : root.ownerDocument.scrollingElement as HTMLElement | null;
+}
+
+function viewportTop(owner: HTMLElement): number {
+ return owner === owner.ownerDocument.scrollingElement ? 0 : owner.getBoundingClientRect().top;
+}
+
+export function useInboxScrollRestoration(
+ rootRef: RefObject<HTMLDivElement | null>,
+ entryKey: string,
+ filter: InboxFilter,
+ visible: readonly { session_id: string }[],
+) {
+ const pending = useRef(saved);
+
+ useLayoutEffect(() => {
+ const snapshot = pending.current;
+ if (!snapshot) return;
+ if (snapshot.entryKey !== entryKey || snapshot.filter !== filter
+ || Date.now() - snapshot.savedAt > INBOX_REVERT_AFTER_MS) {
+ pending.current = null;
+ return;
+ }
+ const root = rootRef.current;
+ const owner = root && scrollOwner(root);
+ if (!root || !owner) return;
+
+ const restore = () => {
+ if (pending.current !== snapshot) return;
+ const rows = new Map(Array.from(root.querySelectorAll<HTMLElement>('[data-inbox-session-id]'))
+ .map((row) => [row.dataset.inboxSessionId, row]));
+ // A returning route may paint before its cached/reconciled rows arrive.
+ // Do not consume the position while the content is still empty.
+ if (rows.size === 0) return;
+ const anchor = snapshot.anchors.find(({ id }) => rows.has(id));
+ const row = anchor && rows.get(anchor.id);
+ const top = snapshot.scrollTop === 0 ? 0 : row && anchor
+ ? owner.scrollTop + row.getBoundingClientRect().top - viewportTop(owner) - anchor.top
+ : 0;
+ writeAppShellScrollTop(owner, top);
+ // Keep the local copy for late layout changes, but never replay this
+ // consumed Chat return after another route remounts the same Inbox entry.
+ if (saved === snapshot) saved = null;
+ };
+
+ restore();
+ const frame = requestAnimationFrame(restore);
+ const observer = typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(restore);
+ observer?.observe(root);
+ observer?.observe(owner);
+ const stop = () => {
+ pending.current = null;
+ if (saved === snapshot) saved = null;
+ observer?.disconnect();
+ cancelAnimationFrame(frame);
+ };
+ const inputs = ['wheel', 'touchstart', 'pointerdown', 'keydown'] as const;
+ inputs.forEach((event) => owner.addEventListener(event, stop, { passive: true, capture: true }));
+ return () => {
+ cancelAnimationFrame(frame);
+ observer?.disconnect();
+ inputs.forEach((event) => owner.removeEventListener(event, stop, true));
+ };
+ }, [entryKey, filter, rootRef, visible]);
+
+ return useCallback(() => {
+ const root = rootRef.current;
+ const owner = root && scrollOwner(root);
+ if (!root || !owner) return;
+ const top = viewportTop(owner);
+ const height = owner.clientHeight;
+ const candidates = Array.from(root.querySelectorAll<HTMLElement>('[data-inbox-session-id]')).map((row) => {
+ const rect = row.getBoundingClientRect();
+ const offset = rect.top - top;
+ const bottom = rect.bottom - top;
+ return {
+ id: row.dataset.inboxSessionId!,
+ top: bottom > 0 && offset < height
+ ? offset
+ : Math.max(0, Math.min(offset, height - rect.height)),
+ distance: bottom <= 0 ? -bottom : offset >= height ? offset - height : 0,
+ };
+ });
+ // Prefer visible rows, then the nearest surviving neighbor if read/archive
+ // updates remove every visible row while Chat is open.
+ candidates.sort((a, b) => a.distance - b.distance);
+ saved = {
+ entryKey,
+ filter,
+ savedAt: Date.now(),
+ scrollTop: owner.scrollTop,
+ anchors: candidates.map(({ id, top: offset }) => ({ id, top: offset })),
+ };
+ pending.current = null;
+ }, [entryKey, filter, rootRef]);
+}