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(ui): keep mobile project session window across chat (#1579)

Call White9436f0eade45
diff --git a/ui/src/components/AppShell.test.tsx b/ui/src/components/AppShell.test.tsx
index 9c5720719..a3667c3b8 100644
--- a/ui/src/components/AppShell.test.tsx
+++ b/ui/src/components/AppShell.test.tsx
@@ -2,9 +2,16 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { cleanup, render, screen } from '@testing-library/react';
-import { MemoryRouter, Route, Routes } from 'react-router-dom';
+import userEvent from '@testing-library/user-event';
+import { MemoryRouter, Route, Routes, useNavigate } from 'react-router-dom';
import type { ReactNode } from 'react';
+import {
+ APP_SHELL_SCROLL_ID,
+ clearMobileProjectsListSnapshot,
+ holdMobileProjectsListForChatReturn,
+ readMobileProjectsListSnapshot,
+} from '../lib/mobileProjectsListMemory';
import { AppShell } from './AppShell';
const viewport = vi.hoisted(() => {
@@ -99,6 +106,7 @@ vi.mock('react-i18next', () => ({
beforeEach(() => {
viewport.isDesktop = false;
+ clearMobileProjectsListSnapshot();
instanceAuth.instanceKind = null;
instanceAuth.capabilities.can_manage_instance = true;
instanceAuth.capabilities.can_chat = true;
@@ -113,6 +121,7 @@ beforeEach(() => {
afterEach(() => {
cleanup();
+ clearMobileProjectsListSnapshot();
vi.clearAllMocks();
});
@@ -161,6 +170,58 @@ describe('AppShell workbench sidebar', () => {
// desktop-only container is gated, not the container.
expect(screen.getAllByText('appShell.title').length).toBeGreaterThan(0);
});
+
+ it('exposes the mobile scroll owner for page-level restoration', async () => {
+ render(
+ <MemoryRouter initialEntries={['/projects']}>
+ <Routes>
+ <Route element={<AppShell />}>
+ <Route path="/projects" element={<div data-testid="projects-surface" />} />
+ </Route>
+ </Routes>
+ </MemoryRouter>,
+ );
+
+ expect(await screen.findByTestId('projects-surface')).toBeTruthy();
+ expect(document.getElementById(APP_SHELL_SCROLL_ID)).not.toBeNull();
+ });
+
+ it('forgets the mobile projects list when leaving chat or projects', async () => {
+ const user = userEvent.setup();
+ holdMobileProjectsListForChatReturn({ visibleCounts: { proj_a: 16 }, scrollTop: 180 });
+
+ const ChatProbe = () => {
+ const navigate = useNavigate();
+ return (
+ <div data-testid="chat-surface">
+ <button type="button" onClick={() => navigate('/inbox')}>
+ leave-chat
+ </button>
+ </div>
+ );
+ };
+
+ render(
+ <MemoryRouter initialEntries={['/chat/ses_1']}>
+ <Routes>
+ <Route element={<AppShell />}>
+ <Route path="/chat/:sessionId" element={<ChatProbe />} />
+ <Route path="/inbox" element={<div data-testid="inbox-surface" />} />
+ </Route>
+ </Routes>
+ </MemoryRouter>,
+ );
+
+ expect(await screen.findByTestId('chat-surface')).toBeTruthy();
+ expect(readMobileProjectsListSnapshot()).toEqual({
+ visibleCounts: { proj_a: 16 },
+ scrollTop: 180,
+ });
+
+ await user.click(screen.getByRole('button', { name: 'leave-chat' }));
+ expect(await screen.findByTestId('inbox-surface')).toBeTruthy();
+ expect(readMobileProjectsListSnapshot()).toEqual({ visibleCounts: {}, scrollTop: 0 });
+ });
});
describe('AppShell Permissions navigation', () => {
diff --git a/ui/src/components/AppShell.tsx b/ui/src/components/AppShell.tsx
index c774822f4..7f3789bba 100644
--- a/ui/src/components/AppShell.tsx
+++ b/ui/src/components/AppShell.tsx
@@ -32,6 +32,7 @@ import { InstallHint } from './InstallHint';
import logoImg from '../assets/logo.png';
import { getEnabledPlatforms, platformSupportsChannels } from '../lib/platforms';
import { useViewportHeightVar } from '../lib/useViewportHeightVar';
+import { APP_SHELL_SCROLL_ID, forgetMobileProjectsListUnlessPreserved } from '../lib/mobileProjectsListMemory';
import { useIsDesktop } from '../lib/useIsDesktop';
import {
adminLandingPath,
@@ -271,6 +272,9 @@ export const AppShell: React.FC = () => {
} = useInstanceAuthorization();
const api = useApi();
const location = useLocation();
+ useEffect(() => {
+ forgetMobileProjectsListUnlessPreserved(location.pathname);
+ }, [location.pathname]);
const [enabledPlatforms, setEnabledPlatforms] = useState<string[]>([]);
const [config, setConfig] = useState<any>(null);
const [memoryNavVisible, setMemoryNavVisible] = useState(false);
@@ -726,6 +730,7 @@ export const AppShell: React.FC = () => {
)}
<main
+ id={APP_SHELL_SCROLL_ID}
className={clsx(
// Mobile: the internal scroll area of the locked flex-column shell, so
// the document itself never scrolls. Desktop: normal flow (min-h-screen
diff --git a/ui/src/components/workbench/ProjectsPage.test.tsx b/ui/src/components/workbench/ProjectsPage.test.tsx
new file mode 100644
index 000000000..7c457a473
--- /dev/null
+++ b/ui/src/components/workbench/ProjectsPage.test.tsx
@@ -0,0 +1,187 @@
+/* @vitest-environment jsdom */
+
+import { useState } from 'react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { cleanup, render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { MemoryRouter } from 'react-router-dom';
+
+import { InstanceAuthorizationContext } from '../../context/InstanceAuthorizationContext';
+import type { ProjectSessionsState } from '../../context/WorkbenchProjectsContext';
+import type { WorkbenchProject, WorkbenchSession } from '../../context/ApiContext';
+import { OWNER_INSTANCE_CAPABILITIES } from '../../lib/sessionInfo';
+import {
+ clearMobileProjectsListSnapshot,
+ holdMobileProjectsListForChatReturn,
+ readMobileProjectsListSnapshot,
+} from '../../lib/mobileProjectsListMemory';
+import { ProjectsPage } from './ProjectsPage';
+
+const tree = vi.hoisted(() => ({
+ projects: [] as WorkbenchProject[],
+ sessions: [] as WorkbenchSession[],
+ loadMore: vi.fn(),
+ toggleExpanded: vi.fn(),
+}));
+
+vi.mock('../../context/WorkbenchInboxContext', () => ({
+ useWorkbenchInbox: () => ({ unreadBySession: {} }),
+}));
+
+vi.mock('../../context/WorkbenchProjectsContext', () => ({
+ useWorkbenchProjectsActions: () => ({
+ renameProject: vi.fn(),
+ archiveProject: vi.fn(),
+ createSessionForProject: vi.fn(),
+ renameSession: vi.fn(),
+ }),
+ useWorkbenchProjectsTree: () => {
+ const [expanded, setExpanded] = useState<Set<string>>(new Set([tree.projects[0]?.id]));
+ const state: ProjectSessionsState = {
+ sessions: tree.sessions,
+ loading: false,
+ loadingMore: false,
+ cursor: 'next',
+ error: false,
+ };
+ return {
+ projects: tree.projects,
+ projectsError: null,
+ refreshProjects: vi.fn(),
+ sessionsOf: () => state,
+ isExpanded: (id: string) => expanded.has(id),
+ toggleExpanded: (id: string) => {
+ tree.toggleExpanded(id);
+ setExpanded((prev) => {
+ const next = new Set(prev);
+ if (next.has(id)) next.delete(id);
+ else next.add(id);
+ return next;
+ });
+ },
+ loadMore: tree.loadMore,
+ reloadSessions: vi.fn(),
+ creatingSession: () => false,
+ };
+ },
+}));
+
+vi.mock('./useSessionActions', () => ({
+ useSessionActions: () => ({ actions: [], archiveDialog: null }),
+}));
+
+vi.mock('./NewProjectDialog', () => ({ NewProjectDialog: () => null }));
+vi.mock('./ProjectAgentsMdDialog', () => ({ ProjectAgentsMdDialog: () => null }));
+vi.mock('./ProjectSettingsDialog', () => ({ ProjectSettingsDialog: () => null }));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+const project: WorkbenchProject = {
+ id: 'proj_a',
+ scope_id: 'avibe::project::proj_a',
+ display_name: 'Alpha',
+ folder_path: '/tmp/alpha',
+ created_at: '2026-08-01T00:00:00Z',
+ last_active_at: '2026-08-19T00:00:00Z',
+ archived: false,
+ capabilities: { can_chat: true, has_folder: true },
+};
+
+const session = (index: number): WorkbenchSession =>
+ ({
+ id: `ses_${index}`,
+ scope_id: 'avibe::project::proj_a',
+ project_id: 'proj_a',
+ title: `Session ${index}`,
+ status: 'active',
+ pinned: false,
+ agent_status: 'idle',
+ workdir: '/tmp/alpha',
+ native_session_id: `native_${index}`,
+ created_at: '2026-08-01T00:00:00Z',
+ updated_at: '2026-08-01T00:00:00Z',
+ last_active_at: '2026-08-19T00:00:00Z',
+ metadata: {},
+ }) as WorkbenchSession;
+
+function renderPage() {
+ const view = render(
+ <InstanceAuthorizationContext.Provider
+ value={{
+ remote: false,
+ instanceKind: null,
+ instanceRole: 'owner',
+ capabilities: OWNER_INSTANCE_CAPABILITIES,
+ }}
+ >
+ <MemoryRouter initialEntries={['/projects']}>
+ <ProjectsPage />
+ </MemoryRouter>
+ </InstanceAuthorizationContext.Provider>,
+ );
+ return view;
+}
+
+beforeEach(() => {
+ tree.projects = [project];
+ tree.sessions = Array.from({ length: 16 }, (_, index) => session(index + 1));
+ tree.loadMore.mockReset();
+ tree.toggleExpanded.mockReset();
+ clearMobileProjectsListSnapshot();
+});
+
+afterEach(() => {
+ cleanup();
+ clearMobileProjectsListSnapshot();
+});
+
+describe('ProjectsPage mobile session window', () => {
+ it('reveals the next cached page without fetching until the cache is exhausted', async () => {
+ const user = userEvent.setup();
+ const view = renderPage();
+
+ expect(screen.getByText('Session 8')).toBeTruthy();
+ expect(screen.queryByText('Session 9')).toBeNull();
+
+ await user.click(screen.getByRole('button', { name: 'projects.loadMore' }));
+ expect(screen.getByText('Session 16')).toBeTruthy();
+ expect(tree.loadMore).not.toHaveBeenCalled();
+ view.unmount();
+ });
+
+ it('captures the revealed window before opening a session', async () => {
+ const user = userEvent.setup();
+ const view = renderPage();
+
+ await user.click(screen.getByRole('button', { name: 'projects.loadMore' }));
+ await user.click(screen.getByText('Session 12'));
+
+ expect(readMobileProjectsListSnapshot().visibleCounts).toEqual({ proj_a: 16 });
+ view.unmount();
+ });
+
+ it('resumes a held window after returning from chat', () => {
+ holdMobileProjectsListForChatReturn({ visibleCounts: { proj_a: 16 }, scrollTop: 180 });
+ const view = renderPage();
+ expect(screen.getByText('Session 16')).toBeTruthy();
+ view.unmount();
+ });
+
+ it('forgets a project window when that project is collapsed and expanded again', async () => {
+ const user = userEvent.setup();
+ const view = renderPage();
+
+ await user.click(screen.getByRole('button', { name: 'projects.loadMore' }));
+ expect(screen.getByText('Session 16')).toBeTruthy();
+
+ await user.click(screen.getByText('Alpha'));
+ expect(screen.queryByText('Session 1')).toBeNull();
+
+ await user.click(screen.getByText('Alpha'));
+ expect(screen.getByText('Session 8')).toBeTruthy();
+ expect(screen.queryByText('Session 9')).toBeNull();
+ view.unmount();
+ });
+});
diff --git a/ui/src/components/workbench/ProjectsPage.tsx b/ui/src/components/workbench/ProjectsPage.tsx
index 9396ae9bf..2f529171f 100644
--- a/ui/src/components/workbench/ProjectsPage.tsx
+++ b/ui/src/components/workbench/ProjectsPage.tsx
@@ -25,6 +25,21 @@ import { useInstanceAuthorization } from '../../context/InstanceAuthorizationCon
import type { ProjectSessionsState } from '../../context/WorkbenchProjectsContext';
import type { WorkbenchProject, WorkbenchSession } from '../../context/ApiContext';
import { formatRelativeTime } from '../../lib/relativeTime';
+import {
+ appShellScrollElement,
+ clearProjectVisibleCount,
+ holdMobileProjectsListForChatReturn,
+ markMobileProjectsListRestored,
+ readAppShellScrollTop,
+ readMobileProjectsListSnapshot,
+ rememberMobileProjectsListCounts,
+ rememberMobileProjectsListOnPageLeave,
+ rememberMobileProjectsListScroll,
+ revealMoreVisibleCount,
+ visibleSessionCountFor,
+ writeAppShellScrollTop,
+ type MobileProjectsVisibleCounts,
+} from '../../lib/mobileProjectsListMemory';
import { canCreateLocalProject } from '../../lib/sessionInfo';
import { Badge } from '../ui/badge';
import { Button } from '../ui/button';
@@ -43,7 +58,6 @@ const DOT: Record<string, string> = {
failed: 'bg-destructive',
idle: 'bg-muted',
};
-const MOBILE_SESSION_PAGE_SIZE = 8;
// One row in a ⋯ popover menu, on the design-system Button idiom (plain button to
// match the desktop sidebar menus). `danger` tints destructive actions (archive).
@@ -78,7 +92,8 @@ const MobileProjectRow: React.FC<{
open: boolean;
state: ProjectSessionsState;
onToggle: () => void;
-}> = ({ project, open, state, onToggle }) => {
+ onLeaveToChat: () => void;
+}> = ({ project, open, state, onToggle, onLeaveToChat }) => {
const { t } = useTranslation();
const navigate = useNavigate();
const { capabilities } = useInstanceAuthorization();
@@ -186,7 +201,10 @@ const MobileProjectRow: React.FC<{
creatingSessionRef.current = true;
try {
const session = await createSessionForProject(project.id);
- if (session) navigate(`/chat/${encodeURIComponent(session.id)}`);
+ if (session) {
+ onLeaveToChat();
+ navigate(`/chat/${encodeURIComponent(session.id)}`);
+ }
} finally {
creatingSessionRef.current = false;
}
@@ -262,7 +280,8 @@ const MobileSessionRow: React.FC<{
canChat: boolean;
canManageMetadata: boolean;
onOpen: () => void;
-}> = ({ projectId, session, unread, canChat, canManageMetadata, onOpen }) => {
+ onLeaveToChat: () => void;
+}> = ({ projectId, session, unread, canChat, canManageMetadata, onOpen, onLeaveToChat }) => {
const { t } = useTranslation();
const { renameSession } = useWorkbenchProjectsActions();
const navigate = useNavigate();
@@ -282,7 +301,10 @@ const MobileSessionRow: React.FC<{
handledRef.current = false;
setRenaming(true);
},
- onOpenSession: (sessionId) => navigate(`/chat/${encodeURIComponent(sessionId)}`),
+ onOpenSession: (sessionId) => {
+ onLeaveToChat();
+ navigate(`/chat/${encodeURIComponent(sessionId)}`);
+ },
});
useEffect(() => {
@@ -395,15 +417,56 @@ export const ProjectsPage: React.FC = () => {
reloadSessions,
} = useWorkbenchProjectsTree();
const [showNewProject, setShowNewProject] = useState(false);
- const [visibleSessionCounts, setVisibleSessionCounts] = useState<Record<string, number>>({});
+ const [visibleSessionCounts, setVisibleSessionCounts] = useState<MobileProjectsVisibleCounts>(
+ () => readMobileProjectsListSnapshot().visibleCounts,
+ );
+ useEffect(() => {
+ const top = readMobileProjectsListSnapshot().scrollTop;
+ const restore = () => writeAppShellScrollTop(appShellScrollElement(), top);
+ restore();
+ const frame = requestAnimationFrame(restore);
+ markMobileProjectsListRestored();
+ const scrollEl = appShellScrollElement();
+ const onScroll = () => rememberMobileProjectsListScroll(readAppShellScrollTop(scrollEl));
+ scrollEl?.addEventListener?.('scroll', onScroll, { passive: true });
+ return () => {
+ cancelAnimationFrame(frame);
+ scrollEl?.removeEventListener?.('scroll', onScroll);
+ };
+ }, []);
+
+ useEffect(() => {
+ rememberMobileProjectsListCounts(visibleSessionCounts);
+ return () => {
+ rememberMobileProjectsListOnPageLeave({
+ visibleCounts: visibleSessionCounts,
+ scrollTop: readMobileProjectsListSnapshot().scrollTop,
+ });
+ };
+ }, [visibleSessionCounts]);
+
+ const captureListForChatReturn = () => {
+ holdMobileProjectsListForChatReturn({
+ visibleCounts: visibleSessionCounts,
+ scrollTop: readAppShellScrollTop(appShellScrollElement()),
+ });
+ };
const openSession = (sessionId: string) => {
- navigate(`/chat/${sessionId}`);
+ captureListForChatReturn();
+ navigate(`/chat/${encodeURIComponent(sessionId)}`);
+ };
+ const toggleProject = (projectId: string) => {
+ const willCollapse = isExpanded(projectId);
+ if (willCollapse) {
+ setVisibleSessionCounts((prev) => clearProjectVisibleCount(prev, projectId));
+ }
+ toggleExpanded(projectId);
};
const revealMoreSessions = (projectId: string, state: ProjectSessionsState, visibleCount: number, loadedCount: number) => {
setVisibleSessionCounts((prev) => ({
...prev,
- [projectId]: visibleCount + MOBILE_SESSION_PAGE_SIZE,
+ [projectId]: revealMoreVisibleCount(visibleCount),
}));
if (loadedCount <= visibleCount && state.cursor) {
loadMore(projectId);
@@ -456,13 +519,19 @@ export const ProjectsPage: React.FC = () => {
const open = isExpanded(project.id);
const state = sessionsOf(project.id);
const allSessionRows = state.sessions ?? [];
- const visibleSessionCount = visibleSessionCounts[project.id] ?? MOBILE_SESSION_PAGE_SIZE;
+ const visibleSessionCount = visibleSessionCountFor(visibleSessionCounts, project.id);
const sessionRows = allSessionRows.slice(0, visibleSessionCount);
const hasHiddenCachedSessions = allSessionRows.length > visibleSessionCount;
const hasMoreSessions = hasHiddenCachedSessions || !!state.cursor;
return (
<div key={project.id} className="overflow-hidden rounded-xl border border-border bg-surface">
- <MobileProjectRow project={project} open={open} state={state} onToggle={() => toggleExpanded(project.id)} />
+ <MobileProjectRow
+ project={project}
+ open={open}
+ state={state}
+ onToggle={() => toggleProject(project.id)}
+ onLeaveToChat={captureListForChatReturn}
+ />
{open && (
<div className="flex flex-col gap-0.5 border-t border-border px-2 py-2">
@@ -494,6 +563,7 @@ export const ProjectsPage: React.FC = () => {
canChat={capabilities.can_chat && project.capabilities.can_chat}
canManageMetadata={capabilities.can_manage_projects || project.capabilities.can_chat}
onOpen={() => openSession(session.id)}
+ onLeaveToChat={captureListForChatReturn}
/>
))}
{hasMoreSessions && (
diff --git a/ui/src/lib/mobileProjectsListMemory.test.ts b/ui/src/lib/mobileProjectsListMemory.test.ts
new file mode 100644
index 000000000..a301803ad
--- /dev/null
+++ b/ui/src/lib/mobileProjectsListMemory.test.ts
@@ -0,0 +1,119 @@
+import { afterEach, describe, expect, it } from 'vitest';
+
+import {
+ MOBILE_SESSION_PAGE_SIZE,
+ clearMobileProjectsListSnapshot,
+ clearProjectVisibleCount,
+ forgetMobileProjectsListUnlessPreserved,
+ holdMobileProjectsListForChatReturn,
+ isChatRoutePath,
+ isMobileProjectsListHeldForChatReturn,
+ markMobileProjectsListRestored,
+ readMobileProjectsListSnapshot,
+ rememberMobileProjectsListCounts,
+ rememberMobileProjectsListOnPageLeave,
+ rememberMobileProjectsListScroll,
+ revealMoreVisibleCount,
+ visibleSessionCountFor,
+ appShellScrollElement,
+ readAppShellScrollTop,
+ writeAppShellScrollTop,
+ writeMobileProjectsListSnapshot,
+} from './mobileProjectsListMemory';
+
+afterEach(() => {
+ clearMobileProjectsListSnapshot();
+});
+
+describe('mobile projects list memory', () => {
+ it('treats only /chat/* as a chat leave', () => {
+ expect(isChatRoutePath('/chat/ses_1')).toBe(true);
+ expect(isChatRoutePath('/projects')).toBe(false);
+ expect(isChatRoutePath('/inbox')).toBe(false);
+ });
+
+ it('pages visible counts from the compact first window', () => {
+ expect(visibleSessionCountFor({}, 'proj_a')).toBe(MOBILE_SESSION_PAGE_SIZE);
+ expect(visibleSessionCountFor({ proj_a: 16 }, 'proj_a')).toBe(16);
+ expect(revealMoreVisibleCount(8)).toBe(16);
+ expect(revealMoreVisibleCount(16)).toBe(24);
+ });
+
+ it("collapsing a project forgets only that project's revealed window", () => {
+ const counts = { proj_a: 24, proj_b: 16 };
+ expect(clearProjectVisibleCount(counts, 'proj_a')).toEqual({ proj_b: 16 });
+ expect(clearProjectVisibleCount(counts, 'proj_missing')).toBe(counts);
+ });
+
+ it('holds a snapshot across chat, then forgets it after restore plus a non-chat leave', () => {
+ holdMobileProjectsListForChatReturn({ visibleCounts: { proj_a: 24 }, scrollTop: 320 });
+ expect(isMobileProjectsListHeldForChatReturn()).toBe(true);
+ forgetMobileProjectsListUnlessPreserved('/chat/ses_12');
+ expect(readMobileProjectsListSnapshot()).toEqual({
+ visibleCounts: { proj_a: 24 },
+ scrollTop: 320,
+ });
+
+ markMobileProjectsListRestored();
+ expect(isMobileProjectsListHeldForChatReturn()).toBe(false);
+ forgetMobileProjectsListUnlessPreserved('/inbox');
+ expect(readMobileProjectsListSnapshot()).toEqual({ visibleCounts: {}, scrollTop: 0 });
+ });
+
+ it('forgets a held snapshot once the user leaves chat for a non-projects page', () => {
+ holdMobileProjectsListForChatReturn({ visibleCounts: { proj_a: 16 }, scrollTop: 80 });
+ forgetMobileProjectsListUnlessPreserved('/inbox');
+ expect(readMobileProjectsListSnapshot()).toEqual({ visibleCounts: {}, scrollTop: 0 });
+ expect(isMobileProjectsListHeldForChatReturn()).toBe(false);
+ });
+
+ it('writes the live window back on a same-page remount instead of dropping it', () => {
+ writeMobileProjectsListSnapshot({ visibleCounts: {}, scrollTop: 0 });
+ rememberMobileProjectsListOnPageLeave({ visibleCounts: { proj_a: 16 }, scrollTop: 80 });
+ expect(readMobileProjectsListSnapshot()).toEqual({
+ visibleCounts: { proj_a: 16 },
+ scrollTop: 80,
+ });
+ });
+
+ it('does not overwrite a chat hold with the page-leave snapshot', () => {
+ holdMobileProjectsListForChatReturn({ visibleCounts: { proj_a: 16 }, scrollTop: 240 });
+ rememberMobileProjectsListOnPageLeave({ visibleCounts: {}, scrollTop: 0 });
+ rememberMobileProjectsListScroll(0);
+ rememberMobileProjectsListCounts({});
+ expect(readMobileProjectsListSnapshot()).toEqual({
+ visibleCounts: { proj_a: 16 },
+ scrollTop: 240,
+ });
+ });
+
+ it('keeps a live scroll offset so a later chat leave can restore it', () => {
+ rememberMobileProjectsListCounts({ proj_a: 16 });
+ rememberMobileProjectsListScroll(240);
+ expect(readMobileProjectsListSnapshot()).toEqual({
+ visibleCounts: { proj_a: 16 },
+ scrollTop: 240,
+ });
+ });
+
+ it('forgets an unrestored snapshot when leaving a non-chat page', () => {
+ writeMobileProjectsListSnapshot({ visibleCounts: { proj_a: 16 }, scrollTop: 80 });
+ forgetMobileProjectsListUnlessPreserved('/inbox');
+ expect(readMobileProjectsListSnapshot()).toEqual({ visibleCounts: {}, scrollTop: 0 });
+ });
+
+ it('rejects a negative or non-finite scroll offset', () => {
+ writeMobileProjectsListSnapshot({ visibleCounts: {}, scrollTop: -12 });
+ expect(readMobileProjectsListSnapshot().scrollTop).toBe(0);
+ writeMobileProjectsListSnapshot({ visibleCounts: {}, scrollTop: Number.NaN });
+ expect(readMobileProjectsListSnapshot().scrollTop).toBe(0);
+ });
+
+ it('reads and writes the shell scroll owner through a duck-typed node', () => {
+ const node = { scrollTop: 12 };
+ writeAppShellScrollTop(node, 180);
+ expect(readAppShellScrollTop(node)).toBe(180);
+ expect(appShellScrollElement({ getElementById: () => node })).toBe(node);
+ expect(readAppShellScrollTop(null)).toBe(0);
+ });
+});
diff --git a/ui/src/lib/mobileProjectsListMemory.ts b/ui/src/lib/mobileProjectsListMemory.ts
new file mode 100644
index 000000000..80645b6a4
--- /dev/null
+++ b/ui/src/lib/mobileProjectsListMemory.ts
@@ -0,0 +1,127 @@
+export const MOBILE_SESSION_PAGE_SIZE = 8;
+export const APP_SHELL_SCROLL_ID = 'app-shell-scroll';
+
+export type MobileProjectsVisibleCounts = Record<string, number>;
+
+export type MobileProjectsListSnapshot = {
+ visibleCounts: MobileProjectsVisibleCounts;
+ scrollTop: number;
+};
+
+const EMPTY_SNAPSHOT: MobileProjectsListSnapshot = { visibleCounts: {}, scrollTop: 0 };
+
+let snapshot: MobileProjectsListSnapshot = EMPTY_SNAPSHOT;
+let heldForChatReturn = false;
+
+export function isChatRoutePath(pathname: string): boolean {
+ return pathname.startsWith('/chat/');
+}
+
+export function isProjectsRoutePath(pathname: string): boolean {
+ return pathname === '/projects';
+}
+
+export function visibleSessionCountFor(
+ counts: MobileProjectsVisibleCounts,
+ projectId: string,
+ pageSize: number = MOBILE_SESSION_PAGE_SIZE,
+): number {
+ return counts[projectId] ?? pageSize;
+}
+
+export function revealMoreVisibleCount(
+ currentCount: number,
+ pageSize: number = MOBILE_SESSION_PAGE_SIZE,
+): number {
+ return currentCount + pageSize;
+}
+
+export function clearProjectVisibleCount(
+ counts: MobileProjectsVisibleCounts,
+ projectId: string,
+): MobileProjectsVisibleCounts {
+ if (!(projectId in counts)) return counts;
+ const next = { ...counts };
+ delete next[projectId];
+ return next;
+}
+
+export function readMobileProjectsListSnapshot(): MobileProjectsListSnapshot {
+ return snapshot;
+}
+
+export function writeMobileProjectsListSnapshot(next: MobileProjectsListSnapshot): void {
+ snapshot = {
+ visibleCounts: { ...next.visibleCounts },
+ scrollTop: Number.isFinite(next.scrollTop) ? Math.max(0, next.scrollTop) : 0,
+ };
+}
+
+export function holdMobileProjectsListForChatReturn(next: MobileProjectsListSnapshot): void {
+ writeMobileProjectsListSnapshot(next);
+ heldForChatReturn = true;
+}
+
+export function markMobileProjectsListRestored(): void {
+ heldForChatReturn = false;
+}
+
+export function rememberMobileProjectsListOnPageLeave(current: MobileProjectsListSnapshot): void {
+ if (heldForChatReturn) return;
+ writeMobileProjectsListSnapshot(current);
+}
+
+export function rememberMobileProjectsListScroll(scrollTop: number): void {
+ if (heldForChatReturn) return;
+ snapshot = {
+ ...snapshot,
+ scrollTop: Number.isFinite(scrollTop) ? Math.max(0, scrollTop) : 0,
+ };
+}
+
+export function rememberMobileProjectsListCounts(visibleCounts: MobileProjectsVisibleCounts): void {
+ if (heldForChatReturn) return;
+ snapshot = {
+ ...snapshot,
+ visibleCounts: { ...visibleCounts },
+ };
+}
+
+export function forgetMobileProjectsListUnlessPreserved(pathname: string): void {
+ // Chat is a detail of this list: keep the revealed window. Any other route
+ // is a real departure, even if the user reached it through chat.
+ if (isProjectsRoutePath(pathname) || isChatRoutePath(pathname)) return;
+ snapshot = EMPTY_SNAPSHOT;
+ heldForChatReturn = false;
+}
+
+export function isMobileProjectsListHeldForChatReturn(): boolean {
+ return heldForChatReturn;
+}
+
+export function clearMobileProjectsListSnapshot(): void {
+ snapshot = EMPTY_SNAPSHOT;
+ heldForChatReturn = false;
+}
+
+type ScrollOwner = {
+ scrollTop: number;
+ addEventListener?(type: 'scroll', listener: () => void, options?: { passive?: boolean }): void;
+ removeEventListener?(type: 'scroll', listener: () => void): void;
+};
+
+export function readAppShellScrollTop(el: ScrollOwner | null | undefined): number {
+ const top = el?.scrollTop;
+ return typeof top === 'number' && Number.isFinite(top) ? Math.max(0, top) : 0;
+}
+
+export function writeAppShellScrollTop(el: ScrollOwner | null | undefined, top: number): void {
+ if (!el) return;
+ el.scrollTop = Number.isFinite(top) ? Math.max(0, top) : 0;
+}
+
+export function appShellScrollElement(
+ root: { getElementById(id: string): ScrollOwner | null } | null = typeof document === 'undefined' ? null : document,
+): ScrollOwner | null {
+ return root?.getElementById(APP_SHELL_SCROLL_ID) ?? null;
+}