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

10.6 KB
Raw Blame
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, waitFor, act, fireEvent } from '@testing-library/react';
import { createMemoryRouter } from 'react-router';
import { RouterProvider } from 'react-router/dom';

// Sharing.jsx pulls in socket.io-client at module scope (auto-connects).
// Stub it so the test runner doesn't try to open a network socket.
vi.mock('../services/socket', () => ({ default: { on: vi.fn(), off: vi.fn() } }));
vi.mock('../services/api', () => ({
  listShareBuckets: vi.fn(),
  createShareBucket: vi.fn(),
  updateShareBucket: vi.fn(),
  deleteShareBucket: vi.fn(),
  listShareInbox: vi.fn(),
  promoteShareInboxItem: vi.fn(),
  dismissShareInboxItem: vi.fn(),
  listShareActivity: vi.fn(),
  getSettings: vi.fn(),
  updateSettings: vi.fn(),
  listUniverseDuplicates: vi.fn(),
  listSeriesDuplicates: vi.fn(),
  listConflicts: vi.fn(),
}));

import Sharing, { SECTIONS, isLiveSubscription } from './Sharing';
import { expectPageNavTabs } from '../test/pageNavTabAssertions.js';
import { expectNoDanglingAriaRefs } from '../test/ariaRefAssertions.js';
import * as api from '../services/api';

const NOW = Date.parse('2026-05-18T12:00:00Z');

describe('isLiveSubscription', () => {
  it('returns true for a subscription row received within the live window', () => {
    const item = {
      subscription: { recordKind: 'universe', recordId: 'u-1' },
      receivedAt: '2026-05-18T11:57:00Z', // 3 min ago
    };
    expect(isLiveSubscription(item, NOW)).toBe(true);
  });

  it('returns false for a subscription row received outside the live window', () => {
    const item = {
      subscription: { recordKind: 'universe', recordId: 'u-1' },
      receivedAt: '2026-05-18T11:50:00Z', // 10 min ago
    };
    expect(isLiveSubscription(item, NOW)).toBe(false);
  });

  it('returns false for a one-shot share (no subscription field) even if recent', () => {
    const item = { subscription: null, receivedAt: '2026-05-18T11:59:30Z' };
    expect(isLiveSubscription(item, NOW)).toBe(false);
  });

  it('returns false when receivedAt is missing or unparseable', () => {
    const subscription = { recordKind: 'universe', recordId: 'u-1' };
    expect(isLiveSubscription({ subscription }, NOW)).toBe(false);
    expect(isLiveSubscription({ subscription, receivedAt: '' }, NOW)).toBe(false);
    expect(isLiveSubscription({ subscription, receivedAt: 'not-a-date' }, NOW)).toBe(false);
  });

  it('returns false for null / non-object inputs without throwing', () => {
    expect(isLiveSubscription(null, NOW)).toBe(false);
    expect(isLiveSubscription(undefined, NOW)).toBe(false);
  });
});

