Skip to content

The agent that grows with you

21.8 KB
Raw Blame
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
import type { ReactNode } from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'

import type { SessionInfo } from '@/hermes'
import { $dismissedWorktreeIds, $sidebarShowAllSessions, dismissWorktree, restoreWorktree } from '@/store/layout'
import { listRepoBranches, removeWorktreePath, switchBranchInRepo } from '@/store/projects'

import {
  EnteredProjectContent,
  type SidebarProjectTree,
  type SidebarSessionGroup,
  SidebarWorkspaceGroup
} from './projects'
import type * as ProjectsModel from './projects/model'
import { SidebarSessionsSection, VIRTUALIZE_THRESHOLD } from './sessions-section'
import type { VirtualSessionListProps } from './virtual-session-list'

const startNewSessionDrag = vi.hoisted(() => vi.fn())
const workspaceOpen = vi.hoisted(() => ({ value: false }))

vi.mock('../new-session-drag', () => ({ startNewSessionDrag }))

// Capture what the virtualized list receives so the divider wiring can be
// asserted on the long-list path too (jsdom can't measure a real viewport).
const virtualPropsHistory = vi.hoisted(() => [] as VirtualSessionListProps[])

vi.mock('./virtual-session-list', () => ({
  VirtualSessionList: (props: VirtualSessionListProps) => {
    virtualPropsHistory.push(props)

    return <div data-testid="virtual-session-list" />
  }
}))

// Flat-list tests only care about dividers: keep session rows inert so they
// can't collide on accessible names or pull in row-level store dependencies.
vi.mock('./session-row', () => ({
  SidebarSessionRow: ({ session }: { session: SessionInfo }) => (
    <div data-testid={`session-row-${session.id}`}>{session.id}</div>
  )
}))

vi.mock('@/i18n', () => ({
  useI18n: () => ({
    t: {
      common: { cancel: 'Cancel' },
      desktop: {},
      sidebar: {
        dateDivider: {
          earlier: 'Earlier',
          earlierThisMonth: 'Earlier this month',
          lastMonth: 'Last month',
          lastWeek: 'Last week',
          older: 'Older',
          thisMonth: 'This month',
          thisWeek: 'This week',
          today: 'Today',
          yesterday: 'Yesterday'
        },
        nav: { 'new-session': 'New session' },
        newSessionIn: (label: string) => `New session in ${label}`,
        noSessions: 'No sessions yet',
        projects: {
          copyPath: 'Copy path',
          enter: (label: string) => `Enter ${label}`,
          forceRemove: 'Force remove',
          menu: 'Actions',
          removeFromSidebar: 'Remove from sidebar',
          removeWorktree: 'Remove worktree',
          removeWorktreeConfirm: 'Remove this worktree?',
          removeWorktreeDirty: 'This worktree has changes.',
          removeWorktreeFailed: 'Could not remove worktree',
          reorder: (label: string) => `Reorder ${label}`,
          reveal: 'Reveal in file manager',
          toggle: (label: string, open: boolean) => `${open ? 'Show' : 'Hide'} ${label} sessions`
        },
        showMoreIn: (count: number, label: string) => `Show ${count} more in ${label}`
      },
      profiles: { switchToProfile: (label: string) => `Switch to ${label}` },
      statusStack: { coding: { switchFailed: (label: string) => `Could not switch to ${label}` } }
    }
  })
}))

vi.mock('./projects/model', async () => ({
  ...(await vi.importActual<typeof ProjectsModel>('./projects/model')),
  latestProjectSessions: () => [],
  useWorkspaceNodeOpen: () => [workspaceOpen.value, vi.fn()]
}))

vi.mock('./projects/project-menu', () => ({
  ProjectContextMenu: ({ children }: { children: ReactNode }) => children,
  ProjectMenu: () => null
}))

vi.mock('@/store/projects', async () => ({
  ...(await vi.importActual('@/store/projects')),
  listRepoBranches: vi.fn(),
  removeWorktreePath: vi.fn(),
  switchBranchInRepo: vi.fn()
}))

