Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

14.5 KB
Raw Blame
import type { ConfigBinding, OkignoreBinding } from '@inkeep/open-knowledge-core';
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { createServedBindingLog } from '@/test-utils/served-binding.test-helper';

type WindowGlobals = { MutationObserver?: typeof MutationObserver; NodeFilter?: typeof NodeFilter };
type GlobalWithDomShims = typeof globalThis &
  WindowGlobals & { window?: WindowGlobals; ResizeObserver?: unknown };
const globalWithDomShims = globalThis as GlobalWithDomShims;
if (
  globalWithDomShims.MutationObserver === undefined &&
  globalWithDomShims.window?.MutationObserver !== undefined
) {
  globalWithDomShims.MutationObserver = globalWithDomShims.window.MutationObserver;
}
if (
  globalWithDomShims.NodeFilter === undefined &&
  globalWithDomShims.window?.NodeFilter !== undefined
) {
  globalWithDomShims.NodeFilter = globalWithDomShims.window.NodeFilter;
}
if (globalWithDomShims.ResizeObserver === undefined) {
  class NoopResizeObserver {
    observe() {}
    unobserve() {}
    disconnect() {}
  }
  globalWithDomShims.ResizeObserver = NoopResizeObserver;
}
if (typeof HTMLElement.prototype.scrollIntoView !== 'function') {
  HTMLElement.prototype.scrollIntoView = () => {};
}

interface BodyProps {
  activeId: string;
  userBinding: ConfigBinding | null;
  okignoreBinding: OkignoreBinding | null;
  okignoreSynced: boolean;
  markdownlintRuleQuery?: { query: string; nonce: number } | null;
}
const probeProps: BodyProps[] = [];

let mockCollabUrl: string | null = 'ws://test.invalid';
let mockProjectConfig: unknown = { contentRules: { markdownlint: { enabled: true } } };

const FAKE_RULE_CATALOG = [
  {
    id: 'MD013',
    alias: 'line-length',
    aliases: ['line-length'],
    name: 'Line length',
    docUrl: '',
    tags: [],
    options: [],
  },
  {
    id: 'MD001',
    alias: 'heading-increment',
    aliases: ['heading-increment'],
    name: 'Heading levels increment',
    docUrl: '',
    tags: [],
    options: [],
  },
];

const SEMANTIC_STATUS_RESPONSE = {
  enabled: true,
  keyPresent: false,
  keyNotRequired: true,
  keySource: null,
  keyHint: null,
  ready: false,
  capable: false,
  embedded: 0,
  total: 0,
};

const servedCore = createServedBindingLog();

vi.doMock('@inkeep/open-knowledge-core/markdown/lint', async () =>
  servedCore.serve('@inkeep/open-knowledge-core/markdown/lint', {
    ...(await vi.importActual<typeof import('@inkeep/open-knowledge-core/markdown/lint')>(
      '@inkeep/open-knowledge-core/markdown/lint',
    )),
    MARKDOWNLINT_RULE_CATALOG: FAKE_RULE_CATALOG,
  }),
);

vi.doMock('@/components/settings/SettingsDialogBodyLazy', () => ({
  SettingsDialogBodyLazy: (props: BodyProps) => {
    probeProps.push(props);
    return (
      <div data-testid="settings-body-probe">
        {props.activeId === 'preferences' ? <div data-field="editor.wordWrap" /> : null}
        {props.activeId === 'search' ? <SearchSection /> : null}
      </div>
    );
  },
}));

vi.doMock('@/editor/DocumentContext', () => ({
  useDocumentContext: () => ({ collabUrl: mockCollabUrl }),
  DocumentProvider: ({ children }: { children: React.ReactNode }) => children,
}));

vi.doMock('@/lib/config-provider', () => ({
  useConfigContext: () => ({
    userBinding: null,
    userSynced: true,
    projectBinding: null,
    projectLocalBinding: null,
    okignoreBinding: null,
    okignoreSynced: false,
    userConfig: null,
    projectConfig: mockProjectConfig,
    projectLocalConfig: null,
    projectLocalSynced: false,
    merged: null,
  }),
}));

vi.doMock('@/lib/handoff/use-claude-desktop-integration', () => ({
  useClaudeDesktopIntegration: () => ({
    desktopPresent: false,
    skillInstalled: false,
    refresh: () => {},
  }),
}));

const { SettingsDialogShell } = await import('./SettingsDialogShell');
const { SearchSection } = await import('./SearchSection');

function latestProbe(): BodyProps | undefined {
  return probeProps[probeProps.length - 1];
}