// The per-bucket detail sub-tab (Inbox | Activity | Settings) is derived from the
// `?tab=` URL search param — not component-local state — so it's deep-linkable
// and stays in sync with browser back/forward.
describe('Sharing bucket detail tab (URL-derived)', () => {
  beforeEach(() => {
    vi.clearAllMocks();
    api.listShareBuckets.mockResolvedValue({
      buckets: [{ id: 'b1', name: 'Bucket One', path: '/tmp/b1', mode: 'inbox' }],
      localSchemaVersion: 1,
    });
    api.getSettings.mockResolvedValue({});
    api.listShareInbox.mockResolvedValue({ items: [] });
    api.listShareActivity.mockResolvedValue({ manifests: [] });
  });

  // Routes mirror App.jsx so `useParams()` resolves section + bucketId.
  const routes = [
    { path: '/sharing', element: <Sharing /> },
    { path: '/sharing/:section', element: <Sharing /> },
    { path: '/sharing/:section/:bucketId', element: <Sharing /> },
  ];
  const renderAt = (entries, initialIndex = entries.length - 1) => {
    const router = createMemoryRouter(routes, { initialEntries: entries, initialIndex });
    render(<RouterProvider router={router} />);
    return router;
  };

  it('renders the tab named by the URL param on a direct link', async () => {
    renderAt(['/sharing/buckets/b1?tab=activity']);
    await waitFor(() => expect(screen.getByText('Bucket One')).toBeInTheDocument());
    // Activity tab content — not the Inbox empty-state.
    expect(screen.getByText('No share activity yet.')).toBeInTheDocument();
    expect(screen.queryByText('No pending imports.')).not.toBeInTheDocument();
  });

  it('falls back to the Inbox tab for a stale/invalid param', async () => {
    renderAt(['/sharing/buckets/b1?tab=bogus']);
    await waitFor(() => expect(screen.getByText('Bucket One')).toBeInTheDocument());
    expect(screen.getByText('No pending imports.')).toBeInTheDocument();
    expect(screen.queryByText('No share activity yet.')).not.toBeInTheDocument();
  });

  it('follows browser back/forward between tabs', async () => {
    const router = renderAt([
      '/sharing/buckets/b1?tab=inbox',
      '/sharing/buckets/b1?tab=settings',
    ], 1);
    // Start on Settings (last history entry).
    await waitFor(() => expect(screen.getByText('Import mode')).toBeInTheDocument());

    // Back → Inbox tab.
    await act(async () => { await router.navigate(-1); });
    await waitFor(() => expect(screen.getByText('No pending imports.')).toBeInTheDocument());
    expect(screen.queryByText('Import mode')).not.toBeInTheDocument();

    // Forward → Settings tab again.
    await act(async () => { await router.navigate(1); });
    await waitFor(() => expect(screen.getByText('Import mode')).toBeInTheDocument());
  });
});

describe('Sharing list and settings reads', () => {
  const routes = [
    { path: '/sharing', element: <Sharing /> },
    { path: '/sharing/:section', element: <Sharing /> },
    { path: '/sharing/:section/:bucketId', element: <Sharing /> },
  ];
  const renderAt = (path) => render(<RouterProvider router={createMemoryRouter(routes, { initialEntries: [path] })} />);

  beforeEach(() => {
    vi.clearAllMocks();
    api.getSettings.mockResolvedValue({ sharingDisplayName: 'Alice', sharingBio: '' });
    api.listShareInbox.mockResolvedValue({ items: [] });
    api.listShareActivity.mockResolvedValue({ manifests: [] });
  });

  it('shows an error row with Retry when the bucket read fails, not "No buckets yet"', async () => {
    api.listShareBuckets.mockRejectedValueOnce(new Error('buckets 500'));
    renderAt('/sharing');

    expect(await screen.findByRole('alert')).toHaveTextContent('Could not load buckets — buckets 500');
    expect(screen.queryByText(/No buckets yet/)).not.toBeInTheDocument();

    api.listShareBuckets.mockResolvedValue({ buckets: [{ id: 'b1', name: 'Bucket One', path: '/tmp/b1', mode: 'inbox' }] });
    fireEvent.click(screen.getByRole('button', { name: 'Retry' }));
    expect((await screen.findAllByText('Bucket One')).length).toBeGreaterThan(0);
  });

  it('shows an error row with Retry when the inbox read fails, not "No pending imports."', async () => {
    api.listShareBuckets.mockResolvedValue({ buckets: [{ id: 'b1', name: 'Bucket One', path: '/tmp/b1', mode: 'inbox' }] });
    api.listShareInbox.mockRejectedValueOnce(new Error('inbox 500'));
    renderAt('/sharing/buckets/b1?tab=inbox');

    expect(await screen.findByRole('alert')).toHaveTextContent('Could not load the inbox — inbox 500');
    expect(screen.queryByText('No pending imports.')).not.toBeInTheDocument();

    fireEvent.click(screen.getByRole('button', { name: 'Retry' }));
    expect(await screen.findByText('No pending imports.')).toBeInTheDocument();
  });

  it('shows an error row with Retry when the activity read fails, not "No share activity yet."', async () => {
    api.listShareBuckets.mockResolvedValue({ buckets: [{ id: 'b1', name: 'Bucket One', path: '/tmp/b1', mode: 'inbox' }] });
    api.listShareActivity.mockRejectedValueOnce(new Error('activity 500'));
    renderAt('/sharing/buckets/b1?tab=activity');

    expect(await screen.findByRole('alert')).toHaveTextContent('Could not load share activity — activity 500');
    expect(screen.queryByText('No share activity yet.')).not.toBeInTheDocument();

    fireEvent.click(screen.getByRole('button', { name: 'Retry' }));
    expect(await screen.findByText('No share activity yet.')).toBeInTheDocument();
  });

  it('locks the display-name editor when the settings read fails so a save cannot replace stored values', async () => {
    api.listShareBuckets.mockResolvedValue({ buckets: [] });
    api.getSettings.mockRejectedValueOnce(new Error('settings 500'));
    renderAt('/sharing');

    expect(await screen.findByRole('alert')).toHaveTextContent('Could not load your display name — settings 500');
    const nameInput = screen.getByLabelText('Your display name');
    expect(nameInput).toBeDisabled();
    expect(screen.getByRole('button', { name: /Save/ })).toBeDisabled();

    fireEvent.click(screen.getByRole('button', { name: 'Retry' }));
    await waitFor(() => expect(nameInput).toHaveValue('Alice'));
    expect(nameInput).not.toBeDisabled();
  });
});

