Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

27.1 KB
Raw Blame
import { useState } from 'react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { MemoryRouter, useLocation } from 'react-router';
import { RECENT_KEY } from '../utils/navWorkingSet.js';
import { CMD_K_SEARCH_OPEN_EVENT } from '../hooks/useCmdKSearch.js';

const getPaletteManifest = vi.fn();
const getInstanceFeatures = vi.fn();
const getDashboardLayouts = vi.fn();
const search = vi.fn(() => Promise.resolve({ sources: [] }));
const listCatalogIngredients = vi.fn(() => Promise.resolve({ items: [] }));
const runPaletteAction = vi.fn(() => Promise.resolve({ ok: true }));
const toast = vi.hoisted(() => {
  const mock = vi.fn();
  mock.success = vi.fn();
  mock.error = vi.fn();
  return mock;
});

vi.mock('../services/api', () => ({
  search: (...args) => search(...args),
  getPaletteManifest: (...args) => getPaletteManifest(...args),
  getInstanceFeatures: (...args) => getInstanceFeatures(...args),
  runPaletteAction: (...args) => runPaletteAction(...args),
  getDashboardLayouts: (...args) => getDashboardLayouts(...args),
  setActiveDashboardLayout: vi.fn(() => Promise.resolve()),
  listCatalogIngredients: (...args) => listCatalogIngredients(...args),
}));

vi.mock('./ui/Toast', () => ({ default: toast }));

import { __resetInstanceFeatureCache } from '../hooks/useInstanceFeatures.js';
import CmdKSearch from './CmdKSearch.jsx';
import Drawer from './Drawer.jsx';

const NAV = [
  { id: 'nav.dashboard', path: '/', label: 'Dashboard', section: 'Home', aliases: [], keywords: [] },
  { id: 'nav.apps', path: '/apps', label: 'Apps', section: 'System', aliases: [], keywords: [] },
  { id: 'nav.brain.inbox', path: '/brain/inbox', label: 'Brain Inbox', section: 'Brain', aliases: [], keywords: [] },
  { id: 'nav.goals', path: '/goals', label: 'Goals', section: 'Life', aliases: [], keywords: [] },
  { id: 'nav.current', path: '/current', label: 'Current Page', section: 'Test', aliases: [], keywords: [] },
  // Gated on an optional instance feature — present in the manifest, hidden by
  // the palette whenever that feature is off.
  { id: 'nav.devtools.jira', path: '/devtools/jira', label: 'JIRA', section: 'Dev Tools', feature: 'jira', aliases: ['jira'], keywords: [] },
];

const FEATURES_ON = [{ id: 'jira', label: 'JIRA', enabled: true }];
const FEATURES_OFF = [{ id: 'jira', label: 'JIRA', enabled: false }];

function LocationProbe() {
  const location = useLocation();
  return <output data-testid="location">{location.pathname}</output>;
}

beforeEach(() => {
  // The feature list is cached at module scope and shared with the sidebar.
  __resetInstanceFeatureCache();
  getInstanceFeatures.mockResolvedValue({ features: FEATURES_ON });
  getPaletteManifest.mockResolvedValue({ nav: NAV, actions: [] });
  getDashboardLayouts.mockResolvedValue({ layouts: [] });
  search.mockReset();
  search.mockResolvedValue({ sources: [] });
  listCatalogIngredients.mockReset();
  listCatalogIngredients.mockResolvedValue({ items: [] });
  runPaletteAction.mockReset();
  runPaletteAction.mockResolvedValue({ ok: true });
  toast.mockReset();
  toast.success.mockReset();
  toast.error.mockReset();
  HTMLElement.prototype.scrollIntoView = vi.fn();
});

const BRAIN_CAPTURE = {
  id: 'brain_capture',
  label: 'Capture to Brain',
  section: 'Brain',
  description: 'Capture a thought',
  aliases: [],
  keywords: [],
  parameters: {
    type: 'object',
    required: ['text'],
    properties: { text: { type: 'string' } },
  },
};

