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.

32.8 KB
Raw Blame
/* @vitest-environment jsdom */

import { act, cleanup, render, screen, waitFor } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import userEvent from '@testing-library/user-event';
import { MemoryRouter, Route, Routes, useLocation, useNavigate } from 'react-router-dom';
import type { Location } from 'react-router-dom';

import {
  SettingsOverlayOriginContext,
  settingsOverlayOpenState,
  useSettingsOverlayOrigin,
} 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 { SettingsOverlayNavigationBoundary } from './SettingsOverlayNavigationBoundary';
import { SettingsLayout } from './SettingsLayout';

const api = vi.hoisted(() => {
  const configChangedHandlers = new Set<(config: unknown) => void>();
  return {
    configChangedHandlers,
    getConfig: vi.fn(),
    getVersion: vi.fn(),
    getMemorySettings: vi.fn(),
    onConfigChanged: vi.fn((handler: (config: unknown) => void) => {
      configChangedHandlers.add(handler);
      return () => configChangedHandlers.delete(handler);
    }),
  };
});
const authorization = vi.hoisted(() => ({
  capabilities: { can_manage_instance: true, can_read_instance: true },
}));
const media = vi.hoisted(() => ({
  matches: false,
  listeners: new Set<(event: MediaQueryListEvent) => void>(),
}));

vi.mock('@/context/ApiContext', () => ({ useApi: () => api }));
vi.mock('@/context/InstanceAuthorizationContext', () => ({
  useInstanceAuthorization: () => authorization,
}));
vi.mock('react-i18next', () => ({
  useTranslation: () => ({ t: (key: string) => key }),
}));
vi.mock('../LanguageSwitcher', () => ({
  LanguageSwitcher: ({ openUpward }: { openUpward?: boolean }) => (
    <div data-testid="language-switcher" data-open-upward={String(openUpward)} />
  ),
}));
vi.mock('../ThemeToggle', () => ({ ThemeToggle: () => <div data-testid="theme-toggle" /> }));
vi.mock('../AccountMenu', () => ({
  AccountMenu: ({ openUpward }: { openUpward?: boolean }) => (
    <div data-testid="account-menu" data-open-upward={String(openUpward)} />
  ),
}));

const NavigationProbe = () => {
  const navigate = useNavigate();
  return (
    <div>
      <button type="button" onClick={() => navigate('/settings/service')}>go-service</button>
      <button type="button" onClick={() => navigate('/settings/platforms/groups')}>go-groups</button>
      <button type="button" onClick={() => navigate(-1)}>go-back</button>
    </div>
  );
};

const SettingsLayoutHarness = () => {
  const location = useLocation();
  const origin = useSettingsOverlayOrigin(location);
  return (
    <SettingsOverlayOriginContext.Provider value={origin}>
      <SettingsLayout />
      <NavigationProbe />
    </SettingsOverlayOriginContext.Provider>
  );
};

type SettingsTestEntry = string | {
  pathname: 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, gateModelHub = false }: {
    shellHasSidebar?: boolean;
    gateModelHub?: boolean;
  } = {},
) => render(
  <MemoryRouter initialEntries={[entry]}>
    <ShellSidebarContext.Provider value={shellHasSidebar}>
    <SettingsOverlayNavigationBoundary desktop={shellHasSidebar}>
    <Routes>
      <Route path="/settings" element={<SettingsLayoutHarness />}>
        <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={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>} />
        <Route path="platforms" element={<div>platforms-body</div>} />
        <Route path="platforms/users" element={<div>users-body</div>} />
        <Route path="platforms/groups" element={<div>groups-body</div>} />
        <Route path="remote-access" element={<div>remote-access-body</div>} />
      </Route>
      <Route path="/chat/:sessionId" element={<div>chat-body</div>} />
    </Routes>
    </SettingsOverlayNavigationBoundary>
    </ShellSidebarContext.Provider>
  </MemoryRouter>,
);

