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

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

// jsdom has no WebGL context, so the three.js stack can't mount. The stub drops
// `children` deliberately: rendering the scene would mount <mesh>/<bufferGeometry>
// as unknown DOM elements and hand back HTMLElements where three.js objects are
// expected. The scene's own maths are covered by goalTreeScene.test.js instead —
// this file covers the chrome around the canvas.
vi.mock('@react-three/fiber', () => ({
  Canvas: () => <div data-testid="goal-tree-canvas" />,
  useFrame: () => {},
  useThree: () => null,
}));
vi.mock('@react-three/drei', () => ({
  OrbitControls: () => null,
  Billboard: () => null,
  Text: () => null,
}));

const { toastError, organizeGoals, createGoal, providerState } = vi.hoisted(() => ({
  toastError: vi.fn(),
  organizeGoals: vi.fn(),
  createGoal: vi.fn(),
  // Mutable so the organize tests can hand the view a selected provider (the
  // Organize button is disabled without one) while the rest keep the bare default.
  providerState: { selectedProviderId: '', selectedModel: '' },
}));

vi.mock('../ui/Toast', () => ({
  default: Object.assign(() => {}, { error: toastError, success: () => {} }),
}));
vi.mock('../../services/api', () => ({
  createGoal,
  organizeGoals,
}));
vi.mock('../../hooks/useProviderModels', async () => {
  const { useState } = await import('react');
  const providers = [
    { id: 'provider-1', name: 'Example Provider', models: ['example-model', 'example-alternate'] },
    { id: 'provider-2', name: 'Other Provider', models: ['other-default', 'other-alternate'] },
  ];
  return {
    default: () => {
      const [selectedProviderId, setSelectedProviderId] = useState(providerState.selectedProviderId);
      const [selectedModel, setSelectedModel] = useState(providerState.selectedModel);
      return {
        providers, selectedProviderId, selectedModel,
        availableModels: providers.find(p => p.id === selectedProviderId)?.models || [],
        setSelectedProviderId: id => { setSelectedProviderId(id); setSelectedModel(providers.find(p => p.id === id)?.models[0] || ''); },
        setSelectedModel, loading: false,
      };
    },
  };
});

// For lifecycle tests (#8108), the mock tracks whether edit state persists across goal switches.
vi.mock('./GoalDetailPanel', async (importOriginal) => {
  const actual = await importOriginal();
  const React = await import('react');
  return {
    ...actual,
    default: ({ goal, onClose, onRefresh }) => {
      const [isEditing, setIsEditing] = React.useState(false);
      const [formTitle, setFormTitle] = React.useState('');

      return (
        <div>
          <span data-testid="detail-panel-goal">{goal.title}</span>
          {isEditing && (
            <div data-testid="edit-form">
              <input
                data-testid="edit-form-title"
                value={formTitle}
                onChange={(e) => setFormTitle(e.target.value)}
                placeholder="Edit title"
              />
              <button type="button" onClick={() => setIsEditing(false)}>cancel-edit</button>
            </div>
          )}
          {!isEditing && (
            <button type="button" onClick={() => { setIsEditing(true); setFormTitle(goal.title); }}>
              start-edit
            </button>
          )}
          <button type="button" onClick={onClose}>close-detail</button>
          <button type="button" onClick={onRefresh}>refresh-detail</button>
        </div>
      );
    },
  };
});

import GoalsTreeView from './GoalsTreeView';

// Invented placeholder goals — never real records from a running install.
const DATA = {
  flat: [
    { id: 'g1', title: 'Sail across an ocean', category: 'mastery', horizon: 'lifetime', goalType: 'apex' },
    { id: 'g2', title: 'Learn celestial navigation', category: 'mastery', horizon: '5-year', parentId: 'g1' },
    { id: 'g3', title: 'Restore the boat', category: 'creative', horizon: '3-year', parentId: 'g1' },
  ],
};

const renderTree = async (data = DATA) => {
  render(<GoalsTreeView data={data} onRefresh={vi.fn()} />);
  await act(async () => {});
};

beforeEach(() => {
  vi.clearAllMocks();
});