const renderBrainCapturePalette = async () => {
  getPaletteManifest.mockResolvedValue({ nav: [], actions: [BRAIN_CAPTURE] });
  render(
    <MemoryRouter>
      <CmdKSearch />
    </MemoryRouter>,
  );
  fireEvent.keyDown(document, { key: 'k', metaKey: true });
  return screen.findByRole('dialog', { name: 'Command palette' });
};

describe('CmdKSearch inline Brain capture', () => {
  it('enters capture mode by mouse with a focused dedicated input', async () => {
    await renderBrainCapturePalette();

    fireEvent.click(await screen.findByRole('option', { name: /Capture to Brain/ }));

    const input = screen.getByRole('textbox', { name: 'Capture to Brain' });
    expect(input).toHaveFocus();
    expect(input).toHaveAttribute('placeholder', 'Thought or URL…');
    expect(input).not.toHaveAttribute('aria-activedescendant');
    expect(screen.queryByRole('listbox')).not.toBeInTheDocument();
    expect(toast).not.toHaveBeenCalled();
  });

  it('does not submit while Enter is committing an IME composition', async () => {
    await renderBrainCapturePalette();
    fireEvent.click(await screen.findByRole('option', { name: /Capture to Brain/ }));
    const input = screen.getByRole('textbox', { name: 'Capture to Brain' });
    fireEvent.change(input, { target: { value: '候補' } });

    fireEvent.keyDown(input, { key: 'Enter', isComposing: true, keyCode: 229 });

    expect(runPaletteAction).not.toHaveBeenCalled();
    expect(input).toHaveValue('候補');
  });

  it('enters capture mode from the keyboard', async () => {
    await renderBrainCapturePalette();
    const input = screen.getByRole('combobox', { name: 'Command palette' });

    fireEvent.keyDown(input, { key: 'Enter' });

    expect(screen.getByRole('textbox', { name: 'Capture to Brain' })).toHaveFocus();
  });

  it('blocks blank drafts and submits trimmed text before closing on success', async () => {
    runPaletteAction.mockResolvedValue({ ok: true, result: { summary: 'Thought captured.' } });
    await renderBrainCapturePalette();
    fireEvent.click(await screen.findByRole('option', { name: /Capture to Brain/ }));
    const input = screen.getByRole('textbox', { name: 'Capture to Brain' });

    fireEvent.change(input, { target: { value: '   ' } });
    fireEvent.keyDown(input, { key: 'Enter' });
    fireEvent.click(screen.getByRole('button', { name: 'Capture thought' }));
    expect(runPaletteAction).not.toHaveBeenCalled();

    fireEvent.change(input, { target: { value: '  Remember this idea  ' } });
    fireEvent.keyDown(input, { key: 'Enter' });

    await waitFor(() => expect(runPaletteAction).toHaveBeenCalledWith('brain_capture', { text: 'Remember this idea' }));
    expect(runPaletteAction).toHaveBeenCalledTimes(1);
    expect(toast.success).toHaveBeenCalledWith('Thought captured.');
    await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument());

    fireEvent.keyDown(document, { key: 'k', metaKey: true });
    fireEvent.click(await screen.findByRole('option', { name: /Capture to Brain/ }));
    expect(screen.getByRole('textbox', { name: 'Capture to Brain' })).toHaveValue('');
  });

  it('prevents duplicate submissions while capture is pending', async () => {
    let resolveCapture;
    runPaletteAction.mockImplementation(() => new Promise((resolve) => { resolveCapture = resolve; }));
    await renderBrainCapturePalette();
    fireEvent.click(await screen.findByRole('option', { name: /Capture to Brain/ }));
    const input = screen.getByRole('textbox', { name: 'Capture to Brain' });
    fireEvent.change(input, { target: { value: 'One thought' } });

    fireEvent.keyDown(input, { key: 'Enter' });
    fireEvent.keyDown(input, { key: 'Enter' });
    fireEvent.click(screen.getByRole('button', { name: 'Capture thought' }));

    expect(runPaletteAction).toHaveBeenCalledTimes(1);
    await act(async () => { resolveCapture({ ok: true, result: { summary: 'Captured.' } }); });
  });

  it('keeps focus inside the dialog during a pending mouse submission', async () => {
    let resolveCapture;
    runPaletteAction.mockImplementation(() => new Promise((resolve) => { resolveCapture = resolve; }));
    await renderBrainCapturePalette();
    fireEvent.click(await screen.findByRole('option', { name: /Capture to Brain/ }));
    const input = screen.getByRole('textbox', { name: 'Capture to Brain' });
    fireEvent.change(input, { target: { value: 'Mouse thought' } });
    const button = screen.getByRole('button', { name: 'Capture thought' });
    button.focus();

    fireEvent.click(button);

    expect(input).toHaveFocus();
    expect(input).toHaveAttribute('readonly');
    await act(async () => { resolveCapture({ ok: true, result: { summary: 'Captured.' } }); });
  });

  it('keeps the full draft open after a failed request without a second error toast', async () => {
    runPaletteAction.mockRejectedValue(new Error('Capture failed'));
    await renderBrainCapturePalette();
    fireEvent.click(await screen.findByRole('option', { name: /Capture to Brain/ }));
    const input = screen.getByRole('textbox', { name: 'Capture to Brain' });
    fireEvent.change(input, { target: { value: '  Keep my spacing  ' } });

    fireEvent.keyDown(input, { key: 'Enter' });

    await waitFor(() => expect(runPaletteAction).toHaveBeenCalledTimes(1));
    expect(screen.getByRole('dialog', { name: 'Command palette' })).toBeInTheDocument();
    expect(input).toHaveValue('  Keep my spacing  ');
    expect(input).toHaveFocus();
    expect(toast.error).not.toHaveBeenCalled();
  });

  it('uses Escape to return to the prior query before closing the palette', async () => {
    await renderBrainCapturePalette();
    const searchInput = screen.getByRole('combobox', { name: 'Command palette' });
    fireEvent.change(searchInput, { target: { value: 'capture' } });
    fireEvent.keyDown(searchInput, { key: 'Enter' });
    const captureInput = screen.getByRole('textbox', { name: 'Capture to Brain' });
    fireEvent.change(captureInput, { target: { value: 'Draft thought' } });
    const leakedEscape = vi.fn();
    window.addEventListener('keydown', leakedEscape);

    fireEvent.keyDown(captureInput, { key: 'Escape' });
    window.removeEventListener('keydown', leakedEscape);

    expect(screen.getByRole('dialog', { name: 'Command palette' })).toBeInTheDocument();
    const restoredSearch = screen.getByRole('combobox', { name: 'Command palette' });
    expect(restoredSearch).toHaveValue('capture');
    expect(restoredSearch).toHaveFocus();
    expect(leakedEscape).not.toHaveBeenCalled();

    fireEvent.keyDown(restoredSearch, { key: 'Escape' });
    await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument());
  });

  it('ignores a pending capture result after Escape returns to search', async () => {
    let resolveCapture;
    runPaletteAction.mockImplementation(() => new Promise((resolve) => { resolveCapture = resolve; }));
    await renderBrainCapturePalette();
    fireEvent.click(await screen.findByRole('option', { name: /Capture to Brain/ }));
    const captureInput = screen.getByRole('textbox', { name: 'Capture to Brain' });
    fireEvent.change(captureInput, { target: { value: 'Pending thought' } });
    fireEvent.keyDown(captureInput, { key: 'Enter' });

    fireEvent.keyDown(captureInput, { key: 'Escape' });
    const searchInput = screen.getByRole('combobox', { name: 'Command palette' });
    fireEvent.change(searchInput, { target: { value: 'keep searching' } });
    await act(async () => { resolveCapture({ ok: true, result: { summary: 'Captured.' } }); });

    expect(screen.getByRole('dialog', { name: 'Command palette' })).toBeInTheDocument();
    expect(searchInput).toHaveValue('keep searching');
    expect(toast.success).not.toHaveBeenCalled();
  });

  it('resets capture state when dismissed through the backdrop', async () => {
    const dialog = await renderBrainCapturePalette();
    fireEvent.click(await screen.findByRole('option', { name: /Capture to Brain/ }));
    fireEvent.change(screen.getByRole('textbox', { name: 'Capture to Brain' }), { target: { value: 'Discard me' } });

    fireEvent.click(dialog.parentElement.querySelector('[aria-hidden="true"]'));
    await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument());

    fireEvent.keyDown(document, { key: 'k', metaKey: true });
    expect(await screen.findByRole('combobox', { name: 'Command palette' })).toHaveValue('');
    fireEvent.click(await screen.findByRole('option', { name: /Capture to Brain/ }));
    expect(screen.getByRole('textbox', { name: 'Capture to Brain' })).toHaveValue('');
  });
});