const noop = vi.fn()

const baseProps = () => ({
  activeSessionId: null,
  emptyState: null,
  label: 'Projects',
  onArchiveSession: noop,
  onDeleteSession: noop,
  onNewSessionInWorkspace: noop,
  onResumeSession: noop,
  onToggle: noop,
  onTogglePin: noop,
  onToggleUnread: noop,
  open: true,
  pinned: false,
  sessions: [] as SessionInfo[],
  workingSessionIdSet: new Set<string>()
})

const group = (overrides: Partial<SidebarSessionGroup> = {}): SidebarSessionGroup => ({
  id: '/repo/.worktrees/feature',
  isMain: false,
  label: 'feature',
  path: '/repo/.worktrees/feature',
  sessions: [],
  ...overrides
})

const project = (overrides: Partial<SidebarProjectTree> = {}): SidebarProjectTree => ({
  id: 'project-1',
  isNoProject: false,
  label: 'Project One',
  path: '/repo/project-one',
  repos: [],
  sessionCount: 0,
  ...overrides
})

function commitLatestDrag() {
  expect(startNewSessionDrag).toHaveBeenCalledOnce()

  const commit = startNewSessionDrag.mock.calls[0]?.[0] as (placement: {
    anchor: string
    before?: null | string
    dir: 'center' | 'right'
  }) => void

  commit({ anchor: 'workspace', before: 'session-tile:next', dir: 'right' })
}

function renderEnteredProjectWithLiveWorktree() {
  return render(
    <EnteredProjectContent
      project={project({ repos: [{ groups: [group()], id: '/repo', label: 'Repo', path: '/repo', sessionCount: 0 }] })}
      renderRows={() => null}
      repoWorktrees={{
        '/repo': [
          { branch: 'feature', detached: false, isMain: false, locked: false, path: '/repo/.worktrees/feature' }
        ]
      }}
    />
  )
}

afterEach(cleanup)

beforeEach(() => {
  $dismissedWorktreeIds.set([])
  $sidebarShowAllSessions.set(false)
  workspaceOpen.value = false
  vi.mocked(removeWorktreePath).mockReset()
  noop.mockClear()
  startNewSessionDrag.mockReset()
  vi.mocked(switchBranchInRepo).mockReset()
  vi.mocked(listRepoBranches).mockReset().mockResolvedValue([])
})

describe('Show all sessions', () => {
  const sessions = Array.from({ length: 6 }, (_, index) => ({ id: `session-${index + 1}` }) as SessionInfo)

  const renderRows = (items: SessionInfo[]) => (
    <>
      {items.map(item => (
        <div key={item.id}>{item.id}</div>
      ))}
    </>
  )

  it('keeps the five-session page by default and renders every loaded workspace session when enabled', () => {
    workspaceOpen.value = true

    render(<SidebarWorkspaceGroup group={group({ sessions })} renderRows={renderRows} />)

    expect(screen.getByText('session-5')).toBeTruthy()
    expect(screen.queryByText('session-6')).toBeNull()

    act(() => $sidebarShowAllSessions.set(true))

    expect(screen.getByText('session-6')).toBeTruthy()
    expect(screen.queryByRole('button', { name: /Show .* more in feature/ })).toBeNull()
  })

  it('does not cap expanded project previews at two date groups', () => {
    workspaceOpen.value = true
    $sidebarShowAllSessions.set(true)
    const now = Math.floor(Date.now() / 1000)

    const previewSessions = [0, 2, 10, 40].map(
      days =>
        ({
          id: `day-${days}`,
          last_active: now - days * 24 * 60 * 60,
          started_at: now - days * 24 * 60 * 60
        }) as SessionInfo
    )

    render(
      <SidebarSessionsSection
        {...baseProps()}
        projectOverview={[project()]}
        projectOverviewPreviews={{ 'project-1': previewSessions }}
      />
    )

    expect(screen.getByText('day-40')).toBeTruthy()
  })
})