// Sharing derives its top section strip from the nav manifest's
// `tabGroup: 'sharing'` (#6383) — this pins the id/label/order the page means to
// render, and that every manifest section has a presentation entry (icon) in
// Sharing.jsx, which would otherwise only surface as a thrown import-time error.
// The page-local "Buckets" label comes from the manifest's `tabLabel`; ⌘K and
// voice still show the page-level "Sharing" for the same `/sharing` route.
describe('Sharing SECTIONS ↔ nav manifest', () => {
  it('renders the sharing tabGroup in page order with a presentation entry each', () => {
    expectPageNavTabs(SECTIONS, [
      'buckets:Buckets', 'duplicates:Duplicates', 'conflicts:Conflicts',
    ]);
  });
});

// #7420: RouteTabsHeader passes no `controlsIdPrefix`, so each section names
// its own panel rather than borrowing an `aria-labelledby` from a tab id that
// doesn't exist. Covers all three sections this page's own tab bar can reach.
describe('Sharing — no dangling aria-controls/aria-labelledby', () => {
  beforeEach(() => {
    vi.clearAllMocks();
    api.listShareBuckets.mockResolvedValue({ buckets: [], localSchemaVersion: 1 });
    api.getSettings.mockResolvedValue({});
    api.listShareInbox.mockResolvedValue({ items: [] });
    api.listShareActivity.mockResolvedValue({ manifests: [] });
    api.listUniverseDuplicates.mockResolvedValue({ groups: [] });
    api.listSeriesDuplicates.mockResolvedValue({ groups: [] });
    api.listConflicts.mockResolvedValue({ conflicts: [] });
  });

  const routes = [{ path: '/sharing/:section', element: <Sharing /> }];
  const renderAt = (entry) => render(
    <RouterProvider router={createMemoryRouter(routes, { initialEntries: [entry] })} />,
  );

  it.each(['buckets', 'duplicates', 'conflicts'])('%s section names every panel it points at', async (section) => {
    const { container } = renderAt(`/sharing/${section}`);
    await waitFor(() => expect(screen.getByRole('tabpanel')).toBeInTheDocument());
    expectNoDanglingAriaRefs(container);
  });
});