describe('CmdKSearch action dispatch', () => {
  const TIME_NOW = { id: 'time_now', label: 'What time is it', section: 'Tools', description: '', aliases: [], keywords: [], parameters: { type: 'object', required: [], properties: {} } };

  const renderActionPalette = async () => {
    getPaletteManifest.mockResolvedValue({ nav: [], actions: [TIME_NOW] });
    render(
      <MemoryRouter>
        <CmdKSearch />
      </MemoryRouter>,
    );
    fireEvent.keyDown(document, { key: 'k', metaKey: true });
    await screen.findByRole('dialog', { name: 'Command palette' });
    const input = screen.getByRole('combobox', { name: 'Command palette' });
    fireEvent.change(input, { target: { value: 'time' } });
    await screen.findByRole('option', { name: /What time is it/ });
    return input;
  };

  it('keeps the palette open with the query intact when an action request rejects', async () => {
    // request() toasts the failure centrally, so the component raises no
    // second toast and the rejection must not escape as unhandled.
    runPaletteAction.mockRejectedValue(new Error('boom'));
    const input = await renderActionPalette();
    fireEvent.keyDown(input, { key: 'Enter' });
    await waitFor(() => expect(runPaletteAction).toHaveBeenCalledWith('time_now'));
    await act(async () => {});
    expect(screen.getByRole('dialog', { name: 'Command palette' })).toBeInTheDocument();
    expect(input).toHaveValue('time');
    expect(input).toHaveFocus();
    expect(toast.error).not.toHaveBeenCalled();
    expect(toast.success).not.toHaveBeenCalled();
  });

  it('toasts the summary and closes when an action resolves', async () => {
    runPaletteAction.mockResolvedValue({ ok: true, result: { summary: 'It is noon.' } });
    const input = await renderActionPalette();
    fireEvent.keyDown(input, { key: 'Enter' });
    await waitFor(() => expect(toast.success).toHaveBeenCalledWith('It is noon.'));
    await waitFor(() => expect(screen.queryByRole('dialog', { name: 'Command palette' })).toBeNull());
  });
});

