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

8.3 KB
Raw Blame
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';

vi.mock('../../services/api', () => ({
  listConflicts: vi.fn(),
  getConflict: vi.fn(),
  resolveConflict: vi.fn(),
  deleteConflict: vi.fn(),
}));
vi.mock('../ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn() } }));
vi.mock('../ui/InlineDiff', () => ({ default: ({ oldText, newText }) => <div data-testid="diff">{oldText}|{newText}</div> }));

import * as api from '../../services/api';
import ConflictsTab from './ConflictsTab';

const entry = {
  id: 'entry-1',
  recordKind: 'universe',
  recordId: 'u-123456789012',
  detectedAt: '2026-05-25T10:00:00Z',
  source: { via: 'push', peerId: 'peer-abc' },
  diffSummary: [
    { field: 'starterPrompt', localValue: 'my local', remoteValue: 'their remote', changed: 'both' },
    { field: 'logline', localValue: 'mine', remoteValue: 'theirs', changed: 'both' },
  ],
  status: 'pending',
};

// The list endpoint returns a compact projection; the full entry loads on expand.
const compact = (e) => ({ ...e, diffSummary: e.diffSummary.map(({ field, changed }) => ({ field, changed })) });

beforeEach(() => {
  vi.clearAllMocks();
  api.listConflicts.mockResolvedValue({ conflicts: [compact(entry)] });
  api.getConflict.mockResolvedValue(entry);
});

describe('ConflictsTab', () => {
  it('shows a retryable load failure and does not claim the queue is empty', async () => {
    api.listConflicts.mockRejectedValueOnce(new Error('journal unavailable'));
    const user = userEvent.setup();
    render(<ConflictsTab />);
    expect(await screen.findByRole('alert')).toHaveTextContent('Could not load pending conflicts.');
    expect(screen.queryByText(/No pending conflicts/)).not.toBeInTheDocument();

    await user.click(screen.getByRole('button', { name: 'Retry' }));
    expect(await screen.findByText(/2 field\(s\)/)).toBeInTheDocument();
    expect(api.listConflicts).toHaveBeenCalledTimes(2);
  });

  it('shows the existing empty copy after a successful empty response', async () => {
    api.listConflicts.mockResolvedValue({ conflicts: [] });
    render(<ConflictsTab />);
    expect(await screen.findByText(/No pending conflicts/)).toBeInTheDocument();
    expect(screen.queryByRole('alert')).not.toBeInTheDocument();
  });

  it('treats a malformed successful payload as a load failure', async () => {
    api.listConflicts.mockResolvedValue({});
    render(<ConflictsTab />);
    expect(await screen.findByRole('alert')).toHaveTextContent('Could not load pending conflicts.');
    expect(screen.queryByText(/No pending conflicts/)).not.toBeInTheDocument();
  });

  it('shows the degraded-detection banner when the base-hash store is latched (#7260)', async () => {
    api.listConflicts.mockResolvedValue({
      conflicts: [],
      conflictDetection: { degraded: true, reason: 'sync_base_hashes.json is present but unreadable — repair or delete it and restart' },
    });
    render(<ConflictsTab />);
    expect(await screen.findByText(/Conflict detection is degraded/)).toBeInTheDocument();
    expect(screen.getByText(/sync_base_hashes\.json/)).toBeInTheDocument();
    // The empty list still renders beneath the warning.
    expect(screen.getByText(/No pending conflicts/)).toBeInTheDocument();
  });

  it('lists pending conflicts', async () => {
    render(<ConflictsTab />);
    await waitFor(() => expect(screen.getByText(/2 field\(s\)/)).toBeInTheDocument());
    expect(screen.getByText(/via push/)).toBeInTheDocument();
  });

  it('fetches the full diff once on first expand and shows no values before that', async () => {
    const user = userEvent.setup();
    render(<ConflictsTab />);
    await waitFor(() => expect(screen.getByText(/2 field\(s\)/)).toBeInTheDocument());
    expect(api.getConflict).not.toHaveBeenCalled();
    expect(screen.queryByTestId('diff')).not.toBeInTheDocument();

    await user.click(screen.getByText(/u-123456789012/));
    expect(await screen.findAllByTestId('diff')).toHaveLength(2);
    expect(api.getConflict).toHaveBeenCalledWith('entry-1', expect.anything());

    await user.click(screen.getByText(/u-123456789012/)); // collapse
    await user.click(screen.getByText(/u-123456789012/)); // re-expand: cached
    expect(api.getConflict).toHaveBeenCalledTimes(1);
  });

  it('removes a resolved row locally without re-listing', async () => {
    api.resolveConflict.mockResolvedValue({ status: 'resolved' });
    const user = userEvent.setup();
    render(<ConflictsTab />);
    await waitFor(() => expect(screen.getByText(/2 field\(s\)/)).toBeInTheDocument());
    await user.click(screen.getByRole('button', { name: /Discard/ }));
    expect(await screen.findByText(/No pending conflicts/)).toBeInTheDocument();
    expect(api.listConflicts).toHaveBeenCalledTimes(1);
  });

  it('restore-all resolves the whole entry', async () => {
    api.resolveConflict.mockResolvedValue({ status: 'resolved' });
    const user = userEvent.setup();
    render(<ConflictsTab />);
    await waitFor(() => expect(screen.getByText(/2 field\(s\)/)).toBeInTheDocument());
    await user.click(screen.getByRole('button', { name: /Restore mine/ }));
    await waitFor(() => expect(api.resolveConflict).toHaveBeenCalledWith('entry-1', { action: 'restore-all' }, expect.anything()));
  });

  it('merge-fields sends only the selected fields', async () => {
    api.resolveConflict.mockResolvedValue({ status: 'resolved' });
    const user = userEvent.setup();
    render(<ConflictsTab />);
    await waitFor(() => expect(screen.getByText(/2 field\(s\)/)).toBeInTheDocument());

    // Expand the entry, select one field, merge.
    await user.click(screen.getByText(/u-123456789012/));
    const checkboxes = await screen.findAllByRole('checkbox');
    await user.click(checkboxes[0]); // starterPrompt
    await user.click(screen.getByRole('button', { name: /Merge 1 selected field/ }));
    await waitFor(() => expect(api.resolveConflict).toHaveBeenCalledWith('entry-1', { action: 'merge-fields', fields: ['starterPrompt'] }, expect.anything()));
  });

  it('discard keeps the synced version', async () => {
    api.resolveConflict.mockResolvedValue({ status: 'resolved' });
    const user = userEvent.setup();
    render(<ConflictsTab />);
    await waitFor(() => expect(screen.getByText(/2 field\(s\)/)).toBeInTheDocument());
    await user.click(screen.getByRole('button', { name: /Discard/ }));
    await waitFor(() => expect(api.resolveConflict).toHaveBeenCalledWith('entry-1', { action: 'discard' }, expect.anything()));
  });

  it('renders per-sub-entry diffs for a field carrying `parts`, and still merges at field granularity', async () => {
    const deepEntry = {
      id: 'entry-2', recordKind: 'universe', recordId: 'u-deep0000000', detectedAt: '2026-05-25T10:00:00Z',
      source: { via: 'sync' },
      diffSummary: [{
        field: 'characters', changed: 'both',
        parts: [
          { path: 'c1', label: 'Alice', changed: 'both', localValue: { bio: 'mine' }, remoteValue: { bio: 'theirs' } },
          { path: 'c2', label: 'Bob', changed: 'local-only', localValue: { bio: 'gone' }, remoteValue: undefined },
        ],
      }],
      status: 'pending',
    };
    api.listConflicts.mockResolvedValue({ conflicts: [compact(deepEntry)] });
    api.getConflict.mockResolvedValue(deepEntry);
    api.resolveConflict.mockResolvedValue({ status: 'resolved' });
    const user = userEvent.setup();
    render(<ConflictsTab />);
    await waitFor(() => expect(screen.getByText(/1 field\(s\)/)).toBeInTheDocument());

    await user.click(screen.getByText(/u-deep0000000/)); // expand
    // Each changed sub-entry is labelled and rendered as its own diff.
    expect(await screen.findByText(/Alice/)).toBeInTheDocument();
    expect(screen.getByText(/Bob/)).toBeInTheDocument();
    expect(screen.getAllByTestId('diff')).toHaveLength(2); // one InlineDiff per part, not one blob

    // Merge still selects the whole field (one checkbox for the field, not per-part).
    const checkboxes = screen.getAllByRole('checkbox');
    expect(checkboxes).toHaveLength(1);
    await user.click(checkboxes[0]);
    await user.click(screen.getByRole('button', { name: /Merge 1 selected field/ }));
    await waitFor(() => expect(api.resolveConflict).toHaveBeenCalledWith('entry-2', { action: 'merge-fields', fields: ['characters'] }, expect.anything()));
  });
});