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

48.1 KB
Raw Blame
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, fireEvent, cleanup, waitFor, act } from '@testing-library/react';
import { MemoryRouter } from 'react-router';
import { findEnabledByRole } from '../../../test/enabledBarrier.js';

const { socketHandlers, socketMock } = vi.hoisted(() => {
  const handlers = new Map();
  const mock = {
    connected: true,
    on: vi.fn((event, handler) => handlers.set(event, handler)),
    off: vi.fn((event, handler) => {
      if (handlers.get(event) === handler) handlers.delete(event);
    }),
    emit: vi.fn()
  };
  return { socketHandlers: handlers, socketMock: mock };
});

vi.mock('../../../services/socket', () => ({ default: socketMock }));
vi.mock('../../../services/apiLocalLlm', async (importOriginal) => ({
  ...await importOriginal(),
  getToolUseModels: vi.fn().mockResolvedValue({ models: [] }),
}));

// Label chips grade their color against the ACTIVE theme mode, so the mode has
// to be steerable per test. The real provider runs a settings fetch on mount,
// which this suite has no business exercising.
const { themeMode } = vi.hoisted(() => ({ themeMode: { current: 'night' } }));
vi.mock('../../ThemeContext', () => ({
  useThemeContext: () => ({ theme: { mode: themeMode.current } }),
}));

vi.mock('../../../services/api', () => ({
  getAppIssues: vi.fn(),
  syncGithubThreads: vi.fn(),
  createSlashdoTask: vi.fn(),
  getProviders: vi.fn(),
  getLocalLlmStatus: vi.fn().mockResolvedValue(null),
  // The tab reads the reviewers a claim will actually run so it can name them
  // (and say whether a claim-work override supplied them).
  getAppClaimReviewers: vi.fn(),
}));

import * as api from '../../../services/api';
import { chipColors, parseColor } from '../../../lib/chipContrast';
import IssuesTab from './IssuesTab';

const ISSUE = {
  number: 42,
  title: 'Crash on save',
  body: 'Repro: open the editor and hit save.',
  url: 'https://github.com/acme/widget/issues/42',
  state: 'open',
  labels: [{ name: 'bug', color: '#d73a4a', description: 'Something is broken' }],
  assignees: ['alice'],
  author: 'carol',
  milestone: null,
  createdAt: '2026-01-01T00:00:00Z',
  updatedAt: '2026-01-02T00:00:00Z',
};

const okPayload = (issues) => ({
  forge: 'github',
  fullName: 'acme/widget',
  issues,
  reason: issues.length ? 'ok' : 'no-open-issues',
  transient: false,
  remedy: null,
});

const renderTab = async ({ open = false } = {}) => {
  const result = render(
    <MemoryRouter>
      <IssuesTab appId="app-1" appName="Widget" />
    </MemoryRouter>
  );
  await act(async () => {});
  if (open) {
    fireEvent.click(screen.getByRole('button', { name: 'Change' }));
    await act(async () => {});
  }
  return result;
};

beforeEach(() => {
  themeMode.current = 'night';
  socketHandlers.clear();
  socketMock.on.mockClear();
  socketMock.off.mockClear();
  socketMock.emit.mockClear();
  api.getAppIssues.mockResolvedValue(okPayload([ISSUE]));
  api.createSlashdoTask.mockResolvedValue({ id: 'task-1' });
  api.getProviders.mockResolvedValue({ providers: [] });
  api.getAppClaimReviewers.mockResolvedValue({
    source: 'defaults', reviewers: ['antigravity'], usernames: [], optionalReviewers: [],
    reviewerMaxRounds: {}, reviewerModels: {}, reviewerEfforts: {}, csv: 'antigravity',
  });
});

afterEach(() => {
  cleanup();
  vi.clearAllMocks();
});