describe('labels toggle', () => {
  // The bug this guards (#3280): the tree rendered unlabelled dots whose identity
  // was only reachable by hovering — which does not exist on a touch device. Names
  // must be on by DEFAULT; the toggle only exists to quiet a dense graph.
  it('defaults to showing goal names', async () => {
    await renderTree();
    expect(screen.getByRole('button', { name: /labels/i })).toHaveAttribute('aria-pressed', 'true');
  });

  it('turns labels off and back on', async () => {
    const user = userEvent.setup();
    await renderTree();
    const toggle = screen.getByRole('button', { name: /labels/i });

    await user.click(toggle);
    expect(toggle).toHaveAttribute('aria-pressed', 'false');

    await user.click(toggle);
    expect(toggle).toHaveAttribute('aria-pressed', 'true');
  });

  it('names the control for screen readers and touch, where the text is hidden', async () => {
    await renderTree();
    // The word "Labels" is `hidden sm:inline`, so on a phone the icon is all
    // that renders — the accessible name has to come from aria-label.
    expect(screen.getByRole('button', { name: /labels/i })).toHaveAttribute('aria-label', 'Labels');
  });
});

it('opens and dismisses the create form without creating a goal', async () => {
  const user = userEvent.setup();
  await renderTree();
  await user.click(screen.getByRole('button', { name: 'Add' }));
  expect(screen.getByRole('textbox', { name: 'New goal title' })).toBeVisible();
  await user.click(screen.getByRole('button', { name: 'Cancel' }));
  expect(screen.queryByRole('textbox', { name: 'New goal title' })).not.toBeInTheDocument();
});

describe('empty state', () => {
  it('skips the canvas when there is nothing to lay out', async () => {
    await renderTree({ flat: [] });
    expect(screen.queryByTestId('goal-tree-canvas')).not.toBeInTheDocument();
    expect(screen.getByText(/no goals to display/i)).toBeInTheDocument();
  });
});

describe('handleOrganize error toasting', () => {
  // Guards #3515: this handler owns the "Failed to organize goals" toast, so the
  // request helper must be told to stay quiet — otherwise a failed AI run stacks
  // two error toasts on top of each other.
  beforeEach(() => {
    Object.assign(providerState, {
      selectedProviderId: 'provider-1',
      selectedModel: 'example-model',
    });
  });
  afterEach(() => {
    Object.assign(providerState, { selectedProviderId: '', selectedModel: '' });
  });

  it('disables organization while a request is pending', async () => {
    const user = userEvent.setup();
    let finish;
    organizeGoals.mockImplementation(() => new Promise(resolve => { finish = resolve; }));
    await renderTree();
    await user.click(screen.getByRole('button', { name: /organize/i }));
    const pending = screen.getByRole('button', { name: /analyzing/i });
    expect(pending).toBeDisabled();
    await user.click(pending);
    expect(organizeGoals).toHaveBeenCalledTimes(1);
    await act(async () => { finish(null); });
    expect(screen.getByRole('button', { name: /organize/i })).toBeEnabled();
  });

  it('asks the API helper to stay silent and toasts the failure exactly once', async () => {
    const user = userEvent.setup();
    organizeGoals.mockRejectedValue(new Error('Organization failed'));
    await renderTree();

    await user.click(screen.getByRole('button', { name: /organize/i }));
    await act(async () => {});

    expect(organizeGoals).toHaveBeenCalledWith(
      { providerId: 'provider-1', model: 'example-model' },
      { silent: true },
    );
    expect(toastError).toHaveBeenCalledTimes(1);
    expect(toastError).toHaveBeenCalledWith('Failed to organize goals');
  });
});

// #9712: selecting the route must reach the request, without starting AI work
// until Organize is clicked; a pending request still locks all three controls.
it('organizes with the chosen provider and model only after submission', async () => {
  const user = userEvent.setup();
  let finish;
  organizeGoals.mockReturnValue(new Promise(resolve => { finish = resolve; }));
  await renderTree({ flat: DATA.flat.slice(0, 2) });
  const provider = screen.getByRole('combobox', { name: 'AI Provider' });
  await user.selectOptions(provider, 'provider-2');
  const model = screen.getByRole('combobox', { name: 'Model' });
  await user.selectOptions(model, 'other-alternate');
  expect(organizeGoals).not.toHaveBeenCalled();

  await user.click(screen.getByRole('button', { name: 'Organize' }));
  expect(organizeGoals).toHaveBeenCalledWith(
    { providerId: 'provider-2', model: 'other-alternate' }, { silent: true },
  );
  expect(provider).toBeDisabled();
  expect(model).toBeDisabled();
  expect(screen.getByRole('button', { name: 'Analyzing...' })).toBeDisabled();
  await act(async () => { finish({ apexGoal: { existingId: null, suggestedTitle: 'Example apex' }, organization: [], suggestedSubApex: [] }); });
  expect(screen.getByText('Goal Organization')).toBeInTheDocument();
  expect(createGoal).not.toHaveBeenCalled();
});