describe('settings dialog search', () => {
  let consoleErrorSpy: ReturnType<typeof vi.spyOn>;

  beforeEach(() => {
    probeProps.length = 0;
    mockCollabUrl = 'ws://test.invalid';
    mockProjectConfig = { contentRules: { markdownlint: { enabled: true } } };
    consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
  });

  afterEach(() => {
    cleanup();
    consoleErrorSpy.mockRestore();
    vi.useRealTimers();
  });

  test('empty query shows the plain group nav, no results list', () => {
    render(<SettingsDialogShell open={true} onOpenChange={() => {}} />);
    expect(screen.getByTestId('settings-sidebar-item-preferences')).toBeDefined();
    expect(screen.queryByTestId('settings-search-results')).toBeNull();
  });

  test('typing a section name filters to a result that navigates on click', async () => {
    const user = userEvent.setup();
    render(<SettingsDialogShell open={true} onOpenChange={() => {}} />);

    await user.type(screen.getByTestId('settings-search-input'), 'Sync');
    const result = await screen.findByTestId('settings-search-result-section:sync');
    expect(screen.queryByTestId('settings-sidebar-item-preferences')).toBeNull();

    await user.click(result);
    expect(latestProbe()?.activeId).toBe('sync');
    expect(screen.getByTestId('settings-sidebar-item-preferences')).toBeDefined();
  });

  test('the merged Agents page is findable under both of its former names', async () => {
    const user = userEvent.setup();
    render(<SettingsDialogShell open={true} onOpenChange={() => {}} />);
    const input = screen.getByTestId('settings-search-input');

    for (const query of ['AI tools', 'Configure agents', 'connections']) {
      await user.clear(input);
      await user.type(input, query);
      expect(
        await screen.findByTestId('settings-search-result-section:agent-connections'),
      ).toBeTruthy();
      expect(screen.queryByTestId('settings-search-result-section:configure-agents')).toBeNull();
    }
  });

  test('the GitHub account block is findable by the GitHub CLI names', async () => {
    const user = userEvent.setup();
    render(<SettingsDialogShell open={true} onOpenChange={() => {}} />);
    const input = screen.getByTestId('settings-search-input');

    for (const query of ['GitHub CLI', 'gh']) {
      await user.clear(input);
      await user.type(input, query);
      expect(
        await screen.findByTestId('settings-search-result-subsection:account:github-account'),
      ).toBeTruthy();
    }

    await user.click(
      screen.getByTestId('settings-search-result-subsection:account:github-account'),
    );
    expect(latestProbe()?.activeId).toBe('account');
  });

  describe('in the desktop app', () => {
    beforeEach(() => {
      (window as unknown as { okDesktop?: unknown }).okDesktop = {
        platform: 'linux',
        appVersion: '0.81.5-cloud.1343',
        config: { ptyAvailable: false },
      };
    });

    afterEach(() => {
      (window as unknown as { okDesktop?: unknown }).okDesktop = undefined;
    });

    test('About & updates is findable as "update" and as "about"', async () => {
      const user = userEvent.setup();
      render(<SettingsDialogShell open={true} onOpenChange={() => {}} />);
      const input = screen.getByTestId('settings-search-input');

      for (const query of ['update', 'about', 'version', 'release notes']) {
        await user.clear(input);
        await user.type(input, query);
        expect(await screen.findByTestId('settings-search-result-section:about')).toBeTruthy();
      }

      await user.click(screen.getByTestId('settings-search-result-section:about'));
      expect(latestProbe()?.activeId).toBe('about');
    });

    test('About & updates is the last sidebar entry, under App', () => {
      render(<SettingsDialogShell open={true} onOpenChange={() => {}} />);

      const items = screen.getAllByTestId(/^settings-sidebar-item-/);
      expect(items.at(-1)?.getAttribute('data-testid')).toBe('settings-sidebar-item-about');
      expect(screen.getByRole('heading', { name: 'App' })).toBeTruthy();
    });

    test('the sidebar version label opens About & updates in place', async () => {
      const user = userEvent.setup();
      render(<SettingsDialogShell open={true} onOpenChange={() => {}} />);

      await user.click(screen.getByRole('button', { name: 'v0.81.5-cloud.1343 About & updates' }));

      expect(latestProbe()?.activeId).toBe('about');
    });
  });

  test('the web host has no About & updates section', async () => {
    const user = userEvent.setup();
    render(<SettingsDialogShell open={true} onOpenChange={() => {}} />);

    await user.type(screen.getByTestId('settings-search-input'), 'update');
    await waitFor(() => {
      expect(screen.getByTestId('settings-search-empty')).toBeDefined();
    });
    expect(screen.queryByTestId('settings-search-result-section:about')).toBeNull();
  });

  test('a markdownlint rule is searchable when the plugin is enabled', async () => {
    const user = userEvent.setup();
    render(<SettingsDialogShell open={true} onOpenChange={() => {}} />);

    await user.type(screen.getByTestId('settings-search-input'), 'MD013');
    const result = await screen.findByTestId('settings-search-result-rule:MD013');

    await user.click(result);
    expect(latestProbe()?.activeId).toBe('plugin:markdownlint');
    expect(latestProbe()?.markdownlintRuleQuery?.query).toBe('MD013');
  });

  test('markdownlint rules are NOT indexed when the plugin is disabled', async () => {
    mockProjectConfig = { contentRules: { markdownlint: { enabled: false } } };
    const user = userEvent.setup();
    render(<SettingsDialogShell open={true} onOpenChange={() => {}} />);

    await user.type(screen.getByTestId('settings-search-input'), 'MD013');
    await waitFor(() => {
      expect(screen.getByTestId('settings-search-empty')).toBeDefined();
    });
    expect(screen.queryByTestId('settings-search-result-rule:MD013')).toBeNull();
  });

  test('rule search results come from the catalog the lint replacement serves', async () => {
    const user = userEvent.setup();
    const since = servedCore.mark();
    render(<SettingsDialogShell open={true} onOpenChange={() => {}} />);
    const input = screen.getByTestId('settings-search-input');

    await user.type(input, 'MD001');
    expect(await screen.findByTestId('settings-search-result-rule:MD001')).toBeTruthy();

    await user.clear(input);
    await user.type(input, 'MD009');
    await waitFor(() => {
      expect(screen.getByTestId('settings-search-empty')).toBeDefined();
    });
    expect(screen.queryByTestId('settings-search-result-rule:MD009')).toBeNull();
    expect(
      servedCore.readersOf(
        '@inkeep/open-knowledge-core/markdown/lint',
        'MARKDOWNLINT_RULE_CATALOG',
        since,
      ),
    ).toEqual(['components/settings/settings-search-index.ts']);
  });

  test('a no-match query renders the empty state', async () => {
    const user = userEvent.setup();
    render(<SettingsDialogShell open={true} onOpenChange={() => {}} />);

    await user.type(screen.getByTestId('settings-search-input'), 'zzzznomatch');
    await waitFor(() => {
      expect(screen.getByTestId('settings-search-empty')).toBeDefined();
    });
    expect(screen.getByTestId('settings-search-result-count').textContent).toContain('0');
  });

  test('navigating to a field flashes and scrolls its [data-field] node', async () => {
    const scrollSpy = vi
      .spyOn(HTMLElement.prototype, 'scrollIntoView')
      .mockImplementation(() => {});
    const user = userEvent.setup();
    render(<SettingsDialogShell open={true} onOpenChange={() => {}} />);

    await user.type(screen.getByTestId('settings-search-input'), 'Word wrap');
    const result = await screen.findByTestId(
      'settings-search-result-field:preferences:editor.wordWrap',
    );
    await user.click(result);

    expect(latestProbe()?.activeId).toBe('preferences');
    await waitFor(() => {
      const field = document.querySelector('[data-field="editor.wordWrap"]');
      expect(field?.classList.contains('animate-settings-nav-flash')).toBe(true);
    });
    expect(scrollSpy).toHaveBeenCalled();
    scrollSpy.mockRestore();
  });

  test('search reveals the tuning fields and reopens them after an explicit collapse', async () => {
    const user = userEvent.setup();
    const fetchSpy = vi
      .spyOn(globalThis, 'fetch')
      .mockResolvedValue(new Response(JSON.stringify(SEMANTIC_STATUS_RESPONSE)));
    const scrollSpy = vi
      .spyOn(HTMLElement.prototype, 'scrollIntoView')
      .mockImplementation(() => {});
    render(<SettingsDialogShell open={true} onOpenChange={() => {}} />);

    for (const query of ['timeout', 'Ollama']) {
      await user.type(screen.getByTestId('settings-search-input'), query);
      await user.click(
        await screen.findByTestId('settings-search-result-subsection:search:performance'),
      );

      expect(await screen.findByTestId('settings-search-max-batch-size')).toBeTruthy();
      expect(screen.getByTestId('settings-search-max-batch-chars')).toBeTruthy();
      expect(screen.getByTestId('settings-search-doc-timeout-seconds')).toBeTruthy();
      expect(
        screen
          .getByTestId('settings-search-performance')
          .classList.contains('animate-settings-nav-flash'),
      ).toBe(true);
      expect(scrollSpy).toHaveBeenCalled();
      await user.click(screen.getByTestId('settings-search-performance-trigger'));
      await waitFor(() =>
        expect(screen.queryByTestId('settings-search-max-batch-size')).toBeNull(),
      );
    }

    scrollSpy.mockRestore();
    fetchSpy.mockRestore();
  });

  test('successful disclosure navigation retires its give-up timer and clears the flash', async () => {
    const user = userEvent.setup();
    const fetchSpy = vi
      .spyOn(globalThis, 'fetch')
      .mockResolvedValue(new Response(JSON.stringify(SEMANTIC_STATUS_RESPONSE)));
    render(<SettingsDialogShell open={true} onOpenChange={() => {}} />);
    await user.type(screen.getByTestId('settings-search-input'), 'timeout');
    vi.useFakeTimers();
    fireEvent.click(screen.getByTestId('settings-search-result-subsection:search:performance'));
    await act(async () => {});
    const disclosure = screen.getByTestId('settings-search-performance');

    expect(screen.getByTestId('settings-search-max-batch-size')).toBeTruthy();
    expect(disclosure.classList.contains('animate-settings-nav-flash')).toBe(true);
    await act(() => vi.advanceTimersByTimeAsync(750));
    expect(disclosure.classList.contains('animate-settings-nav-flash')).toBe(false);
    expect(vi.getTimerCount()).toBe(0);
    fetchSpy.mockRestore();
  });
});