describe('CmdKSearch dialog accessibility', () => {
  it('keeps the active option stable through filtering and executes the indicated destination', async () => {
    render(
      <MemoryRouter initialEntries={['/current']}>
        <CmdKSearch />
        <LocationProbe />
      </MemoryRouter>,
    );
    fireEvent.keyDown(document, { key: 'k', metaKey: true });
    const input = await screen.findByRole('combobox', { name: 'Command palette' });
    const listbox = screen.getByRole('listbox', { name: 'Command palette results' });
    await screen.findByRole('option', { name: /Brain Inbox/ });
    expect(input).toHaveAttribute('aria-controls', listbox.id);
    expect(input).toHaveAttribute('aria-expanded', 'true');
    const options = within(listbox).getAllByRole('option');
    expect(new Set(options.map((option) => option.id)).size).toBe(options.length);
    expect(options.every((option) => option.id)).toBe(true);
    expect(input).toHaveAttribute('aria-activedescendant', options[0].id);
    fireEvent.keyDown(input, { key: 'ArrowDown' });
    expect(input).toHaveAttribute('aria-activedescendant', options[1].id);
    expect(options[1]).toHaveAttribute('aria-selected', 'true');
    expect(input).toHaveFocus();
    fireEvent.keyDown(input, { key: 'ArrowUp' });
    expect(input).toHaveAttribute('aria-activedescendant', options[0].id);

    const brainId = screen.getByRole('option', { name: /Brain Inbox/ }).id;
    fireEvent.change(input, { target: { value: 'brain' } });
    expect(input).toHaveAttribute('aria-activedescendant', brainId);
    fireEvent.change(input, { target: { value: 'zzzzzz' } });
    expect(input).not.toHaveAttribute('aria-activedescendant');
    fireEvent.change(input, { target: { value: 'brain' } });
    expect(input).toHaveAttribute('aria-activedescendant', brainId);
    fireEvent.keyDown(input, { key: 'Enter' });
    expect(screen.getByTestId('location')).toHaveTextContent('/brain/inbox');
  });

  it('clears hidden search selections during loading and owns expanded results without owning buttons', async () => {
    const source = (title) => ({
      id: 'brain', label: 'Brain', icon: 'Brain',
      results: Array.from({ length: 4 }, (_, i) => ({ id: String(i), title: title + i, url: '/brain/' + title })),
    });
    search.mockResolvedValueOnce({ sources: [source('First')] })
      .mockResolvedValueOnce({ sources: [source('Next')] });
    render(<MemoryRouter><CmdKSearch /></MemoryRouter>);
    await act(async () => { fireEvent.keyDown(document, { key: 'k', metaKey: true }); });
    const input = screen.getByRole('combobox');
    fireEvent.change(input, { target: { value: 'zz' } });
    const first = await screen.findByRole('option', { name: 'First0' });
    expect(input).toHaveAttribute('aria-activedescendant', first.id);
    const listbox = screen.getByRole('listbox');
    expect(within(listbox).queryByRole('button')).not.toBeInTheDocument();
    const user = userEvent.setup();
    screen.getByRole('button', { name: 'Show 1 more from Brain' }).focus();
    await user.keyboard('[Enter]');
    expect(input).toHaveFocus();
    const expanded = within(listbox).getAllByRole('option');
    expect(expanded).toHaveLength(4);
    expect(new Set(expanded.map((option) => option.id)).size).toBe(4);
    expect(screen.getByRole('option', { name: 'First0' }).id).toBe(first.id);
    fireEvent.change(input, { target: { value: 'yy' } });
    expect(input).not.toHaveAttribute('aria-activedescendant');
    expect(screen.queryByRole('option')).not.toBeInTheDocument();
    const next = await screen.findByRole('option', { name: 'Next0' });
    expect(input).toHaveAttribute('aria-activedescendant', next.id);
    expect(document.getElementById(first.id)).toBeNull();
    expect(input).toHaveFocus();
  });

  it('traps focus inside the modal and restores it to the opener on close', async () => {
    render(
      <MemoryRouter>
        <button type="button">Open palette shortcut</button>
        <CmdKSearch />
      </MemoryRouter>,
    );

    const opener = screen.getByRole('button', { name: 'Open palette shortcut' });
    opener.focus();
    fireEvent.keyDown(document, { key: 'k', metaKey: true });

    const dialog = await screen.findByRole('dialog', { name: 'Command palette' });
    expect(dialog).toHaveAttribute('aria-modal', 'true');

    const input = within(dialog).getByRole('combobox', { name: 'Command palette' });
    expect(input).toHaveFocus();

    fireEvent.keyDown(input, { key: 'Tab' });
    expect(input).toHaveFocus();
    fireEvent.keyDown(input, { key: 'Tab', shiftKey: true });
    expect(input).toHaveFocus();

    fireEvent.keyDown(input, { key: 'Escape' });
    await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument());
    expect(opener).toHaveFocus();
  });

  it('closes only the palette on the first Escape when opened over a Drawer', async () => {
    const user = userEvent.setup();
    const Harness = () => {
      const [open, setOpen] = useState(true);
      return (
        <MemoryRouter>
          <Drawer open={open} onClose={() => setOpen(false)} title="Settings">
            <button type="button">Drawer control</button>
          </Drawer>
          <CmdKSearch />
        </MemoryRouter>
      );
    };
    render(<Harness />);
    const control = screen.getByRole('button', { name: 'Drawer control' });
    control.focus();
    await user.keyboard('{Meta>}k{/Meta}');
    await screen.findByRole('dialog', { name: 'Command palette' });

    await user.keyboard('{Escape}');
    await waitFor(() => expect(screen.queryByRole('dialog', { name: 'Command palette' })).not.toBeInTheDocument());
    expect(screen.getByRole('dialog', { name: 'Settings' })).toBeInTheDocument();
    expect(control).toHaveFocus();

    await user.keyboard('{Escape}');
    await waitFor(() => expect(screen.queryByRole('dialog', { name: 'Settings' })).not.toBeInTheDocument());
  });

  it('opens when the shared command-palette event is dispatched', async () => {
    render(
      <MemoryRouter>
        <CmdKSearch />
      </MemoryRouter>,
    );

    act(() => document.dispatchEvent(new Event(CMD_K_SEARCH_OPEN_EVENT)));

    expect(await screen.findByRole('dialog', { name: 'Command palette' })).toBeInTheDocument();
  });
});