// An entered project/Home must reach every session it holds (#70421, #83157,
// #93878): the lane's first page stays short, but the way to the rest is a
// labeled row, not a hover-only glyph, and it pages in real steps.
describe('entered project reaches every session', () => {
  const many = (count: number, prefix = 'session') =>
    Array.from({ length: count }, (_, index) => ({ id: `${prefix}-${index + 1}` }) as SessionInfo)

  const renderRows = (items: SessionInfo[]) => <div data-testid="rows">{items.map(item => item.id).join(',')}</div>
  const shownCount = () => screen.getByTestId('rows').textContent?.split(',').filter(Boolean).length ?? 0

  it('labels the lane "show more" row with visible text, not just a tooltip', () => {
    workspaceOpen.value = true

    render(<SidebarWorkspaceGroup group={group({ sessions: many(12) })} renderRows={renderRows} />)

    expect(shownCount()).toBe(5)
    fireEvent.click(screen.getByText('Show 7 more in feature'))
    expect(shownCount()).toBe(12)
    expect(screen.queryByText(/Show .* more in feature/)).toBeNull()
  })

  it('pages a long lane in PROJECT_SESSION_PAGE steps past the first five', () => {
    workspaceOpen.value = true

    render(<SidebarWorkspaceGroup group={group({ sessions: many(60) })} renderRows={renderRows} />)

    fireEvent.click(screen.getByText('Show 50 more in feature'))
    expect(shownCount()).toBe(55)
    fireEvent.click(screen.getByText('Show 5 more in feature'))
    expect(shownCount()).toBe(60)
  })

  it('pages an entered Home instead of rendering every chat at once', () => {
    const home = project({
      id: '__no_project__',
      isNoProject: true,
      label: 'Home',
      path: null,
      repos: [
        {
          groups: [group({ id: '__no_project__', sessions: many(60) })],
          id: '__no_project__',
          label: 'Home',
          path: null,
          sessionCount: 60
        }
      ],
      sessionCount: 60
    })

    render(<EnteredProjectContent project={home} renderRows={renderRows} />)

    expect(shownCount()).toBe(50)
    fireEvent.click(screen.getByText('Show 10 more in Home'))
    expect(shownCount()).toBe(60)
  })
})

