From 93d21e561232551930a22390433a15ef9f5acdb6 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Sat, 14 Nov 2026 13:27:02 +0700 Subject: [PATCH] Preserve the mobile sidebar when returning from Settings (#9641) * fix(app): preserve mobile sidebar continuity through Settings Retain the sidebar for the Settings visit so Back resumes the original navigation surface without a new drawer animation. Native screen appearance owns the handoff because pathname and layout updates precede presentation. * fix(app): keep settings navigation imports lightweight Keep the Settings visit state accessible without loading native presentation hooks, and exercise continuity with a scrolled list and complete paint capture. --- docs/mobile-panels.md | 17 +++- .../e2e/browser/settings-navigation.spec.ts | 89 ++++++++++++++++++ packages/app/e2e/support/helpers/settings.ts | 92 +++++++++++++++++++ packages/app/src/app/_layout.tsx | 64 +++++++++++-- packages/app/src/components/left-sidebar.tsx | 24 ++--- packages/app/src/mobile-panels/model.test.ts | 19 ++++ packages/app/src/mobile-panels/model.ts | 14 ++- packages/app/src/mobile-panels/provider.tsx | 15 ++- packages/app/src/mobile-panels/selection.ts | 7 +- .../app/src/navigation/settings-navigation.ts | 35 ++++++- .../navigation/settings-presentation/index.ts | 46 +++++++++- .../settings-presentation/model.test.ts | 36 ++++++++ .../navigation/settings-presentation/model.ts | 47 +++++++++- .../settings-presentation/session/index.ts | 6 ++ packages/app/src/screens/settings-screen.tsx | 10 +- .../index.ts | 6 +- .../navigation.test.ts | 10 ++ .../navigation.ts | 8 +- packages/app/src/stores/panel-store/index.ts | 9 +- .../app/src/stores/panel-store/state.test.ts | 24 +++++ packages/app/src/stores/panel-store/state.ts | 10 +- 21 files changed, 531 insertions(+), 57 deletions(-) create mode 100644 packages/app/src/navigation/settings-presentation/session/index.ts diff --git a/docs/mobile-panels.md b/docs/mobile-panels.md index 21849788d..a45e20909 100644 --- a/docs/mobile-panels.md +++ b/docs/mobile-panels.md @@ -27,9 +27,17 @@ interface MobilePanelSelection { Every semantic target change increments `revision`. Repeating the current target is idempotent. Compact panel selection is not persisted; a cold start begins at `agent`. -Only an overlay sidebar holds `agent-list`, and only a compact layout holds `file-explorer`. App -chrome publishes the layout (compact or wide, and the left sidebar presentation `overlay`, `dock`, or -`hidden`) to `panel-store`, which drops any target the layout does not present. A stale +An overlay sidebar holds `agent-list`, and only a compact layout holds `file-explorer`. +A compact Settings visit entered from the sidebar suspends it: the host stays mounted and +laid out on native. Its target and scroll position survive until return to the originating +workspace. Route changes and `onLayout` both precede native screen appearance, so the sidebar +stays visible until Settings emits the native navigator's `transitionEnd`. Web uses layout. +Input and activity stop during the handoff. Widening or leaving for another destination discards +the return. Commands issued while suspended settle immediately behind Settings, so explicit +agent navigation does not reveal a closing sidebar animation. + +App chrome publishes the layout (compact or wide, and the left sidebar presentation `overlay`, +`dock`, `hidden`, or `suspended`) to `panel-store`, which drops any target the layout does not present. A stale `agent-list` would reopen the overlay on the next collapse; a stale `file-explorer` after widening would block the navigation swipe, which begins only from `agent`. @@ -120,7 +128,8 @@ definition, no longer eligible to begin. the overlay host fills the window. - The overlay's backdrop covers the whole window; safe-area padding applies to the sidebar and workspace content only. It closes by swiping back, tapping the backdrop, or picking a destination: - every sidebar destination closes the overlay before it navigates. + workspace destinations close the overlay before navigating. Settings suspends the compact + sidebar for the duration of its visit instead. - Animated panel nodes use React Native static styles plus inline theme values. Do not attach Unistyles-generated styles to those nodes; Unistyles and Reanimated patching the same Fabric node has caused native crashes. diff --git a/packages/app/e2e/browser/settings-navigation.spec.ts b/packages/app/e2e/browser/settings-navigation.spec.ts index e46962d61..054a91318 100644 --- a/packages/app/e2e/browser/settings-navigation.spec.ts +++ b/packages/app/e2e/browser/settings-navigation.spec.ts @@ -1,3 +1,4 @@ +import { writeFile } from "node:fs/promises"; import { test, expect } from "../support/fixtures"; import { buildHostWorkspaceRoute, @@ -6,10 +7,16 @@ import { buildSettingsRoute, buildSettingsSectionRoute, } from "@/utils/host-routes"; +import { openCompactSidebar } from "../support/helpers/usage-sidebar-item"; import { gotoAppShell, openSettings } from "../support/helpers/app"; import { getE2EDaemonPort } from "../support/helpers/daemon-port"; import { closeCompactSettings, + captureCompactSidebarReturn, + openSettingsFromCompactSidebar, + captureCompactSidebarContext, + expectCompactSidebarOpen, + closeCompactSidebar, scrollSettingsSidebarToEnd, revealSettingsSidebarSection, expectSettingsSidebarScrollSettled, @@ -374,6 +381,87 @@ test.describe("Settings sidebar navigation", () => { test.describe("Settings — compact master-detail", () => { test.use({ viewport: { width: 390, height: 844 } }); + test("returning from Settings preserves the open sidebar from the first paint", async ({ + page, + withWorkspace, + }, testInfo) => { + const workspace = await withWorkspace({ prefix: "settings-sidebar-continuity-" }); + for (let i = 0; i < 12; i++) await withWorkspace({ prefix: "settings-sidebar-scroll-" }); + await openWorkspace(page, workspace); + await openCompactSidebar(page); + await expectCompactSidebarOpen(page); + const expectContextPreserved = await captureCompactSidebarContext(page); + const openingFrames = await captureCompactSidebarReturn(page, () => + openSettingsFromCompactSidebar(page), + ); + await writeFile( + testInfo.outputPath("sidebar-opening-frames.json"), + JSON.stringify(openingFrames, null, 2), + ); + expect(openingFrames.some((frame) => frame.settingsVisible)).toBe(true); + expect(openingFrames.every((frame) => frame.sidebarVisible || frame.settingsVisible)).toBe( + true, + ); + await openSettingsSection(page, "appearance"); + await goBackInSettings(page); + const frames = await captureCompactSidebarReturn(page, () => closeCompactSettings(page)); + await writeFile( + testInfo.outputPath("sidebar-return-frames.json"), + JSON.stringify(frames, null, 2), + ); + await testInfo.attach("sidebar-return-frames", { + body: JSON.stringify(frames, null, 2), + contentType: "application/json", + }); + const workspaceFrames = frames.filter((frame) => !frame.pathname.startsWith("/settings")); + expect(workspaceFrames.length).toBeGreaterThan(0); + expect(workspaceFrames.every((frame) => frame.sidebarVisible)).toBe(true); + const firstX = workspaceFrames[0]!.closeX; + expect( + workspaceFrames.every((frame) => Math.abs((frame.closeX ?? Infinity) - firstX!) < 1), + ).toBe(true); + await expectCompactSidebarOpen(page); + await expectContextPreserved(); + await openSettingsFromCompactSidebar(page); + const backFrames = await captureCompactSidebarReturn(page, async () => { + await page.goBack(); + }); + await writeFile( + testInfo.outputPath("browser-back-frames.json"), + JSON.stringify(backFrames, null, 2), + ); + await testInfo.attach("browser-back-frames", { + body: JSON.stringify(backFrames, null, 2), + contentType: "application/json", + }); + const backWorkspaceFrames = backFrames.filter( + (frame) => !frame.pathname.startsWith("/settings"), + ); + expect(backWorkspaceFrames.length).toBeGreaterThan(0); + expect(backWorkspaceFrames.every((frame) => frame.sidebarVisible)).toBe(true); + await expectCompactSidebarOpen(page); + await closeCompactSidebar(page); + }); + + test("widening during Settings discards the mobile sidebar return", async ({ + page, + withWorkspace, + }) => { + const workspace = await withWorkspace({ prefix: "settings-sidebar-resize-" }); + await openWorkspace(page, workspace); + await openCompactSettings(page, buildHostWorkspaceRoute(getServerId(), workspace.workspaceId)); + await page.setViewportSize({ width: 1000, height: 844 }); + await expect(page.getByTestId("settings-detail-pane")).toBeVisible(); + await page.setViewportSize({ width: 390, height: 844 }); + await goBackInSettings(page); + await expectCompactSettingsList(page); + await closeCompactSettings(page); + await expect(page.getByRole("button", { name: "Close sidebar", exact: true })).toBeHidden(); + await expect( + page.getByRole("button", { name: "Open menu", exact: true }).first(), + ).toBeInViewport(); + }); + test("the compact tab switcher reopens after Settings hides its workspace", async ({ page }) => { const workspace = await seedMockAgentWorkspace({ repoPrefix: "settings-tab-switcher-", @@ -401,6 +489,7 @@ test.describe("Settings — compact master-detail", () => { await expect(newAgent).toHaveCount(0); await closeCompactSettings(page); + await closeCompactSidebar(page); await expect(switcher).toBeVisible(); await expect(newAgent).toHaveCount(0); await switcher.click(); diff --git a/packages/app/e2e/support/helpers/settings.ts b/packages/app/e2e/support/helpers/settings.ts index d877484ee..ee5aae1f4 100644 --- a/packages/app/e2e/support/helpers/settings.ts +++ b/packages/app/e2e/support/helpers/settings.ts @@ -737,3 +737,95 @@ export async function normalizeSettingsFontSizes(page: Page): Promise { await expect(input).toHaveValue(minimum); } } + +/** Sample actual paints, including the first workspace frame after Settings. */ +export async function captureCompactSidebarReturn(page: Page, returnAction: () => Promise) { + await page.evaluate(() => { + const capture = { + frames: [] as { + time: number; + pathname: string; + sidebarVisible: boolean; + settingsVisible: boolean; + closeX: number | null; + }[], + stopped: false, + }; + Object.assign(window, { __sidebarFrameCapture: capture }); + const start = performance.now(); + function sample() { + if (capture.stopped) return; + const close = document.querySelector('[data-testid="sidebar-close"]'); + capture.frames.push({ + time: performance.now() - start, + pathname: location.pathname, + settingsVisible: + document + .querySelector('[data-testid="settings-sidebar"]') + ?.checkVisibility({ checkOpacity: true, checkVisibilityCSS: true }) ?? false, + sidebarVisible: + (close?.checkVisibility({ checkOpacity: true, checkVisibilityCSS: true }) ?? false) && + close!.getBoundingClientRect().x >= 0 && + close!.getBoundingClientRect().right <= innerWidth, + closeX: close?.getBoundingClientRect().x ?? null, + }); + requestAnimationFrame(sample); + } + requestAnimationFrame(sample); + }); + await returnAction(); + return page.evaluate(async () => { + const capture = ( + window as typeof window & { + __sidebarFrameCapture: { + frames: { + time: number; + pathname: string; + sidebarVisible: boolean; + settingsVisible: boolean; + closeX: number | null; + }[]; + stopped: boolean; + }; + } + ).__sidebarFrameCapture; + await new Promise((resolve) => setTimeout(resolve, 1500)); + capture.stopped = true; + return capture.frames; + }); +} + +export async function captureCompactSidebarContext(page: Page) { + const sidebar = await page.getByTestId("sidebar-project-workspace-list-scroll").elementHandle(); + if (!sidebar) throw new Error("Open sidebar has no workspace list"); + await expect + .poll(() => sidebar.evaluate((el) => el.scrollHeight - el.clientHeight)) + .toBeGreaterThan(0); + const offset = await sidebar.evaluate((el) => { + el.scrollTop = el.scrollHeight; + return el.scrollTop; + }); + expect(offset).toBeGreaterThan(0); + return async () => { + expect(await sidebar.evaluate((el) => el.isConnected)).toBe(true); + expect(await sidebar.evaluate((el) => el.scrollTop)).toBe(offset); + await sidebar.dispose(); + }; +} + +export async function expectCompactSidebarOpen(page: Page) { + await expect(page.getByRole("button", { name: "Close sidebar", exact: true })).toBeInViewport(); +} + +export async function closeCompactSidebar(page: Page) { + await page.getByRole("button", { name: "Close sidebar", exact: true }).click(); + await expect( + page.getByRole("button", { name: "Open menu", exact: true }).first(), + ).toBeInViewport(); +} + +export async function openSettingsFromCompactSidebar(page: Page) { + await page.getByRole("button", { name: "Settings", exact: true }).click(); + await expectAppRoute(page, buildSettingsRoute()); + await expectCompactSettingsList(page); +} diff --git a/packages/app/src/app/_layout.tsx b/packages/app/src/app/_layout.tsx index 8577eb97e..787e0c20e 100644 --- a/packages/app/src/app/_layout.tsx +++ b/packages/app/src/app/_layout.tsx @@ -87,7 +87,10 @@ import { type StartupBlocker, } from "@/navigation/host-runtime-bootstrap"; import { registerWorkspaceRouteNavigationRef } from "@/navigation/workspace-route-navigation"; -import { useSettingsRouteEntry } from "@/navigation/settings-presentation"; +import { + useSettingsRouteEntry, + useSettingsSidebarPresentation, +} from "@/navigation/settings-presentation"; import { ThemedStack } from "@/navigation/themed-stack"; import { shouldUseDesktopDaemon } from "@/desktop/daemon/desktop-daemon"; import { AgentNavigationListener } from "@/desktop/agent-navigation"; @@ -473,12 +476,16 @@ function AppContainer({ children, chromeEnabled: chromeEnabledOverride }: AppCon viewportWidth, }), }); - const sidebarPresentation = resolveLeftSidebarPresentation({ - chromeEnabled, - isCompactLayout, - isFocusModeEnabled: isWorkspaceFocusModeEnabled, - desktopSidebarVisible, - }); + const { presentation: sidebarPresentation, visible: sidebarVisible } = + useSettingsSidebarPresentation({ + visible: chromeEnabled, + presentation: resolveLeftSidebarPresentation({ + chromeEnabled, + isCompactLayout, + isFocusModeEnabled: isWorkspaceFocusModeEnabled, + desktopSidebarVisible, + }), + }); const applyPanelLayout = usePanelStore((state) => state.applyPanelLayout); // Publishes the layout to the store, which owns the panel targets each layout allows. useLayoutEffect(() => { @@ -546,7 +553,11 @@ function AppContainer({ children, chromeEnabled: chromeEnabledOverride }: AppCon - {isCompactLayout ? themedSidebarChrome : null} + {isCompactLayout ? ( + + {themedSidebarChrome} + + ) : null} @@ -584,6 +595,34 @@ function AppContainer({ children, chromeEnabled: chromeEnabledOverride }: AppCon ); } +// Keep native scroll ranges and gesture hosts intact while Settings covers the sidebar. +function CompactSidebarHost({ + visible, + interactive, + children, +}: { + visible: boolean; + interactive: boolean; + children: ReactNode; +}) { + return ( + + {children} + + ); +} + function AppContainerLifetime({ children, sidebarGesturesEnabled, @@ -614,14 +653,18 @@ function SidebarChrome({ const isCompactLayout = useIsCompactFormFactor(); const isMobileActive = useIsMobilePanelActive("agent-list"); const overlay = presentation === "overlay"; - const active = resolveSidebarActivity(presentation !== "hidden", overlay, isMobileActive); + const active = resolveSidebarActivity( + presentation !== "hidden" && presentation !== "suspended", + overlay, + isMobileActive, + ); const hardwareKeyboardPresent = useHardwareKeyboardPresent(); return ( - {mounted ? ( + {mounted || presentation === "suspended" ? ( ) : null} @@ -1007,6 +1050,7 @@ export default function RootLayout() { } const layoutStyles = StyleSheet.create((theme) => ({ + compactSidebarHost: { position: "absolute", top: 0, bottom: 0, left: 0, right: 0 }, surfaceFill: { flex: 1, backgroundColor: theme.colors.surface0, diff --git a/packages/app/src/components/left-sidebar.tsx b/packages/app/src/components/left-sidebar.tsx index ba40ab41f..38b01fd33 100644 --- a/packages/app/src/components/left-sidebar.tsx +++ b/packages/app/src/components/left-sidebar.tsx @@ -1,6 +1,5 @@ import { SidebarViewSlot } from "@/plugins/sidebar-view"; import { useAddHost } from "@/hosts/add-host"; -import { router } from "expo-router"; import { CircleGauge, FolderPlus, @@ -85,8 +84,9 @@ import { useOwnsWindowChromeCorner, WindowChromeSafeArea } from "@/utils/desktop import { useCloseAgentListGesture } from "@/mobile-panels/gestures"; import { useLeftPanelWidth } from "@/mobile-panels/provider"; import { MobilePanelOverlay } from "@/mobile-panels/presentation"; -import { buildSettingsRoute } from "@/utils/host-routes"; -import { openHostOverview } from "@/navigation/settings-navigation"; +import { buildSettingsHostSectionRoute } from "@/utils/host-routes"; +import { useActiveWorkspaceSelection } from "@/stores/navigation-active-workspace-store"; +import { openSettingsFromSidebar } from "@/navigation/settings-navigation"; import { UsageSidebarItem, UsageSidebarRoot, useUsageSummary, useOpenSidebarUsage } from "@/usage"; import { SidebarAgentListSkeleton } from "./sidebar-agent-list-skeleton"; import { SidebarCalloutSlot } from "./sidebar-callout-slot"; @@ -157,6 +157,7 @@ export const LeftSidebar = memo(function LeftSidebar({ const { t } = useTranslation(); const insets = useSafeAreaInsets(); const isCompactLayout = useIsCompactFormFactor(); + const activeWorkspace = useActiveWorkspaceSelection(); const showMobileAgent = usePanelStore((state) => state.showMobileAgent); const { @@ -193,25 +194,26 @@ export const LeftSidebar = memo(function LeftSidebar({ const openProjectPicker = useOpenAddProject(); const { open: openImportSession, sheet: importSessionSheet } = useImportSession(); - // Each destination closes the navigation overlay first. Closing is idempotent, so a docked - // sidebar runs the same handler. + // Workspace destinations close the overlay; Settings retains it for the return journey. const handleOpenProject = useCallback(() => { void openProjectPicker(); }, [openProjectPicker]); const handleSettings = useCallback(() => { - showMobileAgent(); - router.push(buildSettingsRoute()); - }, [showMobileAgent]); + openSettingsFromSidebar({ workspace: activeWorkspace, isCompact: isCompactLayout }); + }, [activeWorkspace, isCompactLayout]); const handleAddHost = useAddHost(); const handleOpenHostSettings = useCallback( (serverId: string) => { - showMobileAgent(); - openHostOverview(serverId); + openSettingsFromSidebar({ + workspace: activeWorkspace, + isCompact: isCompactLayout, + route: buildSettingsHostSectionRoute(serverId, "host"), + }); }, - [showMobileAgent], + [activeWorkspace, isCompactLayout], ); const labels = useMemo( diff --git a/packages/app/src/mobile-panels/model.test.ts b/packages/app/src/mobile-panels/model.test.ts index ca4ef04a8..a77c9684b 100644 --- a/packages/app/src/mobile-panels/model.test.ts +++ b/packages/app/src/mobile-panels/model.test.ts @@ -305,3 +305,22 @@ describe("mobile panel ownership", () => { }); }); }); + +it("lands an explicit destination while the sidebar is suspended without a slide", () => { + const state = createMobilePanelMotionState({ target: "agent-list", revision: 1 }); + const result = transitionMobilePanel(state, { + type: "command", + selection: { target: "agent", revision: 2 }, + immediate: true, + }); + expect(result).toEqual({ + immediateTarget: "agent", + state: { + target: "agent", + revision: 2, + gesture: null, + motionTarget: "agent", + settledTarget: "agent", + }, + }); +}); diff --git a/packages/app/src/mobile-panels/model.ts b/packages/app/src/mobile-panels/model.ts index 363bcfc45..9b59eea3c 100644 --- a/packages/app/src/mobile-panels/model.ts +++ b/packages/app/src/mobile-panels/model.ts @@ -17,6 +17,7 @@ export interface MobilePanelCommit { export interface MobilePanelTransition { animationTarget?: MobilePanelView; + immediateTarget?: MobilePanelView; commit?: MobilePanelCommit; state: MobilePanelMotionState; } @@ -48,7 +49,7 @@ function settleMobilePanelAtPosition( } export type MobilePanelEvent = - | { type: "command"; selection: MobilePanelSelection } + | { type: "command"; selection: MobilePanelSelection; immediate?: boolean } | { type: "gesture.begin"; origin: MobilePanelView } | { type: "gesture.finish"; @@ -78,6 +79,17 @@ export function transitionMobilePanel( if (event.selection.revision <= state.revision) { return { state }; } + if (event.immediate) { + return { + immediateTarget: event.selection.target, + state: { + ...event.selection, + gesture: null, + motionTarget: event.selection.target, + settledTarget: event.selection.target, + }, + }; + } // An interrupted drag left the position between anchors, so it moves back even when the // target is unchanged. Without a drag, the command adopts motion already heading there. const continuesCurrentMotion = !state.gesture && state.motionTarget === event.selection.target; diff --git a/packages/app/src/mobile-panels/provider.tsx b/packages/app/src/mobile-panels/provider.tsx index 77c00558c..8fdf4ab5d 100644 --- a/packages/app/src/mobile-panels/provider.tsx +++ b/packages/app/src/mobile-panels/provider.tsx @@ -157,6 +157,11 @@ export function MobilePanelsProvider({ children }: { children: ReactNode }) { const animateTransition = useCallback( (transition: MobilePanelTransition) => { "worklet"; + if (transition.immediateTarget) { + cancelAnimation(position); + position.value = getMobilePanelAnchor(transition.immediateTarget); + return; + } if (!transition.animationTarget) { return; } @@ -170,25 +175,27 @@ export function MobilePanelsProvider({ children }: { children: ReactNode }) { ); const applySelection = useCallback( - (selection: MobilePanelSelection) => { + (selection: MobilePanelSelection, immediate: boolean) => { "worklet"; const currentState = motionState.value; const transition = transitionMobilePanel(currentState, { type: "command", selection, + immediate, }); if (transition.state === currentState) { return; } motionState.value = transition.state; animateTransition(transition); + if (immediate) scheduleOnRN(publishActivePanel, selection.target, selection.revision); }, - [animateTransition, motionState], + [animateTransition, motionState, publishActivePanel], ); useEffect(() => { - return subscribeMobilePanelSelection((selection) => { - scheduleOnUI(applySelection, selection); + return subscribeMobilePanelSelection((selection, immediate) => { + scheduleOnUI(applySelection, selection, immediate); }); }, [applySelection]); diff --git a/packages/app/src/mobile-panels/selection.ts b/packages/app/src/mobile-panels/selection.ts index f47d9e737..2ee7769b3 100644 --- a/packages/app/src/mobile-panels/selection.ts +++ b/packages/app/src/mobile-panels/selection.ts @@ -2,13 +2,14 @@ import { usePanelStore, type MobilePanelSelection } from "@/stores/panel-store"; /** Observe panel commands, including layout commands published before subscription. */ export function subscribeMobilePanelSelection( - onSelection: (selection: MobilePanelSelection) => void, + onSelection: (selection: MobilePanelSelection, immediate: boolean) => void, ) { const unsubscribe = usePanelStore.subscribe((state, previousState) => { if (state.mobilePanel !== previousState.mobilePanel) { - onSelection(state.mobilePanel); + onSelection(state.mobilePanel, state.layout.leftSidebar === "suspended"); } }); - onSelection(usePanelStore.getState().mobilePanel); + const state = usePanelStore.getState(); + onSelection(state.mobilePanel, state.layout.leftSidebar === "suspended"); return unsubscribe; } diff --git a/packages/app/src/navigation/settings-navigation.ts b/packages/app/src/navigation/settings-navigation.ts index 123b23077..889eb093f 100644 --- a/packages/app/src/navigation/settings-navigation.ts +++ b/packages/app/src/navigation/settings-navigation.ts @@ -1,5 +1,8 @@ import { router, type Href } from "expo-router"; -import { navigateToLastWorkspace } from "@/stores/navigation-active-workspace-store"; +import { + navigateToWorkspace, + navigateToLastWorkspace, +} from "@/stores/navigation-active-workspace-store"; import { buildOpenProjectRoute, buildProjectSettingsRoute, @@ -10,6 +13,27 @@ import { type SettingsSectionSlug, } from "@/utils/host-routes"; +import type { ActiveWorkspaceSelection } from "@/stores/last-workspace-selection"; +import { usePanelStore } from "@/stores/panel-store"; +import { + beginSettingsSidebarVisit, + getSettingsSidebarReturn, +} from "@/navigation/settings-presentation/session"; + +export function openSettingsFromSidebar(input: { + workspace: ActiveWorkspaceSelection | null; + isCompact: boolean; + route?: Href; +}): void { + const panels = usePanelStore.getState(); + if (input.isCompact && input.workspace && panels.mobilePanel.target === "agent-list") { + beginSettingsSidebarVisit(input.workspace); + } else { + panels.showMobileAgent(); + } + router.push(input.route ?? buildSettingsRoute()); +} + export type SettingsView = | { kind: "plugin"; serverId: string; pluginId: string; screenId: string } | { kind: "root" } @@ -27,6 +51,15 @@ export function openProjectSettings(serverId: string, projectId: string): void { export function returnFromSettings(view: SettingsView): void { if (view.kind === "root") { + const destination = getSettingsSidebarReturn(); + if (destination && usePanelStore.getState().mobilePanel.target === "agent-list") { + navigateToWorkspace({ + serverId: destination.serverId, + workspaceId: destination.workspaceId, + surface: "sidebar", + }); + return; + } if (!navigateToLastWorkspace()) { router.replace(buildOpenProjectRoute()); } diff --git a/packages/app/src/navigation/settings-presentation/index.ts b/packages/app/src/navigation/settings-presentation/index.ts index cdf86b0d1..62dbb3022 100644 --- a/packages/app/src/navigation/settings-presentation/index.ts +++ b/packages/app/src/navigation/settings-presentation/index.ts @@ -1,19 +1,24 @@ +import { useIsCompactFormFactor } from "@/constants/layout"; +import { usePanelStore, type LeftSidebarPresentation } from "@/stores/panel-store"; import { useCallback, useLayoutEffect, useRef } from "react"; import { ScrollView, type NativeScrollEvent, type NativeSyntheticEvent } from "react-native"; import { usePathname, useRootNavigationState } from "expo-router"; +import { useIsFocused, type ParamListBase } from "expo-router/react-navigation"; +import { useNavigation } from "expo-router"; +import type { NativeStackNavigationProp } from "expo-router/native-stack"; +import { isWeb } from "@/constants/platform"; import { useStore } from "zustand"; import { useIsLastWorkspaceSelectionHydrated, useLastWorkspaceSelection, } from "@/stores/navigation-active-workspace-store"; -import { createSettingsPresentation } from "./model"; - -const selection = createSettingsPresentation(); +import { settingsPresentation as selection } from "./session"; // Mount once above the sibling Settings routes so replacements and Back share // one visit, and leaving Settings gives the next workspace entry a fresh default. export function useSettingsRouteEntry(): void { const pathname = usePathname(); + const isCompact = useIsCompactFormFactor(); const navigationState = useRootNavigationState(); const routeKey = navigationState?.routes[navigationState.index]?.key; const workspace = useLastWorkspaceSelection(); @@ -21,15 +26,46 @@ export function useSettingsRouteEntry(): void { const workspaceServerId = workspace?.serverId ?? null; useLayoutEffect(() => { if (isWorkspaceHydrated && routeKey) { - selection.enterRoute({ key: routeKey, pathname }, workspaceServerId); + if (!isCompact) selection.clearSidebarReturn(); + if (selection.enterRoute({ key: routeKey, pathname }, workspaceServerId)) { + usePanelStore.getState().showMobileAgent(); + } } - }, [pathname, routeKey, workspaceServerId, isWorkspaceHydrated]); + }, [pathname, routeKey, workspaceServerId, isWorkspaceHydrated, isCompact]); } export function useSettingsHostSelection(): string | null { return useStore(selection.store, (state) => state.selectedServerId); } +export function useSettingsSidebarPresentation(input: { + presentation: LeftSidebarPresentation; + visible: boolean; +}): { presentation: LeftSidebarPresentation; visible: boolean } { + const origin = useStore(selection.store, (state) => state.sidebarReturn); + const pathname = usePathname(); + const compact = useIsCompactFormFactor(); + if (compact && origin && (pathname === "/settings" || pathname.startsWith("/settings/"))) { + return { presentation: "suspended", visible: origin.phase === "opening" }; + } + return input; +} + +// Native layout precedes screen appearance; only the navigator can finish that handoff. +export function useSettingsContentPresented() { + const focused = useIsFocused(); + const navigation = useNavigation>(); + useLayoutEffect(() => { + if (isWeb) return; + return navigation.addListener("transitionEnd", ({ data }) => { + if (!data.closing) selection.presentContent(); + }); + }, [navigation]); + return useCallback(() => { + if (isWeb && focused) selection.presentContent(); + }, [focused]); +} + export const selectSettingsHost = selection.selectHost; // Sibling routes remount the wide sidebar. Only the current mount owns its diff --git a/packages/app/src/navigation/settings-presentation/model.test.ts b/packages/app/src/navigation/settings-presentation/model.test.ts index a8970b17b..73188bb39 100644 --- a/packages/app/src/navigation/settings-presentation/model.test.ts +++ b/packages/app/src/navigation/settings-presentation/model.test.ts @@ -130,3 +130,39 @@ describe("Settings sidebar presentation", () => { expect(settings.attachSidebar().offset).toBe(0); }); }); + +describe("Settings sidebar return", () => { + it("retains the origin through nested Settings and consumes it on return", () => { + const settings = createSettingsPresentation(); + const origin = { serverId: "host", workspaceId: "workspace" }; + settings.beginSidebarVisit(origin); + settings.enterRoute({ key: "root", pathname: "/settings" }, "host"); + settings.enterRoute({ key: "appearance", pathname: "/settings/appearance" }, "host"); + expect(settings.store.getState().sidebarReturn).toEqual({ ...origin, phase: "opening" }); + settings.presentContent(); + expect(settings.store.getState().sidebarReturn).toEqual({ ...origin, phase: "covered" }); + expect( + settings.enterRoute({ key: "workspace", pathname: "/h/host/workspace/workspace" }, "host"), + ).toBe(false); + expect(settings.store.getState().sidebarReturn).toBeNull(); + }); + + it("discards the sidebar when returning to a different workspace", () => { + const settings = createSettingsPresentation(); + settings.beginSidebarVisit({ serverId: "host", workspaceId: "workspace" }); + settings.enterRoute({ key: "root", pathname: "/settings" }, "host"); + expect(settings.enterRoute({ key: "other", pathname: "/h/host/workspace/other" }, "host")).toBe( + true, + ); + expect(settings.store.getState().sidebarReturn).toBeNull(); + }); + + it("does not carry sidebar returns into another visit or a wide layout", () => { + const settings = createSettingsPresentation(); + settings.beginSidebarVisit({ serverId: "host", workspaceId: "workspace" }); + settings.clearSidebarReturn(); + settings.enterRoute({ key: "root", pathname: "/settings" }, "host"); + expect(settings.store.getState().sidebarReturn).toBeNull(); + expect(createSettingsPresentation().store.getState().sidebarReturn).toBeNull(); + }); +}); diff --git a/packages/app/src/navigation/settings-presentation/model.ts b/packages/app/src/navigation/settings-presentation/model.ts index 2a88e9d82..c6784a11c 100644 --- a/packages/app/src/navigation/settings-presentation/model.ts +++ b/packages/app/src/navigation/settings-presentation/model.ts @@ -1,3 +1,5 @@ +import type { ActiveWorkspaceSelection } from "@/stores/last-workspace-selection"; +import { parseHostWorkspaceRouteFromPathname } from "@/utils/host-routes"; import { createStore } from "zustand/vanilla"; interface SettingsRouteEntry { @@ -7,15 +9,34 @@ interface SettingsRouteEntry { interface SettingsSelectionState { selectedServerId: string | null; + sidebarReturn: (ActiveWorkspaceSelection & { phase: "opening" | "covered" }) | null; } export function createSettingsPresentation() { - const store = createStore(() => ({ selectedServerId: null })); + const store = createStore(() => ({ + selectedServerId: null, + sidebarReturn: null, + })); const enteredRoutes = new Map(); let inSettings = false; let sidebarOffset = 0; let sidebarOwner: object | null = null; + function beginSidebarVisit(workspace: ActiveWorkspaceSelection) { + store.setState({ sidebarReturn: { ...workspace, phase: "opening" } }); + } + + function presentContent() { + const origin = store.getState().sidebarReturn; + if (origin?.phase === "opening") { + store.setState({ sidebarReturn: { ...origin, phase: "covered" } }); + } + } + + function clearSidebarReturn() { + if (store.getState().sidebarReturn) store.setState({ sidebarReturn: null }); + } + function attachSidebar() { const owner = {}; sidebarOwner = owner; @@ -35,17 +56,24 @@ export function createSettingsPresentation() { function enterRoute( { key, pathname }: SettingsRouteEntry, workspaceServerId: string | null, - ): void { + ): boolean { const isSettings = pathname === "/settings" || pathname.startsWith("/settings/"); if (!isSettings) { + const origin = store.getState().sidebarReturn; + const destination = parseHostWorkspaceRouteFromPathname(pathname); + const discardSidebar = + origin !== null && + (origin.serverId !== destination?.serverId || + origin.workspaceId !== destination?.workspaceId); + clearSidebarReturn(); sidebarOffset = 0; sidebarOwner = null; inSettings = false; enteredRoutes.clear(); - return; + return discardSidebar; } // A retained route returning through Back must not replay its old host intent. - if (enteredRoutes.get(key) === pathname) return; + if (enteredRoutes.get(key) === pathname) return false; const isNewVisit = !inSettings; inSettings = true; enteredRoutes.set(key, pathname); @@ -56,11 +84,20 @@ export function createSettingsPresentation() { } else if (isNewVisit) { store.setState({ selectedServerId: workspaceServerId }); } + return false; } function selectHost(serverId: string): void { store.setState({ selectedServerId: serverId }); } - return { store, enterRoute, selectHost, attachSidebar }; + return { + store, + enterRoute, + selectHost, + attachSidebar, + beginSidebarVisit, + clearSidebarReturn, + presentContent, + }; } diff --git a/packages/app/src/navigation/settings-presentation/session/index.ts b/packages/app/src/navigation/settings-presentation/session/index.ts new file mode 100644 index 000000000..519539966 --- /dev/null +++ b/packages/app/src/navigation/settings-presentation/session/index.ts @@ -0,0 +1,6 @@ +import { createSettingsPresentation } from "../model"; + +/** @package */ +export const settingsPresentation = createSettingsPresentation(); +export const beginSettingsSidebarVisit = settingsPresentation.beginSidebarVisit; +export const getSettingsSidebarReturn = () => settingsPresentation.store.getState().sidebarReturn; diff --git a/packages/app/src/screens/settings-screen.tsx b/packages/app/src/screens/settings-screen.tsx index abd19f5a1..1d98e8e28 100644 --- a/packages/app/src/screens/settings-screen.tsx +++ b/packages/app/src/screens/settings-screen.tsx @@ -1,3 +1,4 @@ +import { useSettingsContentPresented } from "@/navigation/settings-presentation"; import { AppearanceText as Text } from "@/appearance/text"; import { useHardwareKeyboardPresent } from "@/keyboard"; import { useAddHost } from "@/hosts/add-host"; @@ -1118,6 +1119,7 @@ export default function SettingsScreen({ view }: SettingsScreenProps) { const appVersion = resolveAppVersion(); const appVersionText = formatVersionWithPrefix(appVersion); const isCompactLayout = useIsCompactFormFactor(); + const onContentLayout = useSettingsContentPresented(); const insets = useSafeAreaInsets(); const insetBottomStyle = useMemo(() => ({ paddingBottom: insets.bottom }), [insets.bottom]); const hosts = useHosts(); @@ -1341,7 +1343,7 @@ export default function SettingsScreen({ view }: SettingsScreenProps) { if (settingsLoading) { return ( - + {t("settings.loading")} ); @@ -1350,7 +1352,7 @@ export default function SettingsScreen({ view }: SettingsScreenProps) { // Mobile root: full-screen sidebar-as-list. if (isCompactLayout && view.kind === "root") { return ( - + + {content} @@ -1382,7 +1384,7 @@ export default function SettingsScreen({ view }: SettingsScreenProps) { // region + traffic-light padding; detail pane renders whatever header the // selected section provides. return ( - + { + revealWorkspace: (workspaceKey, surface) => { useWorkspaceLayoutStore.getState().focusWorkspace(workspaceKey); - usePanelStore.getState().showMobileAgent(); + const panels = usePanelStore.getState(); + if (surface === "sidebar") panels.showMobileAgentList(); + else panels.showMobileAgent(); }, getSessionWorkspaces: (serverId) => useSessionStore.getState().sessions[serverId]?.workspaces, isWorkspaceLayoutHydrated: () => useWorkspaceLayoutStore.persist.hasHydrated(), diff --git a/packages/app/src/stores/navigation-active-workspace-store/navigation.test.ts b/packages/app/src/stores/navigation-active-workspace-store/navigation.test.ts index 5dbc29252..db68e0560 100644 --- a/packages/app/src/stores/navigation-active-workspace-store/navigation.test.ts +++ b/packages/app/src/stores/navigation-active-workspace-store/navigation.test.ts @@ -77,6 +77,16 @@ describe("workspace navigation", () => { expect(revealed).toEqual([null]); }); + it("returns to the sidebar without revealing workspace content first", () => { + const surfaces: (string | undefined)[] = []; + const { deps, navigations } = createFakeDeps({ + revealWorkspace: (_workspaceKey, surface) => surfaces.push(surface), + }); + navigateToWorkspace({ serverId: "server", workspaceId: "workspace", surface: "sidebar" }, deps); + expect(surfaces).toEqual(["sidebar"]); + expect(navigations).toEqual(["/h/server/workspace/workspace"]); + }); + it("reveals an explicit target after opening instead of forcing center", () => { const workspace = { id: "workspace" } as WorkspaceDescriptor; const { deps, revealed } = createFakeDeps({ diff --git a/packages/app/src/stores/navigation-active-workspace-store/navigation.ts b/packages/app/src/stores/navigation-active-workspace-store/navigation.ts index bbc55701d..ed73b7ed2 100644 --- a/packages/app/src/stores/navigation-active-workspace-store/navigation.ts +++ b/packages/app/src/stores/navigation-active-workspace-store/navigation.ts @@ -23,6 +23,7 @@ export interface NavigateToWorkspaceInput { serverId: string; workspaceId: string; target?: WorkspaceTabTarget; + surface?: "sidebar"; pin?: boolean; placement?: WorkspaceTabPlacement; asTab?: boolean; @@ -35,7 +36,7 @@ export interface NavigateToWorkspaceDeps extends PrepareWorkspaceTabDeps { rememberLastWorkspace: (selection: ActiveWorkspaceSelection) => void; navigateToRoute: (route: string) => void; revealTab: (workspaceKey: string, tabId: string | null) => void; - revealWorkspace: (workspaceKey: string) => void; + revealWorkspace: (workspaceKey: string, surface?: "sidebar") => void; } export interface NavigateToLastWorkspaceDeps extends NavigateToWorkspaceDeps { @@ -100,7 +101,10 @@ export function navigateToWorkspace( if (input.target) { prepareWorkspaceTab({ ...input, target: input.target }, { openTab }); } else { - deps.revealWorkspace(`${input.serverId}:${resolvedWorkspaceId ?? input.workspaceId}`); + deps.revealWorkspace( + `${input.serverId}:${resolvedWorkspaceId ?? input.workspaceId}`, + input.surface, + ); } const route = buildHostWorkspaceRoute(input.serverId, input.workspaceId); diff --git a/packages/app/src/stores/panel-store/index.ts b/packages/app/src/stores/panel-store/index.ts index 660f2d1b6..8673030fd 100644 --- a/packages/app/src/stores/panel-store/index.ts +++ b/packages/app/src/stores/panel-store/index.ts @@ -52,6 +52,7 @@ export type ExpandedPathsUpdate = string[] | ((currentPaths: string[]) => string export interface PanelState { // Mobile: React's durable target plus the generation that owns it. mobilePanel: MobilePanelSelection; + layout: PanelLayout; // Desktop: independent sidebar toggles desktop: DesktopSidebarState; @@ -120,6 +121,7 @@ export const usePanelStore = create()( (set) => ({ // Mobile always starts at agent view mobilePanel: { target: "agent", revision: 0 }, + layout: { isCompact: false, leftSidebar: "hidden" }, // Desktop defaults based on platform desktop: { @@ -215,7 +217,12 @@ export const usePanelStore = create()( applyPanelLayout: (layout) => set((state) => { const mobilePanel = reconcileMobilePanel(state.mobilePanel, layout); - return mobilePanel === state.mobilePanel ? state : { mobilePanel }; + const layoutUnchanged = + state.layout.isCompact === layout.isCompact && + state.layout.leftSidebar === layout.leftSidebar; + return mobilePanel === state.mobilePanel && layoutUnchanged + ? state + : { mobilePanel, layout }; }), setExpandedPathsForWorkspace: (workspaceKey, paths) => diff --git a/packages/app/src/stores/panel-store/state.test.ts b/packages/app/src/stores/panel-store/state.test.ts index 317d4fd9a..b9613ab02 100644 --- a/packages/app/src/stores/panel-store/state.test.ts +++ b/packages/app/src/stores/panel-store/state.test.ts @@ -171,6 +171,30 @@ describe("panel-store wide navigation overlay", () => { expect(usePanelStore.getState().mobilePanel.target).toBe("agent"); }); + it("retains the sidebar through a suspended layout without publishing motion", () => { + const panels = usePanelStore.getState(); + panels.applyPanelLayout({ isCompact: true, leftSidebar: "overlay" }); + panels.showMobileAgentList(); + const selection = usePanelStore.getState().mobilePanel; + panels.applyPanelLayout({ isCompact: true, leftSidebar: "suspended" }); + expect(usePanelStore.getState().mobilePanel).toBe(selection); + panels.applyPanelLayout({ isCompact: true, leftSidebar: "overlay" }); + expect(usePanelStore.getState().mobilePanel).toBe(selection); + }); + + it("publishes an immediate destination when navigation closes a suspended sidebar", () => { + const panels = usePanelStore.getState(); + panels.showMobileAgentList(); + panels.applyPanelLayout({ isCompact: true, leftSidebar: "suspended" }); + const commands: boolean[] = []; + const unsubscribe = subscribeMobilePanelSelection((_selection, immediate) => + commands.push(immediate), + ); + panels.showMobileAgent(); + unsubscribe(); + expect(commands).toEqual([true, true]); + }); + it("drops the overlay target once the sidebar is no longer presented as an overlay", () => { usePanelStore.getState().showMobileAgentList(); usePanelStore.getState().applyPanelLayout({ isCompact: false, leftSidebar: "overlay" }); diff --git a/packages/app/src/stores/panel-store/state.ts b/packages/app/src/stores/panel-store/state.ts index a9971fa45..5e9cc2119 100644 --- a/packages/app/src/stores/panel-store/state.ts +++ b/packages/app/src/stores/panel-store/state.ts @@ -26,8 +26,8 @@ export interface PanelLayoutInput { isCompact: boolean; } -/** How app chrome presents the left sidebar: over the workspace, beside it, or not at all. */ -export type LeftSidebarPresentation = "overlay" | "dock" | "hidden"; +/** Sidebar presentation; suspended retains an overlay while Settings covers it. */ +export type LeftSidebarPresentation = "overlay" | "dock" | "hidden" | "suspended"; /** The panels app chrome presents, which decide the mobile panel targets that can stay selected. */ export interface PanelLayout extends PanelLayoutInput { @@ -77,7 +77,7 @@ export function setMobilePanelTarget( } /** - * Only an overlay sidebar shows the `agent-list` target. A docked or hidden sidebar drops it, so + * Only an overlay or suspended sidebar holds `agent-list`. A docked or hidden sidebar drops it, so * a stale target cannot resurface the overlay on the next collapse. Always invalidate in-flight * gestures, even when an opening swipe has not committed `agent-list` yet. */ @@ -98,7 +98,9 @@ export function reconcileMobilePanel( layout: PanelLayout, ): MobilePanelSelection { const sidebarReconciled = - layout.leftSidebar === "overlay" ? selection : dropOverlayAgentList(selection); + layout.leftSidebar === "overlay" || layout.leftSidebar === "suspended" + ? selection + : dropOverlayAgentList(selection); if (!layout.isCompact && sidebarReconciled.target === "file-explorer") { return setMobilePanelTarget(sidebarReconciled, "agent"); }