describe('CmdKSearch recent destinations', () => {
  it('leads with shared nav history, resolves deep links, and fills with non-duplicate defaults', async () => {
    localStorage.setItem(RECENT_KEY, JSON.stringify([
      '/current',
      '/apps/example-app',
      '/brain/inbox',
      '/stale-route',
    ]));

    render(
      <MemoryRouter initialEntries={['/current']}>
        <CmdKSearch />
        <LocationProbe />
      </MemoryRouter>,
    );

    fireEvent.keyDown(document, { key: 'k', metaKey: true });
    await screen.findByText('Recent destinations');
    await act(async () => {});

    const options = screen.getAllByRole('option');
    expect(within(options[0]).getByText('Apps')).toBeInTheDocument();
    expect(within(options[0]).getByText(/\/apps\/example-app/)).toBeInTheDocument();
    expect(within(options[1]).getByText('Brain Inbox')).toBeInTheDocument();
    expect(screen.getAllByText('Brain Inbox')).toHaveLength(1);
    expect(screen.queryByText('Current Page')).not.toBeInTheDocument();
    expect(screen.getByText('Dashboard')).toBeInTheDocument();

    fireEvent.click(options[0]);
    await waitFor(() => expect(screen.getByTestId('location')).toHaveTextContent('/apps/example-app'));
  });
});