describe('project-associated new-session drag sources', () => {
  it('drags from the project overview + with the project cwd', () => {
    const onNewSessionSplit = vi.fn()

    render(
      <SidebarSessionsSection {...baseProps()} onNewSessionSplit={onNewSessionSplit} projectOverview={[project()]} />
    )

    fireEvent.pointerDown(screen.getByRole('button', { name: 'New session in Project One' }), { button: 0 })
    commitLatestDrag()

    expect(onNewSessionSplit).toHaveBeenCalledWith('right', {
      anchor: 'workspace',
      before: 'session-tile:next',
      cwd: '/repo/project-one'
    })
  })

  it('drags from a workspace/worktree + with that lane cwd', async () => {
    const onNewSessionSplit = vi.fn()

    render(
      <SidebarSessionsSection
        {...baseProps()}
        groups={[group({ sessions: [{ id: 'workspace-session' } as SessionInfo] })]}
        onNewSessionSplit={onNewSessionSplit}
      />
    )

    fireEvent.pointerDown(screen.getByRole('button', { name: 'New session in feature' }), { button: 0 })
    commitLatestDrag()

    await waitFor(() => {
      expect(onNewSessionSplit).toHaveBeenCalledWith('right', {
        anchor: 'workspace',
        before: 'session-tile:next',
        cwd: '/repo/.worktrees/feature'
      })
    })
  })

  it('switches a main-checkout lane to its labeled branch before creating the dragged session', async () => {
    const onNewSessionSplit = vi.fn()
    vi.mocked(switchBranchInRepo).mockResolvedValue(undefined)
    vi.mocked(listRepoBranches).mockResolvedValue([
      { checkedOut: false, isDefault: true, isRemote: false, name: 'main', worktreePath: null }
    ])

    render(
      <SidebarSessionsSection
        {...baseProps()}
        groups={[
          group({
            id: '/repo::main',
            isMain: true,
            label: 'main',
            path: '/repo',
            sessions: [{ id: 'main-session' } as SessionInfo]
          })
        ]}
        onNewSessionSplit={onNewSessionSplit}
      />
    )

    fireEvent.pointerDown(screen.getByRole('button', { name: 'New session in main' }), { button: 0 })
    commitLatestDrag()

    await waitFor(() => expect(onNewSessionSplit).toHaveBeenCalledOnce())
    expect(switchBranchInRepo).toHaveBeenCalledWith('/repo', 'main')
    expect(vi.mocked(switchBranchInRepo).mock.invocationCallOrder[0]).toBeLessThan(
      onNewSessionSplit.mock.invocationCallOrder[0]
    )
  })

  it('opens on the current checkout when the lane label is not a branch git knows (#108694)', async () => {
    // A row with no recorded git_branch is labelled with the `main` fallback;
    // on a `master` repo `git switch main` dies, so the switch must be skipped.
    const onNewSessionSplit = vi.fn()
    vi.mocked(listRepoBranches).mockResolvedValue([
      { checkedOut: true, isDefault: true, isRemote: false, name: 'master', worktreePath: '/repo' }
    ])

    render(
      <SidebarSessionsSection
        {...baseProps()}
        groups={[
          group({
            id: '/repo::main',
            isMain: true,
            label: 'main',
            path: '/repo',
            sessions: [{ id: 'main-session' } as SessionInfo]
          })
        ]}
        onNewSessionSplit={onNewSessionSplit}
      />
    )

    fireEvent.pointerDown(screen.getByRole('button', { name: 'New session in main' }), { button: 0 })
    commitLatestDrag()

    await waitFor(() => {
      expect(onNewSessionSplit).toHaveBeenCalledWith('right', {
        anchor: 'workspace',
        before: 'session-tile:next',
        cwd: '/repo'
      })
    })
    expect(listRepoBranches).toHaveBeenCalledWith('/repo')
    expect(switchBranchInRepo).not.toHaveBeenCalled()
  })

  it('does not run a branch switch for a non-git lane before creating the dragged session', async () => {
    // A plain non-git folder still gets an isMain lane from the backend
    // heuristic, but `git switch <folder-name>` there dies with "fatal: not a
    // git repository" (#61362). The lane's isGit=False flag must suppress the
    // switch while the new session still lands in the folder.
    const onNewSessionSplit = vi.fn()

    render(
      <SidebarSessionsSection
        {...baseProps()}
        groups={[
          group({
            id: '/www/notes::branch::main',
            isGit: false,
            isMain: true,
            label: 'notes',
            path: '/www/notes',
            sessions: [{ id: 'notes-session' } as SessionInfo]
          })
        ]}
        onNewSessionSplit={onNewSessionSplit}
      />
    )

    fireEvent.pointerDown(screen.getByRole('button', { name: 'New session in notes' }), { button: 0 })
    commitLatestDrag()

    await waitFor(() => {
      expect(onNewSessionSplit).toHaveBeenCalledWith('right', {
        anchor: 'workspace',
        before: 'session-tile:next',
        cwd: '/www/notes'
      })
    })
    expect(switchBranchInRepo).not.toHaveBeenCalled()
  })

  it('drags from an entered-project repo + with that repo cwd', () => {
    const onNewSessionSplit = vi.fn()

    const repoA = {
      groups: [group({ id: '/repo/a::main', isMain: true, label: 'main', path: '/repo/a' })],
      id: '/repo/a',
      label: 'Repo A',
      path: '/repo/a',
      sessionCount: 1
    }

    const repoB = {
      groups: [group({ id: '/repo/b::main', isMain: true, label: 'main', path: '/repo/b' })],
      id: '/repo/b',
      label: 'Repo B',
      path: '/repo/b',
      sessionCount: 1
    }

    render(
      <SidebarSessionsSection
        {...baseProps()}
        onNewSessionSplit={onNewSessionSplit}
        projectContent={project({ repos: [repoA, repoB], sessionCount: 1 })}
      />
    )

    fireEvent.pointerDown(screen.getByRole('button', { name: 'New session in Repo A' }), { button: 0 })
    commitLatestDrag()

    expect(onNewSessionSplit).toHaveBeenCalledWith('right', {
      anchor: 'workspace',
      before: 'session-tile:next',
      cwd: '/repo/a'
    })
  })

  it('renders declared repo headers before the project has any sessions', () => {
    const repo = (id: string, label: string) => ({ groups: [], id, label, path: id, sessionCount: 0 })

    render(
      <SidebarSessionsSection
        {...baseProps()}
        emptyState={<div>No sessions in this project</div>}
        projectContent={project({
          repos: [repo('/repo/a', 'Repo A'), repo('/repo/b', 'Repo B')],
          sessionCount: 0
        })}
      />
    )

    expect(screen.getByRole('button', { name: 'New session in Repo A' })).toBeTruthy()
    expect(screen.getByRole('button', { name: 'New session in Repo B' })).toBeTruthy()
    expect(screen.queryByText('No sessions in this project')).toBeNull()
  })

  it('drags profile-group add buttons to start a session in that profile', async () => {
    const onNewSessionSplit = vi.fn()

    render(
      <SidebarWorkspaceGroup
        group={group({ id: 'reviewer', label: 'Reviewer', mode: 'profile', path: null })}
        onNewSession={noop}
        onNewSessionSplit={onNewSessionSplit}
        renderRows={() => null}
      />
    )

    fireEvent.pointerDown(screen.getByRole('button', { name: 'New session in Reviewer' }), { button: 0 })

    expect(startNewSessionDrag).toHaveBeenCalledOnce()
    commitLatestDrag()

    await waitFor(() =>
      expect(onNewSessionSplit).toHaveBeenCalledWith('right', {
        anchor: 'workspace',
        before: 'session-tile:next',
        cwd: null,
        profile: 'reviewer'
      })
    )
  })

  it('does not expose a drag or click source for kanban aggregate lanes', () => {
    const onNewSessionSplit = vi.fn()
    const kanbanGroup = group({ id: 'kanban:review', isKanban: true, label: 'Review board' })

    const kanbanProject = project({
      repos: [
        {
          groups: [kanbanGroup],
          id: '/repo',
          label: 'Repo',
          path: '/repo',
          sessionCount: 0
        }
      ]
    })

    render(
      <EnteredProjectContent
        onNewSession={noop}
        onNewSessionSplit={onNewSessionSplit}
        project={kanbanProject}
        renderRows={() => null}
      />
    )

    expect(screen.queryByRole('button', { name: 'New session in Review board' })).toBeNull()
    expect(startNewSessionDrag).not.toHaveBeenCalled()
    expect(onNewSessionSplit).not.toHaveBeenCalled()
  })
})

