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

6.7 KB
Raw Blame
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { fireEvent, render, screen } from '@testing-library/react';

vi.mock('../../../services/api', () => ({
  applyProcessAction: vi.fn(),
  getProcessesList: vi.fn(),
}));

vi.mock('../../../hooks/useProcessSnapshot', () => ({
  useProcessSnapshot: () => ({
    data: [{ name: 'example-api', status: 'online', pid: 1, cpu: 0, memory: 0, uptime: null, restarts: 0, pm_id: 1 }],
    loading: false,
    refetch: vi.fn(),
  }),
}));

vi.mock('../../../hooks/useProcessLogs', () => ({
  useProcessLogs: vi.fn(() => ({ logs: [], status: 'connecting', retry: vi.fn(), clear: vi.fn() })),
}));

vi.mock('../../../lib/clipboard', () => ({ copyToClipboard: vi.fn() }));
vi.mock('../../BrailleSpinner', () => ({ default: () => null }));
vi.mock('../../ui/FormField', () => ({ FormField: ({ children }) => children }));
vi.mock('../../ui/ProcessLogLines', () => ({ default: () => null, LogStreamBadge: () => null }));
// `formatCount` is deliberately NOT stubbed — a stub that returns the raw
// number would make the "N lines" assertions blind to a grouping regression.
vi.mock('../../../utils/formatters', async (importOriginal) => ({
  ...(await importOriginal()),
  formatBytes: vi.fn(() => '0 B'),
  formatDurationMs: vi.fn(),
  formatTimeOfDaySeconds: vi.fn((timestamp) => `time-${timestamp}`),
}));

import { useProcessLogs } from '../../../hooks/useProcessLogs';
import { copyToClipboard } from '../../../lib/clipboard';
import ProcessesTab from './ProcessesTab';

describe('ProcessesTab', () => {
  beforeEach(() => {
    vi.clearAllMocks();
    useProcessLogs.mockReturnValue({ logs: [], status: 'connecting', retry: vi.fn(), clear: vi.fn() });
  });

  it('passes its app id to the expanded process log subscription', () => {
    render(<ProcessesTab appId="app-1" pm2ProcessNames={['example-api']} />);

    fireEvent.click(screen.getByRole('button', { name: 'Expand details for example-api' }));

    expect(useProcessLogs).toHaveBeenLastCalledWith('example-api', { lines: 500, appId: 'app-1' });
  });

  it('copies the current live log snapshot from both viewers in display order', () => {
    useProcessLogs.mockReturnValue({
      logs: [
        { line: 'boot ok', type: 'stdout', timestamp: 100 },
        { line: 'failed once', type: 'stderr', timestamp: 200 },
      ],
      status: 'live',
      clear: vi.fn(),
    });
    render(<ProcessesTab appId="app-1" pm2ProcessNames={['example-api']} />);

    fireEvent.click(screen.getByRole('button', { name: 'Expand details for example-api' }));
    fireEvent.click(screen.getByRole('button', { name: 'Copy logs' }));

    const expected = '[time-100] [stdout] boot ok\n[time-200] [stderr] failed once';
    expect(copyToClipboard).toHaveBeenLastCalledWith(expected, 'Logs copied');

    fireEvent.click(screen.getByTitle('Fullscreen'));
    const copyButtons = screen.getAllByRole('button', { name: 'Copy logs' });
    fireEvent.click(copyButtons[1]);
    expect(copyToClipboard).toHaveBeenLastCalledWith(expected, 'Logs copied');
    expect(copyToClipboard).toHaveBeenCalledTimes(2);
  });

  it('disables copy actions when the live log snapshot is empty', () => {
    render(<ProcessesTab appId="app-1" pm2ProcessNames={['example-api']} />);

    fireEvent.click(screen.getByRole('button', { name: 'Expand details for example-api' }));
    expect(screen.getByRole('button', { name: 'Copy logs' })).toBeDisabled();

    fireEvent.click(screen.getByTitle('Fullscreen'));
    expect(screen.getAllByRole('button', { name: 'Copy logs' })).toEqual([
      expect.objectContaining({ disabled: true }),
      expect.objectContaining({ disabled: true }),
    ]);
  });

  // On "glass" themes a bordered/rounded `.bg-port-card` gets a backdrop-filter,
  // which makes it the containing block for `position:fixed` descendants — an
  // inline overlay would be sized to the card, not the viewport. Portaling to
  // <body> is the escape, so assert the overlay leaves the component's subtree.
  it('portals the fullscreen log overlay to <body> so glass-theme cards cannot trap it', () => {
    const { container } = render(<ProcessesTab appId="app-1" pm2ProcessNames={['example-api']} />);

    fireEvent.click(screen.getByRole('button', { name: 'Expand details for example-api' }));
    fireEvent.click(screen.getByTitle('Fullscreen'));

    const overlay = document.body.querySelector('.fixed.inset-0');
    expect(overlay).toBeTruthy();
    // Rendered out of the tab tree entirely, directly under <body>.
    expect(container.contains(overlay)).toBe(false);
    expect(overlay.parentElement).toBe(document.body);
    expect(screen.getByText('Logs: example-api')).toBeTruthy();
    expect(screen.getByTestId('fullscreen-log-controls')).toHaveClass('flex-wrap');

    // Exiting fullscreen tears the portaled overlay back down.
    fireEvent.click(screen.getByRole('button', { name: 'Exit fullscreen' }));
    expect(document.body.querySelector('.fixed.inset-0')).toBeNull();
  });

  it('fullscreen log viewer has dialog semantics and ARIA attributes', () => {
    render(<ProcessesTab appId="app-1" pm2ProcessNames={['example-api']} />);

    fireEvent.click(screen.getByRole('button', { name: 'Expand details for example-api' }));
    fireEvent.click(screen.getByTitle('Fullscreen'));

    const dialog = screen.getByRole('dialog', { name: 'Logs for example-api' });
    expect(dialog).toBeTruthy();
    expect(dialog).toHaveAttribute('aria-modal', 'true');
    expect(dialog).toHaveAttribute('aria-label', 'Logs for example-api');
  });

  it('pressing Escape closes the fullscreen log viewer', () => {
    render(<ProcessesTab appId="app-1" pm2ProcessNames={['example-api']} />);

    fireEvent.click(screen.getByRole('button', { name: 'Expand details for example-api' }));
    fireEvent.click(screen.getByTitle('Fullscreen'));

    expect(screen.getByRole('dialog', { name: 'Logs for example-api' })).toBeTruthy();

    // Press Escape to close fullscreen
    fireEvent.keyDown(screen.getByRole('dialog', { name: 'Logs for example-api' }), { key: 'Escape' });

    // Dialog should be gone
    expect(screen.queryByRole('dialog', { name: 'Logs for example-api' })).toBeNull();
  });

  it('fullscreen log viewer traps focus within the modal', () => {
    useProcessLogs.mockReturnValue({
      logs: [{ line: 'test', type: 'stdout', timestamp: 100 }],
      status: 'connecting',
      clear: vi.fn(),
    });
    render(<ProcessesTab appId="app-1" pm2ProcessNames={['example-api']} />);

    fireEvent.click(screen.getByRole('button', { name: 'Expand details for example-api' }));
    fireEvent.click(screen.getByTitle('Fullscreen'));

    const dialog = screen.getByRole('dialog', { name: 'Logs for example-api' });

    // Focus should be inside the modal (on the exit button or another control)
    expect(dialog.contains(document.activeElement)).toBe(true);
  });
});