// The manifest ships gated entries tagged rather than filtered, so the palette
// has to apply the gate itself — filtering server-side would leave ⌘K offering
// hidden pages until a reload, because it fetches the manifest once per session.
describe('CmdKSearch instance feature gating', () => {
  const openAndSearch = async (query) => {
    render(
      <MemoryRouter initialEntries={['/current']}>
        <CmdKSearch />
        <LocationProbe />
      </MemoryRouter>,
    );
    fireEvent.keyDown(document, { key: 'k', metaKey: true });
    const input = await screen.findByRole('combobox', { name: 'Command palette' });
    fireEvent.change(input, { target: { value: query } });
    await act(async () => {});
  };

  it('offers a gated page while its feature is on', async () => {
    await openAndSearch('jira');
    expect(screen.getByText('JIRA')).toBeInTheDocument();
  });

  it('hides a gated page when its feature is off', async () => {
    getInstanceFeatures.mockResolvedValue({ features: FEATURES_OFF });

    await openAndSearch('jira');
    expect(screen.queryByText('JIRA')).not.toBeInTheDocument();
  });

  it('shows gated pages when the feature list cannot be read', async () => {
    getInstanceFeatures.mockRejectedValue(new Error('offline'));

    await openAndSearch('jira');
    expect(screen.getByText('JIRA')).toBeInTheDocument();
  });
});