describe('flat-list date-divider new-session drag source', () => {
  // Five fresh sessions, then a genuine 3-day pause: `groupEntriesByRecency`
  // cuts the run right there, so the flat list renders exactly one divider
  // below the head.
  const datedSessions = (): SessionInfo[] => {
    const now = Math.floor(Date.now() / 1000)

    return [
      ...Array.from({ length: 5 }, (_, i) => ({ id: `fresh-${i}` })),
      ...Array.from({ length: 2 }, (_, i) => ({ id: `older-${i}` }))
    ].map((row, i) => ({
      handoff_platform: null,
      handoff_state: null,
      id: row.id,
      last_active: i < 5 ? now - i * 60 : now - 3 * 24 * 60 * 60,
      profile: 'default',
      started_at: i < 5 ? now - i * 60 : now - 3 * 24 * 60 * 60
    })) as unknown as SessionInfo[]
  }

  it('drags from a date divider "+" without a cwd (flat recents)', () => {
    const onNewSessionSplit = vi.fn()

    render(
      <SidebarSessionsSection
        {...baseProps()}
        grouping="date"
        onNewSessionSplit={onNewSessionSplit}
        sessions={datedSessions()}
      />
    )

    fireEvent.pointerDown(screen.getByRole('button', { name: 'New session' }), { button: 0 })
    commitLatestDrag()

    expect(onNewSessionSplit).toHaveBeenCalledWith('right', {
      anchor: 'workspace',
      before: 'session-tile:next'
    })
  })

  it('wires the same divider action into the virtualized long list', () => {
    virtualPropsHistory.length = 0
    const onNewSessionSplit = vi.fn()

    const longList = Array.from({ length: VIRTUALIZE_THRESHOLD + 5 }, (_, i) => ({
      handoff_platform: null,
      handoff_state: null,
      id: `session-${i}`,
      last_active: Math.floor(Date.now() / 1000) - i * 60,
      profile: 'default',
      started_at: Math.floor(Date.now() / 1000) - i * 60
    })) as unknown as SessionInfo[]

    render(
      <SidebarSessionsSection
        {...baseProps()}
        grouping="date"
        onNewSessionSplit={onNewSessionSplit}
        sessions={longList}
      />
    )

    const lastProps = virtualPropsHistory.at(-1)

    expect(lastProps?.dividerAction).toBeTruthy()

    // jsdom can't measure a virtual viewport, so mount the divider action the
    // virtualizer would render and assert its drag wiring directly.
    render(<>{lastProps!.dividerAction}</>)
    fireEvent.pointerDown(screen.getByRole('button', { name: 'New session' }), { button: 0 })
    commitLatestDrag()

    expect(onNewSessionSplit).toHaveBeenCalledWith('right', {
      anchor: 'workspace',
      before: 'session-tile:next'
    })
  })

  it('renders no divider "+" when the section lacks a plain-create handler', () => {
    render(
      <SidebarSessionsSection
        {...baseProps()}
        grouping="date"
        onNewSessionInWorkspace={undefined}
        onNewSessionSplit={vi.fn()}
        sessions={datedSessions()}
      />
    )

    expect(screen.queryByRole('button', { name: 'New session' })).toBeNull()
  })

  it('keeps the divider "+" click-only without a split handler', () => {
    const onNewSessionInWorkspace = vi.fn()

    render(
      <SidebarSessionsSection
        {...baseProps()}
        grouping="date"
        onNewSessionInWorkspace={onNewSessionInWorkspace}
        sessions={datedSessions()}
      />
    )

    fireEvent.pointerDown(screen.getByRole('button', { name: 'New session' }), { button: 0 })

    expect(startNewSessionDrag).not.toHaveBeenCalled()
  })
})

describe('explicit worktree dismissal', () => {
  it('resurfaces removed worktrees on discovery but not a subsequent explicit hide', async () => {
    dismissWorktree('/repo/.worktrees/feature', { removed: true })
    renderEnteredProjectWithLiveWorktree()
    expect(screen.getByTitle(/feature/)).toBeTruthy()
    dismissWorktree('/repo/.worktrees/feature')
    await waitFor(() => expect(screen.queryByTitle(/feature/)).toBeNull())
  })

  it('hides a live lane without removing the worktree and permits explicit restore', async () => {
    renderEnteredProjectWithLiveWorktree()
    fireEvent.pointerDown(screen.getByRole('button', { name: 'Actions' }), { button: 0, ctrlKey: false })
    fireEvent.click(await screen.findByText('Remove worktree…'))
    fireEvent.click(await screen.findByRole('button', { name: 'Remove from sidebar' }))
    await waitFor(() => expect(screen.queryByTitle(/feature/)).toBeNull())
    expect(removeWorktreePath).not.toHaveBeenCalled()
    restoreWorktree('/repo/.worktrees/feature')
    await waitFor(() => expect(screen.getByTitle(/feature/)).toBeTruthy())
  })
})