beforeEach(() => {
  window.localStorage.clear();
  authorization.capabilities.can_manage_instance = true;
  media.matches = false;
  media.listeners.clear();
  api.configChangedHandlers.clear();
  api.getConfig.mockResolvedValue({ capabilities: { model_hub: { enabled: true } } });
  api.getVersion.mockResolvedValue({
    current: '3.1.4',
    latest: '3.1.4',
    has_update: false,
    error: null,
    build: { kind: 'package' },
  });
  api.getMemorySettings.mockResolvedValue({ status: 'ok', enabled: true });
  vi.stubGlobal('matchMedia', vi.fn().mockReturnValue({
    get matches() {
      return media.matches;
    },
    addEventListener: (_type: string, listener: (event: MediaQueryListEvent) => void) => media.listeners.add(listener),
    removeEventListener: (_type: string, listener: (event: MediaQueryListEvent) => void) => media.listeners.delete(listener),
  }));
});

afterEach(() => {
  cleanup();
  vi.clearAllMocks();
  vi.unstubAllGlobals();
});

describe('SettingsLayout', () => {
  it('closes a desktop overlay back to its exact opening route', async () => {
    media.matches = true;
    const user = userEvent.setup();
    const origin: Location = {
      pathname: '/chat/ses_7',
      search: '?message=m1',
      hash: '#tail',
      state: { source: 'search' },
      key: 'chat-origin',
    };

    renderLayout({
      pathname: '/settings/replies',
      state: settingsOverlayOpenState(origin),
    });

    const close = screen.getByRole('button', { name: 'settings.close' });
    await user.click(close);
    expect(await screen.findByText('chat-body')).toBeTruthy();
  });

  it('leaves the top bar to the desktop shell and keeps the rail way out', async () => {
    media.matches = true;
    Object.defineProperty(window, '__AVIBE_DESKTOP_SHELL__', { value: true, configurable: true });
    try {
      const user = userEvent.setup();
      renderLayout({
        pathname: '/settings/general',
        state: settingsOverlayOpenState({
          pathname: '/chat/ses_7',
          search: '',
          hash: '',
          state: null,
          key: 'chat-origin',
        }),
      });

      expect(screen.queryByRole('banner')).toBeNull();
      expect(screen.queryByRole('button', { name: 'settings.close' })).toBeNull();
      await user.click(screen.getByRole('button', { name: 'settings.backToApp' }));
      expect(await screen.findByText('chat-body')).toBeTruthy();
    } finally {
      Reflect.deleteProperty(window, '__AVIBE_DESKTOP_SHELL__');
    }
  });

  it('lists Computer Use under System only inside the desktop shell, whatever the viewport', () => {
    // A wide browser tab is a desktop viewport but not the desktop host.
    media.matches = true;
    const view = renderLayout('/settings/shortcuts');
    expect(screen.queryByRole('link', { name: 'settings.sections.computerUse' })).toBeNull();
    view.unmount();

    Object.defineProperty(window, '__AVIBE_DESKTOP_SHELL__', { value: true, configurable: true });
    try {
      for (const canManage of [true, false]) {
        authorization.capabilities.can_manage_instance = canManage;
        const shellView = renderLayout('/settings/shortcuts');
        const link = screen.getByRole('link', { name: 'settings.sections.computerUse' });
        expect(link.getAttribute('href')).toBe('/settings/computer-use');
        const systemRows = screen.getAllByRole('link').map((row) => row.getAttribute('href'));
        expect(systemRows.indexOf('/settings/computer-use')).toBe(
          systemRows.indexOf('/settings/shortcuts') + 1,
        );
        shellView.unmount();
      }
    } finally {
      Reflect.deleteProperty(window, '__AVIBE_DESKTOP_SHELL__');
    }
  });

  it('keeps the settings rail fixed while the route pane owns vertical scrolling', () => {
    renderLayout('/settings/replies');

    const routePane = screen.getByText('replies-body').closest('section');
    const shell = routePane?.parentElement?.parentElement;
    const navigation = screen.getByRole('navigation', { name: 'settings.navigationLabel' });

    expect(routePane?.className).toContain('overflow-y-auto');
    expect(navigation.className).not.toContain('overflow-y-auto');
    // The return row is pinned above the scrolling section list, so the way out
    // of Settings never scrolls away from the top of the rail.
    const returnRow = navigation.firstElementChild;
    expect(returnRow?.getAttribute('aria-label')).toBe('settings.backToApp');
    expect(returnRow?.className).not.toContain('overflow-y-auto');
    expect(navigation.querySelector('.overflow-y-auto')).toBeTruthy();
    expect(shell?.className).toContain('h-full');
    expect(shell?.className).toContain('min-h-0');
    expect(shell?.className).toContain('overflow-hidden');
    expect(shell?.className).toContain('md:h-[var(--app-shell-h)]');
    expect(shell?.className).not.toContain('md:h-auto');
    expect(shell?.className).not.toContain('min-h-full');
  });

  // Opening standalone Settings swaps this rail IN FOR the app sidebar, so it
  // has to be the width that sidebar was — a width the owner dragged it to
  // included — or the left column jumps as Settings opens. Inline Settings sits
  // beside that sidebar, where matching it would spend a second full-width
  // column on a secondary nav, so it stays 196.
  it.each([
    ['standalone', 'md:w-[var(--app-sidebar-w)]', 'md:w-[196px]'],
    ['inline', 'md:w-[196px]', 'md:w-[var(--app-sidebar-w)]'],
  ] as const)('sizes the rail for a %s menu', (placement, expected, rejected) => {
    media.matches = true;
    window.localStorage.setItem(SETTINGS_MENU_PLACEMENT_STORAGE_KEY, placement);
    renderLayout('/settings/general');

    const navigation = screen.getByRole('navigation', { name: 'settings.navigationLabel' });
    expect(navigation.className).toContain(expected);
    expect(navigation.className).not.toContain(rejected);
  });

  // The inline rail is 196px because it sits beside a 248px sidebar. Where the
  // shell draws none — the setup wizard, a single-app tab — that rail would be
  // narrowed for a neighbour that is not there, so the stored preference is not
  // in force, and is not forgotten for the windows that do have one.
  it('sizes the rail standalone where the shell draws no sidebar, even when inline is stored', () => {
    media.matches = true;
    window.localStorage.setItem(SETTINGS_MENU_PLACEMENT_STORAGE_KEY, 'inline');

    renderLayout('/settings/models', { shellHasSidebar: false });

    const navigation = screen.getByRole('navigation', { name: 'settings.navigationLabel' });
    expect(navigation.className).toContain('md:w-[var(--app-sidebar-w)]');
    expect(navigation.className).not.toContain('md:w-[196px]');
  });

  it.each(['/settings/models', '/settings/models/'])(
    'lets Model Hub fill the route pane at %s',
    (path) => {
      renderLayout(path);

      const modelHubFrame = screen.getByText('models-body').parentElement;
      expect(modelHubFrame?.className).toContain('min-h-full');
      expect(modelHubFrame?.className).not.toContain('mx-auto');
      expect(modelHubFrame?.className).not.toMatch(/(?:^|\s)(?:[\w-]+:)*max-w-/);
    },
  );

  // General and the other ordinary Settings sections share the standalone
  // 944px outer frame (880px content after desktop padding). Model Hub keeps
  // the full route pane for its own full-height surface.
  it.each(['/settings/general', '/settings/general/'])(
    'keeps General in the common standalone content column at %s',
    (path) => {
      renderLayout(path);

      const generalFrame = screen.getByText('general-body').parentElement;
      expect(generalFrame?.className).toContain('mx-auto');
      expect(generalFrame?.className).toContain('max-w-[944px]');
      expect(generalFrame?.className).not.toContain('min-h-full');
    },
  );

  it('keeps standard settings pages constrained', () => {
    renderLayout('/settings/replies');

    const standardFrame = screen.getByText('replies-body').parentElement;
    expect(standardFrame?.className).toContain('mx-auto');
    expect(standardFrame?.className).toContain('max-w-[944px]');
    expect(standardFrame?.className).not.toContain('min-h-full');
  });

  it('renders the three-group rail and feature-gated owner sections', () => {
    renderLayout('/settings/replies');

    expect(screen.getByText('replies-body')).toBeTruthy();
    expect(screen.getByText('settings.groups.agents')).toBeTruthy();
    expect(screen.getByText('settings.groups.connections')).toBeTruthy();
    expect(screen.getByText('settings.groups.system')).toBeTruthy();
    expect(screen.getByRole('link', { name: 'settings.sections.models' })).toBeTruthy();
  });

  it('keeps Models on the rail before config resolves and while Model Hub is disabled', async () => {
    let resolveConfig: ((config: unknown) => void) | undefined;
    api.getConfig.mockImplementation(
      () => new Promise((resolve) => {
        resolveConfig = resolve;
      }),
    );
    renderLayout('/settings/replies');

    expect(screen.getByRole('link', { name: 'settings.sections.models' })).toBeTruthy();
    expect(resolveConfig).toBeTypeOf('function');

    await act(async () => {
      resolveConfig?.({ capabilities: { model_hub: { enabled: false } } });
    });
    expect(screen.getByRole('link', { name: 'settings.sections.models' })).toBeTruthy();
  });

  // AUTH-SETUP-125: Settings opened over the wizard offers only the sections the
  // setup visit keeps, so no row leads out of the setup and loses its step.
  it('offers only the setup visit sections over the wizard', () => {
    const setup: Location = { pathname: '/setup', search: '', hash: '', state: null, key: 'setup' };
    renderLayout(
      { pathname: '/settings/general', state: settingsOverlayOpenState(setup, null) },
      { shellHasSidebar: false },
    );

    expect(screen.getByText('general-body')).toBeTruthy();
    expect(screen.getByRole('link', { name: 'settings.sections.general' })).toBeTruthy();
    expect(screen.getByRole('link', { name: 'settings.sections.models' })).toBeTruthy();
    const rail = screen.getByRole('navigation', { name: 'settings.navigationLabel' });
    expect(rail.querySelectorAll('a[href^="/settings/"]')).toHaveLength(2);
    expect(screen.queryByRole('link', { name: 'settings.sections.replies' })).toBeNull();
    expect(screen.queryByRole('button', { name: 'nav.messagingPlatforms' })).toBeNull();
  });

  it('keeps a disabled Model Hub inside the setup overlay instead of leaving for Backends', async () => {
    const setup: Location = { pathname: '/setup', search: '', hash: '', state: null, key: 'setup' };
    api.getConfig.mockResolvedValue({ capabilities: { model_hub: { enabled: false } } });
    renderLayout(
      { pathname: '/settings/models', state: settingsOverlayOpenState(setup, null) },
      { shellHasSidebar: false, gateModelHub: true },
    );

    expect(await screen.findByText('general-body')).toBeTruthy();
    expect(screen.queryByText('backends-body')).toBeNull();
    expect(screen.queryByText('models-body')).toBeNull();
    const rail = screen.getByRole('navigation', { name: 'settings.navigationLabel' });
    expect(rail.querySelectorAll('a[href^="/settings/"]')).toHaveLength(2);
    expect(screen.getByRole('link', { name: 'settings.sections.models' })).toBeTruthy();
    expect(screen.getByRole('link', { name: 'settings.sections.general' })).toBeTruthy();
    expect(screen.queryByRole('link', { name: 'settings.sections.replies' })).toBeNull();
    expect(screen.queryByRole('button', { name: 'nav.messagingPlatforms' })).toBeNull();
  });

  it('opens Messaging Platforms by default and still allows manual collapse', async () => {
    const user = userEvent.setup();
    renderLayout('/settings/service');

    const platforms = screen.getByRole('button', { name: 'nav.messagingPlatforms' });
    expect(platforms.getAttribute('aria-expanded')).toBe('true');
    expect(screen.getByRole('link', { name: 'settings.sections.platformConnections' })).toBeTruthy();
    expect(screen.getByRole('link', { name: 'nav.users' })).toBeTruthy();
    await waitFor(() => expect(screen.getByRole('link', { name: 'nav.channels' })).toBeTruthy());

    await user.click(platforms);
    expect(platforms.getAttribute('aria-expanded')).toBe('false');
    expect(screen.queryByRole('link', { name: 'settings.sections.platformConnections' })).toBeNull();

    await user.click(platforms);
    expect(platforms.getAttribute('aria-expanded')).toBe('true');
  });

  it('auto-expands Platforms and selects the matching nested destination', async () => {
    renderLayout('/settings/platforms/groups');

    expect(screen.getByText('groups-body')).toBeTruthy();
    await waitFor(() => {
      expect(screen.getByRole('button', { name: 'nav.messagingPlatforms' }).getAttribute('aria-expanded')).toBe('true');
    });
    expect(screen.getByRole('link', { name: 'nav.channels' }).className).toContain('bg-mint-soft');
    expect(screen.getByRole('link', { name: 'settings.sections.platformConnections' }).className).not.toContain('bg-mint-soft');
    expect(screen.getByRole('link', { name: 'settings.sections.platformConnections' }).getAttribute('aria-current')).toBeNull();
  });

  it('hides Groups when no enabled platform supports group settings', async () => {
    api.getConfig.mockResolvedValue({
      capabilities: { model_hub: { enabled: true } },
      platforms: { enabled: ['wechat'] },
    });
    renderLayout('/settings/replies');

    expect(screen.getByRole('link', { name: 'settings.sections.platformConnections' })).toBeTruthy();
    expect(screen.getByRole('link', { name: 'nav.users' })).toBeTruthy();
    await waitFor(() => expect(screen.queryByRole('link', { name: 'nav.channels' })).toBeNull());
  });

  it('refreshes Groups visibility after successful platform config changes', async () => {
    api.getConfig.mockResolvedValue({
      capabilities: { model_hub: { enabled: true } },
      platforms: { enabled: ['wechat'] },
    });
    renderLayout('/settings/replies');

    await waitFor(() => expect(screen.queryByRole('link', { name: 'nav.channels' })).toBeNull());
    expect(screen.getByRole('link', { name: 'settings.sections.models' })).toBeTruthy();

    act(() => {
      api.configChangedHandlers.forEach((handler) => handler({
        capabilities: { model_hub: { enabled: true } },
        platforms: { enabled: ['slack'] },
      }));
    });
    expect(screen.getByRole('link', { name: 'nav.channels' })).toBeTruthy();
    expect(screen.getByRole('link', { name: 'settings.sections.models' })).toBeTruthy();

    act(() => {
      api.configChangedHandlers.forEach((handler) => handler({
        capabilities: { model_hub: { enabled: true } },
        platforms: { enabled: ['wechat'] },
      }));
    });
    expect(screen.queryByRole('link', { name: 'nav.channels' })).toBeNull();
    expect(screen.getByRole('link', { name: 'settings.sections.models' })).toBeTruthy();
  });

  it('restores the default expanded disclosure after navigation', async () => {
    const user = userEvent.setup();
    renderLayout('/settings/replies');

    expect(screen.getByRole('button', { name: 'nav.messagingPlatforms' }).getAttribute('aria-expanded')).toBe('true');
    await user.click(screen.getByRole('button', { name: 'nav.messagingPlatforms' }));
    expect(screen.getByRole('button', { name: 'nav.messagingPlatforms' }).getAttribute('aria-expanded')).toBe('false');
    await user.click(screen.getByRole('button', { name: 'go-service' }));
    await user.click(screen.getByRole('button', { name: 'go-back' }));
    expect(screen.getByRole('button', { name: 'nav.messagingPlatforms' }).getAttribute('aria-expanded')).toBe('true');

    await user.click(screen.getByRole('button', { name: 'go-groups' }));
    expect(screen.getByRole('button', { name: 'nav.messagingPlatforms' }).getAttribute('aria-expanded')).toBe('true');
    await user.click(screen.getByRole('button', { name: 'nav.messagingPlatforms' }));
    expect(screen.getByRole('button', { name: 'nav.messagingPlatforms' }).getAttribute('aria-expanded')).toBe('false');
    await user.click(screen.getByRole('button', { name: 'go-service' }));
    await user.click(screen.getByRole('button', { name: 'go-back' }));
    expect(screen.getByRole('button', { name: 'nav.messagingPlatforms' }).getAttribute('aria-expanded')).toBe('true');
  });

  it('moves language and appearance into General and keeps the account menu in the rail', () => {
    renderLayout('/settings/replies');

    // Language and appearance are a Settings SECTION now, reachable and
    // linkable like every other one — not two icons wedged into the rail
    // footer where nothing else about the interface lives.
    expect(screen.queryByTestId('language-switcher')).toBeNull();
    expect(screen.queryByTestId('theme-toggle')).toBeNull();
    expect(screen.getByRole('link', { name: 'settings.sections.general' }).getAttribute('href'))
      .toBe('/settings/general');
    expect(screen.getByTestId('account-menu').getAttribute('data-open-upward')).toBe('true');
  });

  it('updates the retained rail when instance-management permission changes', async () => {
    const surface = () => (
      <MemoryRouter initialEntries={['/settings/general']}>
        <Routes>
          <Route path="/settings" element={<SettingsLayoutHarness />}>
            <Route path="general" element={<div>general-body</div>} />
          </Route>
        </Routes>
      </MemoryRouter>
    );
    const view = render(surface());
    expect(await screen.findByRole('link', { name: 'settings.sections.backends' })).toBeTruthy();
    authorization.capabilities.can_manage_instance = false;
    view.rerender(surface());
    expect(screen.queryByRole('link', { name: 'settings.sections.backends' })).toBeNull();
    expect(screen.getByText('general-body')).toBeTruthy();
    expect(screen.getByRole('link', { name: 'settings.sections.replies' })).toBeTruthy();
    authorization.capabilities.can_manage_instance = true;
    view.rerender(surface());
    expect(await screen.findByRole('link', { name: 'settings.sections.backends' })).toBeTruthy();
  });

  it('keeps member preferences, Replies, and Access while preserving the phase-2 permission gate', () => {
    authorization.capabilities.can_manage_instance = false;
    renderLayout('/settings/replies');

    expect(screen.getByText('replies-body')).toBeTruthy();
    expect(screen.getByRole('link', { name: 'settings.sections.replies' })).toBeTruthy();
    expect(screen.getByRole('link', { name: 'settings.sections.shortcuts' })).toBeTruthy();
    expect(screen.getByRole('link', { name: 'settings.sections.access' })).toBeTruthy();
    expect(screen.queryByRole('link', { name: 'settings.sections.service' })).toBeNull();
    expect(api.getVersion).not.toHaveBeenCalled();
    expect(api.getConfig).not.toHaveBeenCalled();
  });

  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('service-body')).toBeNull();
  });


  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();
    // The redirect lands in the DOM one commit before the trail effect records
    // where it landed, so reading storage the instant the page appears catches a
    // real but momentary disagreement. The contract is that the memory follows
    // the redirect, not that it arrives in the same commit.
    await waitFor(() => {
      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 resumed section', (path, body) => {
    media.matches = true;
    window.localStorage.setItem(SETTINGS_LAST_SECTION_STORAGE_KEY, '/settings/service');
    renderLayout(path);

    expect(screen.getByText(body)).toBeTruthy();
    expect(screen.queryByText('general-body')).toBeNull();
  });

  it('keeps the narrow root as the explicit section list a detail page can return to', async () => {
    const user = userEvent.setup();
    media.matches = false;
    renderLayout('/settings');

    // 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();

    await user.click(general);
    expect(await screen.findByText('general-body')).toBeTruthy();
    expect(screen.getByRole('link', { name: 'settings.backToSections' }).getAttribute('href')).toBe('/settings');
  });

  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();
    act(() => {
      media.matches = true;
      media.listeners.forEach((listener) => listener({ matches: true } as MediaQueryListEvent));
    });

    await waitFor(() => expect(screen.getByText('general-body')).toBeTruthy());
  });


  it('keeps the mobile header below the safe-area inset', () => {
    renderLayout('/settings/replies');

    expect(screen.getByRole('banner').className).toContain('pt-[env(safe-area-inset-top)]');
  });

  it('keeps mobile navigation and the Back action touch-sized', () => {
    renderLayout('/settings');

    expect(screen.getByRole('link', { name: 'settings.sections.replies' }).className).toContain('min-h-11');
    const back = screen.getByRole('link', { name: 'settings.backToWorkbench' });
    expect(back.getAttribute('href')).toBe('/');
    expect(back.className).toContain('size-11');
  });

  it('unwinds a retained overlay from the phone root instead of pushing a second home', async () => {
    // A phone that opened Settings over a surface worth keeping now has the same
    // origin the desktop controls close through, so its root back has to close
    // rather than navigate: pushing '/' would leave the whole Settings chain one
    // Back away from the user.
    const user = userEvent.setup();
    const origin: Location = {
      pathname: '/chat/ses_7',
      search: '?message=m1',
      hash: '#tail',
      state: { source: 'search' },
      key: 'chat-origin',
    };

    renderLayout({ pathname: '/settings', state: settingsOverlayOpenState(origin) });

    const back = screen.getByRole('button', { name: 'settings.backToWorkbench' });
    expect(back.className).toContain('size-11');
    expect(back.className).toContain('md:hidden');
    await user.click(back);
    expect(await screen.findByText('chat-body')).toBeTruthy();
  });

  it('keeps a retained origin on ordinary links inside settings', () => {
    // Only the root action leaves; a section's back still steps one level up the
    // rail, and does it as a link so the origin rides along with the push.
    renderLayout({
      pathname: '/settings/replies',
      state: settingsOverlayOpenState({
        pathname: '/chat/ses_7',
        search: '',
        hash: '',
        state: null,
        key: 'chat-origin',
      } as Location),
    });

    const back = screen.getByRole('link', { name: 'settings.backToSections' });
    expect(back.getAttribute('href')).toBe('/settings');
    expect(screen.queryByRole('button', { name: 'settings.backToSections' })).toBeNull();
  });

  it('shows the current version with a safe-area-aware mobile popup', async () => {
    const user = userEvent.setup();
    renderLayout('/settings');

    const version = await screen.findByTitle('dashboard.versionTitle');
    expect(version.parentElement?.parentElement?.className).toContain('md:hidden');

    await user.click(version);
    const popup = screen.getByText('dashboard.versionAndUpdate').closest('.fixed');
    expect(popup?.className).toContain('top-[calc(4.5rem+env(safe-area-inset-top))]');
    expect(popup?.className).toContain('max-h-[calc(100dvh-5.5rem-env(safe-area-inset-top))]');
  });

  it('keeps mobile navigation and detail controls above the bottom safe-area inset', () => {
    renderLayout('/settings/replies');

    expect(screen.getByRole('navigation', { name: 'settings.navigationLabel' }).className).toContain(
      'env(safe-area-inset-bottom)',
    );
    expect(screen.getByText('replies-body').closest('section')?.firstElementChild?.className).toContain(
      'env(safe-area-inset-bottom)',
    );
  });

  it.each([
    ['/settings/replies', '/settings', 'settings.backToSections'],
    ['/settings/platforms/groups', '/settings', 'settings.backToSections'],
    ['/settings/backends/claude', '/settings/backends', 'settings.backToSection'],
  ])('returns one mobile level from %s', (path, target, label) => {
    renderLayout(path);

    const back = screen.getByRole('link', { name: label });
    expect(back.getAttribute('href')).toBe(target);
    expect(back.className).toContain('md:hidden');
  });

  it('animates a mobile detail screen without carrying that motion onto desktop', () => {
    renderLayout('/settings/replies');

    const frame = screen.getByText('replies-body').parentElement;
    expect(frame?.className).toContain('slide-in-from-right-4');
    expect(frame?.className).toContain('md:animate-none');
  });
});