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): resume the last Settings section, and open the list on mobile (#2092)

Call White482cca9b05fc
diff --git a/ui/src/components/AppShell.test.tsx b/ui/src/components/AppShell.test.tsx
index d46a0d5f3..54c067895 100644
--- a/ui/src/components/AppShell.test.tsx
+++ b/ui/src/components/AppShell.test.tsx
@@ -25,6 +25,7 @@ import {
SETTINGS_MENU_PLACEMENT_STORAGE_KEY,
useStandaloneSettingsMenu,
} from '../lib/settingsMenuPlacement';
+import { SETTINGS_LAST_SECTION_STORAGE_KEY } from '../lib/settingsSectionMemory';
import { AppShell } from './AppShell';
const viewport = vi.hoisted(() => {
@@ -783,6 +784,66 @@ describe('AppShell persistent Workbench chrome', () => {
expect(screen.queryByTestId('account-menu')).toBeNull();
});
+ it('opens Settings on the section this device was left on', async () => {
+ viewport.isDesktop = true;
+ window.localStorage.setItem(SETTINGS_LAST_SECTION_STORAGE_KEY, '/settings/backends');
+ const user = userEvent.setup();
+
+ render(
+ <MemoryRouter initialEntries={['/']}>
+ <Routes>
+ <Route element={<AppShell />}>
+ <Route index element={<div data-testid="workbench" />} />
+ <Route path="settings/backends" element={<div data-testid="backends" />} />
+ </Route>
+ </Routes>
+ </MemoryRouter>,
+ );
+
+ expect(await screen.findByTestId('workbench')).toBeTruthy();
+ // Resolved on the link itself, not left to the Settings root to redirect,
+ // so the section is what the click paints rather than what a second frame
+ // corrects — and so the href a user hovers names where they will land.
+ const settingsToggle = screen.getByRole('link', { name: 'appShell.openControlPanel' });
+ expect(settingsToggle.getAttribute('href')).toBe('/settings/backends');
+
+ await user.click(settingsToggle);
+ expect(await screen.findByTestId('backends')).toBeTruthy();
+ });
+
+ it('follows the section another tab moved to', async () => {
+ viewport.isDesktop = true;
+ window.localStorage.setItem(SETTINGS_LAST_SECTION_STORAGE_KEY, '/settings/backends');
+
+ render(
+ <MemoryRouter initialEntries={['/']}>
+ <Routes>
+ <Route element={<AppShell />}>
+ <Route index element={<div data-testid="workbench" />} />
+ </Route>
+ </Routes>
+ </MemoryRouter>,
+ );
+
+ expect(await screen.findByTestId('workbench')).toBeTruthy();
+ const settingsToggle = screen.getByRole('link', { name: 'appShell.openControlPanel' });
+ expect(settingsToggle.getAttribute('href')).toBe('/settings/backends');
+
+ // A second tab of the same origin selecting a different row reaches this
+ // one as a storage event. Without a subscriber the link keeps offering the
+ // section the rail has left, for as long as nothing else rerenders here.
+ act(() => {
+ window.localStorage.setItem(SETTINGS_LAST_SECTION_STORAGE_KEY, '/settings/replies');
+ window.dispatchEvent(new StorageEvent('storage', {
+ key: SETTINGS_LAST_SECTION_STORAGE_KEY,
+ newValue: '/settings/replies',
+ }));
+ });
+
+ expect(screen.getByRole('link', { name: 'appShell.openControlPanel' }).getAttribute('href'))
+ .toBe('/settings/replies');
+ });
+
it('uses the Settings button to return to the route that opened Settings', async () => {
viewport.isDesktop = true;
const user = userEvent.setup();
diff --git a/ui/src/components/AppShell.tsx b/ui/src/components/AppShell.tsx
index b1c4c18c5..424cb8957 100644
--- a/ui/src/components/AppShell.tsx
+++ b/ui/src/components/AppShell.tsx
@@ -31,10 +31,8 @@ import { useViewportHeightVar } from '../lib/useViewportHeightVar';
import { APP_SHELL_SCROLL_ID, forgetMobileProjectsListUnlessPreserved } from '../lib/mobileProjectsListMemory';
import { useIsDesktop } from '../lib/useIsDesktop';
import { adoptPersistedLanguage } from '../lib/useLanguageSelection';
-import {
- isOwnerOnlyPath,
- SETTINGS_LANDING_PATH,
-} from '../lib/adminNavigation';
+import { isOwnerOnlyPath } from '../lib/adminNavigation';
+import { useSettingsResumePath } from '../lib/settingsSectionMemory';
import {
closeSettingsOverlay,
isChromelessShellPath,
@@ -178,6 +176,10 @@ export const AppShell: React.FC = () => {
// implies visible, so the mount site has to carry the viewport too.
const isDesktop = useIsDesktop();
const { capabilities } = useInstanceAuthorization();
+ // Where the sidebar's Settings control points: the section this device was
+ // left on, or General when there is none to resume. Subscribed, because the
+ // rail that moves it can be in another tab of the same origin.
+ const settingsEntryPath = useSettingsResumePath(capabilities.can_manage_instance);
const api = useApi();
const location = useLocation();
const navigate = useNavigate();
@@ -506,7 +508,10 @@ export const AppShell: React.FC = () => {
) : (
<Link
data-settings-toggle="true"
- to={SETTINGS_LANDING_PATH}
+ // Resolved on the link rather than left to the Settings root
+ // to redirect, so the click paints the section in one frame and
+ // the href names where it goes.
+ to={settingsEntryPath}
title={t('appShell.openControlPanel')}
aria-label={t('appShell.openControlPanel')}
className="group flex w-11 shrink-0 items-center justify-center rounded-lg border border-border-strong text-foreground transition-colors hover:bg-foreground/[0.04]"
diff --git a/ui/src/components/apps/MobileDockDrawer.test.tsx b/ui/src/components/apps/MobileDockDrawer.test.tsx
index bf920a903..f35ffbf28 100644
--- a/ui/src/components/apps/MobileDockDrawer.test.tsx
+++ b/ui/src/components/apps/MobileDockDrawer.test.tsx
@@ -27,7 +27,7 @@ afterEach(() => {
});
describe('MobileDockDrawer settings entry', () => {
- it('opens Settings on General, the same place a desktop entry lands', async () => {
+ it('opens Settings on the section list a phone has to navigate from', async () => {
const user = userEvent.setup();
const onClose = vi.fn();
@@ -42,15 +42,16 @@ describe('MobileDockDrawer settings entry', () => {
);
const chip = screen.getByRole('link', { name: 'more.controlPanel' });
- expect(chip.getAttribute('href')).toBe('/settings/general');
+ expect(chip.getAttribute('href')).toBe('/settings');
await user.click(chip);
- // A phone's ordinary way into Settings is a destination, not a menu: the
- // section list stays reachable from General's back row, but it is not what
- // tapping 设置 hands the user.
- expect(await screen.findByText('general-page')).toBeTruthy();
- expect(screen.queryByText('section-list')).toBeNull();
+ // A phone shows one Settings screen at a time, so landing inside a section
+ // hides every other one behind a Back the user has to find first. The menu
+ // is the screen that names them all, and it is what tapping 设置 hands over;
+ // the rail a desktop keeps beside the page is what excuses it there.
+ expect(await screen.findByText('section-list')).toBeTruthy();
+ expect(screen.queryByText('general-page')).toBeNull();
expect(onClose).toHaveBeenCalled();
});
});
diff --git a/ui/src/components/apps/MobileDockDrawer.tsx b/ui/src/components/apps/MobileDockDrawer.tsx
index 8d8983978..f90d3aa47 100644
--- a/ui/src/components/apps/MobileDockDrawer.tsx
+++ b/ui/src/components/apps/MobileDockDrawer.tsx
@@ -8,7 +8,6 @@ import { showPageAvatar, showPageIconUrl } from '../../apps/showPageAvatar';
import { ShowPageAvatarContent } from '../../apps/showPageAvatarTile';
import { useDock } from '../../context/DockContext';
import { dockIdToSession } from '../../context/dockDoc';
-import { SETTINGS_LANDING_PATH } from '../../lib/adminNavigation';
import { useAuthAccount } from '../../lib/useAuthAccount';
import { useShowPageInventory } from '../useShowPages';
import { MoreAccountSection, MoreAppearanceSection, MoreConnectionSection } from '../workbench/MorePage';
@@ -224,9 +223,13 @@ export const MobileDockDrawer: React.FC<{ open: boolean; onClose: () => void }>
{/* Footer chip row — the absorbed More-page content. 设置 navigates; 账号
and 更多 open a small overflow sheet. Appearance lives inside 更多 so
- the three English labels fit without truncation. */}
+ the three English labels fit without truncation.
+
+ 设置 goes to the Settings root, which on a phone IS the section list:
+ a viewport with no rail beside the page has to be handed the menu, or
+ the way to every other section is a Back the user has to discover. */}
<div className="mt-4 flex items-stretch gap-2 border-t border-border pt-3">
- <Link to={SETTINGS_LANDING_PATH} onClick={onClose} className={chipClass}>
+ <Link to="/settings" onClick={onClose} className={chipClass}>
<Settings className="size-4 shrink-0" />
<span className="truncate">{t('more.controlPanel')}</span>
</Link>
diff --git a/ui/src/components/settings/SettingsLayout.test.tsx b/ui/src/components/settings/SettingsLayout.test.tsx
index c354e58ff..9dcc4e1bf 100644
--- a/ui/src/components/settings/SettingsLayout.test.tsx
+++ b/ui/src/components/settings/SettingsLayout.test.tsx
@@ -13,6 +13,8 @@ import {
} from '@/lib/settingsOverlay';
import { ShellSidebarContext } from '@/context/ShellSidebarContext';
import { SETTINGS_MENU_PLACEMENT_STORAGE_KEY } from '@/lib/settingsMenuPlacement';
+import { SETTINGS_LAST_SECTION_STORAGE_KEY } from '@/lib/settingsSectionMemory';
+import { ModelHubCapabilityGate } from './models/ModelHubCapabilityGate';
import { SettingsLayout } from './SettingsLayout';
const api = vi.hoisted(() => {
@@ -82,12 +84,23 @@ type SettingsTestEntry = string | {
state?: unknown;
};
+// Model Hub is the one section that answers a disabled feature with a redirect
+// of its own. Off by default because the gate renders nothing until its config
+// read lands, which the synchronous layout cases below would not survive; the
+// case that is about the redirect opts in and gets the real gate.
+const modelHubRoute = (gated: boolean) => (gated
+ ? <ModelHubCapabilityGate><div>models-body</div></ModelHubCapabilityGate>
+ : <div>models-body</div>);
+
// `shellHasSidebar` stands in for what AppShell publishes around this layout.
// It defaults to the context's own default — an ordinary shell route, which is
// what every case but the sidebar-less one below is about.
const renderLayout = (
entry: SettingsTestEntry,
- { shellHasSidebar = true }: { shellHasSidebar?: boolean } = {},
+ { shellHasSidebar = true, gateModelHub = false }: {
+ shellHasSidebar?: boolean;
+ gateModelHub?: boolean;
+ } = {},
) => render(
<MemoryRouter initialEntries={[entry]}>
<ShellSidebarContext.Provider value={shellHasSidebar}>
@@ -96,7 +109,8 @@ const renderLayout = (
<Route path="general" element={<div>general-body</div>} />
<Route path="backends" element={<div>backends-body</div>} />
<Route path="backends/claude" element={<div>claude-body</div>} />
- <Route path="models" element={<div>models-body</div>} />
+ <Route path="models" element={modelHubRoute(gateModelHub)} />
+ <Route path="memory" element={<div>memory-body</div>} />
<Route path="replies" element={<div>replies-body</div>} />
<Route path="shortcuts" element={<div>shortcuts-body</div>} />
<Route path="service" element={<div>service-body</div>} />
@@ -407,24 +421,87 @@ describe('SettingsLayout', () => {
expect(api.getConfig).not.toHaveBeenCalled();
});
- it('opens General from /settings even after a remembered Backends visit', async () => {
- // Ordinary Settings is a destination, not a resume: whatever the last visit
- // was, the landing is the section every role can read.
- window.localStorage.setItem('avibe.settings.last-path', '/settings/backends');
+ it('resumes the remembered section from /settings', async () => {
+ // Ordinary Settings is a return, not a first read: the section the rail was
+ // left on is the one the next entry opens.
+ window.localStorage.setItem(SETTINGS_LAST_SECTION_STORAGE_KEY, '/settings/backends');
+ media.matches = true;
+ renderLayout('/settings');
+
+ expect(await screen.findByText('backends-body')).toBeTruthy();
+ expect(screen.queryByText('general-body')).toBeNull();
+ });
+
+ it('records the section a detail page belongs to, not the detail page', async () => {
+ media.matches = true;
+ renderLayout('/settings/backends/claude');
+
+ expect(await screen.findByText('claude-body')).toBeTruthy();
+ // A provider page is inside Backends, and Backends is the row the rail can
+ // show as current, so that is what a later entry has to be able to resume.
+ expect(window.localStorage.getItem(SETTINGS_LAST_SECTION_STORAGE_KEY))
+ .toBe('/settings/backends');
+ });
+
+ it.each([
+ ['a section that no longer exists', '/settings/retired-section'],
+ ['a section this visitor may not open', '/settings/service'],
+ ])('falls back to General for %s', async (_case, remembered) => {
+ // An owner's remembered page can outlive the capability that let them read
+ // it, and a release can retire a section under a path storage still holds.
+ // Neither may hand anyone a route the rail would not offer them today.
+ authorization.capabilities.can_manage_instance = false;
+ window.localStorage.setItem(SETTINGS_LAST_SECTION_STORAGE_KEY, remembered);
media.matches = true;
renderLayout('/settings');
expect(await screen.findByText('general-body')).toBeTruthy();
- expect(screen.queryByText('backends-body')).toBeNull();
+ expect(screen.queryByText('service-body')).toBeNull();
+ });
+
+ it('keeps remembering a section whose rail row a feature flag took down', async () => {
+ // Memory's row leaves the rail when memory is switched off, but the page
+ // stays the setup surface — the one the Dependencies page's Configure
+ // button links to. Being somewhere the rail cannot show as current is a
+ // real place to be, so it is a real place to come back to.
+ renderLayout('/settings/memory');
+ await waitFor(() => {
+ expect(screen.getByRole('link', { name: 'settings.sections.memory' })).toBeTruthy();
+ });
+
+ api.getMemorySettings.mockResolvedValueOnce({ status: 'ok', enabled: false });
+ act(() => window.dispatchEvent(new Event('avibe:memory-settings-changed')));
+
+ // The row going is how this test knows the projection settled; before that
+ // an absent row is only a read that has not landed.
+ await waitFor(() => {
+ expect(screen.queryByRole('link', { name: 'settings.sections.memory' })).toBeNull();
+ });
+ expect(window.localStorage.getItem(SETTINGS_LAST_SECTION_STORAGE_KEY))
+ .toBe('/settings/memory');
+ });
+
+ it('follows a disabled section to the page it redirects to', async () => {
+ // Model Hub answers a disabled hub with its own redirect, so a resumed
+ // memory of it does not strand anyone: the section it lands on is the one
+ // recorded, and the next entry opens there.
+ api.getConfig.mockResolvedValue({ capabilities: { model_hub: { enabled: false } } });
+ window.localStorage.setItem(SETTINGS_LAST_SECTION_STORAGE_KEY, '/settings/models');
+ media.matches = true;
+ renderLayout('/settings', { gateModelHub: true });
+
+ expect(await screen.findByText('backends-body')).toBeTruthy();
+ expect(window.localStorage.getItem(SETTINGS_LAST_SECTION_STORAGE_KEY))
+ .toBe('/settings/backends');
});
it.each([
['/settings/backends', 'backends-body'],
['/settings/platforms', 'platforms-body'],
['/settings/remote-access', 'remote-access-body'],
- ])('keeps the explicit deep link %s authoritative over the landing page', (path, body) => {
+ ])('keeps the explicit deep link %s authoritative over the resumed section', (path, body) => {
media.matches = true;
- window.localStorage.setItem('avibe.settings.last-path', '/settings/service');
+ window.localStorage.setItem(SETTINGS_LAST_SECTION_STORAGE_KEY, '/settings/service');
renderLayout(path);
expect(screen.getByText(body)).toBeTruthy();
@@ -436,10 +513,10 @@ describe('SettingsLayout', () => {
media.matches = false;
renderLayout('/settings');
- // This root is the phone's section-NAVIGATION screen, not its ordinary way
- // in: the dock chip goes straight to General at every width (see
- // MobileDockDrawer). Redirecting the root as well would leave General's back
- // row pointing at a screen that bounces the user back to General.
+ // This root IS the phone's ordinary way in — the dock chip points here (see
+ // MobileDockDrawer), because one screen at a time means the section list is
+ // the only place every other section is reachable from. Only a desktop,
+ // which keeps the rail beside the page, resolves it through to a section.
const general = screen.getByRole('link', { name: 'settings.sections.general' });
expect(general.getAttribute('href')).toBe('/settings/general');
expect(screen.queryByText('general-body')).toBeNull();
@@ -449,7 +526,20 @@ describe('SettingsLayout', () => {
expect(screen.getByRole('link', { name: 'settings.backToSections' }).getAttribute('href')).toBe('/settings');
});
- it('selects General when a mobile root viewport becomes desktop', async () => {
+ it('selects the resumed section when a mobile root viewport becomes desktop', async () => {
+ window.localStorage.setItem(SETTINGS_LAST_SECTION_STORAGE_KEY, '/settings/backends');
+ renderLayout('/settings');
+
+ expect(screen.queryByText('backends-body')).toBeNull();
+ act(() => {
+ media.matches = true;
+ media.listeners.forEach((listener) => listener({ matches: true } as MediaQueryListEvent));
+ });
+
+ await waitFor(() => expect(screen.getByText('backends-body')).toBeTruthy());
+ });
+
+ it('selects General when a mobile root viewport becomes desktop with nothing to resume', async () => {
renderLayout('/settings');
expect(screen.queryByText('general-body')).toBeNull();
diff --git a/ui/src/components/settings/SettingsLayout.tsx b/ui/src/components/settings/SettingsLayout.tsx
index f048b3fb0..4eb1b1445 100644
--- a/ui/src/components/settings/SettingsLayout.tsx
+++ b/ui/src/components/settings/SettingsLayout.tsx
@@ -29,6 +29,7 @@ import { useApi } from '@/context/ApiContext';
import { useInstanceAuthorization } from '@/context/InstanceAuthorizationContext';
import { memoryNavShouldBeVisible } from '@/lib/memorySettings';
import { SETTINGS_LANDING_PATH } from '@/lib/adminNavigation';
+import { settingsResumePath, writeLastSettingsSection } from '@/lib/settingsSectionMemory';
import { getEnabledPlatforms, platformSupportsChannels } from '@/lib/platforms';
import { useIsDesktop } from '@/lib/useIsDesktop';
import {
@@ -354,10 +355,33 @@ export const SettingsLayout: React.FC = () => {
section: t(activeTrail.at(-1)?.labelKey ?? 'nav.settings'),
});
+ // Choosing a rail row is a lasting preference, not a step inside one visit,
+ // so the next ordinary entry resumes it. The trail's last item is what gets
+ // recorded: a detail page inside a section resumes at the section that owns
+ // it, which is the row the rail can show as current.
+ //
+ // Where the person actually is, is the whole input. A feature-gated row
+ // (Models, Memory, Channels) can leave the rail while its page stays routed,
+ // and that does not make the page the wrong place to be: Memory with memory
+ // off is the setup surface, and a Model Hub that is off redirects itself —
+ // which arrives here as the section it redirected to and corrects the memory
+ // on its own. Nothing here consults the feature projections the rail draws
+ // rows from, so a pending or failed read can neither erase a preference nor
+ // record the wrong one.
+ useEffect(() => {
+ const section = activeTrail.at(-1);
+ if (section) writeLastSettingsSection(section.path);
+ }, [activeTrail]);
+
+ // The root is the phone's section list — the one screen a viewport with no
+ // rail beside the page can navigate from, and what its entry points at. A
+ // desktop keeps that rail on screen, so the root has nothing left to show
+ // there and resolves through to a section: the resumed one, the same answer
+ // its entry link resolves for itself.
useEffect(() => {
if (!atRoot || !isDesktop) return;
- navigate(SETTINGS_LANDING_PATH, { replace: true });
- }, [atRoot, isDesktop, navigate]);
+ navigate(settingsResumePath(capabilities.can_manage_instance), { replace: true });
+ }, [atRoot, capabilities.can_manage_instance, isDesktop, navigate]);
return (
<div className="flex h-full min-h-0 flex-col overflow-hidden bg-background md:h-[var(--app-shell-h)]">
diff --git a/ui/src/lib/adminNavigation.ts b/ui/src/lib/adminNavigation.ts
index 4df85e781..e4010a507 100644
--- a/ui/src/lib/adminNavigation.ts
+++ b/ui/src/lib/adminNavigation.ts
@@ -5,9 +5,12 @@ export const isMemorySettingsPath = (pathname: string): boolean =>
matchesRoute(pathname, '/settings/memory');
/**
- * Ordinary Settings always opens General, irrespective of the last visited
- * subsection. General is readable by every role, so the landing page needs no
- * capability fallback; explicit deep links stay authoritative on their own.
+ * Where Settings opens when there is no section to resume: a first visit, a
+ * device whose storage refused the write, or a remembered section that has
+ * since been retired or put out of this visitor's reach. General is readable by
+ * every role, so the fallback needs no capability check of its own — the resume
+ * does, and settingsSectionMemory applies it. Explicit deep links stay
+ * authoritative over both.
*/
export const SETTINGS_LANDING_PATH = '/settings/general';
diff --git a/ui/src/lib/settingsSectionMemory.test.ts b/ui/src/lib/settingsSectionMemory.test.ts
new file mode 100644
index 000000000..f1cbd86dd
--- /dev/null
+++ b/ui/src/lib/settingsSectionMemory.test.ts
@@ -0,0 +1,83 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { SETTINGS_LANDING_PATH } from './adminNavigation';
+import {
+ SETTINGS_LAST_SECTION_STORAGE_KEY,
+ readLastSettingsSection,
+ settingsResumePath,
+ writeLastSettingsSection,
+} from './settingsSectionMemory';
+
+type SectionStorage = Pick<Storage, 'getItem' | 'setItem'>;
+
+const storageHolding = (section?: string): SectionStorage => {
+ const entries = new Map<string, string>();
+ if (section) entries.set(SETTINGS_LAST_SECTION_STORAGE_KEY, section);
+ return {
+ getItem: (key) => entries.get(key) ?? null,
+ setItem: vi.fn((key, value) => { entries.set(key, value); }),
+ };
+};
+
+const blockedStorage: SectionStorage = {
+ getItem: () => { throw new Error('storage blocked'); },
+ setItem: () => { throw new Error('storage blocked'); },
+};
+
+describe('settings section memory', () => {
+ it('reads back the section it recorded', () => {
+ const storage = storageHolding();
+ writeLastSettingsSection('/settings/backends', storage);
+ expect(readLastSettingsSection(storage)).toBe('/settings/backends');
+ });
+
+ it('resumes the remembered section', () => {
+ expect(settingsResumePath(true, storageHolding('/settings/backends')))
+ .toBe('/settings/backends');
+ });
+
+ it('lands on General when there is nothing to resume', () => {
+ expect(settingsResumePath(true, storageHolding())).toBe(SETTINGS_LANDING_PATH);
+ });
+
+ it('degrades to General instead of throwing when storage is blocked', () => {
+ expect(() => writeLastSettingsSection('/settings/backends', blockedStorage)).not.toThrow();
+ expect(settingsResumePath(true, blockedStorage)).toBe(SETTINGS_LANDING_PATH);
+ });
+
+ it.each([
+ ['a section this release no longer routes', '/settings/retired-section', true],
+ ['a path outside Settings', '/projects', true],
+ ["an owner's section an ordinary member cannot open", '/settings/service', false],
+ // Route matching strips a query or fragment and the capability check does
+ // not, so a hand-edited value could otherwise carry an owner-only section
+ // past the guard on the strength of its suffix alone.
+ ['an owner-only section wearing a query string', '/settings/service?tab=status', false],
+ ['a section wearing a fragment', '/settings/backends#claude', true],
+ ])('falls back to General for %s', (_case, remembered, canManageInstance) => {
+ expect(settingsResumePath(canManageInstance, storageHolding(remembered)))
+ .toBe(SETTINGS_LANDING_PATH);
+ });
+
+ it('does not rewrite the section it already holds', () => {
+ const storage = storageHolding('/settings/backends');
+ writeLastSettingsSection('/settings/backends', storage);
+ expect(storage.setItem).not.toHaveBeenCalled();
+ });
+
+ it('still resumes an owner-only section for the owner', () => {
+ expect(settingsResumePath(true, storageHolding('/settings/service')))
+ .toBe('/settings/service');
+ });
+
+ it.each(['/settings/memory', '/settings/models', '/settings/platforms/groups'])(
+ 'resumes %s whatever its feature flag is doing',
+ (remembered) => {
+ // A feature flag decides which rows the rail advertises, not which pages a
+ // person may be on: Memory with memory off is its setup surface, and a
+ // Model Hub that is off redirects itself. Reading config here would only
+ // let a pending or failed projection throw away a preference.
+ expect(settingsResumePath(true, storageHolding(remembered))).toBe(remembered);
+ },
+ );
+});
diff --git a/ui/src/lib/settingsSectionMemory.ts b/ui/src/lib/settingsSectionMemory.ts
new file mode 100644
index 000000000..b4da2fc83
--- /dev/null
+++ b/ui/src/lib/settingsSectionMemory.ts
@@ -0,0 +1,124 @@
+import { useSyncExternalStore } from 'react';
+
+import { isOwnerOnlyPath, SETTINGS_LANDING_PATH } from './adminNavigation';
+import { isApplicationRouteHref } from './applicationRoutes';
+
+/**
+ * Which Settings section this device opened last.
+ *
+ * Settings is a place people return to, not a page they read once: whoever
+ * spent the last visit on Backends is far likelier to want Backends again than
+ * General, and re-selecting it on every entry is work the surface can do for
+ * them. Only the *section* is remembered — the rail row that was selected — so
+ * a detail page inside one (a backend's provider page, the log viewer) resumes
+ * at the row the rail can actually show as current.
+ *
+ * A per-person, per-device view preference of the same tier as the theme and
+ * the menu placement, so it lives in localStorage rather than in instance
+ * config, where one member's last visit would move every other member's
+ * landing. Storage conventions mirror settingsMenuPlacement: versioned
+ * `avibe.*` key, injectable storage for tests, best-effort try/catch so blocked
+ * storage degrades to the ordinary landing instead of throwing, and a change
+ * event so a link rendered elsewhere can follow the rail.
+ *
+ * What may be resumed is a question about the route, not about the feature
+ * flags: the value has to name a route this release still declares, and a
+ * section this visitor's capabilities allow. A feature flag decides which rows
+ * the rail advertises, not which pages a person may stand on — Memory with
+ * memory switched off is the setup surface the Dependencies page's Configure
+ * button links to, and Model Hub with the hub switched off redirects itself
+ * (ModelHubCapabilityGate), which moves this memory to wherever it lands.
+ * `pwaRouteMemory` restores the very same paths on the very same terms.
+ */
+export const SETTINGS_LAST_SECTION_STORAGE_KEY = 'avibe.settings.last-section.v1';
+export const SETTINGS_LAST_SECTION_CHANGED_EVENT = 'avibe:settings-last-section-changed';
+
+type SectionStorage = Pick<Storage, 'getItem' | 'setItem'>;
+
+function browserStorage(storage?: SectionStorage): SectionStorage | undefined {
+ return storage ?? (typeof window !== 'undefined' ? window.localStorage : undefined);
+}
+
+function announceSectionChange(): void {
+ // `storage` events only reach *other* tabs; this covers the entry controls
+ // rendered beside the rail in this one.
+ if (typeof window !== 'undefined') {
+ window.dispatchEvent(new Event(SETTINGS_LAST_SECTION_CHANGED_EVENT));
+ }
+}
+
+export function readLastSettingsSection(storage?: SectionStorage): string | null {
+ try {
+ return browserStorage(storage)?.getItem(SETTINGS_LAST_SECTION_STORAGE_KEY) ?? null;
+ } catch {
+ return null;
+ }
+}
+
+export function writeLastSettingsSection(path: string, storage?: SectionStorage): void {
+ try {
+ const target = browserStorage(storage);
+ // Selecting the row you are already on is not a change, and announcing one
+ // would re-render every subscriber on each navigation inside a section.
+ if (!target || target.getItem(SETTINGS_LAST_SECTION_STORAGE_KEY) === path) return;
+ target.setItem(SETTINGS_LAST_SECTION_STORAGE_KEY, path);
+ } catch {
+ // View memory is best-effort in private browsing and restricted storage contexts.
+ return;
+ }
+ announceSectionChange();
+}
+
+/**
+ * Where an ordinary Settings entry opens: the section this device was left on,
+ * or the landing page when there is nothing to resume.
+ */
+export function settingsResumePath(
+ canManageInstance: boolean,
+ storage?: SectionStorage,
+): string {
+ const remembered = readLastSettingsSection(storage);
+ if (!remembered || !remembered.startsWith('/settings/')) return SETTINGS_LANDING_PATH;
+ // Only a bare section path is ever recorded, so a query or fragment means a
+ // value this surface did not write. Rejecting it keeps both checks below
+ // reading the same string: a suffix that route matching strips but the
+ // capability check does not would otherwise walk an owner-only section past
+ // the guard and hand a member a destination their route guard then bounces.
+ if (/[?#]/.test(remembered)) return SETTINGS_LANDING_PATH;
+ // A path an older release wrote, or hand-edited storage: resume only what this
+ // release still routes, rather than handing the surface its not-found page.
+ if (!isApplicationRouteHref(remembered)) return SETTINGS_LANDING_PATH;
+ // A remembered page can outlive the capability that made it readable.
+ if (!canManageInstance && isOwnerOnlyPath(remembered)) return SETTINGS_LANDING_PATH;
+ return remembered;
+}
+
+function subscribeToLastSettingsSection(listener: () => void): () => void {
+ if (typeof window === 'undefined') return () => undefined;
+ const onStorage = (event: StorageEvent) => {
+ if (event.key === SETTINGS_LAST_SECTION_STORAGE_KEY) listener();
+ };
+ window.addEventListener('storage', onStorage);
+ window.addEventListener(SETTINGS_LAST_SECTION_CHANGED_EVENT, listener);
+ return () => {
+ window.removeEventListener('storage', onStorage);
+ window.removeEventListener(SETTINGS_LAST_SECTION_CHANGED_EVENT, listener);
+ };
+}
+
+/**
+ * The same answer as `settingsResumePath`, kept current for a control that
+ * displays it. An entry link renders long before it is clicked, and the section
+ * can move under it meanwhile: the same person can have this origin open in two
+ * tabs, and the one that is not in Settings has to follow the one that is, or
+ * it keeps offering — and showing in its href — a section the rail left.
+ */
+export function useSettingsResumePath(canManageInstance: boolean): string {
+ // The snapshot is a plain string, so identity comparison is value comparison
+ // and no caching layer is needed between reads.
+ return useSyncExternalStore(
+ subscribeToLastSettingsSection,
+ () => settingsResumePath(canManageInstance),
+ () => SETTINGS_LANDING_PATH,
+ );
+}