describe('CmdKSearch global search staleness', () => {
  it('does not let a slow older-query response overwrite the newer query results', async () => {
    vi.useFakeTimers();

    // First (stale) query resolves late; second (current) query resolves fast.
    let resolveStale;
    const stalePromise = new Promise((res) => { resolveStale = res; });
    search
      .mockImplementationOnce(() => stalePromise)
      .mockImplementationOnce(() => Promise.resolve({
        sources: [{ id: 'brain', label: 'Brain', icon: 'Brain', results: [{ title: 'Fresh result', snippet: 'new', url: '/brain/x' }] }],
      }));

    render(
      <MemoryRouter initialEntries={['/current']}>
        <CmdKSearch />
      </MemoryRouter>,
    );

    await act(async () => {
      fireEvent.keyDown(document, { key: 'k', metaKey: true });
    });

    const input = screen.getByPlaceholderText(/Go to page/);

    // Type first query and let its debounce elapse so the stale request fires.
    await act(async () => { fireEvent.change(input, { target: { value: 'aa' } }); });
    await act(async () => { await vi.advanceTimersByTimeAsync(300); });
    expect(search).toHaveBeenNthCalledWith(1, 'aa');

    // Type second query; its cleanup marks the first effect cancelled.
    await act(async () => { fireEvent.change(input, { target: { value: 'bb' } }); });
    await act(async () => { await vi.advanceTimersByTimeAsync(300); });
    expect(search).toHaveBeenNthCalledWith(2, 'bb');

    // Now the stale response finally arrives — it must be ignored.
    await act(async () => {
      resolveStale({ sources: [{ id: 'brain', label: 'Brain', icon: 'Brain', results: [{ title: 'Stale result', snippet: 'old', url: '/brain/y' }] }] });
      await Promise.resolve();
    });

    expect(screen.getByText('Fresh result')).toBeInTheDocument();
    expect(screen.queryByText('Stale result')).not.toBeInTheDocument();

    vi.useRealTimers();
  });
});

describe('CmdKSearch catalog lookup failure', () => {
  it('says catalog matches may be missing instead of a bare "No results", and clears on the next query', async () => {
    vi.useFakeTimers();
    listCatalogIngredients.mockRejectedValueOnce(new Error('catalog down'));
    render(
      <MemoryRouter initialEntries={['/current']}>
        <CmdKSearch />
      </MemoryRouter>,
    );
    await act(async () => { fireEvent.keyDown(document, { key: 'k', metaKey: true }); });
    const input = screen.getByPlaceholderText(/Go to page/);

    await act(async () => { fireEvent.change(input, { target: { value: 'zzzz' } }); });
    await act(async () => { await vi.advanceTimersByTimeAsync(300); });
    expect(screen.getByRole('alert')).toHaveTextContent(/catalog search failed/i);

    await act(async () => { fireEvent.change(input, { target: { value: 'zzzzy' } }); });
    expect(screen.queryByRole('alert')).not.toBeInTheDocument();
    await act(async () => { await vi.advanceTimersByTimeAsync(300); });
    expect(screen.queryByRole('alert')).not.toBeInTheDocument();
    expect(screen.getByText(/No results for/)).toBeInTheDocument();

    vi.useRealTimers();
  });
});

describe('CmdKSearch knowledge search failure', () => {
  it('shows a failure row instead of stale results when search() rejects, and clears on the next query', async () => {
    vi.useFakeTimers();
    search
      .mockResolvedValueOnce({ sources: [{ id: 'brain', label: 'Brain', icon: 'brain', results: [{ id: 'r1', title: 'Stale result', url: '/brain/r1' }] }] })
      .mockRejectedValueOnce(new Error('search down'))
      .mockResolvedValueOnce({ sources: [] });
    render(
      <MemoryRouter initialEntries={['/current']}>
        <CmdKSearch />
      </MemoryRouter>,
    );
    await act(async () => { fireEvent.keyDown(document, { key: 'k', metaKey: true }); });
    const input = screen.getByPlaceholderText(/Go to page/);

    await act(async () => { fireEvent.change(input, { target: { value: 'aaaa' } }); });
    await act(async () => { await vi.advanceTimersByTimeAsync(300); });
    expect(screen.getByText('Stale result')).toBeInTheDocument();

    await act(async () => { fireEvent.change(input, { target: { value: 'bbbb' } }); });
    await act(async () => { await vi.advanceTimersByTimeAsync(300); });
    expect(screen.getByRole('alert')).toHaveTextContent(/search failed/i);
    expect(screen.queryByText('Stale result')).not.toBeInTheDocument();

    await act(async () => { fireEvent.change(input, { target: { value: 'cccc' } }); });
    expect(screen.queryByRole('alert')).not.toBeInTheDocument();

    vi.useRealTimers();
  });
});