describe('IssuesTab', () => {
  it('auto-queries open issues on mount and renders title, labels, and assignees', async () => {
    await renderTab();

    expect(await screen.findByText('Crash on save')).toBeInTheDocument();
    expect(api.getAppIssues).toHaveBeenCalledWith('app-1');
    expect(screen.getByText('#42')).toBeInTheDocument();
    // Scoped by the row chip's own title — the label also appears as a filter
    // toggle in the header, so a bare getByText('bug') is ambiguous.
    expect(screen.getByTitle('Something is broken')).toHaveTextContent('bug');
    expect(screen.getByText(/alice/)).toBeInTheDocument();
    expect(screen.getByText('acme/widget')).toBeInTheDocument();
  });

  it('renders the issue link as a button with accessible name, external URL, and touch target', async () => {
    await renderTab();

    const linkButton = await screen.findByRole('button', { name: 'Open issue 42 on GitHub' });
    expect(linkButton).toBeInTheDocument();
    expect(linkButton).toHaveAttribute('href', 'https://github.com/acme/widget/issues/42');
    expect(linkButton).toHaveAttribute('target', '_blank');
    expect(linkButton).toHaveAttribute('rel', 'noreferrer');
    expect(linkButton.className).toContain('pointer-coarse:min-h-9');
    expect(linkButton).toHaveTextContent('GitHub');
  });

  it('activates the issue link button on Space keydown', async () => {
    const openSpy = vi.spyOn(window, 'open').mockImplementation(() => null);
    await renderTab();

    const linkButton = await screen.findByRole('button', { name: 'Open issue 42 on GitHub' });
    fireEvent.keyDown(linkButton, { key: ' ' });
    expect(openSpy).toHaveBeenCalledWith('https://github.com/acme/widget/issues/42', '_blank', 'noreferrer');
    openSpy.mockRestore();
  });

  // The AA guarantee itself is `lib/chipContrast.test.js`'s job. What this suite
  // owns is the wiring: the chip is styled for the ACTIVE theme mode, not a
  // hardcoded one. #fef2c0 is GitHub's default pale yellow — the color that
  // rendered as white-on-cream before chips were graded per mode.
  it.each(['day', 'night'])('styles label chips for the %s theme mode', async (mode) => {
    themeMode.current = mode;
    api.getAppIssues.mockResolvedValue(okPayload([{
      ...ISSUE,
      labels: [{ name: 'plan', color: '#fef2c0', description: 'Planned work' }],
    }]));
    await renderTab();

    const chip = await screen.findByTitle('Planned work');
    expect(chip).toHaveTextContent('plan');
    // parseColor on both sides: jsdom normalizes an inline `#rrggbb` to `rgb(…)`,
    // so comparing the raw strings would pass no matter which mode was used.
    const other = mode === 'day' ? 'night' : 'day';
    expect(parseColor(chip.style.color)).toEqual(parseColor(chipColors('#fef2c0', mode).color));
    expect(parseColor(chip.style.color)).not.toEqual(parseColor(chipColors('#fef2c0', other).color));
  });

  it('leaves a colorless label on the neutral chip instead of an inline color', async () => {
    api.getAppIssues.mockResolvedValue(okPayload([{
      ...ISSUE,
      labels: [{ name: 'feature', color: null, description: 'No forge color' }],
    }]));
    await renderTab();

    const chip = await screen.findByTitle('No forge color');
    expect(chip.style.color).toBe('');
    expect(chip.className).toContain('text-gray-300');
  });

  it('shows a comment count only for issues that have comments', async () => {
    api.getAppIssues.mockResolvedValue(okPayload([
      { ...ISSUE, number: 42, title: 'Crash on save', commentCount: 3 },
      { ...ISSUE, number: 43, title: 'Add CSV export', commentCount: 1 },
      { ...ISSUE, number: 44, title: 'Untouched', commentCount: 0 },
    ]));
    await renderTab();

    await screen.findByText('Crash on save');
    // Spelled out rather than a bare digit beside an icon, so the count reads
    // the same to a screen reader as its `opened by …` / `updated …` siblings.
    expect(screen.getByText(/3 comments/)).toBeInTheDocument();
    expect(screen.getByText(/1 comment$/)).toBeInTheDocument();
    expect(screen.queryByText(/0 comment/)).not.toBeInTheDocument();
  });

  it('keeps the description collapsed until the user expands it', async () => {
    await renderTab();

    const title = await screen.findByText('Crash on save');
    expect(screen.queryByText(/Repro: open the editor/)).not.toBeInTheDocument();

    fireEvent.click(title);
    expect(await screen.findByText(/Repro: open the editor/)).toBeInTheDocument();

    fireEvent.click(title);
    await waitFor(() => expect(screen.queryByText(/Repro: open the editor/)).not.toBeInTheDocument());
  });

  it('does not override an unresolved app completion policy when claiming', async () => {
    api.getAppClaimReviewers.mockReturnValue(new Promise(() => {}));
    await renderTab();
    fireEvent.click(await screen.findByRole('button', { name: /Claim/ }));
    await waitFor(() => expect(api.createSlashdoTask).toHaveBeenCalled());
    expect(api.createSlashdoTask.mock.calls.at(-1)[2]).not.toHaveProperty('prCompletion');
  });

  it('claims an issue with its prefetched content pinned to the /do:next task', async () => {
    await renderTab();

    fireEvent.click(await screen.findByRole('button', { name: /Claim/ }));

    await waitFor(() => expect(api.createSlashdoTask).toHaveBeenCalledWith(
      'next', 'app-1', {
        target: '42',
        issueContext: {
          number: 42,
          title: 'Crash on save',
          body: 'Repro: open the editor and hit save.',
          url: 'https://github.com/acme/widget/issues/42'
        }
      }, { silent: true }
    ));
    expect(await screen.findByRole('link', { name: /Queued/ })).toBeInTheDocument();
  });

  it('tracks the claimed task from queued through active and completed over the CoS socket', async () => {
    await renderTab();

    fireEvent.click(await screen.findByRole('button', { name: /Claim/ }));
    expect(await screen.findByRole('link', { name: /Queued/ })).toBeInTheDocument();

    act(() => socketHandlers.get('cos:tasks:changed')({
      task: { id: 'task-1', status: 'in_progress' }
    }));
    expect(await screen.findByRole('link', { name: /Active/ })).toBeInTheDocument();

    act(() => socketHandlers.get('cos:tasks:changed')({
      task: { id: 'task-1', status: 'completed' }
    }));
    expect(await screen.findByRole('link', { name: /Completed/ })).toBeInTheDocument();
  });

  it('does not treat a failed agent completion as a completed task', async () => {
    await renderTab();

    fireEvent.click(await screen.findByRole('button', { name: /Claim/ }));
    expect(await screen.findByRole('link', { name: /Queued/ })).toBeInTheDocument();

    act(() => socketHandlers.get('cos:agent:completed')({
      taskId: 'task-1', result: { success: false },
    }));

    expect(screen.getByRole('link', { name: /Queued/ })).toBeInTheDocument();
    expect(screen.queryByRole('link', { name: /Completed/ })).not.toBeInTheDocument();
  });

  it('applies every task update that arrives in the same tick', async () => {
    const SECOND_ISSUE = {
      ...ISSUE,
      number: 43,
      title: 'Sync conflict',
      url: 'https://github.com/acme/widget/issues/43',
    };
    api.getAppIssues.mockResolvedValue(okPayload([ISSUE, SECOND_ISSUE]));
    api.createSlashdoTask
      .mockResolvedValueOnce({ id: 'task-1' })
      .mockResolvedValueOnce({ id: 'task-2' });
    await renderTab();

    const claimButtons = await screen.findAllByRole('button', { name: /Claim/ });
    fireEvent.click(claimButtons[0]);
    fireEvent.click(claimButtons[1]);
    await waitFor(() => expect(api.createSlashdoTask).toHaveBeenCalledTimes(2));

    act(() => {
      socketHandlers.get('cos:tasks:changed')({ task: { id: 'task-1', status: 'completed' } });
      socketHandlers.get('cos:tasks:changed')({ task: { id: 'task-2', status: 'completed' } });
    });

    await waitFor(() => expect(screen.getAllByRole('link', { name: /Completed/ })).toHaveLength(2));
  });

  it('removes every CoS socket listener when unmounted', async () => {
    const listenerCountBeforeMount = socketHandlers.size;
    const { unmount } = await renderTab();

    expect(socketHandlers.size).toBe(listenerCountBeforeMount + 4);
    unmount();
    expect(socketHandlers.size).toBe(listenerCountBeforeMount);
  });

  it('does not lose an active socket update that arrives before the POST response', async () => {
    let resolveClaim;
    api.createSlashdoTask.mockImplementation(() => new Promise(resolve => { resolveClaim = resolve; }));
    await renderTab();

    fireEvent.click(await screen.findByRole('button', { name: /Claim/ }));
    const pendingClaim = screen.getByRole('button', { name: 'Queuing…' });
    expect(pendingClaim).toHaveAttribute('aria-busy', 'true');
    expect(pendingClaim).toHaveTextContent('Claim');
    expect(pendingClaim).not.toHaveTextContent('Queuing…');
    expect(pendingClaim.querySelector('svg')).toHaveClass('animate-spin');
    act(() => socketHandlers.get('cos:tasks:changed')({
      task: {
        id: 'task-1', status: 'in_progress',
        metadata: { app: 'app-1', claimTarget: '42' }
      }
    }));
    expect(await screen.findByRole('link', { name: /Active/ })).toBeInTheDocument();

    await act(async () => {
      resolveClaim({ id: 'task-1', status: 'pending' });
    });
    expect(screen.getByRole('link', { name: /Active/ })).toBeInTheDocument();
  });

  // This tab offers no reviewer picker, so before it named them the reviewer
  // chain a Claim would run was invisible here — and it is not the Code
  // Reviewers panel's list whenever a claim-work override exists. That gap sent
  // claims to codex + claude for weeks after the install default had been moved.
  it('names the reviewers a Claim will run, and blames the claim-work override that supplied them', async () => {
    api.getAppClaimReviewers.mockResolvedValue({
      source: 'task-override', reviewers: ['codex', 'claude'], usernames: [], optionalReviewers: [],
      reviewerMaxRounds: {}, reviewerModels: {}, reviewerEfforts: {}, csv: 'codex,claude',
    });

    await renderTab({ open: true });

    expect(await screen.findByText('codex,claude')).toBeInTheDocument();
    expect(screen.getByRole('link', { name: 'claim-work override' })).toHaveAttribute('href', '/cos/schedule');
  });

  it('points at the Code Reviewers panel when no override is in play', async () => {
    await renderTab({ open: true });

    expect(await screen.findByText('antigravity')).toBeInTheDocument();
    expect(screen.queryByText(/claim-work/)).not.toBeInTheDocument();
    expect(screen.getByRole('link', { name: 'defaults' })).toHaveAttribute('href', '/models/code-reviewers');
  });

  it('says nothing about reviewers when the lookup failed, rather than implying none are configured', async () => {
    // "couldn't ask" and "nothing configured" must not collapse — an empty chain
    // rendered here would read as a claim that merges with no review at all.
    api.getAppClaimReviewers.mockRejectedValue(new Error('offline'));

    await renderTab();

    expect(await screen.findByText('Crash on save')).toBeInTheDocument();
    expect(screen.queryByText('Reviewers')).not.toBeInTheDocument();
  });

  it('shows and submits the configured default without touching the override controls', async () => {
    api.getProviders.mockResolvedValue({
      activeProvider: 'codex',
      providers: [{ id: 'codex', name: 'Codex', type: 'cli', command: 'codex', enabled: true,
        models: ['gpt-5'], defaultModel: 'gpt-5', effort: 'high' }],
    });
    await renderTab({ open: true });
    await screen.findByText('Crash on save');
    await waitFor(() => expect(screen.getByLabelText('Provider')).toHaveValue('codex'));
    expect(screen.getByLabelText('Model')).toHaveValue('gpt-5');
    expect(screen.getByRole('option', { name: 'Default effort — high' }).selected).toBe(true);
    fireEvent.click(screen.getByRole('button', { name: /Claim/ }));
    await waitFor(() => expect(api.createSlashdoTask).toHaveBeenCalledWith(
      'next', 'app-1', expect.objectContaining({ provider: 'codex', model: 'gpt-5', effort: undefined }),
      { silent: true }
    ));
  });

  it('sends the page-level provider/model/effort pin along with a claim', async () => {
    api.getProviders.mockResolvedValue({
      providers: [{
        id: 'claude', name: 'Claude', type: 'cli', enabled: true,
        models: ['claude-opus-5', 'claude-sonnet-5'], defaultModel: 'claude-sonnet-5',
      }],
    });
    await renderTab({ open: true });

    await screen.findByText('Crash on save');
    fireEvent.change(await screen.findByLabelText('Provider'), { target: { value: 'claude' } });
    fireEvent.change(screen.getByLabelText('Model'), { target: { value: 'claude-opus-5' } });

    fireEvent.click(screen.getByRole('button', { name: /Claim/ }));

    await waitFor(() => expect(api.createSlashdoTask).toHaveBeenCalledWith(
      'next', 'app-1',
      {
        target: '42',
        issueContext: {
          number: 42,
          title: 'Crash on save',
          body: 'Repro: open the editor and hit save.',
          url: 'https://github.com/acme/widget/issues/42'
        },
        provider: 'claude',
        model: 'claude-opus-5',
        effort: undefined
      },
      { silent: true }
    ));
  });

  it('sends a reviewer effort override without pinning untouched defaults', async () => {
    await renderTab({ open: true });
    fireEvent.click(await screen.findByRole('button', { name: 'Edit reviewers' }));
    fireEvent.change(await screen.findByLabelText('Reasoning effort for Antigravity'), { target: { value: 'high' } });
    fireEvent.click(screen.getByRole('button', { name: /Claim/ }));
    await waitFor(() => expect(api.createSlashdoTask).toHaveBeenCalled());
    const payload = api.createSlashdoTask.mock.calls[0][2];
    expect(payload.reviewerEfforts).toEqual({ antigravity: 'high' });
    expect(payload).not.toHaveProperty('reviewers');
    expect(payload).not.toHaveProperty('reviewerModels');
    expect(payload).not.toHaveProperty('stopMode');
  });

  it('blocks an empty claim review chain, leaves replans alone, and restores inheritance', async () => {
    await renderTab({ open: true });
    fireEvent.click(await screen.findByRole('button', { name: 'Edit reviewers' }));
    fireEvent.click(await screen.findByRole('button', { name: /Remove Antigravity/i }));
    expect(screen.getByRole('button', { name: /Claim/ })).toBeDisabled();
    expect(screen.getByRole('alert')).toHaveTextContent('Add an AI reviewer or a GitHub/GitLab user');
    fireEvent.click(screen.getByRole('button', { name: /Replan/ }));
    await waitFor(() => expect(api.createSlashdoTask).toHaveBeenCalled());
    expect(api.createSlashdoTask.mock.calls[0][2]).not.toHaveProperty('reviewers');
    fireEvent.click(screen.getByRole('button', { name: 'Use configured reviewers' }));
    expect(screen.queryByRole('alert')).not.toBeInTheDocument();
    expect(screen.getByRole('button', { name: /Remove Antigravity/i })).toBeInTheDocument();
    expect(screen.getByRole('button', { name: /Claim/ })).toBeEnabled();
  });

  it('lets a claim iterate with only a GitHub/GitLab reviewer', async () => {
    await renderTab({ open: true });
    fireEvent.click(await screen.findByRole('button', { name: 'Edit reviewers' }));
    fireEvent.click(await screen.findByRole('button', { name: /Remove Antigravity/i }));
    expect(screen.getByRole('button', { name: /Claim/ })).toBeDisabled();
    fireEvent.change(screen.getByLabelText('Add a GitHub/GitLab reviewer username'), { target: { value: '@reviewer-one' } });
    fireEvent.click(screen.getByRole('button', { name: 'Add reviewer username' }));
    expect(screen.queryByRole('alert')).not.toBeInTheDocument();
    fireEvent.click(screen.getByRole('button', { name: /Claim/ }));
    await waitFor(() => expect(api.createSlashdoTask).toHaveBeenCalled());
    expect(api.createSlashdoTask.mock.calls[0][2]).toMatchObject({ reviewers: [], usernames: ['reviewer-one'] });
  });

  it('collapses run settings into a truthful summary that Change expands', async () => {
    await renderTab();

    const summary = screen.getByTestId('run-settings-summary');
    expect(summary).toHaveTextContent(/^Auto · .+ · antigravity$/);
    expect(screen.queryByLabelText('Provider')).not.toBeInTheDocument();
    const change = screen.getByRole('button', { name: 'Change' });
    expect(change).toHaveAttribute('aria-expanded', 'false');

    fireEvent.click(change);
    await act(async () => {});
    expect(screen.getByRole('button', { name: 'Hide' })).toHaveAttribute('aria-expanded', 'true');
    fireEvent.change(screen.getByLabelText(/Extra context/), { target: { value: 'Keep it small.' } });
    expect(summary).toHaveTextContent(/· \+ context$/);
  });

  it('keeps an invalid review override visible by forcing the settings open', async () => {
    await renderTab({ open: true });
    fireEvent.click(await screen.findByRole('button', { name: 'Edit reviewers' }));
    fireEvent.click(await screen.findByRole('button', { name: /Remove Antigravity/i }));

    expect(screen.getByRole('alert')).toHaveTextContent('Add an AI reviewer or a GitHub/GitLab user');
    expect(screen.queryByRole('button', { name: 'Hide' })).not.toBeInTheDocument();
  });

  it('opens the settings automatically once a code-review override is active', async () => {
    await renderTab({ open: true });
    fireEvent.click(await screen.findByRole('button', { name: 'Edit reviewers' }));
    fireEvent.change(await screen.findByLabelText('Reasoning effort for Antigravity'), { target: { value: 'high' } });

    expect(screen.queryByRole('button', { name: 'Hide' })).not.toBeInTheDocument();
    expect(screen.getByRole('button', { name: 'Use configured reviewers' })).toBeInTheDocument();
  });

  it('shows a failed issues load above the run settings', async () => {
    api.getAppIssues.mockRejectedValue(new Error('forge down'));
    await renderTab();

    const banner = await screen.findByText(/Couldn.t load issues — forge down/);
    const summary = screen.getByTestId('run-settings-summary');
    expect(banner.compareDocumentPosition(summary) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
  });

  it('clears review overrides when switching apps', async () => {
    const view = await renderTab({ open: true });
    fireEvent.click(await screen.findByRole('button', { name: 'Edit reviewers' }));
    fireEvent.change(await screen.findByLabelText('Reasoning effort for Antigravity'), { target: { value: 'high' } });
    view.rerender(<MemoryRouter><IssuesTab appId="app-2" appName="Other" /></MemoryRouter>);
    await screen.findByRole('button', { name: 'Edit reviewers' });
    fireEvent.click(screen.getByRole('button', { name: /Claim/ }));
    await waitFor(() => expect(api.createSlashdoTask).toHaveBeenCalled());
    expect(api.createSlashdoTask.mock.calls[0][1]).toBe('app-2');
    expect(api.createSlashdoTask.mock.calls[0][2]).not.toHaveProperty('reviewerEfforts');
  });

  it('sends optional override context with the selected claim', async () => {
    await renderTab({ open: true });

    await screen.findByText('Crash on save');
    fireEvent.change(screen.getByLabelText(/Extra context/), {
      target: { value: 'Prefer a small, focused fix and add a regression test.' }
    });
    fireEvent.click(screen.getByRole('button', { name: /Claim/ }));

    await waitFor(() => expect(api.createSlashdoTask).toHaveBeenCalledWith(
      'next', 'app-1',
      expect.objectContaining({
        target: '42',
        overrideContext: 'Prefer a small, focused fix and add a regression test.'
      }),
      { silent: true }
    ));
  });

  it('re-enables the Claim button when queuing fails, instead of stranding it', async () => {
    api.createSlashdoTask.mockRejectedValue(new Error('CoS is not running'));
    await renderTab();

    fireEvent.click(await screen.findByRole('button', { name: /Claim/ }));

    await findEnabledByRole('button', { name: /Claim/ });
    expect(screen.queryByRole('link', { name: /Queued/ })).not.toBeInTheDocument();
  });

  it('filters the list by title, label, or assignee', async () => {
    api.getAppIssues.mockResolvedValue(okPayload([
      ISSUE,
      { ...ISSUE, number: 43, title: 'Add CSV export', labels: [], assignees: [] },
    ]));
    await renderTab();

    await screen.findByText('Crash on save');
    fireEvent.change(screen.getByLabelText('Filter issues'), { target: { value: 'csv' } });

    expect(screen.getByText('Add CSV export')).toBeInTheDocument();
    expect(screen.queryByText('Crash on save')).not.toBeInTheDocument();
  });

  it('filters to unassigned issues when the toggle is enabled', async () => {
    api.getAppIssues.mockResolvedValue(okPayload([
      ISSUE,
      { ...ISSUE, number: 43, title: 'Add CSV export', labels: [], assignees: [] },
    ]));
    await renderTab();

    await screen.findByText('Crash on save');
    const toggle = screen.getByRole('button', { name: 'Unassigned only' });
    expect(toggle).toHaveAttribute('aria-pressed', 'false');

    fireEvent.click(toggle);

    expect(await screen.findByText('Add CSV export')).toBeInTheDocument();
    expect(screen.queryByText('Crash on save')).not.toBeInTheDocument();
    expect(toggle).toHaveAttribute('aria-pressed', 'true');

    fireEvent.click(toggle);
    expect(await screen.findByText('Crash on save')).toBeInTheDocument();
  });

  it('filters issues by the selected filed-by author and restores all when cleared', async () => {
    api.getAppIssues.mockResolvedValue(okPayload([
      { ...ISSUE, number: 42, title: 'Crash on save', author: 'carol' },
      { ...ISSUE, number: 43, title: 'Add CSV export', author: 'alice' },
      { ...ISSUE, number: 44, title: 'Fix styling', author: 'bob' },
    ]));
    await renderTab();

    await screen.findByText('Crash on save');
    const filedBySelect = screen.getByLabelText('Filed by');
    expect(filedBySelect).toHaveValue('');

    // Authors are ordered alphabetically with 'All' first
    const options = Array.from(filedBySelect.querySelectorAll('option')).map(o => ({ value: o.value, text: o.textContent }));
    expect(options).toEqual([
      { value: '', text: 'All' },
      { value: 'alice', text: 'alice' },
      { value: 'bob', text: 'bob' },
      { value: 'carol', text: 'carol' },
    ]);

    // Select alice
    fireEvent.change(filedBySelect, { target: { value: 'alice' } });
    expect(await screen.findByText('Add CSV export')).toBeInTheDocument();
    expect(screen.queryByText('Crash on save')).not.toBeInTheDocument();
    expect(screen.queryByText('Fix styling')).not.toBeInTheDocument();
    expect(screen.getByText('1 of 3 open')).toBeInTheDocument();

    // Select bob
    fireEvent.change(filedBySelect, { target: { value: 'bob' } });
    expect(await screen.findByText('Fix styling')).toBeInTheDocument();
    expect(screen.queryByText('Add CSV export')).not.toBeInTheDocument();
    expect(screen.queryByText('Crash on save')).not.toBeInTheDocument();

    // Reset back to All
    fireEvent.change(filedBySelect, { target: { value: '' } });
    expect(await screen.findByText('Crash on save')).toBeInTheDocument();
    expect(screen.getByText('Add CSV export')).toBeInTheDocument();
    expect(screen.getByText('Fix styling')).toBeInTheDocument();
    expect(screen.getByText('3 open')).toBeInTheDocument();
  });

  it('hides in-progress issues by default and lists them once the chip is toggled on', async () => {
    api.getAppIssues.mockResolvedValue(okPayload([
      ISSUE,
      {
        ...ISSUE,
        number: 43,
        title: 'Being worked right now',
        labels: [
          { name: 'bug', color: '#d73a4a', description: '' },
          { name: 'in-progress', color: '#0e8a16', description: '' },
        ],
      },
    ]));
    await renderTab();

    await screen.findByText('Crash on save');
    expect(screen.queryByText('Being worked right now')).not.toBeInTheDocument();
    expect(screen.getByText('1 of 2 open')).toBeInTheDocument();

    const chip = screen.getByRole('button', { name: /in-progress/ });
    expect(chip).toHaveAttribute('aria-pressed', 'false');

    fireEvent.click(chip);
    expect(await screen.findByText('Being worked right now')).toBeInTheDocument();
    expect(chip).toHaveAttribute('aria-pressed', 'true');
  });

  it('hides blocked issues by default and lists them once the chip is toggled on', async () => {
    api.getAppIssues.mockResolvedValue(okPayload([
      ISSUE,
      {
        ...ISSUE,
        number: 43,
        title: 'Waiting on a dependency',
        labels: [{ name: 'blocked', color: '#b60205', description: '' }],
      },
    ]));
    await renderTab();

    await screen.findByText('Crash on save');
    expect(screen.queryByText('Waiting on a dependency')).not.toBeInTheDocument();
    expect(screen.getByText('1 of 2 open')).toBeInTheDocument();

    const chip = screen.getByRole('button', { name: 'blocked (1)' });
    expect(chip).toHaveAttribute('aria-pressed', 'false');

    fireEvent.click(chip);
    expect(await screen.findByText('Waiting on a dependency')).toBeInTheDocument();
    expect(chip).toHaveAttribute('aria-pressed', 'true');
  });

  it('hides needs-input issues by default and lists them once the chip is toggled on', async () => {
    api.getAppIssues.mockResolvedValue(okPayload([
      ISSUE,
      {
        ...ISSUE,
        number: 43,
        title: 'Needs feedback from user',
        labels: [{ name: 'needs-input', color: '#d4c5f9', description: '' }],
      },
    ]));
    await renderTab();

    await screen.findByText('Crash on save');
    expect(screen.queryByText('Needs feedback from user')).not.toBeInTheDocument();
    expect(screen.getByText('1 of 2 open')).toBeInTheDocument();

    const chip = screen.getByRole('button', { name: 'needs-input (1)' });
    expect(chip).toHaveAttribute('aria-pressed', 'false');

    fireEvent.click(chip);
    expect(await screen.findByText('Needs feedback from user')).toBeInTheDocument();
    expect(chip).toHaveAttribute('aria-pressed', 'true');
  });

  it('hides needs-decision issues by default and lists them once the chip is toggled on', async () => {
    api.getAppIssues.mockResolvedValue(okPayload([
      ISSUE,
      {
        ...ISSUE,
        number: 43,
        title: 'Needs architecture decision',
        labels: [{ name: 'needs-decision', color: '#d4c5f9', description: '' }],
      },
    ]));
    await renderTab();

    await screen.findByText('Crash on save');
    expect(screen.queryByText('Needs architecture decision')).not.toBeInTheDocument();
    expect(screen.getByText('1 of 2 open')).toBeInTheDocument();

    const chip = screen.getByRole('button', { name: 'needs-decision (1)' });
    expect(chip).toHaveAttribute('aria-pressed', 'false');

    fireEvent.click(chip);
    expect(await screen.findByText('Needs architecture decision')).toBeInTheDocument();
    expect(chip).toHaveAttribute('aria-pressed', 'true');
  });

  it('tints the issue card background for in-progress and blocked labels, blocked winning when both are present', async () => {
    // The tint is theme-aware (port-warning / port-error tokens), so the row
    // stays readable in every theme instead of shipping a hardcoded color.
    api.getAppIssues.mockResolvedValue(okPayload([
      ISSUE,
      { ...ISSUE, number: 43, title: 'Being worked right now', labels: [{ name: 'in-progress', color: '#0e8a16', description: '' }] },
      { ...ISSUE, number: 44, title: 'Waiting on a dependency', labels: [{ name: 'blocked', color: '#b60205', description: '' }] },
      {
        ...ISSUE, number: 45, title: 'Worked but stuck',
        labels: [
          { name: 'in-progress', color: '#0e8a16', description: '' },
          { name: 'blocked', color: '#b60205', description: '' },
        ],
      },
    ]));
    await renderTab();

    await screen.findByText('Crash on save');
    fireEvent.click(screen.getByRole('button', { name: /in-progress/ }));
    fireEvent.click(screen.getByRole('button', { name: 'blocked (2)' }));

    // The tinted div is the row root — exactly 4 levels above the title button.
    const rowOf = (title) => screen.getByText(title).closest('div').parentElement.parentElement.parentElement;
    expect(rowOf('Crash on save').classList.contains('bg-port-card')).toBe(true);
    expect(rowOf('Being worked right now').classList.contains('bg-port-warning/10')).toBe(true);
    expect(rowOf('Waiting on a dependency').classList.contains('bg-port-error/10')).toBe(true);
    expect(rowOf('Worked but stuck').classList.contains('bg-port-error/10')).toBe(true);
  });

  it('toggles a label chip off to hide every issue carrying that label', async () => {
    api.getAppIssues.mockResolvedValue(okPayload([
      ISSUE,
      { ...ISSUE, number: 43, title: 'Add CSV export', labels: [{ name: 'feature', color: null, description: '' }] },
    ]));
    await renderTab();

    await screen.findByText('Crash on save');
    // Facet counts come from the fetched issues, one chip per distinct label.
    const bugChip = screen.getByRole('button', { name: 'bug (1)' });
    expect(screen.getByRole('button', { name: 'feature (1)' })).toBeInTheDocument();

    fireEvent.click(bugChip);
    await waitFor(() => expect(screen.queryByText('Crash on save')).not.toBeInTheDocument());
    expect(screen.getByText('Add CSV export')).toBeInTheDocument();

    fireEvent.click(screen.getByRole('button', { name: 'Show all labels' }));
    expect(await screen.findByText('Crash on save')).toBeInTheDocument();
  });

  it('hides every issue from Hide all labels and restores them from Show all labels', async () => {
    api.getAppIssues.mockResolvedValue(okPayload([
      ISSUE,
      { ...ISSUE, number: 43, title: 'Add CSV export', labels: [{ name: 'feature', color: null, description: '' }] },
      { ...ISSUE, number: 44, title: 'Untagged cleanup', labels: [] },
    ]));
    await renderTab();

    await screen.findByText('Crash on save');
    expect(screen.getByText('Add CSV export')).toBeInTheDocument();
    expect(screen.getByText('Untagged cleanup')).toBeInTheDocument();
    expect(screen.getByRole('button', { name: 'Hide all labels' })).toBeInTheDocument();
    expect(screen.queryByRole('button', { name: 'Show all labels' })).not.toBeInTheDocument();

    fireEvent.click(screen.getByRole('button', { name: 'Hide all labels' }));
    await waitFor(() => expect(screen.queryByText('Crash on save')).not.toBeInTheDocument());
    expect(screen.queryByText('Add CSV export')).not.toBeInTheDocument();
    expect(screen.queryByText('Untagged cleanup')).not.toBeInTheDocument();
    expect(screen.getByText('No open issues match the current label filters.')).toBeInTheDocument();
    expect(screen.getByRole('button', { name: 'Show all labels' })).toBeInTheDocument();
    expect(screen.queryByRole('button', { name: 'Hide all labels' })).not.toBeInTheDocument();

    fireEvent.click(screen.getByRole('button', { name: 'Show all labels' }));
    expect(await screen.findByText('Crash on save')).toBeInTheDocument();
    expect(screen.getByText('Add CSV export')).toBeInTheDocument();
    expect(screen.getByText('Untagged cleanup')).toBeInTheDocument();
    expect(screen.getByRole('button', { name: 'Hide all labels' })).toBeInTheDocument();
  });

  it('after Hide all, turning one label back on lists every issue that carries it', async () => {
    // Exclude-all (the naive Hide-all) would still drop a `critical`+`bug`
    // issue when `bug` stayed hidden. Include mode is what "show only critical"
    // has to mean.
    api.getAppIssues.mockResolvedValue(okPayload([
      {
        ...ISSUE,
        title: 'Crash on save',
        labels: [
          { name: 'bug', color: '#d73a4a', description: '' },
          { name: 'critical', color: '#b60205', description: '' },
        ],
      },
      { ...ISSUE, number: 43, title: 'Add CSV export', labels: [{ name: 'feature', color: null, description: '' }] },
      { ...ISSUE, number: 44, title: 'Page is down', labels: [{ name: 'critical', color: '#b60205', description: '' }] },
      { ...ISSUE, number: 45, title: 'Untagged cleanup', labels: [] },
    ]));
    await renderTab();

    await screen.findByText('Crash on save');
    fireEvent.click(screen.getByRole('button', { name: 'Hide all labels' }));
    await waitFor(() => expect(screen.queryByText('Crash on save')).not.toBeInTheDocument());

    fireEvent.click(screen.getByRole('button', { name: 'critical (2)' }));
    expect(await screen.findByText('Crash on save')).toBeInTheDocument();
    expect(screen.getByText('Page is down')).toBeInTheDocument();
    expect(screen.queryByText('Add CSV export')).not.toBeInTheDocument();
    expect(screen.queryByText('Untagged cleanup')).not.toBeInTheDocument();
    expect(screen.getByRole('button', { name: 'critical (2)' })).toHaveAttribute('aria-pressed', 'true');
    expect(screen.getByRole('button', { name: 'bug (1)' })).toHaveAttribute('aria-pressed', 'false');
  });

  it('never ships a filter chip with both a graded color and the theme utilities that override it', async () => {
    // `.bg-port-bg` / `.border-port-border` / day-mode `.text-gray-300` are all
    // `!important` in index.css, and author `!important` beats an inline style —
    // so a chip carrying both renders in theme neutrals with its label color
    // silently dead. Colored chips drop the utilities; colorless ones keep them.
    api.getAppIssues.mockResolvedValue(okPayload([
      ISSUE,
      { ...ISSUE, number: 43, labels: [{ name: 'feature', color: null, description: '' }] },
    ]));
    await renderTab();

    const colored = await screen.findByRole('button', { name: 'bug (1)' });
    expect(colored.style.color).not.toBe('');
    expect(colored.className).not.toMatch(/text-gray-300|bg-port-bg|border-port-border/);

    const colorless = screen.getByRole('button', { name: 'feature (1)' });
    expect(colorless.style.color).toBe('');
    expect(colorless.className).toContain('text-gray-300');

    // Hidden chips are struck through in theme neutrals — no inline color to lose.
    fireEvent.click(colored);
    const hidden = await screen.findByRole('button', { name: 'bug (1)' });
    expect(hidden.style.color).toBe('');
    expect(hidden.className).toContain('line-through');
  });

  it('resets label, assignee, and filed-by filters when the app changes', async () => {
    const inProgress = {
      ...ISSUE,
      number: 43,
      title: 'Being worked right now',
      author: 'alice',
      labels: [{ name: 'in-progress', color: '#0e8a16', description: '' }],
    };
    api.getAppIssues.mockResolvedValue(okPayload([ISSUE, inProgress]));
    const { rerender } = await renderTab();

    fireEvent.click(await screen.findByRole('button', { name: /in-progress/ }));
    expect(await screen.findByText('Being worked right now')).toBeInTheDocument();
    fireEvent.click(screen.getByRole('button', { name: 'Unassigned only' }));
    fireEvent.change(screen.getByLabelText('Filed by'), { target: { value: 'alice' } });
    expect(screen.getByLabelText('Filed by')).toHaveValue('alice');

    rerender(
      <MemoryRouter>
        <IssuesTab appId="app-2" appName="Other" />
      </MemoryRouter>
    );
    await act(async () => {});

    await waitFor(() => expect(screen.queryByText('Being worked right now')).not.toBeInTheDocument());
    expect(screen.getByRole('button', { name: 'Unassigned only' })).toHaveAttribute('aria-pressed', 'false');
    expect(screen.getByLabelText('Filed by')).toHaveValue('');
  });

  it('ignores a stale in-flight response when the app changes mid-request', async () => {
    // Switching apps updates this component in place, so a slow first response
    // must not land on top of the newer app's list.
    let resolveFirst;
    api.getAppIssues
      .mockImplementationOnce(() => new Promise(res => { resolveFirst = res; }))
      .mockResolvedValueOnce(okPayload([{ ...ISSUE, number: 99, title: 'Second app issue' }]));

    const { rerender } = render(
      <MemoryRouter><IssuesTab appId="app-1" appName="Widget" /></MemoryRouter>
    );
    rerender(
      <MemoryRouter><IssuesTab appId="app-2" appName="Other" /></MemoryRouter>
    );
    await act(async () => {});
    expect(await screen.findByText('Second app issue')).toBeInTheDocument();

    // The first app's response arrives late — it must be discarded.
    resolveFirst(okPayload([ISSUE]));
    await waitFor(() => expect(screen.getByText('Second app issue')).toBeInTheDocument());
    expect(screen.queryByText('Crash on save')).not.toBeInTheDocument();
  });

  it('says "couldn\'t reach" for a transient failure — never "no open issues"', async () => {
    api.getAppIssues.mockResolvedValue({
      forge: 'github', fullName: 'acme/widget', issues: [],
      reason: 'gh-unauthenticated', transient: true, headline: null, remedy: 'run gh auth login',
    });
    await renderTab();

    expect(await screen.findByText(/Couldn't reach GitHub/)).toBeInTheDocument();
    expect(screen.getByText(/run gh auth login/)).toBeInTheDocument();
    expect(screen.queryByText(/No open issues on this tracker/)).not.toBeInTheDocument();
  });

  it('renders the server\'s headline verbatim instead of inferring one from the reason', async () => {
    // A glab whose JSON output flag moved answers with its human table at exit 0
    // — reachable, just unreadable. Only the server-side classifier can tell
    // those apart, so it ships the sentence; the client must not second-guess it
    // with a reason table, which is how an authenticated user got told to
    // authenticate.
    api.getAppIssues.mockResolvedValue({
      forge: 'gitlab', fullName: 'group/proj', issues: [],
      reason: 'glab-output-not-json', transient: true,
      headline: "Reached GitLab, but couldn't read its answer",
      remedy: 'update `glab` — its JSON output flag moved (check `glab issue list --help`)',
    });
    await renderTab();

    expect(await screen.findByText(/Reached GitLab, but couldn't read its answer/)).toBeInTheDocument();
    expect(screen.getByText(/its JSON output flag moved/)).toBeInTheDocument();
    expect(screen.queryByText(/Couldn't reach GitLab/)).not.toBeInTheDocument();
    expect(screen.queryByText(/retry once the CLI is authenticated/)).not.toBeInTheDocument();
    expect(screen.queryByText(/No open issues on this tracker/)).not.toBeInTheDocument();
  });

  it('falls back to the reachability framing when the server ships no headline', async () => {
    // Older reasons (and any the server adds without copy) still read sensibly
    // rather than rendering a blank banner.
    api.getAppIssues.mockResolvedValue({
      forge: 'gitlab', fullName: 'group/proj', issues: [],
      reason: 'some-new-reason', transient: true, headline: null, remedy: null,
    });
    await renderTab();

    expect(await screen.findByText(/Couldn't reach GitLab/)).toBeInTheDocument();
    expect(screen.getByText(/some-new-reason/)).toBeInTheDocument();
  });

  it('explains a non-forge origin instead of showing an empty list', async () => {
    api.getAppIssues.mockResolvedValue({
      forge: null, fullName: null, issues: [], reason: 'unsupported-forge', transient: false, remedy: null,
    });
    await renderTab();

    expect(await screen.findByText(/isn't GitHub or GitLab/)).toBeInTheDocument();
  });

  it('points at the Work Tracker setting when the tracker owns no forge issues', async () => {
    // The server refuses to list issues a Claim here would not actually touch.
    api.getAppIssues.mockResolvedValue({
      forge: null, tracker: 'jira', fullName: null, issues: [],
      reason: 'tracker-not-a-forge', transient: false, remedy: null,
    });
    await renderTab();

    expect(await screen.findByText(/Work Tracker isn't a forge issue tracker/)).toBeInTheDocument();
    // No issues ⇒ no Claim button that would queue a mis-routed run.
    expect(screen.queryByRole('button', { name: /Claim/ })).not.toBeInTheDocument();
  });
});

// Replan is a SECOND opinion on an already-planned issue, launched from the same
// row as Claim. The failure modes worth pinning are the ones where the two runs
// bleed into each other: the wrong slashdo command, or one run's lifecycle events
// swapping out the other's button.
describe('IssuesTab replan', () => {
  it('queues the replan command with the same pin and prefetched content a claim gets', async () => {
    await renderTab();

    fireEvent.click(await screen.findByRole('button', { name: /Replan/ }));

    await waitFor(() => expect(api.createSlashdoTask).toHaveBeenCalledWith(
      'replan', 'app-1', {
        target: '42',
        issueContext: {
          number: 42,
          title: 'Crash on save',
          body: 'Repro: open the editor and hit save.',
          url: 'https://github.com/acme/widget/issues/42'
        }
      }, { silent: true }
    ));
    expect(await screen.findByRole('link', { name: /Replan #42: Queued/ })).toBeInTheDocument();
  });

  it('leaves the Claim button live while a replan of the same issue is running', async () => {
    await renderTab();

    fireEvent.click(await screen.findByRole('button', { name: /Replan/ }));
    expect(await screen.findByRole('link', { name: /Replan #42: Queued/ })).toBeInTheDocument();
    expect(screen.getByRole('button', { name: /Claim/ })).toBeEnabled();
  });

  // Before the POST resolves there is no task id to match on, so the socket path
  // falls back to the target the server stamped. Reading `claimTarget` there
  // would light up the Claim row from a replan's events (and vice versa).
  it('matches a pre-response socket update on replanTarget, never on claimTarget', async () => {
    let resolveReplan;
    api.createSlashdoTask.mockImplementation(() => new Promise(resolve => { resolveReplan = resolve; }));
    await renderTab();

    fireEvent.click(await screen.findByRole('button', { name: /Replan/ }));
    act(() => socketHandlers.get('cos:tasks:changed')({
      task: { id: 'task-9', status: 'in_progress', metadata: { app: 'app-1', claimTarget: '42' } }
    }));
    // A claim's event must not advance the replan row.
    expect(screen.getByRole('button', { name: /Claim/ })).toBeInTheDocument();

    act(() => socketHandlers.get('cos:tasks:changed')({
      task: { id: 'task-9', status: 'in_progress', metadata: { app: 'app-1', replanTarget: '42' } }
    }));
    expect(await screen.findByRole('link', { name: /Replan #42: Active/ })).toBeInTheDocument();

    await act(async () => { resolveReplan({ id: 'task-9', status: 'pending' }); });
    expect(screen.getByRole('link', { name: /Replan #42: Active/ })).toBeInTheDocument();
  });

  it('re-enables the Replan button when queuing fails, instead of stranding it', async () => {
    api.createSlashdoTask.mockRejectedValue(new Error('tracker is not a forge'));
    await renderTab();

    fireEvent.click(await screen.findByRole('button', { name: /Replan/ }));
    await findEnabledByRole('button', { name: /Replan/ });
  });

  it('allows selecting merge-on-green, hides reviewer controls, and sends prCompletion', async () => {
    await renderTab({ open: true });

    expect(await screen.findByText('Reviewers')).toBeInTheDocument();
    expect(screen.getByRole('button', { name: 'Edit reviewers' })).toBeInTheDocument();

    fireEvent.change(screen.getByLabelText('After PR'), { target: { value: 'merge-on-green' } });

    expect(screen.queryByText('Reviewers')).not.toBeInTheDocument();
    expect(screen.queryByRole('button', { name: 'Edit reviewers' })).not.toBeInTheDocument();

    fireEvent.click(screen.getByRole('button', { name: /Claim/ }));

    await waitFor(() => expect(api.createSlashdoTask).toHaveBeenCalled());
    const [, , payload] = api.createSlashdoTask.mock.calls.at(-1);
    expect(payload.prCompletion).toBe('merge-on-green');
    expect(payload.reviewers).toBeUndefined();
  });

  it('unblocks claim when switching to merge-on-green even after removing all reviewers', async () => {
    await renderTab({ open: true });

    fireEvent.click(await screen.findByRole('button', { name: 'Edit reviewers' }));
    fireEvent.click(await screen.findByRole('button', { name: /Remove Antigravity/i }));
    expect(screen.getByRole('button', { name: /Claim/ })).toBeDisabled();

    fireEvent.change(screen.getByLabelText('After PR'), { target: { value: 'merge-on-green' } });
    expect(screen.getByRole('button', { name: /Claim/ })).toBeEnabled();

    fireEvent.click(screen.getByRole('button', { name: /Claim/ }));
    await waitFor(() => expect(api.createSlashdoTask).toHaveBeenCalled());
    const [, , payload] = api.createSlashdoTask.mock.calls.at(-1);
    expect(payload.prCompletion).toBe('merge-on-green');
    expect(payload.reviewers).toBeUndefined();
  });
});

// One click imports the server-selected account's assignments, independent of
// the visible list filters, and blocks another click until the request settles.
it('tracks assigned GitHub issues explicitly and links to the resulting Brain list', async () => {
  api.getAppIssues.mockResolvedValue(okPayload([ISSUE]));
  let finish;
  api.syncGithubThreads.mockImplementation(() => new Promise(resolve => { finish = resolve; }));
  await renderTab();
  const button = await findEnabledByRole('button', { name: 'Track my assigned issues in Brain' });
  fireEvent.click(button);
  expect(api.syncGithubThreads).toHaveBeenCalledWith({ appId: 'app-1' }, { silent: true });
  expect(button.disabled).toBe(true);
  expect(screen.getByRole('link', { name: 'Open Threads' }).getAttribute('href')).toBe('/brain/threads');
  await act(async () => finish({ created: 1, updated: 0, possiblyTruncated: false }));
  expect(button.disabled).toBe(false);
});